The rules of five/three/zero

Usually, the existence of a single constructor indicates that the others should get implemented too (or explicitly forbidden/deleted). This is called the rule of five (or three, depending on the standard). However, there is only one member in your class, _tocc, and it has well-defined constructors for all the usual cases.

Here, we should follow the rule of zero: declare and define no constructors at all, as the default constructors will do the right thing. See also CppCoreGuidelines C.20.

Use already known data

While there is no bug in your code, there are some optimization flaws. Let's have a look at tocc<int>::push, compiled via gcc 9.2 -S -O3 (CompilerExplorer; I had to [[gnu::noinline]] to keep the assembly sane).

tocc<int>::push(int const&):
    sub     rsp, 24
    mov     rdx, QWORD PTR [rdi+16]
    mov     ecx, DWORD PTR [rsi]
    test    rdx, rdx
    je      .L31
    lea     r8, [rdi+8]
    mov     rax, rdx
    mov     rsi, r8
    jmp     .L32
.L48:
    mov     rsi, rax
    mov     rax, QWORD PTR [rax+16]
    test    rax, rax
    je      .L33
.L32:
    cmp     DWORD PTR [rax+32], ecx
    jge     .L48
    mov     rax, QWORD PTR [rax+24]
    test    rax, rax
    jne     .L32
.L33:
    cmp     rsi, r8
    je      .L31
    cmp     DWORD PTR [rsi+32], ecx
    jg      .L31
    mov     rax, r8
    jmp     .L36
.L50:
    mov     rax, rdx
    mov     rdx, QWORD PTR [rdx+16]
    test    rdx, rdx
    je      .L49
.L36:
    cmp     ecx, DWORD PTR [rdx+32]
    jle     .L50
    mov     rdx, QWORD PTR [rdx+24]
    test    rdx, rdx
    jne     .L36
.L49:
    cmp     r8, rax
    je      .L41
    cmp     ecx, DWORD PTR [rax+32]
    jl      .L41
    add     QWORD PTR [rax+40], 1
    add     rsp, 24
    ret
.L31:
    mov     rsi, rsp
    mov     DWORD PTR [rsp], ecx
    mov     QWORD PTR [rsp+8], 1
    call    std::pair<std::_Rb_tree_iterator<std::pair<int const, long> >, bool> std::_Rb_tree<int, std::pair<int const, long>, std::_Select1st<std::pair<int const, long> >, std::less<int>, std::allocator<std::pair<int const, long> > >::_M_emplace_unique<std::pair<int, long> >(std::pair<int, long>&&)
    add     rsp, 24
    ret
.L41:
    mov     edi, OFFSET FLAT:.LC0
    call    std::__throw_out_of_range(char const*)

That's a lot of conditional jumps. 11 jumps depend on test or cmp. However, we only have a single comparison. What happens here?

Well, first of all, a call to map<T>::at isn't free. It always has some additional boundary check, which prevents us from undefined behaviour but exchanges this boon for some additional code and an potential exception.

However, if we're in the second branch in push, then we already know that there is an element! After all, we found it beforehand:

void push(const T& item)
{
    if(_tocc.find(item) == _tocc.end())
        _tocc.insert(std::pair<T, long int>(item, 1));
    else
        _tocc.at(item)++;  // find() did not return end()!
}

Instead of at, we should use the iterator for several reasons:

we already have the element at hand,
we're guaranteed to have an element, so the boundary check in at() is not necessary,
we don't need to search the element a second time and therefore stay \$\mathcal O(1)\$ instead of \$\mathcal O(\log n)\$

So let's use the iterator instead and let's replace std::pair<T, long int> with std::make_pair while we're at it:

void push(const T& item)
{
    const auto it = _tocc.find(item);
    if(it == _tocc.end()) {
        _tocc.insert(std::make_pair(item, 1));
    } else {
        it->second++;
    }
}

What's the new assembly?

tocc<int>::push(int const&):
    mov     rax, QWORD PTR [rdi+16]
    mov     edx, DWORD PTR [rsi]
    test    rax, rax
    je      .L31
    lea     rsi, [rdi+8]
    mov     rcx, rsi
    jmp     .L32
.L44:
    mov     rcx, rax
    mov     rax, QWORD PTR [rax+16]
    test    rax, rax
    je      .L33
.L32:
    cmp     DWORD PTR [rax+32], edx
    jge     .L44
    mov     rax, QWORD PTR [rax+24]
    test    rax, rax
    jne     .L32
.L33:
    cmp     rsi, rcx
    je      .L31
    cmp     DWORD PTR [rcx+32], edx
    jle     .L36
.L31:
    sub     rsp, 24
    lea     rsi, [rsp+8]
    mov     DWORD PTR [rsp+8], edx
    mov     DWORD PTR [rsp+12], 1
    call    std::pair<std::_Rb_tree_iterator<std::pair<int const, long> >, bool> std::_Rb_tree<int, std::pair<int const, long>, std::_Select1st<std::pair<int const, long> >, std::less<int>, std::allocator<std::pair<int const, long> > >::_M_emplace_unique<std::pair<int, int> >(std::pair<int, int>&&)
    add     rsp, 24
    ret
.L36:
    add     QWORD PTR [rcx+40], 1
    ret

Only 6 conditional jumps, only ~55% the original amount. However, keep in mind that the reduction of asm instructions was not the goal of this section. Instead, we re-used already known values and didn't repeat ourselves (only one find() call).

The same holds for pop()'s usage of map::erase(), which can also take an iterator instead of a Key, but that's left as an exercise.

Documentation and (internal) comments

Good job on the comments! However, keep in mind that Doxygen and other programs use special syntax to discern  documentation comments and implementation comments.

Naming

The sole member of our class almost has the same name as your class. This makes it somewhat confusing, as we use _tocc to actually implement tocc. Naming is hard, though, and I cannot come up with a nicer name; counter, key_counter or key_counter_map don't have the same ring to it, although the latter is the most descriptive variant.

Interface

At the moment, a user must know the name of all items in the tocc to check their count afterwards. An iterator interface would be tremendously helpful.

We could even reuse std::map::const_iterator, if you only want constant iteration:

using iterator_type = std::map<T, long int>::iterator_type;

iterator_type begin() { return _tocc.begin(); }
...


I have created a function to prevent the one second delay.
Added moment().tz(timezone) as variable
Added all elements as variable
Added the date and time directly to the elements
Added a shorter way to add options

var list = moment.tz.names();
var timezone;

// elements
var elTimezoneList = document.getElementById('timezone_list');
var elTime = document.getElementById('show_time');
var elDate = document.getElementById('show_date');

// loop over timezones and set options
for(var i = 0; i < list.length; i++) {
   elTimezoneList.appendChild(new Option(list[i], list[i]));
}

// time function to prevent the 1s delay
var setTime = function() {
  var time = moment().tz(timezone);

  // set time in html
  elTime.innerHTML= time.format('h:mm:ss a');

  // set date in html
  elDate.innerHTML = time.format('MMMM Do YYYY');
}

// on change select
elTimezoneList.onchange = function(){
  // set selected timezone
  timezone = elTimezoneList.options[elTimezoneList.selectedIndex].text;

  setTime();
  setInterval(setTime, 1000);
}
<!DOCTYPE html>

    <title>Html clock</title>

    <link rel="stylesheet" type="text/css" href="stylesheet.css">

    <select id="timezone_list"></select>


File Async writer using Tasks or new features of .Net 4.5?

Before I explain how would I improve that code, I'll first mention two problems I will not try to fix (because I'm not sure how to do it properly):

Disposable singleton is a really weird combination. If something should be available anytime and anywhere, it should be a singleton. On the other hand, if something has a limited lifetime and holds an expensive resource (like an open file), it should be disposable. Those two don't go together very well.
Finalizer should execute as fast as possible. It certainly shouldn't take a lock that may not be released for quite some time (because there may be many threads also holding the lock).

The problems my solution will solve:

Writing to the log may not be in the correct order, lock doesn't guarantee any ordering.
Dispose() may not write all outstanding messages. This is again because lock doesn't guarantee ordering.
If a write attempt happens after Dispose() (either because Log() was called after Dispose(), or because of the ordering problems mentioned above), an exception will be thrown on the ThreadPool. This exception can't be caught from outside of Logger and will bring down the whole application. (More reason not to have disposable singletons.)
If there are many calls to Log() at the same time, or if the writing takes too long, there may be many threads, all waiting on the same lock.
While the message is being written, there is a thread blocking until it finishes.

My solution using TPL Dataflow (which uses .Net 4.5 extensively, available from NuGet) solves the issues so that:

Writing to the log will be always in the correct order.
Dispose() will first write all outstanding messages before returning.
If Log() is called after Dispose(), it will directly throw an exception.
There will be at most one thread doing the writing, at any time.
While the message is being written, no thread is waiting for it to finish.

public sealed class Logger : IDisposable
{
    private static readonly Logger Instance = new Logger();

    private readonly ActionBlock<string> m_writerBlock;

    private static bool Disposed;

    private Logger()
    {
        var writer = new StreamWriter("c:\\temp\\logtester.log", true);
        m_writerBlock = new ActionBlock<string>(s => writer.WriteLineAsync(s));
        m_writerBlock.Completion.ContinueWith(_ => writer.Dispose());
    }

    public static void Log(string message)
    {
        if (!Instance.m_writerBlock.Post(message))
            throw new ObjectDisposedException("Logger");
    }

    public void Dispose()
    {
        if (Disposed)
            return;

        m_writerBlock.Complete();
        m_writerBlock.Completion.Wait();

        Disposed = true;
    }
}

This works correctly, because the ActionBlock will take care of almost anything needed here, like ordering, synchronization and scheduling Tasks when necessary. WriteLineAsync() returns a Task and the block will use this Task to asynchronously wait for it to finish.


Having children call parent's public events with data generated from a protected event

The events in the base class don't follow the standards:

public event Action<TEventArgs> DeviceArrived;
public event Action<TEventArgs> DeviceRemoved;

protected event Action<string> DeviceArrival;
protected event Action<string> DeviceRemoval;

I'd be expecting something like this:

public event EventHandler<TEventArgs> AfterDeviceArrived;
public event EventHandler<TEventArgs> AfterDeviceRemoved;

protected event EventHandler<SomeEventArgsClass> BeforeDeviceArrived;
protected event EventHandler<SomeEventArgsClass> BeforeDeviceRemoved;

Couple points:

Events can be declared with any delegate type (Action<T> works), but the convention is to use an EventHandler or EventHandler<TEventArgs> delegate.
Convention for naming events that come in pairs (raised before and after such or such "thing" happens) is to prefix the event names with "Before" and "After", and use past tense as you've done.
OnDeviceChange should be called OnDeviceChanged.. but it's not clear why the method needs to raise both ...Arrived and ...Removed events without [apparently] doing anything in-between.

A base class shouldn't know, or care, about whether it has derived classes or not. You've got that right, but a derived class that's listening for events raised in the base class, doesn't make sense to me.

I don't think events are the appropriate way to accomplish what you're trying to do here. That said I'm not sure exactly what you're trying to accomplish (trimmed code does that ;) - but I'd venture to suggest templated methods instead of events.

In the base class:

// todo: remove notion of "event args"
protected abstract void OnDeviceArrived(TEventArgs e);
protected abstract void OnDeviceRemoved(TEventArgs e);

The base class can call these methods even though they're not implemented - abstract methods must be implemented in the derived classes for the code to even compile.

So instead of this:

     if (e.Arrival && DeviceArrived != null)
         DeviceArrived(e);
     if (!e.Arrival && DeviceRemoved != null)
         DeviceRemoved(e);

You just have that:

    if (e.Arrival)
    {
        OnDeviceArrived(e);
    }
    else
    {
        OnDeviceRemoved(e);
    }

And the derived classes have the implementations:

protected override void OnDeviceArrived(TEventArgs e)
{
    // ...
}

protected override void OnDeviceRemoved(TEventArgs e)
{
    // ...
}


Python implementation of a singly linked list

raise + except + raise = raise

def remove(self, index):
    try:
        if index < 0 or index >= self.size:
            raise ValueError

            ...

    except ValueError:
        raise ValueError('Index cannot be negative or greater than the size of the list')

It make no sense to except and raise again, simplify to:

if index < 0 or index >= self.size:
    raise IndexError('Index cannot be negative or greater than the size of the list')

...

The function will look like:

def insert(self, item):
    if item is None:
        raise ValueError('Cannot add None item to a list')
    self.size += 1
    if self.root is None:
        self.root = Node(item)
    else:
        p = Node(item)
        p.next = self.root
        self.root = p

for instead of counting loop

for is a more streamlined way of looping n times than a while loop:

        count = 0
        while count < index:
            current = current.next
            count += 1

Becomes:

for _ in range(index):
    current = current.next

(Please note _ is a convention meaning the value will not be used)


How to implement Publish-subscribe pattern in PHP?

There is nothing wrong with having the loggers everywhere. If you clutter all your classes with some kind of event notification it would look worst :)

But, Logger should not be called with a static method. You can create a pool of Loggers and your call will look like:

$log=Logger::get("Database");
$log->info("foo");

The big advantage is that you can put a configuration file in your project and define the log level of every logger independently.

According your questions you have really big plans. You want to write a template engine, a logging framework, an ORM and I guess somewhere in between your real application. Trust me when I tell you, you will fail. (I and most likely everybody else here tried it already :) ). For all your components there are mature frameworks out there. Find the one you like!!


It there a pattern used to process a same function but assign the result to a different variable regarding to a different condition?

First, it looks like the ID, OutcomeID and OutcomeNoteID belong together, so I think it it makes sense to extract them into a separate class (though my naming of it is just a guess):

class Hearing
{
    public int ID { get; private set; }

    public int OutcomeID { get; private set; }

    public int OutcomeNoteID { get; private set; }

    public Hearing(int id)
    {
         ID = id;
    }

    public void SetOutcome(int outcomeId, int outcomeNoteId)
    {
        OutcomeID = outcomeId;
        OutcomeNoteID = outcomeNoteId;
    }
}

With that, your code could be changed to something like:

Hearing hearing;
if (string.Equals(isStandardFlag, "STANDARD", StringComparison.InvariantCultureIgnoreCase))
    hearing = centreSession.StandardHearing;
else
    hearing = centreSession.NonStandardHearing;

hearing.SetOutcome(
    disciplineSvc.SaveResultA(hearing.ID, OffenceID, Outcome),
    disciplineSvc.SaveResultB(hearing.ID, txt1.Text, "ResultHearing"));

Some additional notes:

I have also changed string.Compare() == 0 to string.Equals(), because I think it expresses the intent better.
Some of the names are quite bad (e.g. txt1 or SaveResultA), you should improve those.
Dealing with ids a lot is not very object-oriented. I think it would make more sense to deal directly with Outcome and OutcomeNote objects, not just their ids.


Get value from a dictionary contained in a dictionary

The 'problem' with this approach is that you perform a lookup twice for each key.

ContainsKey
indexer lookup [..]

code

if (response.ContainsKey("GB") && response["GB"].ContainsKey(new DateTime(2001, 04, 01)))
{
    GB2001 = response["GB"][new DateTime(2001, 04, 01)];
}

Use TryGetValue to combine lookup and indexer.

string GB2001;
if (response.TryGetValue("GB", out var country))
{
    country?.TryGetValue(new DateTime(2001, 04, 01), out GB2001);
}


Making a TableViewDataSource more independent of the data it utilizes

My concern is that my TableViewDataSource is too tightly coupled with having to know about how my Conductor class functions, and I could like to decouple some of the logic.

Create a protocol which defines the data in the form that the data source needs. This will separate the requirements of the data from the implementation of the class providing the data, which would give you flexibility to change the behaviour of the Orchestra object without also having to change the data source.

The orchestra object should implement the protocol and provide the data in the required format. You can use a class extension on the orchestra or conductor to add the required code.

  Is calling the Singleton to populate my data source ok? And if not, what are better ways to make my TableViewDataSource more independent?

Using Singletons often leads to problems. It would be better to follow the dependency inversion principle and pass an instance of the conductor to the data source. From the code you have shown you only seem to be using the orchestra, and so the conductor itself is not needed.

Example

The example below shows how to:

Define a protocol.
Use a class extension to have a class conform to the protocol.
Update the data source to use the protocol instead of the concrete class.
Pass the orchestra instance into the data source.

1. Define a protocol:

protocol Performers {
    var numberOfSections: Int {
        get
    }
    func numberOfPerformers(inSection: Int) -> Int
    func performer(atIndex: Int, inSection: Int) -> Performer
}

2. Add a class extension on Orchestra to conform to the Performers protocol:

extension Orchestra: Performers {
    var numberOfSections: Int {
        return 2
    }

    func numberOfPerformers(inSection section: Int) -> Int {
        if section == 0 {
            return performers.count ?? 0
        } else {
            return nonPerformers.count ?? 0
        }
    }

    func performer(atIndex index: Int, inSection section: Int) -> Performer {
        if section == 0 {
            return performers[index]
        } else {
            return nonPerformers[index]
        }
    }
}

3. Modify the data source to use the protocol

class OrchestraViewDataSource: NSObject, UITableViewDataSource {

    var performers: Performers?

    override init(performers: Performers?) {
        super.init()
        self.performers = performers
    }

    func numberOfSections(in tableView: UITableView) -> Int {
        return performers?.numberOfSections ?? 0
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return performers?.numberOfPerformers(inSection: section) ?? 0
    }

    //... Additional code omitted
}

4. Pass the orchestra instance to the data source

let currentOrchestra = User.shared.currentOrchestra
let dataSource = OrchestraViewDataSource(performers: orchestra)


I am not completely sure if your question is as easy as it sounds (or if I am missing something), but here's my thought on things.

Using a singleton class for this does not make much sense in my opinion. There's no state to be stored, and therefore there's no need for an object at all. Instead, it sounds like you could put it in an utility method.

public static SearchItem createSearchItem(Cursor cursor) {
    SearchItem searchItem = new SearchItem();
    searchItem.setId(cursor.getInt(cursor.getColumnIndex(COLUMN_NAME_ID)));
    searchItem.setOrigin(cursor.getString(cursor.getColumnIndex(COLUMN_NAME_ORIGIN)));
    searchItem.setDestination(cursor.getString(cursor.getColumnIndex(COLUMN_NAME_DESTINATION)));
    searchItem.setTimeStamp(cursor.getLong(cursor.getColumnIndex(COLUMN_NAME_TIMESTAMP)));
    return searchItem:
}


Displaying JSON data from a server in a UICollectionView

I will address a few points that are the most important in my opinion.

Be consistent.

You're using URL but right after that you're also using NSURL. You're using NSData but later have to cast it to Data. Etc.

The right way would be, instead, to only use URL and Data, and forget the other types.

let requestURL = URL(string:self.videos[indexPath.row])
let request = URLRequest(url: requestURL!)
let imageUrl = URL(string: imageString)
let imageData = try! Data(contentsOf: imageUrl!)

cell.imageCell.image = UIImage(data: imageData)

Don't force unwrap.

You should not force unwrap your Optionals but use safe unwrapping instead, with if let or guard let.

A classic solution in your case is to have a ready-made placeholder image in your project - that way, if the download of an image fails, you can use the placeholder instead.

if let imageUrl = URL(string: imageString),
    let imageData = try? Data(contentsOf: imageUrl)
{
    cell.imageCell.image = UIImage(data: imageData)
} else {
    cell.imageCell.image = placeholder
}

Download asynchronously

You are downloading your list of images URLs with Alamofire but you're downloading the images themselves with NSData(contentsOf: imageUrl! as URL).

The problem is that this method is synchronous and blocks the main thread. If the network is suddenly slow or stops working, your app will lag or freeze.

Instead, download asynchronously with Alamofire, URLSession, etc.

Since you already know how to use Alamofire, I'm showing it with URLSession as an alternative:

if let imageUrl = URL(string: imageString) {
    URLSession.shared.dataTask(with: URLRequest(url: imageUrl)) { (data, response, error) in
        if let data = data {
            DispatchQueue.main.async {
                cell.imageCell.image = UIImage(data: data)
            }
        } else {
            DispatchQueue.main.async {
                cell.imageCell.image = placeholder
            }
        }
    }.resume()
}

Note that because .dataTask is asynchronous, and because we have to do all UI operations on the main thread, we have to set the image using DispatchQueue.main.async once it's downloaded.

This way, the UI won't freeze if there's network issues.
Style

This one is rather subjective, but in Swift there's a few common style guides you should follow:

Classes should start with an uppercase letter:

class VCWatch

class CVCell

Type declaration should have a space after the colon:

var images: [String] = []
var videos: [String] = []
var lableTitles: [String] = []

Parenthesis are not necessary for a boolean condition:

if imageData != nil {
    cell.imageCell.image = UIImage(data: imageData)
}

You can omit the type declaration when the compiler already knows the type:

let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "VideoCell", for: indexPath) as! cvCell

You can use short syntax for arrays and dictionaries:

[String: AnyObject] // instead of Dictionary<String,AnyObject>


Missing element from array (D&C) - code design/aesthetic improvement

I don't follow the definition:

"Given an array of n-1 numbers (int) from 0 to n, find the missing number".

So if n == 7, as in your example code, there should be 6 numbers (n-1) in the
array.  There are 8 numbers in the the range "0 to n" (0,1,2,3,4,5,6,7).
Perhaps the problem definition meant "0 to n-1" or "0 up to n, not including
n".

Your example code has seven numbers and n == 7:

int n = 7;
int v[] = {7,0,4,1,3,6,2};

I would expect n to be 8 for an array of 7 numbers where one of the 8 is
missing.

Anyway, your example works, printing '5', but if you replace, say the 2 with a 5
it now prints '3'.  Unless I messed up!

On the code, C ignores white space (unlike say Python).  Look at the
if-else chain at the beginning of find:

if (left == right)
  if (flagR != 0)
    return v[left] + 1;
  if (flagL != 0)
    return v[left] - 1;
else
{
  int exp0 = 0; // expected bits of 0

According to the indentation of statements, you intended the if (flagR != 0)
and if (flagL != 0) to be dependent upon left == right, as in:

if (left == right) {
    if (flagR != 0) {
        return v[left] + 1;
    }
    if (flagL != 0) {
        return v[left] - 1;
    }
}
else {
    int exp0 = 0; // expected bits of 0

But what the compiler will see is

if (left == right) {
    if (flagR != 0) {
        return v[left] + 1;
    }
}
if (flagL != 0) {
    return v[left] - 1;
}
else {
    int exp0 = 0; // expected bits of 0

If you get the editor to re-indent the code for you (or use UNIX indent
command), you will see that your indenting is wrong.  The lesson is always to
use braces to say explicitly what you mean.

The same goes for your other expressions:

for (int i=left+flagL;i<=right+flagR;i++)
  if (get_bit(i,max_bit) == 0)
    exp0++;
  else
    exp1++;

should be more like this:

for (int i = left + flagL; i <= right + flagR; i++) {
    if (get_bit(i, max_bit) == 0) {
        exp0++;
    } else {
        exp1++;
    }
}

In this case, there is no misunderstanding by the compiler but you should add the braces nevertheless - consider what happens if you don't add explicit braces with:

for (int i=left+flagL;i<=right+flagR;i++)
  if (get_bit(i,max_bit) == 0)
    exp0++;
  else
    exp1++;
    something_else();


Ruby if block refactor from new synthax needed

Guidelines Rubocop

The guidelines favor if/case over multi-line ternary operator when a line is too long.

  Maximum Line Length   Limit lines to 80 characters.
  No Multi-line Ternary   Avoid multi-line ?: (the ternary operator); use if/unless instead.
  Use if/case Returns   Leverage the fact that if and case are expressions which return a result.

Refactored Code

def show
  identification_document = IdentificationDocument.find(params[:id])
  authorize identification_document
  return unless identification_document

  document =
    if params[:size] == 'resized'
       identification_document.id_document_resized
    else
       identification_document.id_document
    end

  send_data(document.file.read, filename: identification_document.file_name)
end


Simple anagram or permutation generator in Python

Your python code is neat, simple and easy to understand (so generally it's good); and yet, something in me doesn't like the use of so many temporary arrays.  How about using a generator?

def anagrams(word):
    """ Generate all of the anagrams of a word. """
    if len(word) < 2:
        yield word
    else:
        for i, letter in enumerate(word):
            if not letter in word[:i]: #avoid duplicating earlier words
                for j in anagrams(word[:i]+word[i+1:]):
                    yield j+letter

if __name__ == "__main__":
    for i in anagrams("acbcddd"):
        print i

I (now) filtered out all duplicates which is almost certain your original intention and is standard in all anagram problems.  I did this by seeing if the same letter was already earlier in the word in which case we will have already generated this anagram.

You would have to do the same, or get rid of duplicates in your list for example by doing

return list(set(tmp))

instead of your current return from anagrams.


First some style notes: The "Yoda notation" is rare to see in JavaScript. Sure, it works, but you won't find many people using it, and just for that reason I'd recommend not using it, but it's your call. Just a heads-up in case others have to work on this code too.

I'd also recommend always using braces, even when they're not strictly necessary. Again, my recommendation, based on what I consider best practices.

In terms of functionality, it appears to match the docs for redis' LREM exactly - nice. Still I see some areas of improvement.

I don't see any need to avoid declaring local variables, though. You code seems just fine as-is on that point. Variables aren't a horrible performance drain or anything like that; there's no reason to avoid them. On the contrary, if you think adding a local variable will make the code more readable, then it's worth it.

Anyway, code review. First a simple thing: Use double quotes, and you don't have to escape single quotes in the string

throw new Error("Wrong number of arguments for 'lrem' command");

For that particular error, it's also easier to simply check arguments.length, and you could make it more informative - what is the correct number of arguments? (see below for an example of what I mean)

I've also removed the "ERR" prefix. It's already an Error object you're throwing, so it's kinda redundant.

Next, you can skip the || [] fallback, and instead do:

var list = this.get(key);

// if list is falsy or empty, or count is zero
if (!list || !list.length || !count) {
  return 0;
}

Next, another error. I've merely changed the wording a little, since it's not a syntax error; it's a semantic error. Besides, if it actually were a syntax error, you ought to be throwing a SyntaxError object. Here however, what we really want is a TypeError

if ('number' !== typeof value && 'string' !== typeof value) {
    throw new TypeError("'value' must be a string or a number");
}

But it might be simpler just to do all these checks upfront, instead of doing it in two different parts of the functions:

if(arguments.length < 3) {
  throw new Error("Wrong number of arguments for 'lrem' function (" + arguments.length + " for 3)");
}

if(typeof value !== 'number' && typeof value !== 'string') {
  throw new TypeError("'value' must be a string or a number");
}

And you might want to check the count argument's type too, while you're at it, but I'll leave that to you.

As for the actual meat of the function, I'd suggest simply using indexOf and lastIndexOf for simplicity.

var limit = Math.abs(count),
    removed = 0,
    indexOf = count < 0 ? list.lastIndexOf : list.indexOf,
    i;

while( removed < limit && (i = indexOf.call(list, value)) !== -1 ) {
  list.splice(i, 1);
  removed++;
}

if(!list.length) {
  this.remove(key);
}

return removed;

I've left out the this.set(key, list) line because I'm not sure it's necessary. While I'm not 100% sure (I just quickly skimmed the code on github), it seems that get returns a reference to the stored array, and, if so, you're removing items directly on that stored array already. No need to set it again.

Of course, if I'm wrong, just add the else-line back in.

All in one block:

lrem: function (key, count, value) {
  if(arguments.length < 3) {
    throw new Error("Wrong number of arguments for 'lrem' function (" + arguments.length + " for 3)");
  }

  if(typeof value !== 'number' && typeof value !== 'string') {
    throw new TypeError("'value' must be a string or a number");
  }

  // TODO: check 'count' type?

  var list = this.get(key);

  if (!list || !list.length || count == 0) {
    return 0;
  }

  var limit = Math.abs(count),
      removed = 0,
      indexOf = count < 0 ? list.lastIndexOf : list.indexOf,
      i;

  while( removed < limit && (i = indexOf.call(list, value)) !== -1 ) {
    list.splice(i, 1);
    removed++;
  }

  if(!list.length) {
    this.remove(key); // remove list entirely, if it's empty
  }

  return removed;
}


For consistency with your use of the <stdbool.h> header and the bool macro, your functions that return a bool should use return true; or return false; instead of returning 0 or 1. There will be no difference in the code but it is easier for a person reading the code to recognize what the return is (and this would also align better with your function documentation where you say that it "returns false").
Also related to comments, the add and get functions say that they add or read "one byte" but, because QueueDataType_t is a 16 bit type, they add or read two bytes.
If supported in your tool chain, queue_is_full and queue_is_empty could take their parameters as const struct queue * queue since they do not make any chances to the queue.
There is a subtle bug when removing the last element from the queue. When a queue is initialized, and when the first element is added, the front_idx and back_idx values both refer to the same slot in the data array. However, when you remove this single element, you still change the idx variable, so the resulting empty queue has the front and back indexes referring to different slots. Then when you add a new element, the indexes are not changed so that this element isn't pointed to by both indexes. This can result in an incorrect value being returned when this elements are removed from the queue. The fix is to not change the idx value when removing the last element.
You can create a function to adjust the indexes forward or backward to avoid having similar and duplicated code. This could then use the % operator (instead of a conditional branch) if appropriate on your embedded system.


Method that reads an input file of a particular format and creates objects corresponding to the file

As you are asking for best practices: methods and exceptions.

First of all, your code does everything in one method, where you could (and should) clearly divide the parts of

looping over the file
parsing a single line
checking uniqueness of the theatres

As you return with a failure anyway if a single line fails, you might as well throw an exception and stop the complete process. If you want to stick to the interface that returns an error/success condition as a result value, you may well catch and return in the outermost method.

Rough sketch:

private static class MyFileParsingException extends RuntimeException {
    ... add a constructor with a message here
}

public String initialise(String pathString) {
    try {
        Path filePath = Paths.get(pathString);
        List<Theater> theatres = Files.lines(filePath)
            .map(this::parseLineToTheater)
            .collect(Collectors.toList());
        checkUniqueness(theatres );
        this.theatres = theatres; // only set if successful
        return ... // success
    }
    catch(IOException e) {
        return ResponseMessages.FILE_NOT_FOUND_ERR_MSG.getDescription();
    }
    catch(MyFileParsingException e) {
        return e.getMessage();
    }
}

private Theater parseLineToTheater(String inputLine) throws MyFileParsingException {
    // parse single line, throw MyFileParsingException with the
    // appropriate message, return the theater
}

private void checkUniqueness(List<Theater> allReadTheaters) throws MyFileParsingException {
    // check, whether the ids are unique, throw MyFileParsingException
    // with DUPLICATE_CODE_ERR_MSG if you find a duplicate
}

Here, you have a trivial outer loop (or in fact a stream), which uses the nio.Files methods (which have been around since java 8, i.e. more than 4 years now - time to start using them), and two more methods which can trivially be unit-tested without even creating a file.

A little twist is extending RuntimeException instead of Exception for the hommade business exception, so that it can be used in a lambda expression. As it extends RuntimeException, the throws declaration is technically not really necessary on the methods, but I like to have them there so that the reader immediately sees that this exception type is to be expected.


Custom moment formats based on string length

How about this (based on the assumption that $ refers to jQuery):

var dateString = $('div').data('date');

function getDateFormat(dateString){

    if(!dateString) return false;

    var dateTimeFormats = ['YYMMDD' ,'YYMMDDHHmm'];

    return dateTimeFormats.filter(function(format){
        return format.length === dateString.length;
    })[0] || false;
}

console.log(getDateFormat(dateString));

jQuery's data() method is preferred over attr() since it's intended to be used with either html5 data attributes (like in your case) or for caching data in the jQuery $.cache.
Try to use more descriptive names and don't use reserved keywords as variable names (or a close call like string vs String in your case).
Check if the date string is defined before making use of it
I suggest that you always do equality checks using the identity operator, ===. Otherwise you might get results like 1 == true since the type is not taken in to consideration
If you want to use Array.prototype.filter in IE < 9, you can add a shim.

http://jsfiddle.net/zb4sfno3/


DiagnosticAnalyzer for Roslyn that guards against catch-all exception clauses

I've never coded a diagnostics analyzer, so I don't know if that's a possibility, but I think these:

private const string DiagnosticId = "SingleGeneralException";
private const string Description = "Verifies whether a try-catch block does not contain just a single Exception clause.";
private const string MessageFormat = "A catch-all clause has been used.";
private const string Category = "Exceptions";

Would be better off defined in a .resx file, so you can localize it - not everyone runs an English IDE, I'd try to have the the messages be shown in the same language as the stack traces.

In these declarations:

    var clause = node as CatchClauseSyntax;
    var exceptionType = clause.Declaration.Type;
    var identifier = semanticModel.GetSymbolInfo(exceptionType);
    var isGeneralException = identifier.Symbol.Name == typeof(Exception).Name;
    var hasMultipleClauses = clause.Parent.ChildNodes().OfType<CatchClauseSyntax>().ToList().Count > 1;

I think the relationships between the variables would be more obvious with some vertical whitespace:

    var clause = node as CatchClauseSyntax;

    var exceptionType = clause.Declaration.Type;
    var hasMultipleClauses = clause.Parent.ChildNodes()
                                          .OfType<CatchClauseSyntax>()
                                          .ToList().Count > 1;

    var identifier = semanticModel.GetSymbolInfo(exceptionType);
    var isGeneralException = identifier.Symbol.Name == typeof(Exception).Name;

I believe there's a possible execution path where the clause would be null (because of the as cast), in which case the next line would throw an easily avoidable NullReferenceException:

    var clause = node as CatchClauseSyntax;
    if (clause == null) return;


Simple c# for-loop program for calculating theoretical earnings from investing (beginner)

Here are some points that I think can make your code look good -

You can improve the readbility like you can group every set of operations with one line space. Like

The local variables can be renamed better as they're not clear to me when I look at the code directly without reading the problem statement. For example inpMonth and inpMonthTrue are confusing.
You can include code comments on the logic that you're performing. For example in the below snippet, it is unclear what exactly is happening.

The main() method can be broken into multiple meaningful methods to improve readability. Assuming that you'll be taking the input from the console

This was just a gist of what I'm trying to convey. It needn't be the exact names, you can create any number of methods for grouping the related logic and code. Breaking a big tall method into multiple meaningful chunks gives more clarity.
Plus, it is always helpful to detect any bugs that arise in the software, so you know where exactly to look into if the Interest is coming wrong for instance.


You can't totally guarantee performance here, since so much is up to how the browser handles DOM manipulation and reflowing content when it's shown/hidden. But there are some things you can improve. Most notably: Don't find and re-find all the elements every time the page changes.

But first, in terms of structure, there's something weird going on. Only the jqPagination stuff is inside a $(document).ready() callback. Yet you're also trying to access page elements before that. The whole point of the ready event is that it fires when you can start using the DOM; if you try before that, the page might not have finished loading. So the browser might literally only have half the page, with the rest still on its way across the interwebs.

So when you do this:

var maxItems = $('li').length

you risk finding zero li elements, because the page isn't ready yet.

Secondly, I worry about the way you're selecting elements. $('li') will select all list item elements anywhere on the page. Doesn't matter if they're part of the list you want to paginate or not. In other words, you're selector casts its net much too wide.

Similarly with the $('active').removeClass('active'); call. Again, that's selecting any element with the active class, regardless of where it is on the page. Using a class named active is a pretty common thing for highlighting links, buttons, and tons of other things. So that line could easily wreak havoc on other parts of the page. Again, too greedy a selector.

Incidentally, I'd also use an ID of the list-pagination buttons, if there's only that one list. Having multiple elements with the class pagination is perhaps less common, but your code certainly doesn't expect more than one, so better to use an ID, which is what you'd use for unique, non-repeated elements.

Back to structure: Your code is split in two. You have the showPage function, which does indeed show pages. But the code to hide the previous page (the removeClass call), is somewhere else. Why? If I call showPage I'd expect it to show a page. Not just show the requested page, and leave previous stuff around. You're also calculating some stuff before calling showPage, despite it being able to do so itself.

In other words, you've added a function, but not given it all the functionality it should probably have.

Finally, you have 5 as a magic number repeated in multiple places. Stick it in a variable and reference that variable instead. That way we a) know what the number is (it's got a name now), and b) you only have to change it in one spot to change the behavior. When it's spread out, maintenance becomes much harder.

I'd do this:

$(function () { // equivalent to $(document).ready(...)
  var perPage = 5,
      allItems = $('#theBigList').children('li'), // change to fit your list's selector
      previousItems = null; // stores the last set of elements

  // a simpler implementation
  function goToPage(page) {
    var offset = (page - 1) * perPage;

    // hide previous items, if any
    if(previousItems) {
      previousItems.removeClass('active');
    }

    // show new items, and store the set
    previousItems = allItems.slice(offset, perPage).addClass('active');
  }

  $('#paginationControls').jqPagination({
    maxPage: Math.ceil(allItems.length / perPage),
    paged: goToPage
  });

  goToPage(1); // might not be necessary if jqPagination automatically invokes its "paged" callback with the argument 1 upon initialization
});

Again, though, if things slow down for very long lists, it's probably because they're very, very long lists. It's not really the javascript that's at fault; it's how fast the browser is.


Shortening Custom Document Property additions

Writing to a document property is a concern in its own right, and thus deserves its own scope. Write a procedure that's responsible only for this!

Public Sub IncrementHeavyDutyCount(ByVal increment As Long)
    With ThisWorkbook.CustomDocumentProperties.Item("numHD")
        .Value = .Value + increment
    End With
End Sub

And now you can increment your counter with a simple, self-explanatory procedure call:

If cell = "Heavy Duty" Then IncrementHeavyDutyCount 4


MySQL/CUPS PDF printer for STAR TSP100 ECO

I would put the configuration of user, password, host, etc into a dictionary. This allows you to load this dictionary from a file, if you don't want to have the password in the code. It makes it also easy to pass it to a db connect function:

# Hard-coded here, but might as well be retrieved from a config file
CONF = {'host': "nope",
        'user': "nope",
        'passwd': "nope",
        'db': "printer"}

def connect(**conf):
    """# Connect to the Printer DB"""
    return MySQLdb.connect(**conf)

db = connect(**conf)

The connect function is even transparent, so you can also pass additional keyword-arguments:

db = connect(raise_on_warnings=True, **conf)

I would split up the main part of the code into separate functions. One to create the files to print, which returns the list of files to print. And a second function for printing that task and cleaning up the task.

The first function is to_print. It yields (instead of returning the list) the files to print (as a list) for every task. Note that I re-used the cursor, since there is no need to create a new one every time.

I also defined a partial function using functools, which makes creating a file_name following the format task_id/file_name a bit easier. I also used str.format to avoid potentially costly string additions (I don't know how large your task_ids are.

In addition I used tuple unpacking to give row[0], row[1] and row[2] meaningful names.

And finally, you should use with..as to automatically close a file after you are finished with it.

def to_print(db):
    sub_query = "SELECT elements.id, elements.count, elements.data FROM elements WHERE task = '%s' ORDER BY count ASC"

    cursor = db.cursor()
    cursor.execute(
        "SELECT task.id, task.header, task.footer FROM task WHERE task.printDate IS NULL ORDER BY task.regDate ASC LIMIT 5")
    for task_id, header, footer in cursor:
        path_join = functools.partial(os.path.join, task_id)
        print_list = []
        if not os.path.exists(task_id):
            os.makedirs(task_id)

        header_file_name = "{}_header.txt".format(path_join(task_id))
        with open(header_file_name, "w") as header_file:
            header_file.write(header)
        print_list.append(header_file_name)

        cursor2 = db.cursor()
        cursor2.execute(sub_query, (task_id,))
        for file_name, elements_count, data in cursor2:
            pdf_file_name = "{}.pdf".format(path_join(file_name))
            with open(pdf_file_name, "wb") as pdf_file:
                pdf_file.write(data)
            print_list.extend([pdf_file_name for _ in range(elements_count)])
        cursor2.close()

        footer_file_name = "{}_footer.txt".format(path_join(task_id))
        with open(footer_file_name, "w") as footer_file:
            footer_file.write(footer)
        print_list.append(footer_file_name)

        yield task_id, print_list
    cursor.close()

The second function marks a task as finished:

def mark_finished(db, task_id):
    cursor = db.cursor()
    cursor.execute(
        "UPDATE task SET printDate = NOW() WHERE id = '%s'", (task_id,))
    cursor.execute(
        "UPDATE elements SET data = null WHERE task = '%s'", (task_id,))
    cursor.close()
    shutil.rmtree(task_id)

It is basically the same as before, only now I re-use the cursor and use the functionality of cursor.execute that you can give it data in the sprintf-like format "name: %s" % ("Graipher",).

Finally, I would put the code calling all of this in a if __name__ == "__main__" guard to allow importing you module from another script.

Here is also the usage of the generator returned by to_print, we just iterate over the tasks. The actual printing is inlined here, you could also stick it into a function.

if __name__ == "__main__":
    db = connect(**CONF)
    for task_id, print_list in to_print(db):
        cups.Connection().printFiles(PRINTER, print_list, "expedition-" + task_id, {})
        mark_finished(db, task_id)
    db.commit()
    db.close()

    print("done")

This can be broken down into even smaller tasks (the writing of the files is still some-what redundant for example), which I did in my final code:

import os
import shutil
import MySQLdb
import cups
import functools
from contextlib import closing

PRINTER = "STARTTSP100"

# Hard-coded here, but might as well be retrieved from a config file
CONF = {'host': "nope",
        'user': "nope",
        'passwd': "nope",
        'db': "printer"}

def connect(**conf):
    """# Connect to the Printer DB"""
    return MySQLdb.connect(**conf)

def create_file(task_id, extension, data):
    file_name = "{}{}".format(os.path.join(task_id, task_id), extension)
    with open(file_name, "w") as write_file:
        write_file.write(data)
    return file_name

def create_files(db, task_id, query):
    cursor = db.cursor()
    cursor.execute(query, task_id)
    for file_name, elements_count, data in cursor:
        pdf_file_name = "{}.pdf".format(os.path.join(task_id, file_name))
        with open(pdf_file_name, "wb") as pdf_file:
            pdf_file.write(data)
        yield [pdf_file_name for _ in range(elements_count)]
    cursor.close()

def to_print(db):
    with db as cursor:
        cursor.execute(
            "SELECT task.id, task.header, task.footer FROM task WHERE task.printDate IS NULL ORDER BY task.regDate ASC LIMIT 5")

        sub_query = "SELECT elements.id, elements.count, elements.data FROM elements WHERE task = '%s' ORDER BY count ASC"

        for task_id, header, footer in cursor:
            if not os.path.exists(task_id):
                os.makedirs(task_id)

            print_list = [create_file(task_id, "_header.txt", header)]

            for files in create_files(db, task_id, sub_query):
                print_list.extend(files)

            print_list.append(create_file(task_id, "_footer.txt", footer))

            yield task_id, print_list

def mark_finished(db, task_id):
    with db as cursor:
        cursor.execute(
            "UPDATE task SET printDate = NOW() WHERE id = '%s'", task_id)
        cursor.execute(
            "UPDATE elements SET data = null WHERE task = '%s'", task_id)
    shutil.rmtree(task_id)

def print_files(print_list, name, printer=PRINTER)
    cups.Connection().printFiles(printer, print_list, name, {})

if __name__ == "__main__":
    with closing(connect(**CONF)) as db:
        for task_id, print_list in to_print(db):
            print_files(print_list, "expedition-" + task_id)
            mark_finished(db, task_id)
    print("done")

Note the addition of contextlib.closing to ensure that the db connection is closed even if an exception is raised somewhere in-between and using with db as cursor to make sure the cursor is also closed and comitted.


A program which adds 2 integers in the range of 0 to 10^100

Here are some things that may help you improve your code.

Break up the code into smaller functions

Right now, everything is done in main. Rather than having everything in one long function, it would be easier to read and maintain if each discrete step were its own function.  Specifically you could divide into input, output and calculation.

Add error checking

If we enter "alpha" and "edward" as integers, the result is 6453621.  That doesn't really make much sense.  Better might be to screen the inputs to make sure they're really decimal digits.

Think of the user

The user runs the program and sees... nothing.  It might be nice to show a user prompt.  Even better, in my view, would be to allow the user to enter the numbers as command line parameters.

Don't leak memory

There is a malloc but no matching free which means that this leaks memory.  The operating system will reclaim that memory when the program ends, but it's best to get into good habits now before you tackle more complex programs.

Eliminate "magic numbers"

This code is littered with "magic numbers," that is, unnamed constants such as 10, 99, 100, etc.  Generally it's better to avoid that and give such constants meaningful names.  That way, if anything ever needs to be changed, you won't have to go hunting through the code for all instances of "99" and then trying to determine if this particular 99 is related to what you're trying to change or not.

Avoid scanf if you can

There are so many well known problems with scanf that you're usually better off avoiding it.  The usual approach is to read in user input into a string using something like fgets to allow specifying the input buffer size (and therefore avoiding buffer overrun vulnerabilities).


Dynamically allocated C strings in C++, concatenation, pointers, etc

There is no need for manual dynamic memory allocation.

Don't use this:

using namespace std;

It causes lots of problems in anything but a small application. So get into the habbit of not using it. If you muse be lazy specifically import the things you need. Notice in the code below I always use the prefix std:: five letters is not a big overhead for being exact.

using std::cout;
using std::ifstream;

For a good discussion see https://stackoverflow.com/q/1452721/14065 my favorite answer to this question is https://stackoverflow.com/a/1453605/14065

Don't write comments where you explain what the code is doing. The code is already verbose enough to explain what. If you are going to comment explain "WHY" you are doing this. Over commenting is a real problem and you should use comments judiciously and explain why. https://softwareengineering.stackexchange.com/a/13/12917

    //Program needs at least one extra argument
    //If less, print 'usage'

If your condition exits the program. Return an error code immediately. This makes the alignment and reading of the rest of your code easier:

    if (argc < 2)
        cout<<"usage: "<< argv[0] <<" <filename>\n";

    else
    {

Easier to write as:

    if (argc < 2)
    {
        cout<<"usage: "<< argv[0] <<" <filename>\n";
        return 1;
    }
    <rest of code>

Same comment as above.

        if (!fin.is_open())
            cout<<"Could not open file\n";

The best way to comment this. Is to put this code in a function with an appropriate name. Then don't write the comments (the code is self explanatory). You may write a comment about "why" you are using 16 as this will help a maintainer to modify dependant code.

            //Calculate size of file
            fin.seekg(0,ios::end);
            unsigned long long size = fin.tellg();
            //Find out how many left over characters
            //if using blocks of 16 characters
            int lastset=size%16;
            //Change size to number of blocks
            size /= 16;

Easier to read as:

            int size = getNumberOf16ByteBlocksFromStream(fin);

It is very rare that you need to use new/delete. It is even rarer that you would use delete as any object created with new should be put in an object that manages its lifespan correctly. If you don't do this writing exception safe code is exceedingly hard.

In this case you can achieve the same affect by using a std::vector

            //File name must be <original filename>.scramble
            //Allocate space
            char* name = new char[sizeof(argv[1])+8];

Use std::vector for simple buffers. Its exception safe.

            std::vector<char>  name(strlen(argv[1]) + 8);

            // To get the address of the first byte use &name[0];

Note that sizeof() gives you the number of bytes in the variable. This does not give you the length of the string. the size of the variable in this case is the size of the pointer that is pointing at the string (so 4 or 8 depending on the system). Use strlen() to get the size of a string.

Also the +8 is wrong. As .scramble is 9 characters and you need to add a byte for the terminating \0 character. So in reality you should use std::string to build the filename. Again the comments are worse the useless (not because you wrote bad comments, but because the comments can go out of sync with the code. Then a maintainer will wonder why the code does not match the comments. Also this code is so trivial that you should be able to see what it is trying to do).

            //Concatenate <original filename>
            strcat_s(name,sizeof(argv[1]),argv[1]);
            //Concatenate ".scramble"
            strcat_s(name,sizeof(argv[1])+8,".scramble");

            // PS you got the usage all long.
            // I am very surprised if this actually runs correctly.
            // Normal operation.
            //   1) string-copy the first part
            //   2) string-cat all subsequent parts.
            //   3) The size (Second field) in <X>_s() functions is the
            //           TOTAL SIZE OF THE BUFFER
            //      not how much you want to copy. This should ALWAYS
            //      match the value you used in allocation.

Easier to write as:

            std::string filename = argv[1];
            filename += ".scramble"

That's is a very small buffer:

            char memblock[16];

You should probably have re-set the stream up where you were messing around with it finding the size.

            fin.seekg(0,ios::beg);

No need to manually close files. The destructor will do that. https://codereview.stackexchange.com/a/544/507

        fin.close();
        fout.close();

This delete is not exception safe.
Not a problem in this code. But in general you should try and make them exception safe so you don't leak. This means using RAII.

            delete[] name;


Advanced multi-conditonal split with an regex in Perl

Think the other way around: try to add a newline to all characters that need one. That way your regex is a bit simpler.

#!/usr/bin/perl -w

use strict;

my $content = do { local $/; <DATA> };

my $regex = qr{
  (?m)
    (^
     |
     :\s*
    )
    \{                  # open curly brace preceded by
                        # beginning of line
                        # OR
                        # colon

  |                     # OR
    [:;\}]              # any of these characters
    (?!\s*\n)           # NOT followed by newline
}x;

$content =~ s/($regex)/$1\n/g;
print $content, "\n";


Why did you create multiple tables for each category?

Surely it would be better to have 1 single table with something like:

id - int
category - enum(lawyer, insurance, etc.)
url - varchar

You might want to have a look at this answer from StackOverflow for a better strpos alternative to your requirements: https://stackoverflow.com/a/9220624/367708


Loading a file from a FAT32 filesystem in 16 bit real mode on x86 (Intel syntax assembly)

Style

  feedback on how clear my comments were and how easy the code was to follow

I'm not a big fan of line comments. I think they make the code a bit harder to follow. That's why I prefer tail comments along with a nice tabular layout of the labels, instructions, operands, and tail comments.
And of course don't write redundant comments like "Update the disk address packet sector count" when looking at the names of the identifiers already tells what is happening.

You've got some pushes and pops that are fairly distant apart. If you would number these (or tag them somehow), verifying what the stack holds and whether the stack was correctly balanced becomes a bit easier.

push    dx                              ; (1)
push    eax                             ; (2)

...

push    ax                              ; (3)
movzx   ax, byte [bpbSectorsPerCluster]
mov     [dapSectorCount], ax
pop     ax                              ; (3)

...

pop     eax                             ; -(2)-
push    eax                             ; -(2)-

...

pop     eax                             ; (2)

...

pop     dx                              ; (1)

Optimizations

mov word [dapDataOffset], dx

Most assemblers will not require you to write this word size tag because the use of the DX register made already clear that this has to be a word-sized operation. Not writing the redundant size tag makes your code a bit clearer.

mov     [dapDataOffset], dx

You did this several times.

xor ebx, ebx
mov bl, byte [bpbSectorsPerCluster]

The instruction set has the MOVZX instruction for this kind of situations. It will also reduce the code's footprint which is important in a bootloader that is limited to just 512 bytes. Notice that here the byte size tag is required.

movzx   ebx, byte [bpbSectorsPerCluster]

You did this several times.

push eax
xor ax, ax
mov al, byte [bpbSectorsPerCluster]
mov word [dapSectorCount], ax
pop eax

Pushing and popping the 32-bit register EAX from real address mode uses an operand size prefix. In this case the high word was never changed and so you can shave off 2 bytes if you only push/pop AX.

Better still, the program doesn't need you to preserve AX at this point. Again 2 bytes less.

movzx   ax, byte [bpbSectorsPerCluster]
mov     [dapSectorCount], ax

pop eax
and ax, 0x007F

; Multiply offset by 4 to get it in bytes
shl ax, 2

; Calculate the memory address of the cluster in the FAT
add ax, 0x7E00

; Read cluster value
mov bx, ax
mov eax, dword [bx]

Here's another opportunity to shave off a byte. Pop the value directly in the register that you'll use to retrieve the cluster number:

pop     ebx
and     bx, 0x7F
shl     bx, 2      ; Multiply offset by 4 to get it in bytes
add     bx, 0x7E00 ; Calculate the memory address of the cluster in the FAT
mov     eax, [bx]  ; Read cluster value

Exactly the same length but less instructions:

pop     ebx
and     ebx, 0x7F
mov     eax, [ebx*4 + 0x00007E00]  ; Read cluster value

; Update the disk address packet sector count
mov word [dapSectorCount], 1

; Update the disk address packet data offset to load the fat to 0x7E00
mov word [dapDataOffset], 0x7E00

The above instructions total 12 bytes. Because dapSectorCount and dapDataOffset follow each other in memory, you can combine the writes. The total then becomes 9 bytes.

; Update dapSectorCount=1 and dapDataOffset=0x7E00 together
mov     dword [dapSectorCount], 0x7E000001

This last optimization is of course killing readability in favor of code size. Your choice!

Beware

Your loadClusterChain routine uses some 32-bit registers. Given that this is 16-bit code the pusha and popa instructions will not preserve the high words. Maybe this can become a problem for the rest of your program!


Cleaning address line data sent to couriers API

First I'd think about names. Isn't Clean() enough for a method inside a class named StringCleaner? Do you need to repeat String?

Still in the prototype you should consider that you're iterating char but replacement is a string. It might be (or not) something to consider, it depends on your requirements.

More about char and string: you're iterating char (which is an UTF-16 code unit). UTF-16 is not fixed size then you're breaking for code points which are not encoded as a single code unit. More about Unicode: not every character is a single code point: you're breaking for surrogates. String might be (or not) normalized, do you need to take care about  it? One grapheme may be represented using two or more code points: think about, for example, ộ Vietnamese character. You may read How can I perform a Unicode aware character by character comparison?

For now let's assume that to iterate char is perfectly fine. If not then read an almost ready to use example in Split a string into chunks of the same length.

In .NET strings are immutable then reading String.Length in a loop is perfectly fine and compiler is capable to optimize it. You already know the maximum length of the string then you may preallocate the StringBuilder buffer to the maximum capacity:

var newString = new StringBuilder(stringToClean.Length);

foreach will help to make code shorter and easier to follow:

foreach (var c in stringToClean)
{
    if (ValidCharacters.Contains(c))
    {
        newString.Append(c);
    }
    else
    {
        newString.Append(replacement);
    }
}

If replacement can be a char it's even easier:

foreach (var c in stringToClean)
    newString.Append(ValidCharacters.Contains(c) ? c : replacement);

You may want to see a LINQ version (in case you find it more readable):

new String(stringToClean.Select(c => ValidCharacters.Contains(c) ? c : replacement));

Performance

In general you should be careful with parameters with a default value, in this case also because of performance. If you add an overload for the common case then you can write:

public static string CleanString(string stringToClean)
    =>  new String(stringToClean.Where(ValidCharacters.Contains(c)));

Searching each character inside the array is something terribly slow. First approach: HashSet<char>. Build the list and search inside the hashed collection. It's WAY faster.

We're talking about true/false values and all valid characters are inside the 7 bit ASCII range...if performance really matters you may use a BitVector. Unfortunately default implementation throws ArgumentOutOfRangeException if you ask for a value outside the assigned range; if you do not want to create a vector of 2^16/8 bytes then you may write your own implementation (see for example Count items existing in 2 Lists for a quick and dirty comparison).


Get radial distance between vector1 and vector2

There is a typo in the y components, both times only entity2 is used. I believe that is a copy-paste error.

Your distance is better known as the manhattan distance. I suggest naming the method after it to avoid surprises.

An other method of getting it uses the absolute value of the differences:

int get_manhattan_dist (coord entity1, coord entity2)
{
    return abs(entity1.X - entity2.X) + abs(entity1.Y - entity2.Y);
}

Of course if you have the manhattan distance you can easily provide the euclidean distance

double get_euclid_dist (coord entity1, coord entity2)
{
    double diffX    = entity1.X - entity2.X;
    double diffY    = entity1.Y - entity2.Y;

    return hypot(diffX, diffY);
}


Unmanaged byte array to managed structure

Expanding on my comment; below you'll find a very simple program that compares the method I suggested with your original example. The results on my machine show that the MemoryMarshal class is about 85x faster. You might want to experiment a bit and try running a similar test with a larger struct; maybe your method is faster for the specific problem that you're trying to solve.

Comparison Code:

using BenchmarkDotNet.Attributes;
using BenchmarkDotNet.Running;
using System;
using System.Runtime.InteropServices;

public readonly struct SomeStruct
{
    private readonly ulong m_x;
    private readonly ulong m_y;
    private readonly ulong m_z;

    public ulong X => m_x;
    public ulong Y => m_y;
    public ulong Z => m_z;

    public SomeStruct(ulong x, ulong y, ulong z) {
        m_x = x;
        m_y = y;
        m_z = z;
    }
}

public class Race
{
    private readonly byte[] m_data = new byte[] {
        0, 0, 0, 0, 0, 0, 0, 0,
        1, 0, 0, 0, 0, 0, 0, 0,
        1, 255, 0, 0, 0, 0, 0, 0,
    };

    [Benchmark(Baseline = true)]
    public SomeStruct A() => MemoryMarshal.Read<SomeStruct>(m_data);
    [Benchmark]
    public SomeStruct B() => Program.ReadUsingMarshalUnsafe<SomeStruct>(m_data, 0, m_data.Length);
}

class Program
{
    static void Main(string[] args) {
        var summary = BenchmarkRunner.Run<Race>();

        Console.ReadKey();
    }

    public static T ReadUsingMarshalUnsafe<T>(byte[] data, int startIndex, int length) {
        byte[] fixedData = new byte[length];
        unsafe {
            fixed (byte* pSource = data, pTarget = fixedData) {
                int index = 0;
                for (int i = startIndex; i < data.Length; i++) {
                    pTarget[index] = pSource[i];
                    index++;
                }
            }

            fixed (byte* p = &fixedData[0]) {
                return (T)Marshal.PtrToStructure(new IntPtr(p), typeof(T));
            }
        }
    }
}

BenchmarkDotNet Results:


Javascript recursive object is defined test

First of all, what you are doing is not recursive (self-calling). It's iterative (looping).

And here's a shorter version of it:

_objectIsDefined = function (obj, path) {

  if (!obj) return false;           // no object, return false
  if (obj && !path) return true;    // has object, no path, return true

  // I suggest var per variable for clarity
  var props = path.split(".");
  var currentObject = obj;

  for (var i = 0; i < props.length; ++i) {
    //store the next property, evaluate and break out if it's undefined
    currentObject = currentObject[props[i]];
    if (!currentObject) return false;
  }

  // If the loop did not break until the last path, then the path exists
  return true;
}


Constructing a tibble from another tibble (without for loops?)

I would use a matrix multiplication. It is both efficient and leads to much shorter code, as you can see:

constructed_tbl <- as.tibble(as.matrix(source_tbl) %*% table(col_conversion_tbl))


This is a well-written program.  It is clear and easy to follow, which are attributes of good software.  With that said, there are still some things that you can do to speed up the performance of the code and there are a few minor comments on formatting.  I'm hoping they will help you improve your code.

Avoid peculiar formatting

I have been programming in C for many, many years, but this line threw me for a moment:

while (b --> 1) { a *= original_a;}

It was the --> that was odd, but of course, it is actually equivalent to this:

while (b-- > 1) {
    a *= original_a;
}

Formatting for clarity, including keeping operators attached to their variables and avoiding one-liners helps others read and understand your code.

Avoid expensive mathematical operations where practical

To speed things along, we can replace this code

int digits_len(int n) {
    int length = 0;
    while(n) {
        n /= 10;
        length++;
    }
    return length;
}

With this:

int digits_len(int n) {
    if (n < 10) return 1;
    else if (n < 100) return 2;
    else if (n < 1000) return 3;
    else if (n < 10000) return 4;
    else if (n < 100000) return 5;
    else if (n < 1000000) return 6;
    else if (n < 10000000) return 7;
    else if (n < 100000000) return 8;
    return 9;
}

It's longer but it avoids the computationally costly division and avoid a loop.  Note, however, that it does not produce sensible results for negative numbers.  It seemed likely that this was acceptable for the increase in speed gained for this program.

Use a table lookup instead of a loop

The power routine, in context, has the property that neither a nor b are greater than 9. With that observation, it's possible to replace the routine with a simple table lookup.  Here's what I used:

const int powtable[10][10] = {
    { 0, 0, 0*0, 0*0*0, 0*0*0*0, 0*0*0*0*0, 0*0*0*0*0*0, 0*0*0*0*0*0*0, 0*0*0*0*0*0*0*0, 0*0*0*0*0*0*0*0*0 },
    { 0, 1, 1*1, 1*1*1, 1*1*1*1, 1*1*1*1*1, 1*1*1*1*1*1, 1*1*1*1*1*1*1, 1*1*1*1*1*1*1*1, 1*1*1*1*1*1*1*1*1 },
    { 0, 2, 2*2, 2*2*2, 2*2*2*2, 2*2*2*2*2, 2*2*2*2*2*2, 2*2*2*2*2*2*2, 2*2*2*2*2*2*2*2, 2*2*2*2*2*2*2*2*2 },
    { 0, 3, 3*3, 3*3*3, 3*3*3*3, 3*3*3*3*3, 3*3*3*3*3*3, 3*3*3*3*3*3*3, 3*3*3*3*3*3*3*3, 3*3*3*3*3*3*3*3*3 },
    { 0, 4, 4*4, 4*4*4, 4*4*4*4, 4*4*4*4*4, 4*4*4*4*4*4, 4*4*4*4*4*4*4, 4*4*4*4*4*4*4*4, 4*4*4*4*4*4*4*4*4 },
    { 0, 5, 5*5, 5*5*5, 5*5*5*5, 5*5*5*5*5, 5*5*5*5*5*5, 5*5*5*5*5*5*5, 5*5*5*5*5*5*5*5, 5*5*5*5*5*5*5*5*5 },
    { 0, 6, 6*6, 6*6*6, 6*6*6*6, 6*6*6*6*6, 6*6*6*6*6*6, 6*6*6*6*6*6*6, 6*6*6*6*6*6*6*6, 6*6*6*6*6*6*6*6*6 },
    { 0, 7, 7*7, 7*7*7, 7*7*7*7, 7*7*7*7*7, 7*7*7*7*7*7, 7*7*7*7*7*7*7, 7*7*7*7*7*7*7*7, 7*7*7*7*7*7*7*7*7 },
    { 0, 8, 8*8, 8*8*8, 8*8*8*8, 8*8*8*8*8, 8*8*8*8*8*8, 8*8*8*8*8*8*8, 8*8*8*8*8*8*8*8, 8*8*8*8*8*8*8*8*8 },
    { 0, 9, 9*9, 9*9*9, 9*9*9*9, 9*9*9*9*9, 9*9*9*9*9*9, 9*9*9*9*9*9*9, 9*9*9*9*9*9*9*9, 9*9*9*9*9*9*9*9*9 }
};
inline int power(int a, int b) {
    return powtable[a][b];
}

The multiplications in the table are all done at compile-time rather than at runtime, so they cost essentially nothing.  (I could, of course, have simply placed the appropriate numbers into the table, but I'm very lazy and prefer to make the computer do all the work!)

Avoid unused arguments

The main routine has the usual arguments of argc and argv but argc is never used.  If you compile with all warnings turned on (which I would recommend), the compiler will correctly complain about the unused variable.  I decided to use it and also to give a hint to the user as to how to use the program:

if (argc < 2) {
    puts("Usage: armstrong maxint\n");
    return 0;
}

Keep using assert

It's refreshing to see code from an avowed beginner at C using assert rationally and correctly.  Bonus points for you!  Also, although I didn't, you might wish to use asserts to assure that the parameters passed to power are indeed both less than 10.

Results

On my machine, the original code, when compiled with -O2 using gcc version 4.9.2 on a 64-bit Linux box, the code runs in 8.1 seconds.  With the changes mentioned above, it runs in 2.4 seconds, or almost 4x faster.


You could replace your get_str_from_file function with the standard read_to_string function:
For instance like so:
use std::fs;

if fs::read_to_string(STATUS).unwrap().trim() == CHARGING_STR) {
    return; //return should be equivalent to std::process::exit(0)
}

This is your implementation:
fn get_str_from_file(file_path: &str) -> String {
    let mut file = File::open(file_path)
        .expect("file not found");
    let mut ret = String::new();
    file.read_to_string(&mut ret)
        .expect("failed to read file");

    ret
}

This is the implementation of std::fs::read_to_string
pub fn read_to_string<P: AsRef<Path>>(path: P) -> io::Result<String> {
    let mut file = File::open(path)?;
    let mut string = String::with_capacity(initial_buffer_size(&file));
    file.read_to_string(&mut string)?;
    Ok(string)
}

Almost identical, except the std lib version is more generic and leaves error handling to the caller. It also uses more efficient memory allocation.
New Type Idiom
The following is not necessarily better, but it is certainly a valid alternative approach.
Instead of relying on using an f32 you could use a wrapper struct around it:
#[derive(Debug, Default, Clone, Copy, PartialEq, PartialOrd)] //not necessary but nice to have
struct ChargeLevel(f32);

This is called New Type Idiom. You could further go ahead and put most of the logic surrounding the charge level into special functions in the ChargeLevel's impl block. Some suggestions:
impl ChargeLevel {
    const WARNING_LEVEL: f32 = 15.0;
    const CRITICAL_LEVEL: f32 = 5.0;

    fn new(now: f32, full: f32) -> Self {
        ChargeLevel((now / full) * 100.0)
    }

    fn is_warning(&self) -> bool {
        self.0 < Self::WARNING_LEVEL
    }

    fn is_critical(&self) -> bool {
        self.0 < Self::CRITICAL_LEVEL
    }
}

You could also combine this struct with the external library stuff:
impl From<ChargeLevel> for NotificationUrgency {
    fn from(level: ChargeLevel) -> Self {
        if level.is_critical() {
            NotificationUrgency::Critical
        } else {
            NotificationUrgency::Normal
        }
    }
}

This would allow you to replace
if charge_level < CHARGE_WARN {
    Notification::new()
        .summary("Battery level low!")
        .body(&format!("Battery level: {0:.1$}%", charge_level, 2))
        .icon("dialog-information")
        .urgency(
            if charge_level < CHARGE_CRIT {
                NotificationUrgency::Critical
            } else {
                NotificationUrgency::Normal
            }
        )
        .timeout(NOTIFICATION_TIMEOUT)
        .show().unwrap();
}

with
if charge_level.is_warning() {
    Notification::new()
        .summary("Battery level low!")
        .body(&format!("Battery level: {0:.1$}%", charge_level.0, 2))
        .icon("dialog-information")
        .urgency(NotificationUrgency::from(charge_level))
        .timeout(NOTIFICATION_TIMEOUT)
        .show()
        .unwrap();
}

A little much for such a small application perhaps, but might give you an example how to write nice abstractions in Rust that don't cost any runtime overhead.
Implementing std::fmt::Display would also make sense for the string formatting, but you get the point.


Communicating with other fragments or to activity

Android application design best practices suggest that fragments should be modular and independent from each other, so that you may able to arrange them differently - not just on screen, but also changing relationships among them - when you are targeting devices with widely different screen sizes, e.g. smartphones and tablets. Those very same best practices suggest that you don't see nor use the whole activity interface in a fragment, but only a subset that you have defined through a proper custom interface, which typically contains callback methods that are invoked in cases such as yours, when an action taken in a fragment must trigger the creation and display of another fragment.

However, note that there is an interesting API that has been thought exactly for the purpose of starting a fragment from another fragment, and possibly returning a result to the caller fragment, much like startActivity and onActivityResult do for activities. I do believe that, while modularity and independence are indeed best design practices, there may be cases when two fragments are strictly intertwined, so much that that dependency is preserved even on different devices; and the cited API is there to help.


Converting a numerical string to the equivalent multipled by 100

It would be much easier with BigDecimals:

String input = "00007.880000";
BigDecimal hundred = BigDecimal.valueOf(100);
BigDecimal result = new BigDecimal(input).multiply(hundred).stripTrailingZeros();

System.out.println(result.toString()); // prints "788"

It works with big numbers well:

String input = "0000123456789123456789.123456789123456789123456789123456789880000";
BigDecimal hundred = BigDecimal.valueOf(100);
BigDecimal result = new BigDecimal(input).multiply(hundred).stripTrailingZeros();

// prints "12345678912345678912.345678912345678912345678912345678988"
System.out.println(result.toString());

Two readings:

Effective Java, 2nd Edition, Item 48: Avoid float and double if exact answers are required
Why not use Double or Float to represent currency?

The original code returns 788.0000 for 00007.880000 which I guess does not fulfill the specification.
Java developers usually start method names with lowercase letters.

  Methods should be verbs, in mixed case with the first letter lowercase, with the first letter of each internal word capitalized.

Source: Code Conventions for the Java TM Programming Language, 9 - Naming Conventions


Classes representing items in an RPG game

public interface SpecialObject
{
    int GetIntParameter
    {
        get;
    }
}

public interface ElementalsObject
{
    int[] GetElementalsParameters
    {
        get;
    }
}

What does "object" mean? If it refers to a domain concept, then it should have a more specific name (any "thing" can be an "object"); if it's a technical term, then it should be removed (all classes are objects, no need to say so explicitly).
GetIntParameter and GetElementalsParameters are pretty poor names. What does the parameter represent? Name the property after that, not after how it may be supplied to the implementing class.

public class Item
{
    private string _name;
    private int _cost;

    public string name
    {
        get { return _name; }
    }

    public int cost
    {
        get { return _cost; }
    }

    public Item(string name, int cost)
    {
        _name = name;
        _cost = cost;
    }
}

This is ok although it doesn't really do much (or anything), just a class holding two properties. You could make the code shorter by writing it like this instead. And remember public properties should be PascalCase.

public class Item
{
    public string Name { get; private set; } // private set only required if not using C# 6.0
    public int Cost { get; private set; }

    public Item(string name, int cost)
    {
        Name = name;
        Cost = cost;
    }
}

So now we see a class implementing your interfaces.

public class Weapon : Item, SpecialObject, ElementalsObject
{
    private int dmgs;
    private int[] elementalsDmgs;

    public int GetIntParameter
    {
        get { return dmgs; }
    }

    public int[] GetElementalsParameters
    {
        get { return elementalsDmgs; }
    }

    public Weapon(string name, int cost, int dmgs, int[] elementalsDmgs = null) : base(name, cost)
    {
        if (elementalsDmgs != null)
            this.elementalsDmgs = elementalsDmgs;
        else
            this.elementalsDmgs = new int[] { 0, 0, 0, 0 };

        this.dmgs = dmgs;
    }
}

First of all the constructor can be shortened by assigning elementalsDmgs like so: this.elementalsDmgs = elementalsDmgs ?? new int[] { 0, 0, 0, 0 };.

Now you see how the property names on your interfaces are unhelpful. What does GetIntParameter mean or return on a Weapon, Armor, or Food object, aside from "an int"? Who knows. What is the meaning of the values that GetElementalsParameters returns on Weapon and Armor? Well I know it returns something to do with "elementals" (whatever that is - maybe that word makes sense in your domain), but who knows the meaning of the parameters?

The much bigger problem is that GetIntParameter actually has no meaning; your classes have int parameters, so you created an interface to represent it so you can get the value from all classes implementing that interface. But on Food and Armor it contains a number of "points", and on Weapon it refers to "damages". (Assuming I'm interpreting "dmgs" correctly - which is another issue, don't skip the vowels! "dmgs" only makes sense to you, everyone else has to guess what it might mean.) The fact that they're always int does not make them in any way related, and is not a shared behaviour or functionality.

class Equipment
{
    public static void Test()
    {
        ...
        string[] el = new string[4] { "Water", "Fire", "Earth", "Wind" };
        ...
        Console.WriteLine(" Elementals parameters: ");
        ...
        Console.WriteLine("  " + el[e] + ": " + eo.GetElementalsParameters[e] + ", ");

Ah, so the elementals parameters are "Water", "Fire", "Earth", "Wind". So the ElementalsObject should have properties with those names, each of which can be assigned an int, rather than a property with an int array. I mean, who can guarantee that the values of the int array were even supplied in the correct order?

if(i is SpecialObject)
      SpecialObject so = (SpecialObject)i;

if(i is ElementalsObject)
      ElementalsObject eo = i as ElementalsObject;

It's not clear why you do this in two different ways just a few lines apart, but neither is the best way to do it as both involve casting twice. What you should do is this, as it only casts once:

 var o = i as SpecialObject;
 if (o != null)
     // cast is valid.

I don't really want to take the time to rewrite the code myself as this doesn't feel like "real" code, more like an experiment. But some suggestions are:

Rename SpecialObject to something clearer; rename GetIntParameter to something to do with points.
Rename the ElementalsObject interface to something clearer; remove current property and replace with properties of actual names (Fire, Water, etc).
Consider whether the above should even be interfaces. To me this calls for a base class for these different types of "items", so you don't have to implement the interface properties on each type of item.
Use a factory for item creation. Creating an item like so new Armor("Storm Cuirass", 1000, 120, new int[4] {0, 0, 0, 60}) is no good as it's too time consuming and error prone.
You shouldn't have to say if (i is SpecialObject) and if (i is ElementalsObject). Use polymorphism to call a method on the objects which returns the correct result per object type. (In this case, you could simply override ToString() in the classes, but again this requires a proper base class structure.)


Python: improve in elegant way (code saving) a function in order to avoid several statements

A possible dictionary based solution:

import os.path

import shapefile
from liblas import file as lasfile

# map fields representing characters to field name and attribute
FIELDS = {
    'i': ('Intensity', 'intensity'),
    'r': ('Return', 'return_number'),
    'n': ('NumberRet', 'number_of_returns'),
    's': ('ScanDir', 'scan_direction'),
    'e': ('FlightEdge', 'flightline_edge'),
    'c': ('Class', 'classification'),
    'a': ('ScanAngle', 'scan_angle'),
}

# assuming that field order is important define it explicitly, otherwise it
# could simply be DEFAULT_PARSE = FIELDS.keys()
DEFAULT_PARSE = 'irnseca'

def enhanced_LAS2SHP(inFile, outFile=None, parse=DEFAULT_PARSE):
    w = shapefile.Writer(shapefile.POINT)
    # add 'Z' field not present in fields map
    w.field('Z', 'C', '10')
    # initialise list of desired record attributes
    attributes = []
    # add mapped 'shapefile' fields and desired attributes to list
    for f in parse:
        field, attr = FIELDS[f]
        w.field(field_name, 'C', '10')
        attributes.append(attr)
    # create record from attributes in list of desired attributes
    for p in lasfile.File(inFile, None, 'r'):
        w.point(p.x, p.y)
        record_args = [float(p.z)]
        record_args += (float(getattr(p, attr)) for attr in attributes)
        w.record(*record_args)
    # if not output filename was supplied derive one from input filename
    if outFile is None:
        inFile_path, inFile_name_ext = os.path.split(os.path.abspath(inFile))
        inFile_name, _ = os.path.splitext(inFile_name_ext)
        outFile = os.path.join(inFile_path, '{}.shp'.format(inFile_name))
    # save records to 'shapefile'
    w.save(outFile)


Non-recursive approach to the Rod-Cutting

The algorithm itself seems to have no problems. It's Dynamic programming and I wouldn't call the int[] maxPrices cache. Cache is something used for speed only, you can clear it anytime and everything must still work.

For example, a straightforward recursive solution to this problem would be damn slow because of recomputing values again and again. It could be made much faster using a cache.

 public static int[] prices = new int[]{1,5,8,9,10,17,17,20};

This way you lose any chance to make it more flexible. You class has two functions: It's both the computing core and the main class. That's fine for a small class, but even then you should separate the tasks.

For the main class, something like

private static final int[] PRICES = new int[] {1, 5, 8, 9, 10, 17, 17, 20};

Here, static final is the way how constants get declared in Java. PRICES is uppercase as a constant should be. And there's a space after each comma.

For the core, pass it explicitly to the bestPrice method. In more complicated cases, you could use an instance field for this.

max_price should be maxPrice in Java. No underscores except in constants.


What jumps me most about this code is that all you do is in 2 functions.

consider moving your "parsing" operations to separate functions, one for validating the format required for parsing and one for the actual parsing:

function isValidQuarterInput(datestring){
   return datestring.split(" ").length == 2;
}

function parseQuarterInputToMonth(datestring){
    var mySplit = datestring.split(" ");
    //move your Q1,Q2,... mapping here
}

then in check_date_period() you can just call the following

if(isValidQuarterInput(from)){monthFrom = parseQuarterInputToMonth(from);}
// this is the alternative ternary operator
monthTo = isValidQuarterInput(to) ? parseQuarterInputToMonth(to) : monthTo;

your var result = false is unnecessary, as you never use it elsewhere, you can just do the following for return:

return dateOne < dateTwo;

I personally would set a boolean wasParsed to be set to true on correct parsing of one input to jump to the new Date() part. This can potentially save execution time, but that's minor. You would have to move the parsing in the following order though:

var wasParsed = false;
if(from.length==4){
  yearFrom = from; monthFrom = 1; dayFrom = 1;
  wasParsed = true;
}

if(!wasParsed){
   if(isValidQuarterInput(from)){
      wasParsed = true;
      monthFrom = parseQuarterInputToMonth(from);
      yearFrom = from.split(" ")[0];
      dayFrom = 1;
   }
}

if(!wasParsed){
  //here is the full date parsing
}
var dateOne = new Date(yearFrom, monthFrom, dayFrom);
wasParsed = false;
//repeat with to


Things that would favor var self = this;

bind isn't supported in IE8 and Safari5. If you aim to build a library or code that supports legacy browsers, then var self = this would be more cross-browser friendly.
Sometimes, callbacks are bound to a certain context when executed like in the case of jQuery's $.each where this is the current item. If you don't want to lose this context but still want to have the parent context, then it's another reason to use var self = this;.
Calling bind creates a brand new function with a forced context. This function creation step might be a performance issue in the large scale especially if you call bind inside a loop.

Reasons that would favor bind

Performance wouldn't be an issue if you just created a bound function once and reused it in several places. Like you can create a bound function and call that bound function in a loop (instead of calling bind in a loop).
bind also alleviates you from doing call(customContext) or apply(customContext) explicitly all the time.
Scope lookup (looking for variables if not found in the current scope) can pose a performance problem especially in very deep scopes. You've probably heard of the tip "passing to local is better".

I'm not saying bind is bad (I use them extensively myself). It just needs to be used in the right situations. Also, the performance issues for both might be so negligible, they can only be seen if you aim to do stuff in less than 16ms (do stuff in 60fps).


Simple medical collection/database about patients visits

File-systems normally make poor databases because you lose the concept of 'atomicity'... let's take a worst-case example:

public void toXml() {
    try {
        File file = new File("jcrf.xml");
        JAXBContext jaxbContext = JAXBContext.newInstance(Jcrf.class);
        Marshaller jaxbMarshaller = jaxbContext.createMarshaller(); // output
        jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        jaxbMarshaller.marshal(this, file);
        jaxbMarshaller.marshal(this, System.out);
    } catch (JAXBException e) {
        e.printStackTrace();
    }
}

What happens if there is an IOException part-way through the jaxbMarshaller.marshal(this, file); ? You end up overwriting the old copy, and losing the new one. Your data is gone.

A more traditional way to prevent this sort of loss is to write the output to a new file, and then do an atomic 'move' operation:

public void toXml() {
    try {
        File file = new File("jcrf.xml.tmp");
        JAXBContext jaxbContext = JAXBContext.newInstance(Jcrf.class);
        Marshaller jaxbMarshaller = jaxbContext.createMarshaller(); // output
        jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        jaxbMarshaller.marshal(this, file);
        jaxbMarshaller.marshal(this, System.out);

        // move tmp file to complete output file.
        Path tmp = file.toPath();
        Path target = Paths.get("jcrf.xml");
        Files.move(tmp, target, CopyOption.REPLACE_EXISTING, CopyOption.ATOMIC_MOVE);

    } catch (JAXBException e) {
        e.printStackTrace();
    }
}

Note the use of the atomic Files.move(...)` command.

One day, when your file-system is full, and you run out of space... you will appreciate that change.


Geocoding and Reverse in python using Geopy

Duplicated code

You should try to follow the Don't Repeat Yourself principle.
In your case, most of the logic is repeated in 2 branches.

You could write :

if pattern.match(arg):
    loc=geolocator.reverse(arg)
else:
    loc=geolocator.geocode(arg)
if loc is not None:
    print(loc.address)
    print(loc.latitude, loc.longitude)
else:
    print "the location doesnt exist"

Alternatively, this could be written using conditional expressions :

loc = geolocator.reverse(arg) if pattern.match(arg) else geolocator.geocode(arg)


Generating Pythagorean triples below an upper bound

It's a good thing that there is a method to calculate the pythagorean triple up to a number, and then a second method to print the results.

About pythagoreanTriple

You can simply the pythagoreanTriple method in several aspects. First of all is performance. The current code does:

for (i = 3; i < n; i++)
    for (j = n; j > i; j--)
        for (k = n; k > j; k--)
            if (i * i + j * j == k * k) {

to check for triplets. This tries every possible combinations of i, j and k and checks if they form a triplet. However, you don't need to loop for every possible k: once you know i and j, you can deduce the only possible k for which (i,j,k) forms a triplet; it is exactly \$k = \sqrt{i^2+j^2}\$, when this result in an integer. Take care because such a calculation can lead to rounding issues, and there are good way to check if a number square root is an integer. I won't comment more on the performance, because if this is really a concern, there are other faster approaches than trying every possible combinations (see for example the Tree of primitive Pythagorean triples).

Second aspect, is the usage of built-in methods.

ArrayList<Integer> tempArray = new ArrayList<>();
tempArray.add(i);
tempArray.add(j);
tempArray.add(k);
pytTri.add(tempArray);

can be written more simply using the built-in Arrays.asList. You can directly have:

pytTri.add(Arrays.asList(i, j, k));

without creating any new ArrayList yourself.

Finally, even if it isn't strictly necessary, consider adding curly braces everywhere.

for (i = 3; i < n; i++)
    for (j = n; j > i; j--)

can quickly lead to problems if you want to add another statement in there, like storing the result of i * i as recommented by coderodde in their answer.

About readFromKeyboard

Currently, the code to retrieve the user input does not validate that only integers can be input. If you try to input a String like "a", an exception will be thrown; consider re-prompting for an input if that happens.

Also, this method creates a new Scanner. In the current code, it is called only once, but if later you want to read a second input from the user, it would be better to create it only once and reuse it. As such, consider creating the Scanner and passing it as parameter of readFromKeyboard.

This also has a direct impact: readFromKeyboard would not read from the keyboard anymore, it would read from a given Scanner, which makes it more reusable, since you could pass any instance of Scanner you want (for example, one reading from a file). And the method should renamed to something like readUpperBound, which makes it clear that its concern is not to read from the keyboard (which is the current technical implementation), but to fetch the upper bound to use in order to create the triplets (which is what it's really supposed to do).


I'd instead use the std::isalpha() to check for the alphabets, and for the rest; use isalnum() plus an or condition for the _ character.

Another check, I'd put is whether the input's length is indeed \$ \gt 0 \$. The code then becomes:

// Check correctness, return corresponding bool.
bool ok_tret(const string& nom) {
    if (nom.length() < 1) {
        // handle null strings
        return false;
    }
    if (not (bool) std::isalpha(nom[0])) {
        cout << err4 << endl;
        return false;
    }
    for (unsigned int i = 1; i < nom.length(); ++i) {
        if (not ((bool) std::isalnum(nom[i]) or nom[i] == '_')) {
                cout << err4 << endl;
                return false;
        }
    }
    return true;
}


Ordering data.frames elegantly by factor

I think the task you are attempting to accomplish (obtain indices to reorder a data frame by several factors, one after another) is already handled well by the built-in order function. Let's consider your sample data:

order(mock_Data$Clinical)
# [1] 1 3 5 7 8 2 4 6 9

As you can see, order is returning row numbers instead of row names; this yields an identical reordered data frame:

identical(mock_Data[reorder_by_factor(mock_Data, mock_Data$Clinical),],
          mock_Data[order(mock_Data$Clinical),])
# [1] TRUE

There are several other advantages of using the built-in order function:

It already smoothly handles reordering by multiple factors, one after another
It can reorder by a mix of factor and numeric variables
It is already implemented and distributed with base R, so you don't need to develop and test your own version of this function

Another advantage is that the built-in order function is more efficient than your implementation. Let's see on a resampled version of your dataset with 1 million rows:

set.seed(144)
big.dat <- mock_Data[sample(seq_len(nrow(mock_Data)), 1e6, replace=T),]
library(microbenchmark)
microbenchmark(reorder_by_factor(big.dat, big.dat$Clinical), order(big.dat$Clinical))
# Unit: milliseconds
#                                          expr      min       lq     mean   median        uq       max neval
#  reorder_by_factor(big.dat, big.dat$Clinical) 562.2527 744.4318 939.0831 898.6288 1054.0008 1678.1246   100
#                       order(big.dat$Clinical) 149.4750 153.2963 199.8178 160.5452  225.9082  459.5558   100

The built-in function runs about 5x faster.


Another downfall of your this.item() function is that if item isn't in this.obj, this._getLibraryObj() will be called every time.

Try

this.item = function(item) {
    if (this.obj) {
        return this.obj[item] || null;
    } else {
        this.obj = this._getLibraryObj();
        return this.item(item);
    }
};

Or if you want it even more minimal:

this.item = function(item) {
    if (this.obj)
        return this.obj[item] || null;

    this.obj = this._getLibraryObj();
    return this.item(item);
};

If you switch up the statements a little bit you get the most readable IMHO:

this.item = function(item) {
    if (!this.obj)
        this.obj = this._getLibraryObj();

    return this.obj[item] || null;
};

One final way to do it would be to do:

this.item = function(item) {
    this.obj = this.obj || this._getLibraryObj();

    return this.obj[item] || null;
};

EDIT:

In light of your comment about needing to re-call getLibraryObj

this.item = function(item) {
    if (!(this.obj && item in this.obj))
        this.obj = this._getLibraryObj();

    return this.obj[item] || null;
};

or:

this.item = function(item) {
    this.obj = this.obj && item in this.obj ? this.obj : this._getLibraryObj();

    return this.obj[item] || null;
};

or a one-liner:

this.item = function(item) {
    return (this.obj = (this.obj && item in this.obj ? this.obj : this._getLibraryObj()))[item] || null;
};