Generating unique alphanumeric ID's of a fixed length

A large part of your id (8 of 13 characters) is actually static.

That leaves you with 260.000 variations (10 (0-9) x 26 (A-Z) x 1000 (0-999)) of ids to assign to your users. After that, you run out of ids. Will that be enough?

In your current code there is not much you can do besides checking wether the id you generated is already in the generatedIDs list and if it is, try again.

Is there a purpose behind generating the ids randomly? Because if they are only used to identify users, it would make more sense to increment them one number at a time and just remember the last id you gave to a user.

User 1:      (0)(0)(A)(000)98XX001
User 2:      (0)(0)(A)(001)98XX001
User 5000:   (0)(0)(E)(999)98XX001
User 80543:  (0)(3)(B)(542)98XX001
User 260000: (0)(9)(Z)(999)98XX001

Here would be the code for that. You hand the function the id you would like to start from and how many ids from that start-id it should generate.

import java.util.ArrayList;
import java.util.List;

public class MainClass
{
  public static void main(String[] args)
  {
    TestClass gen = new TestClass();
    gen.generateIDs("04X99798XX001", 10);
  }
}

public class TestClass
{
  public static Integer letterToInt(char letter) {
    return letter - 'A' + 1;
  }

  public static char intToLetter(int number) {
    return (char) (90 - (26 - number));
  }

  private static List<String> generatedIDs = new ArrayList<String>();

  public static void generateIDs(String lastID, Integer numOfUsers) {
    String first = lastID.substring(1, 2);
    char second = lastID.substring(2, 3).charAt(0);
    String third = lastID.substring(3, 6);

    Integer firstNum = Integer.parseInt(first);
    Integer secondNum = letterToInt(second);
    Integer thirdNum = Integer.parseInt(third);

    for (Integer i = new Integer(0); i < numOfUsers; i++) {
      thirdNum = new Integer(thirdNum.intValue() + 1);

      if (thirdNum > 999) {
        thirdNum = new Integer(0);
        secondNum = new Integer(secondNum.intValue() + 1);
      }

      if (secondNum > 26) {
        secondNum = new Integer(1);
        firstNum = new Integer(firstNum.intValue() + 1);
      }

      if (firstNum > 9) {
        // Ran out of IDs, do something.
        return;
      }

      first = String.valueOf(firstNum);
      second = intToLetter(secondNum);
      third = String.valueOf(thirdNum);

      while (third.length() < 3) {
        third = "0" + third;
      }

      String nextID = "0" + first + intToLetter(secondNum) + String.valueOf(third) + "98XX001";
      generatedIDs.add(nextID);

      System.out.println(nextID);
    }
  }
}

The result looks like this.

04X99898XX001
04X99998XX001
04Y00098XX001
04Y00198XX001
04Y00298XX001
04Y00398XX001
04Y00498XX001
04Y00598XX001
04Y00698XX001
04Y00798XX001


Check if an image download from the Internet has already started

Just a note:

... and return type

class CheckingResult {
    public boolean isDownloadingNecessary;
}

Please don't. An encapsulated boolean goes really too far. Especially on Android as an empty class costs 500 bytes. The method is probably fine, the name could be improved to something less boolean-like. You could also use a ConcurrentSet like

private final Set<imageView> startedDownloads = Sets.newConcurrentHashSet();

private boolean registerDownload(View imageView, String url) {
    return startedDownloads.add(imageView);
}

This assumes Guava, but without it, you could use a ConcurrentHashMap with a dummy value instead. No idea what everything your LOCK_CHECKING_TAG_AND_URL gets used for, so my replacement may not be equivalent. I also removed your tagging in favor of placing the View itself in the set, which may be completely wrong. But why did you chose to use tags instead?

With whatever reason, this should be explained.

If it was because of memory, you could use a WeakReference<View> (with a delegating equals, which makes it too complicated).


Java number sorting algorithm - remove ugly break

//find length of array to control loop
    int length = numbers.length-1;

    //do not exceed length of array in loop
    for (int outer = 0; outer<length; outer++){

        //reset second counter
        int inner = 0;

        //keep looping while two consecutive numbers are not in order
        while (numbers[outer+inner]>numbers[outer+inner+1]) {

            //swap numbers that are not in order
            int temp = numbers[outer+inner];
            numbers[outer+inner] = numbers[outer+inner+1];
            numbers[outer+inner+1] = temp;

            //decrement and see if numbers need swapped again
            inner--;

            //break on negative index to prevent overflow error
            if (outer+inner<0) {
                break;
            }
        }
    }

Consider

    for (int i = 1; i < numbers.length; i++) {
        // insert the ith element in its correct position among the elements up to i
        for (int j = i; j > 0 && numbers[j - 1] > numbers[j]; j--) {
            int temp = numbers[j - 1];
            numbers[j - 1] = numbers[j];
            numbers[j] = temp;
        }
    }

Rather than calculate inner + outer, we just track one value, which we call j.  Because we set it to the value of i, it will have the same values as inner + outer had in the original.

By moving the check for negative values into the loop control, we don't have to break.  We do end up doing an extra check because of that.

I prefer more horizontal whitespace to break up each line into more easily readable pieces.

I reduced the comments down to just one, which I believe is the only line that actually requires thinking to read.  I tried to explain the goal of that section of code rather than simply restate what the code does.

Incidentally, this algorithm is called an insertion sort.  It's one of the \$\mathcal{O}(n^2)\$ sorts.  The built-in sort that Java uses is capable of \$\mathcal{O}(n\log n)\$ complexity.  You would normally only use an insertion sort for small input sizes.  For any decent sized input, a loglinear sort like quicksort or mergesort would be faster.  Of course, you may be reinventing-the-wheel on purpose, for learning purposes.  When you do that, including the tag can better focus feedback.


Even without memoization, I cut the calculation time by about 40% when I switched from your version of binomial to the following:

static uint64_t permute(uint8_t n, uint8_t k) {
    uint64_t result = 1;

    for (; n > k; --n) {
        result *= n;
    }

    return result;
}

static inline uint64_t binomial(uint8_t n, uint8_t k) {
    if ( n - k > k ) {
        return permute(n, n - k) / permute(k, 1);
    } else {
        return permute(n, k) / permute(n - k, 1);
    }
}

Note that you could use the ternary operator rather than the if in binomial.

static inline uint64_t binomial(uint8_t n, uint8_t k) {
    return ( n - k > k )
        ? permute(n, n - k) / permute(k, 1)
        : permute(n, k) / permute(n - k, 1);
}

I find the if easier to follow in a complex statement like that.

The reason this works is that \$ \binom{n}{k} = \frac{n!}{k!(n-k)!}\$ can also be written as

$$ \frac{n * (n-1) * ... * (k+1)*k!}{k!(n-k)!} = \frac{n * (n-1) * ... * (k+1)}{(n-k)!} $$

and replacing factorial(k) with permute(k, 1) works because

$$ \frac{n!}{1!} = n! $$

It's unclear if memoization of the factorials would help more.  It may depend on how many values you need to calculate.


Alien Numbers - how Scala-ish is my solution?

You should definitely use scala.io.Source for File-IO
I wouldn't consider String splitting a responsibility of a general-purpose class. This should be done in the main loop
For tuples you can write map{ case (one,two) => ... }, which is often clearer than using x._1 and x._2
You don't need to write return if it's the last statement of the block
You can use pattern matching when defining vals: val Array(x, y, z) = line.split(" ")

Here is my attempt:

case class Langs(num:String, srcLang:String, dstLang:String)

object Langs {
  def fromLine(line:String):Langs = {
    val Array(num, srcLang, dstLang) = line.split(" ")
    Langs(num, srcLang, dstLang)
  }
}

object Translate {
  def lang2int(lang:String,num:String):Long = {
    val dmap = lang.toList.zipWithIndex.toMap
    val digitsList = num map dmap
    val valueList = digitsList.reverse.zipWithIndex map {
      case (one, two) => one -> math.pow(dmap.size, two)}
    valueList.map{case (one,two) => one*two}.sum.toLong
  }

  def int2lang(lang:String, num:Long):String = {
    val dmap = (0.toLong to lang.size zip lang).toMap
    Iterator.iterate(num)( _/dmap.size).takeWhile(_ > 0).map(n =>
      dmap(n % dmap.size)).mkString.reverse
  }

  def lang2lang(l:Langs):String = int2lang(l.dstLang,lang2int(l.srcLang,l.num))
}

Eliminating the while loop isn't that straight-forward, maybe someone else has an idea how to avoid that Iterator train-wreck.

[Edit]

I asked in another forum for a better solution for int2lang, and got this answer:

def int2lang(lang: String, num: Long): String = {
  val dmap = (0L to lang.size) zip lang toMap
  val size = dmap.size
  def loop(num: Long, l: List[Char]): List[Char] =
    if (num == 0) l else loop(num/size, dmap(num%size) :: l)
  loop(num, Nil).mkString
}

The nice thing about this is that the reverse is gone.


JavaScript function for the get a specifed weekday n-weeks before / in the future

var milliSecondsDay = 24 * 60 * 60 * 1000;

This is a constant. Use all caps and underscore to indicate such. If you can use ES6, use const instead of var.

var currentDate = new Date();
var currentStamp = currentDate.getTime();

Use Date.now() to get the current timestamp. This saves you from creating a Date object.

return day.slice(-2) + separator + month.slice(-2) + separator + year;

Appears that you are using zero-padding. Create a separate function for it to make it reusable.

getDayBeforeIn

You aren't really returning the day, you're returning a Date object. Either you rename this to reflect the return value, like getDateBeforeIn or return a representation of the day of the week.


Only need to point out one thing.

Constructor:

    p = new T[sz];

Destructor:

    delete p;

This code is broken. If you allocation with new [] you MUST destroy with delete [].

In the operator+= and operator-=

Ptr& operator+=(int i) {
    check_range(index+i);
    index += i;
    p+= i;
    return *this;
}

Ptr& operator-=(int i) {
    check_range(index-i);
    index -= i;
    p -= i;
    return *this;
}

Thus moving p during the lifetime of the object is not a good idea (because you must call delete on the pointer returned by new). So if you are going to move p you need to keep track of the original pointer in another member. But I would not move it all. You are adjusting index so why adjust p?

These can't return by reference:

Ptr& operator+(int i) {
    Ptr old{*this};
    return old+=1;
}

Ptr& operator-(int i) {
    Ptr old{*this};
    return old-=1;
}

You have to return by value because you are creating new values.

I am surprised that this works:

    Ptr old{*this};

Because you have deleted the copy constructor.

Ptr(const Ptr&) = delete;

If it compiles I am not sure what is happening. But it is definitely not good.

In the constructor you should prefer initializer list.

Ptr(T* t, int s = 1) {
    sz = s;              // Initializer list
    p = new T[sz];       // Initializer list.

    // This seems inefficient.
    // Since the line above has just called the constructor on each element
    // element in the array. You are now calling the assignment operator
    // on each element in the array.
    for (int i = 0; i < sz; ++i) {
        p[i] = t[i];
    }
}

You can optimize the above

Ptr(T* t, int s = 1)
    : sz(s)
    , p(reinterpret_cast<T*>(new char[s * sizeof(T)])  // Allocate aligned but uninitialized memory.
{
    for (int i = 0; i < sz; ++i) {
        new (p + i) T(t[i]);       // Its called placement new.
                                   // The `(p + i)` is the address where you want the
                                   // construction to take place (ie don't allocate)
                                   // Then we use the copy constructor to create the
                                   // copy
    }
}


Accessing a UIView's parent UIViewController using the UIResponder chain

Your code is correct and there is nothing wrong with checking if an optional is nil unless you actually need the value if it is not.

Here is an example where the comparison to nil is inappropriate:

if someOptional != nil {
 doSomethingWith(someOptional!)
}

This of course should be written as

if let something = someOptional {
  doSomethingWith(something)
}

But in your case there is nothing wrong with the check.

A recursive version would also require the check for nil, but it could be written using an if let statement. But this version would have to take a responder as parameter:

func viewController(responder: UIResponder) -> UIViewController? {
    if let vc = responder as? UIViewController {
        return vc
    }

    if let next = responder.next {
        return viewController(responder: next)
    }

    return nil
}

A more elegant way to express this would be a calculated property in an extension on UIResponder:

extension UIResponder {
    var viewController: UIViewController? {
        if let vc = self as? UIViewController {
            return vc
        }

        return next?.viewController
    }
}

Here the explicit check for nil can be eliminated thanks to optional chaining.

I would prefer your repeat/while solution though. But in the end it is a matter of taste.

The performance of the recursive version will be worse unless the compiler can do tail call elimination there. I am not sure if it will be able to do so. But this should hardly matter. If you get to a situation where this is a bottleneck you have worse problems.


Nested loop to transform MongoDB results

It looks like you are basically doing a filter + flatMap. You can also use destructing:

var dict = _(this.data.userinfo).filter(Boolean).flatMap(info => {
  return info.weightdata.map(({name, value, weight}) => {
    return {name, value, weight};
  });
}).value();


Rearranging an array such that positive and negative elements are at alternate positions

Worst case

Picturing the worst case helps understanding the problem.
The test failing probably uses an array of size n containing n/2 positive numbers followed by n/2 negative numbers (or vice-versa).

Current implementation

Note that when you find an element out of place, you are iterating twice through the indices, until you find the correct element: one time two found its position, another to move all elements in between.
You can combine both operations into one. Still this algorithm resembles the insertion sort. It will be quadratic in the worst case that I described (more specifically, (n/2)^2).

Using extra space

One efficient way to solve this is to build the correct array from the beginning. This requires O(1) of extra space.
You create 3 arrays: one to buffer positive numbers, other to buffer negative numbers, and a 3rd one with the final result.

When reading from stdin:

Place the number in the 3rd array if it matches the position, otherwise store it in the appropriate array;
If the number matches, try to use numbers stored in the positive/negative numbers arrays to keep filing the 3rd array (using FIFO).

What we are doing is essentially merging 3 sorted arrays: stdin, the array with positive numbers and the array with negative numbers.

This should run linearly, requiring 2 writes per number out of place.


Check column values are in different sets

I would do:

with(data, length(intersect(Country[train], Country[!train])) == 0)


Just a quick note: a Status (or ConnectionStatus) enum with ONLINE and OFFLINE values would be more readable here.


Will this static method keep context (Activity) all time and are there memory leaks?

A memory leak in Java is a situation where some objects are not used by application any more, but GC fails to recognize them as unused. As a result, these objects remain in memory indefinitely reducing the amount of memory available to the application.

  Will this static method keep context (Activity)

SharedPreference could fail:

  Unlike commit(), which writes its preferences out to persistent storage synchronously, apply() commits its changes to the in-memory SharedPreferences immediately but starts an asynchronous commit to disk and you won't be notified of any failures. If another editor on this SharedPreferences does a regular commit() while a apply() is still outstanding, the commit() will block until all async commits are completed as well as the commit itself.

http://developer.android.com/reference/android/content/SharedPreferences.Editor.html

  Are there memory leaks ?

No.

  Is there a better way to get values from SharedPreferences? I'm looking for the best way to do this.

SharedPreferences - Best method

Java provides many ways of storing application data. One of those ways leads us to the SharedPreferences object which is used to store private primitive data in key-value pairs.

All logic are based only on three simple classes:

SharedPreferences
SharedPreferences.Editor
SharedPreferences.OnSharedPreferenceChangeListener

SharedPreferences

SharedPreferences is main of them. It's responsible for getting (parsing) stored data, provides interface for getting Editor object and interfaces for adding and removing OnSharedPreferenceChangeListener

To create SharedPreferences you will need Context object (can be an application Context)
getSharedPreferences method parses Preference file and creates Map object for it
You can create it in few modes provided by Context, it's strongly recommended to use MODE_PRIVATE because creating world-readable/writable files is very dangerous, and likely to cause security holes in applications.

Editor

SharedPreferences.Editor is an Interface used for modifying values in a SharedPreferences object. All changes you make in an editor are batched, and not copied back to the original SharedPreferences until you call commit() or apply()

Use simple interface to put values in Editor
Save values synchronous with commit() or asynchronous with apply which is faster. In fact of using different threads using commit() is safer. Thats why I prefer to use commit().
Remove single value with remove() or clear all values with clear()

Performance & Tips

SharedPreferences is a Singleton object so you can easily get as many references as you want, it opens file only when you call getSharedPreferences first time, or create only one reference for it.
As SharedPreferences is a Singleton object you can change any of It's instances and not be scared that their data will be different
Remember the larger the Preference object is the longer get, commit, apply, remove and clear operations will be. So it's highly recommended to separate your data in different small objects.
Your Preferences won't be removed after Application update. So there are cases when you need to create some migration scheme. For example you have Application that parse local JSON in start of application, to do this only after first start you decided to save boolean flag wasLocalDataLoaded. After some time you updated that JSON and released new application version. Users will update their applications but they will not load new JSON because they already done it in first application version.
SharedPreferences are stored in an xml file in the app data folder


def kruskal(graph):
    for v in graph.keys():      # <- O(V)
        parent[v] = v
        rank[v] = 0

    edges = []
    mst = []

    # this for loop creates a list of all edges O(E)
    for outer_key in graph.keys():
        for inner_key, inner_weight in graph[outer_key].items():
            edges.append((inner_weight, outer_key, inner_key))

    edges.sort()    # <- this is O(ElogE) and where the complexity comes from

    for edge in edges:
        weight, v, u = edge

        if find(v) != find(u):
            union(v, u)           # <- union-find, let's check this in a second
            mst.append(edge)
                                  # ... so the whole for loop is O(E*O(union))
    return mst

So, your overall complexity is O(ElogE + E*O(union))

Let's look at your union-find implementation:

def find(v):   # find with path compression
    if parent[v] != v:
        parent[v] = find(parent[v])

    return parent[v]

def union(v, u):    # union by rank
    root1 = find(v)
    root2 = find(u)

    if rank[root1] > rank[root2]:
        parent[root2] = root1
    else:
        parent[root1] = root2
        if rank[root1] == rank[root2]:
            rank[root2] += 1

According to Wikipedia, this implementation is in O(inverse Ackermann(n)), so that means for the overall implementation we get

O(ElogE), which is purely driven by the sort, or as Wikipedia says

O(T_sort(E) + E*(inverse Ackermann(V)))

In other words, your kruskal algorithm is fine complexity-wise.

Your Prims algorithm is O(ElogE), the main driver here is the PriorityQueue. Notice that your loop will be called O(E) times, and the inner loop will only be called O(E) times in total. So the main driver is adding and retriveving stuff from the Priority Queue. The operations on the PriorityQueue are in O(logE), so O(ElogE) in total for the whole loop.


A few things in addition to what @Jamal and @200_success already wrote:

g++ on Mac OS X won't compile this code, because of #include "stdafx.h" and the int _tmain(int argc, _TCHAR* argv[]) signature. It's good to keep your code portable, unless you have a special reason not to. g++ can compile if you drop the stdafx.h import and if change the main declaration.
... and since you're not using the arguments of main, you could just declare without any args: int main() { ... }.
As you already used true in the checkPrime function, why not use it in the infinite while loop in main, instead of 1 == 1.
This may be a matter of taste, but I think while (true) { ... } is generally more readable and intuitive than do { ... } while (true).
... actually, as @200_success pointed out, a for (int currentNum = 2; ; currentNum++) { ... } loop would be even better: this way currentNum is declared in the block where it is used, eliminating potential side effects, and the counter is a natural element in a for loop. Notice the empty terminating condition, making this an infinite loop.
In checkPrime you named the variable int Number, but the common convention is to not capitalize variable names, use simply int number instead.
As @leetnightshade pointed out, place the opening curly either always on the same line as the function name ("Egyption brackets"), or always on the next line.

Suggested implementation

#include <iostream>

bool isPrime(int number)
{
    for (int a = 2; a < number; a++) {
        if (number % a == 0) {
            return false;
        }
    }
    return true;
}

int main()
{
    for (int currentNum = 2; ; currentNum++) {
        if (isPrime(currentNum)) {
            std::cout << currentNum << " ";
        }
    }
}

This compiles with g++ without warnings and runs fine in Mac OS X and GNU/Linux. I would hope it works as expected in Windows too.


Convert integer to full text string duration

You should look into the TimeSpan struct, which provides a nice method TimeSpan.FromSeconds().

Having filled a TimeSpan struct by e.g calling the FromSeconds() method, you can just access its properties Seconds, Minutes and Hours.

Instead of concating strings like you do, you should consider to use a StringBuilder.

To get rid of the If ... Else If you can just use the singular and only if the value is greater than 1 you add a s to the string/StringBuilder.

Based on the .NET Naming Guidelines method parameters should be named using camelCase casing hence TotalSeconds should be totalSeconds

Implementing the mentioned points will look like so

Public Function SecondsFullText(ByVal totalSeconds As Double) As String

    Dim timeSpan As TimeSpan = TimeSpan.FromSeconds(totalSeconds)
    Dim stringBuilder As StringBuilder = New StringBuilder()

    Dim hours As Integer = timeSpan.Hours
    Dim minutes As Integer = timeSpan.Minutes
    Dim seconds As Integer = timeSpan.Seconds

    stringBuilder.Append(ToText(hours, "hour"))
    If hours > 0 AndAlso (minutes > 0 OrElse seconds > 0) Then
        stringBuilder.Append(" ")
    End If
    stringBuilder.Append(ToText(minutes, "minute"))
    If minutes > 0 AndAlso seconds > 0 Then
        stringBuilder.Append(" ")
    End If
    stringBuilder.Append(ToText(seconds, "second"))
    Return stringBuilder.ToString()

End Function

Private Function ToText(value As Integer, singularName As String) As String

    If value = 0 Then Return String.Empty
    If value = 1 Then Return String.Format("{0} {1}", value, singularName)
    Return String.Format("{0} {1}s", value, singularName)

End Function


I noticed you're using app as a module name (which is understandable, since it's what the tutorial in the Mithril site does now). For real apps, you should try to name your modules more descriptively. For example, if the module displays a list of Posts, you might want to call it posts or postList.

Instead of calling m.request from vm, I normally pull the request out into a method on the model class, for example:

var Post = function(data) {
  var data = data || {};
  this.id = m.prop(data.id);
  this.title = m.prop(data.title);
  this.content = m.prop(data.content);
}
Post.list = function() {
  return m.request({method: 'GET', url: '/posts', type: app.Post})
}

You might optionally want to wrap m.request itself in another method, e.g.

var req = function(args) {
  return m.request(args)
}
/*...*/
Post.list = function() {
  return req({method: 'GET', url: '/posts', type: app.Post})
}

This lets you easily configure requests globally (e.g. if you need to set HTTP headers on all requests)

On a side note, I generally don't recommend using the background:true + m.redraw combo (especially on first render), unless you have a really good reason. When you do that, you're allowing your view to run early, which means all of your asynchronous data needs to be considered nullable, which in turn means you need more defensive code in the view. It's also a band-aid solution if the root of the problem is a slow web service.

Re: this comment: "TODO: add request error handler (how to?)"

Assuming you created a model method for posting as well:

Post.save = function(args) {
  return m.request({method: 'POST', url: '/posts', data: args, unwrapError: unwrap})
}

Then you can use the rejection handler of the promise to bind errors to a getter-setter

self.error = m.prop("")
self.add = function() {
  /*...*/
  Post.save()
    .then(null, self.error)
}

You can define the unwrapError function to drill down into a response to get the desired error message string out of the JSON structure. (There's also the extract option which lets you handle the response at the XHR level)

So, if your response looks like {msg: "something died"}, then you could write unwrapError: function(e) {return e.msg}, and then to display the error, you would simply call vm.error() in the view, which would return the "something died" string.

I also normally use a layout wrapping module, which looks something like this:

var layout = {}

layout.controller = function(module) {
  this.controller = new module.controller
  this.view = module.view
}

layout.view = function(ctrl) {
  return m(".layout", [
    ctrl.view(ctrl.controller)
  ])
}

layout.wrap = function(routes) {
  var map = {}
  Object.keys(routes).map(function(r) {
    map[r] = {
      controller: function() {
        return new layout.controller(routes[r])
      },
      view: layout.view
    }
  })
  return map
}

Then I can wrap modules like this:

m.route(document, "/", layout.wrap({
  "/": posts
}))

With this, the inner modules don't need to redefine the layout stuff all the time.

Regarding usage of vm versus using the controller, you only really need view-models if you need your modules to be globally accessible by other modules (this usually only happens when you have a deep hierarchy of sub-templates).

Most of the time, using fat controllers yield shorter, clearer code than using view-models (see app.vm.init + app.controller vs add.controller).

Still on the topic of controllers, one technique that I've seen in angular styleguides is to code controllers like this:

foo.controller = function() {
  var foo = {bar: 1}
  return {
    foo: foo
    doStuff: doStuff
  }

  function doStuff() {
    alert(foo.bar)
  }
}

This style avoids issues with this scoping and makes it easier to scan the public signature of the controller.

When using m.route, I recommend that you bind to document.body instead of document, so that you can put stylesheets in <head> and take advantage of the browser downloading/rendering optimizations.

Other than those, the code looks fairly well organized. The views are well written, and the code is easy to read, overall.


Is this a good user control layout for WPF?

There are 2 things that I could critisize on your code with the information you gave us:

Don't load style resources inside the usercontrol. Let the application hold control over how to style a usercontrol
Try not to use a grid in this context, because it prevents the control from adopting itself to new sizes of the window. StackPanels and Dockpanel are much better for this


Remove all occurrences of an element from an array, in place

A much simpler solution is to have an "input pointer" i and an "output pointer" o.

public int removeElement(int[] numbers, int value) {
    int o = 0;
    for (int i = 0; i < numbers.length; i++) {
        if (numbers[i] != value) {
            numbers[o++] = numbers[i];
        }
    }
    return o;
}


How can I refactor to avoid repetition finding the index of strings in a list?

Let's start with a simpler problem where there's just one choice:

for (var i = 0; i < compressors.Count; i++)
{
    if (compressors[i].StartsWith(firstChoice, StringComparison.OrdinalIgnoreCase))
    {
        return i;
    }
}

return 0;

(I would much prefer returning -1 if no match is found, but requirements are requirements.)

Now we can build on top of this to deal with the second preference:

var secondChoiceIndex = -1;
for (var i = 0; i < compressors.Count; i++)
{
    if (compressors[i].StartsWith(firstChoice, StringComparison.OrdinalIgnoreCase))
    {
        return i;
    }

    if (secondChoiceIndex == -1 && compressors[i].StartsWith(secondChoice, StringComparison.OrdinalIgnoreCase))
    {
        secondChoiceIndex = i;
    }
}

return secondChoiceIndex == -1 ? 0 : secondChoiceIndex;


Hmmm,

Well I think the way you are going about it, while functionally correct won't scale well.

Ideally you want to try more of an aggregation. Off the top of my head I would approach this like:

interface Skill
{
   string Name{get;}
   double value{get;}
}

now with this base object you can write the rest of your code doing calculations based on your skills value.

As for the modifying, well nothing else needs to know if a Skill is modified to use it.
To handle that I would make a ModifiedSkill agnostic from everything else:

public interface ModifiedSkill : Skill
{
    IEnumerable<Modifier> Modifiers { get; }

    double BaseValue { get; }
    double Value { get; }

}

Now, what is a modifier you ask? well:

public interface Modifier
{
    string Name { get; }
    string Cause { get; }
    double Apply(double skill);
    Boolean Active { get; set; }
}

So that is all the interfaces you need to cover pretty much all eventualities, allowing for some potentially cool things down the line like timed modifiers or conditional modifiers or whatever.

Now, how to actually implement this?

Public class ModifiedSkillImpl : ModifiedSkill
    {
        private readonly List<Modifier> _modifiers;
        private readonly double _baseValue;

        public ModifiedSkillImpl(string name, double baseValue, IEnumerable<Modifier> modifiers)
        {
        if (name == null) throw new ArgumentNullException("name");
        if (modifiers == null) throw new ArgumentNullException("modifiers");
        Name = name;
        _baseValue = baseValue;
        _modifiers = modifiers.ToList();
    }

    public string Name { get; private set; }

    public IEnumerable<Modifier> Modifiers
    {
        get
        {
            return _modifiers;
        }
    }

    public double BaseValue
    {
        get
        {
            return _baseValue;
        }
    }

    public double Value
    {
        get
        {
            return Modifiers.Aggregate(_baseValue, (current, modifier) => modifier.Apply(current));
        }
    }
}

Now, this is only one example of course, you could do a lot of alternate skill implementations.
The final step would be i suppose to create PoisonModifier/ItchyLeftEarModifier etc
and then apply them with some effect like +5% -20% etc, or whatever.

This separation also means that while most things will be using the Skill.Value which in the case of a modified skill will be the modified version some special something could check if the skill is a Modified skill, if so cast it and use the base stat instead!

(one final note)
I was a bit wasteful with the Value aggregation in ModifiedSkillImpl, tbh I would probably have a private variable for modified Skill and only recalculate if the modifiers had changed since last call but you know, this is just a quick POC.


Your if conditions can be simplified. Instead of this:

if ( `tcsh -f -c "ls -1 DSC*.jpg >& /dev/null" && echo yes` == "yes" ) then

You could write like this:

if ( `ls DSC*.jpg >& /dev/null && echo x` != "" ) then

That is:

you don't need to spawn a tcsh sub-shell
you don't need the -1 for ls to list files in a single column because you redirect that to /dev/null anyway
the `...` part will only output anything if there were files, so you don't need yes == yes, it's enough to check for emptiness

If you don't mind using Bash instead of Tcsh, then the ifs can be even more simple:

if ls DSC*.jpg &> /dev/null; then

A lot less useless fluff.

With Bash you could simplify the repetitive blocks with a function, for example:

check_files() {
    glob=$1
    flags=$2
    nomsg=$3
    echo Checking "$glob"
    if ls $glob &>/dev/null; then
        jhead -a$flags -ft -autorot -n $glob
    else
        echo $nomsg
    fi
    echo
}

check_files 'DSC*.jpg' nef 'no Nikon jpg files'
check_files 'DSC*.JPG' NEF 'no Nikon JPG files'
check_files 'p*.jpg' rw2 'no Canon jpg files'
check_files 'P*.JPG' RW2 'no Canon JPG files'


How can I optimize this array.each in ruby?

Are you aware of Enumerable#group_by?

def grouped_items
  @items.group_by{|item| item.date}
end


Concise and exception-prone method for running method on component

Are there certain exceptions you can anticipate for onActorConnected?  Let's make an encompassing checked exception ActorUnconnectableException, though this would need to be be made more finegrained for particular connectivity issues:
class ActorUnconnectableException extends Exception {
    ActorUnconnectableException(Actor actor, MatchComponent component) {
        super(
            String.format("actor: %s cannot connect to component: %s", actor.getName(), component.getName())
        );
    }
}

And declare onActorConnect within MatchComponent like this:
void onActorConnect(Actor actor) throws ActorUnconnectableException {
    ...
}

The reason I advocate for a checked exception here is because it sounds like the it is hard to guarantee that an Actor is connectable without attempting to connect it. If we were able to verify that an Actor is connectable beforehand, an unchecked exception would be better suited here.
For something like a string that we're trying to parse as a number, let's say this parsable string is typed in our frontend. We can enforce through whatever frontend framework that this string contains only digits. That's why Integer::parseInt throws an unchecked exception, it expects that the validation is done before hand.
Another thing that can be improved is this:
if (actors.contains(actor))
     throw new IllegalArgumentException(format("Actor '%s' is already connected.", actor.getName()));

actors.add(actor);

Apart from adding braces for the if, we can utilize the fact that actors::add returns true if actor is not contained, otherwise false, like this:
boolean actorAdded = actors.add(actor);

if (!actorAdded) {
    throw new IllegalArgumentException(format("Actor '%s' is already connected.", actor.getName()));
}

This should remain an unchecked exception cause the calling code should be able to determine whether it already added an Actor equal to actor beforehand.
The rest of connectActor ends up looking like this:
var unconnectableComponents = new ArrayList<MatchComponent>();

for (MatchComponent component : components) {
    try {
        component.onActorConnect(actor);
    }
    catch (ActorUnconnectableException e) {
        unconnectableComponents.add(component);
    }
}

// Log `unconnectableComponents` or create new exception to report their collective failure.

This definitely ends up looking verbose, but the idea is that we want things outside of the calling code's control (like whether can actor is in fact connectable, which sounds like it can't be decided beforehand) to be checked at compile time.


Is there a simpler way of copying and pasting one inputs value into other input with the same name

One minor improvement I can think of is to create a variable to hold the input element since the element is used twice like

$(document).on('click', '.--copy', function () {
    var $input = $(this).closest('div').find('input'), input_name = $input.attr('name').split('-')[0];
    $('input[name^=' + input_name + ']').val($input.val());
});

Demo: Fiddle


Solution discussion on the best way to reverse a number in Python

First, a note on complexity. Both your implementation and the reference implementation do indeed have O(n) complexity in the number of input digits in the best case, but O(log(n)) in the range of the input number.
This depends, mind you, on the expected range of the input number. For "typical values" below the limit of machine precision, which these days will be \$2^{63}\$ for most people, the contents of the reference implementation's inner loop will be constant-time. However, Python has automatic support for arbitrary precision, and if that support is used, the reference implementation will end up being super-linear in the worst case.
As for reversal of a negative number, I think it makes less sense to automatically abs() than just to raise, because - if you interpret the number as a string - negative numbers are non-reversible. I say this knowing that it violates the reference implementation if you interpret it as a specification, but I don't think the specification makes much sense.


Strictly typed dynamic proxy to call dynamic object

It would be very useful to see the associated MethodInfo instance while implementing source in the situation like this:

interface IMyWebApi
{
    [Description("GET orders/{0}")]
    Order GetOrder(int id);
}

IWebApi api = Proxy.Create<IMyWebApi>(new RestApi("http://example.com/api"));
Order order = api.GetOrder(33);

So I made the proxy injecting it when DescriptionAttribute is provided:

[TestMethod]
public void Call()
{
    dynamic c = new ExpandoObject();
    c.Add = (Func<int, int, int>)((a, b) => a + b);
    c.Divide = (Func<MethodInfo, int, int, int>)((mi, a, b) => a / b);

    ICalculator proxy = Proxy.Create<ICalculator>(c);
    Assert.AreEqual(3, proxy.Add(1, 2));
    Assert.AreEqual(2, proxy.Divide(4, 2));
}

public interface ICalculator
{
    int Add(int a, int b);

    [Description]
    int Divide(int a, int b);
}

It should provide access to all interface method attributes and return types.

Updated Interceptor looks like this now:

class Interceptor : IInterceptor
{
    public Interceptor(object target) => Target = target;
    object Target { get; }
    public void Intercept(IInvocation invocation) =>
        invocation.ReturnValue = Dynamic.InvokeMember(
            Target,
            invocation.Method.Name,
            invocation.Method.IsDefined(typeof(DescriptionAttribute))
                ? invocation.Arguments.Prepend(invocation.Method).ToArray()
                : invocation.Arguments);
}


The two pop() functions have very different semantics, this is probably more of a taste issue, but i'd normally like to see such a difference in a difference in function name. Yes the signature is different, but there isn't really anything that would tell a user that one is blocking and the other one isn't.

With the copy and move operations, it might help if you thought about the semantics, when does one usually copy an object, when is it moved. Does the expectation that a user has from a copy constructor or the move constructor match what you are doing. It sounds like with the move operator you have some different functionality in mind. If that is that case I'd normally put that in a separate function. Also think of how this queue should be used, is a move or a copy a valid operation.


Weighted graph from a matrix (list-of-lists)

Well, both node_name and make_graph can be a bit smaller, yes.

def node_name(row_index, col_index):
    return "{},{}".format(row_index, col_index)

format will do the string conversion automatically, no need to call str.

I'd also give everything a bit more space to make it more readable.

def make_graph(matrix):
    graph = {}

    width, height = len(matrix[0]), len(matrix)

    columns = range(width)
    for rowindex in range(height):
        for colindex in columns:
            graph[node_name(rowindex, colindex)] = x = {}

            # Up
            if rowindex > 0:
                x[node_name(rowindex - 1, colindex)] = matrix[rowindex - 1][colindex]
            # Down
            if rowindex < height - 1:
                x[node_name(rowindex + 1, colindex)] = matrix[rowindex + 1][colindex]
            # Left
            if colindex > 0:
                x[node_name(rowindex, colindex - 1)] = matrix[rowindex][colindex - 1]
            # Right
            if colindex < width - 1:
                x[node_name(rowindex, colindex + 1)] = matrix[rowindex][colindex + 1]

    return graph

Except caching more things this would look okay to me.  Relying a
rectangular matrix seems obvious to me, so width and height can be
precomputed.  Using range also makes it more clear that you really
want the coordinates, not the row or column values.

In the interest of verbosity I'd also just i and j for indexes, but
that's your choice obviously.

Also, you know that {(1, 1): 1} works, right?  Because there doesn't
seem to be a pressing reason to use node_name at all.  In contrast to
a list a tuple is immutable and can be used as a dictionary key, see
also this wiki page for a more thorough discussion on that.


Firstly, I'd suggest not duplicating the overloading logic of range. Instead:

def rangeth(*args):
    print range(*args)

Just take your arguments and pass them onto to range.

Secondly, I'd write a function that takes a single number and produces the "th"ified version.

def as_th(number):
    number = str(number)
    if number[-2:] in ['11','12','13]:
         return "{}{}".format(number, 'th')
    else:
         return "{}{}".format(number, places.get(number[-1], 'th'))

I think that makes it easier to follow.

Then have you rangeth function be:

def rangeth(*args):
    return map(as_th, range(*args))


I think your code looks pretty good already. It follows conventions and your indentation and variable names are precise. There's not much to review.

But if you're targeting modern browsers (IE9+) I would suggest a different approach using map and would separate the random logic into a function. I'd also declare the element up top so I know at first glance that the code is working with the DOM. It may seem like more code at first but it's good for code reuse, plus I think it reads better; the intent is more clear:

(function() {
  "use strict";

  var el = document.getElementById("quotes");

  var quotes = [
    ["Stay Hungry. Stay Foolish.", "Steve Jobs"],
    ["Good Artists Copy, Great Artists Steal.", "Pablo Picasso"],
    ["Argue with idiots, and you become an idiot.", "Paul Graham"],
    ["Be yourself; everyone else is already taken.", "Oscar Wilde"],
    ["Simplicity is the ultimate sophistication.", "Leonardo Da Vinci"]
  ];

  function rand(xs) {
    return xs.slice(0).sort(function(){
      return .5 - Math.random();
    });
  }

  function quote(q) {
    return "
&ldquo;"+ q[0] +"&rdquo; &mdash; "+ q[1] +"
";
  }

  el.innerHTML = rand(quotes).map(quote).join('');

}());


Largest Sum Contiguous Subarray - Kadene's algorithm

I have some suggestions for your code.
Replace the for loop with an enhanced 'for' loop
In your code, you don’t actually need the index provided by the loop, you can use the enhanced version.
before
for (int i = 0; i < a.length; i++) {
//[...]
}

after
for (int current : a) {
//[...]
}

Variable and parameter name should be in camelCase style
The variables should be in camelCase.


In my experience no, using curl is much better an reliable. I use the following code in one of my projects, this always works (and allows redirects, if you don't want to set CURLOPT_MAXREDIRS to 0).

<?php

/**
 * Check if the URL is reachable.
 *
 * @param string $url
 *   The URL to check.
 * @return this
 * @throws \LogicException
 */
public function checkReachability($url) {
  $ch = curl_init($url);
  curl_setopt_array($ch, [
    CURLOPT_AUTOREFERER    => true,
    CURLOPT_CONNECTTIMEOUT => 5,
    CURLOPT_ENCODING       => "",
    CURLOPT_FOLLOWLOCATION => true,
    CURLOPT_MAXREDIRS      => 1,
    CURLOPT_NOBODY         => true,
    CURLOPT_SSL_VERIFYHOST => false,
    CURLOPT_SSL_VERIFYPEER => false,
    CURLOPT_TIMEOUT        => 5,
    // It's very important to let other webmasters know who's probing their servers.
    CURLOPT_USERAGENT      => "Mozilla/5.0 (compatible; StackOverflow/0.0.1; +https://codereview.stackexchange.com/)",
  ]);
  curl_exec($ch);
  $code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
  curl_close($ch);
  if ($code !== 200) {
    throw new LogicException("The URL doesn’t exists (more specifically isn’t reachable).");
  }
  return $this;
}

?>

Of course you have the problem that you don't always have curl available, a fallback would be.

<?php

// PHP 5.3+
stream_context_set_default(array("http" => array(
  "method"     => "HEAD",
  "user_agent" => "Mozilla/5.0 (compatible; StackOverflow/0.0.1; +https://codereview.stackexchange.com/)",
)));

set_error_handler(function ($errno, $errstr, $errfile, $errline ) {
  throw new LogicException("The URL doesn’t exists (more specifically isn’t reachable).");
});
$headers = get_headers($url);
restore_error_handler();

// String comparisons should be made with ==
if (!isset($headers[0]) || substr($headers[0], 9, 3) != "200") {
  throw new LogicException("The URL doesn’t exists (more specifically isn’t reachable).");
}

?>


Consider the iterator pattern with the methods hasNextCombination() and nextCombination(). Let your implementation follow the implications. Maybe you have to introduce a buffer. The loadCombination()-method inverts the responsibility and let you do strange things like clearing the given list if the client gives you messy data. The standard iterator pattern is the way to go. Pass your list of elements to the constructor of your Iterator. Make defensive copies to avoid side effects. Return the combination of the elements directly. The Client should be responsible to collect them in a list.
Even this suggestion will be obsolete (1.). Do not check for "null" values. If the client gives you "null" then he should expect that the program will not work properly. Giving up the responsibility of the client to not pass null values has serious consequences for your source code. You will end up checking everything for null because you cannot count on anything. There are some exceptions to that which should be known: The parent of the root of a hierarchy may be null, lazy initialization is dealing with null and son find()-methods may return null that has to be evaluated immediatly. In all other cases: Never pass null, never check null and never return null.
Break the generateNextCombination()-method into smaller pieces. If you experience problems then it surely has to do with the multiple return statements. Multiple return statements will hinder you to apply refactorings like "extract method". Furthermore: extending your code is much more predictable. Avoid multiple return statements in a method. Provide a proper control flow until the end of the method.
As a matter of common usage do not use ++k. Use k++ instead. You yourself are switching between suffix and prefix notation. Keep doing one thing consistently to have the least surprise. Do not forget to adapt your breaking conditions.
As it is used in the test, do not take my suggestion too serious here but: Avoid using bit shifting. I do not event know if there is a significant speed up. After all it doesn't matter until your application critical on this. And most of the applications aren't. The reason is you introduce low level language structures in a high level language.


PHP allows computed variable names, but it's nearly always a bad idea.  Unless you are careful about variable naming conventions, you could easily trash a variable accidentally, possibly introducing a security vulnerability.

You would be better off using an associative array.

// Generate dynamic variables testing for equality of
// of $exception and an Enum value from ExceptionModel
foreach ($exceptionModels as $constName => $constValue) {
    $detected[$constName] = $exception === $constValue;
}

if ($detected['ALLER']) {
    echo "ExceptionModel is aller.";
} else if ($detected['AVOIR_IRR']) {
    echo "ExceptionModel is avoir_irr.";
} else {
    echo "ExceptionModel was neither, it is: " . $exception;
}


Form submission handler with terms and conditions checkbox and double-click prevention

A couple thoughts:

Don't keep re-querying the DOM with jQuery selectors. This is poor from a performance standpoint.  Put the jQuery collection into a variable and don't keep re-querying the DOM every time you need to work with the collection.

For example:

var $applyButton = $('#applyButton');
var $btnBenefitsCancel = $('#btnBenefitsCancel');

Or for case when you need to find one element in collection like your :first selector:

var $checkboxErrorText = $(.checkboxErrorText);
if($checkboxErrorText.length) {
    $checkboxErrorText.first().removeClass('hidden');
}

A good rule of thumb is if you find yourself using the selector (or some subselection of it) more than once, put it into a variable.

Why do you need to check if there are any elements that meet the condition for adding the click handlers?  You could easily remove the $(*).length checks and your code would function exactly the same (and probably make Sonar very happy at the same time). Same thing applies to the checkboxErrorText example. It is OK to try to operate against a zero length jQuery collection in most cases. I would reserve such tests of collection size to those cases where you need to have alternate code behavior if the selector returns an empty collection. This is not really the case for the use cases you have shown (though it could be if you needed to do something like log an error or alert the end user of an empty selection result).
Be more consistent in how you name your DOM element id's. It is confusing to have one button name like applyButton and another like btnBenefitsCancel. You can read up on semantic naming for your HTML id's, class names, etc. to formulate a good approach on having a consistent naming strategy.
You have some really long line of code, which make your code hard to read.

For example, take this line of code:

            $("#termsConditionsChBx").removeClass('checkbox-checked').removeClass('checkbox').removeClass('checkbox-error').addClass('checkbox-error');

You could make this more readable in several ways.  First just breaking up across lines:

            $("#termsConditionsChBx")
                .removeClass('checkbox-checked')
                .removeClass('checkbox')
                .removeClass('checkbox-error')
                .addClass('checkbox-error');

But you can also pass multiple class name into removeClass() and addClass(), so you could actually implement like this if you like:

            $("#termsConditionsChBx")
                .removeClass('checkbox checkbox-checked checkbox-error')
                .addClass('checkbox-error');

This approach would actually perform better as well, as the collection would only be iterated a single time to remove all those classes as opposed to iterating three times due to having having three different removeClass() calls. If you are working with large collections, this could add up.

The same approach of splitting longer lines of code across multiple lines could also be applied to longer conditionals like this line of code:

        if (appProcessing.isTermsChecked() && !$('#applyButton').hasClass('noClick')) {

Could be:

        if (
            appProcessing.isTermsChecked() &&
            !$('#applyButton').hasClass('noClick')
        ) {

If you should consider incorporating style checks into your static code analysis such that you can automatically flag style issues like lines of code that are too long (typically ~80 characters).


Oriented-object approach on how to control different classes cleanly

CommandManager referes to a CommandControllable, and CommandControllable refers to a set of CommandManagers. Who controls who? Such loops in dependency graph should be avoided.

Then, think if the Actor model can be applied in your case.


A couple things right off the bat:

You use jQuery('#maincontainer') multiple times. You should consider caching that somewhere. Either as part of your object or a separate variable.

// Wherever you use jQuery('#maincontainer'), use ajaxUpdate.mainContainer
ajaxUpdate.mainContainer = jQuery('#maincontainer');

I would suggest passing the this from your event handlers directly to updateMainContent since that is the only method that uses it.
Unless you have plans to significantly change the way events are handled between search, submenu, and mainmenu, you can can just have one method that handles those events.
complete gets called whether it's an error or success. No need to remove the loading class on success and complete.
Your beforeSend function is unnecessary since it doesn't actually manipulate any of the data before the AJAX call or cancel the AJAX call. You can move the addClass to before the jQuery.ajax. From the jQuery docs:

  A pre-request callback function that can be used to modify the jqXHR (in jQuery 1.4.x,
  XMLHTTPRequest) object before it is sent. Use this to set custom headers, etc. ...
  Returning false in the beforeSend function will cancel the request.

You can chain the following lines together (to remove another call to jQuery):

jQuery('#main-menu li').removeClass('active');
jQuery('#main-menu li:eq('+State.data.main+')').addClass('active');

Like so:

jQuery('#main-menu li').removeClass('active')
    .filter(':eq('+State.data.main+')').addClass('active');

Switching your AJAX call to a .get and using the promise API cleans up the code a little and makes it a bit more concise.
In your success response, you don't need to define data since you're just passing it directly to History.pushstate.

Not knowing the HTML structure, I think that's the best I can give you. Here's a fiddle with all of these things implemented.

I'm more than happy to answer any questions if you have them. Hopefully this will help you out.


Leetcode longest substring without repeating characters

Complexity
Your solution has time complexity \$\mathcal{O}(N^4)\$, which is very bad. There is a \$\mathcal{O}(N)\$ solution for this problem. Consider for example the string:
abcdecfghij

Instead of taking substrings and checking if the substring has duplicates, instead keep track of the last position seen for any possible character. This is basically an array of 256 ints, which you should initialize to -1 to indicate that you've never seen the character before. Then, iterate over the string character by character, and check if the character you look at has already been seen. If not, update its position in the array. So after processing abcde, you will have a = 0, b = 1, c = 2, d = 3, e = 4 and the rest is still -1. Then when you encounter c again, you know you have a duplicate. But instead of starting over from the second character of the string, you should start instead from the character right after the first c, so at position 3. And you know you already have a valid substring up to and including the second c. So then you can continue from there. You continue until you find a character with a recorded position that is equal to or more than the starting position of the current substring. Here is a possible implementation in C++:
#include <array>
#include <utility>

int longest_sub(const std::string &s) {
    std::array<int, 256> last_positions;
    last_positions.fill(-1);

    int min_position = 0;
    int maximum_length = 0;

    for (size_t i = 0; i < s.size(); ++i) {
        int &last_position = last_positions[static_cast<unsigned char>(s[i])];

        if (last_position >= min_position) {
            // We encountered a duplicate
            min_position = last_position + 1;
        }

        maximum_length = std::max(maximum_length, int(i + 1 - min_position));
        last_position = i;
    }

    return maximum_length;
}


Comparing strings, ignoring case, punctuation, and whitespace

You might want to create a combined CharacterSet of punctuation and whitespace first and then apply this set using a single operation. This should speed things up. Please have a look at this code snippet:

let punctuation = CharacterSet.punctuationCharacters
let whitespace = CharacterSet.whitespaces
let unwanted = punctuation.union(whitespace)
let components = filterString.components(separatedBy: unwanted).joined(" ")
let filterStringContainsSearchText = components.contains(searchText)


Iterate comparison - How can I write this better?

I'm not a VB.Net developer, but if I were writing this in C# I would use the Contains method on your collection. I'm assuming that your collection is a list of strings in this case.

I've included what the code might look like in VB.Net below. I give no guarantees that it works though. :)

Dim dt As DataTable = SomeDataTable

For Each dr As DataRow In dt.Rows
    Dim myColumn As String = dr("column").ToString().Trim()

    If collection.Contains(myColumn, StringComparer.OrdinalIgnoreCase) Then
        'Do your stuff here
    End If
Next


Should I make some checks for security or just the dimensions and size checks?

It would be simple to check the type of the file uploaded. For example, you could check if the type is an image. For example, if the user uploads a PNG file, $_FILES['avatar']['type'] should be image/png, so a check for that value starting with image would be a simple conditional (e.g. using strpos() and looking for it to return 0, or preg_match('^image/', $_FILES['avatar']['type]).

The HTML could also be updated to only accept certain file types. One technique for this is to add the accept attribute to the input element with a value like image/* to limit the selectable files to images. While this does not prevent a user from selecting any file (or modifying a file to look like an image), it can act like a filter to the file selection dialog if the OS and browser support it. Read more about this in answers to Limit file format when using ?

<input type="file" id="input" name="image" accept="image/*">

One could also add a change handler to check the extension of the file submitted (bear in mind that the user can also change the extension of a file through the OS).

var allowedExtensions = ['jpg', 'gif', 'bmp', 'png', 'tif'];
document.addEventListener('DOMContentLoaded', function() {
  var fileInput = document.getElementById('input');
  fileInput.addEventListener('change', function(e) {
    var parts = this.value.split('.');
    if (allowedExtensions.indexOf(parts[parts.length - 1].toLowerCase()) < 0) {
      this.value = ''; // clear value
      console.log('invalid extension');
    }
  });
});
<input type="file" id="input" name="image" accept="image/*">

Combining one or both of those approaches with the server-side check would be a good approach. Bearing in mind that a user could alter the HTML attributes with tools like browser consoles, as well as submit a form manually with their own page or a tool like Postman, the server-side check should be utilized for optimal protection.

Other Feedback

JavaScript

Variable croppable

It apppears that croppable is set to true in the ready function:

ready: function () {
    croppable = true;
    button.onclick = function () {

While it would be undefined before that line, the onclick function wouldn't be set until after that is set to true, so the following block seems superflous in the onclick function:

if (!croppable) {
    return;
}

This is because by the time the click handler is set on the button, that variable will have been set to true so the condition will never evaluate to a truthy value.

I also noticed in that onclick function that three variables (i.e. croppedCanvas, roundedCanvas, and roundedImage) are declared before the conditional return. There isn't really any reason to declare those variables before the condition. Then those variables can be declared whenever assigned.

Cache DOM references

DOM lookups aren't exactly cheap, so it may be better to store references to elements fetched via document.getElementById() as well as using the jQuery function in variables and referencing those variables later.

Use consistent DOM lookups

Much of the code uses jQuery to look up elements, but then there are other places using document.getElementById(). If you are going to have jQuery, it makes sense to use it for all DOM lookups - for the case of getting a single element (e.g. image and button) .get() can be used to access the element.

So these lines:

var image = document.getElementById('image'),
    button = document.getElementById('button');

Can be simplified using jQuery and .get():

var image = $('#image').get(0),
    button = $('#button').get(0);

Variable name reused

While moving image and button out of the onload callback I noticed that image was used for an Image object and then inside the callback re-assigned to the element with id attribute image. It is wise not to re-use variables like that... Perhaps a better name for the variable referencing the element would be imageElement.

PHP

You state that upload.php contains the following:

if( isset($_FILES['avatar']) and !$_FILES['avatar']['error'] ){
  file_put_contents( "uploads/image.png", file_get_contents($_FILES['avatar']['tmp_name']) );
}

Is there any error handling/response to the client as to to activity on the server? What happens if the write to "uploads/image.png" would fail?


Compacting this repetitive JavaScript bit which trims values in an object

With single traversal on keys list and trimming all fields of type string:

Object.keys(shippingAddress).forEach((k) => {
    if (typeof shippingAddress[k] == 'string') {
        shippingAddress[k] = shippingAddress[k].trim();
    }
})


Arranging Buttons on a Process Enumerating Application

What will happen when there are more processes than you can fit buttons for on your form?

You're doing the hard work by hand, reinventing a wheel that's already there for you... and as you saw, it's not exactly scaling very well.

The wheel in question is called a FlowLayoutPanel, a winforms layout control that automatically handles control positioning for you, taking overflowing controls to a new row or column, depending on how you configured it - it even handles scrollbars for you, if you have more items than can fit into the panel.

That said, your wheel has a number of squeaky parts:

if (process.ButtonText == "") continue;

Comparing a string against an empty string, would usually be written like this:

if (string.IsNullOrWhiteSpace(process.ButtonText)
{
    continue;
}

In all versions/attempts of your layout code, you hard-coded the key values.

140 / the column width, should be computed from the width of a button
7 is arbitrary and should be allowed to change if/when the form is maximized or resized. Your screenshots crop the top part, but if you haven't removed the min/maximize buttons and allow resizing of the form, the user can easily wreck your layout; it doesn't take the button height into consideration either.

BUG?

It's a little beyond the scope of this review, but this line can potentially blow everything up:

button.Click += (x, y) => process.Kill();

There's a chance your application will not-so-graciously crash and burn if you bring up your app, then start task manager and kill a process, and then click the button for that process in your app.

The process to kill won't exist anymore, and if ProcessHelper.Kill() doesn't handle that situation, boom! Make sure your wrapper wraps the operation in a try..catch block.


First of all, it's a job for at least three separate functions (that should
belong to the different classes at best, but that would be a different story), each throwing its own exceptions.

protected function sendRequest($data)
{
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $this->apiUrl);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER,FALSE);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST,2);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    $data = curl_exec($ch);
    if ($error = curl_error($ch)) {
        throw new Exception($error);
    }
    curl_close($ch);
    return $data;
}
protected function jsonDecode($json)
{
    $data = json_decode($json);
    if (json_last_error()) {
        throw new Exception(json_last_error_msg());
    }
    return $data;
}
protected function requestApi($data)
{
    $data = $this->authApi + $data;
    $data = [
        'data' => json_encode($data)
    ];
    $response = $this->sendRequest($data);
    $answer = $this->jsonDecode($response);

    if (isset($answer->success) && $answer->success == true))) {
        return $answer;
    }
    if (isset($answer->message) {
        throw new \Exception('API error: ' . $answer->message  );
    }
    throw new \Exception("Unknown API response: $response" );
}

As of the logger, I would call it in the exception handler/catch block and thus avoid repetitive calls.


Searching for songs on an Android application

In general the code seems fine and it is not horrible or anything, but I think you could surely have improvements.

High level

Currently your code returns null if audioCursor == null, I think this should be an exception, possibly an existing one, or a custom one. I'm not exactly sure what it does, so I cannot give more advice.

General coding style

I suggest you to change your coding style to more consistent and I think you can enhance readability with some simple changes.

Take a look at:

Cursor audioCursor = c.getContentResolver().query(
        MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
        new String[] { "*" }, MediaStore.Audio.Media.DATA + " = " + songPath, null, Media.TITLE + " ASC");

I understand that CodeReview is quite limited in width and your IDE is not necessarily so limited, but since you decided to split up the arguments, I would prefer it like this:

Cursor audioCursor = c.getContentResolver().query(
    MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
    new String[] { "*" },
    MediaStore.Audio.Media.DATA + " = " + songPath,
    null,
    Media.TITLE + " ASC"
);

This way all arguments are clearly visible and it looks consistent.

Similar arguments hold for:

String path = audioCursor.getString(audioCursor
        .getColumnIndex(MediaStore.Audio.Media.DATA));

Here you are breaking up one argument, I would prefer to break it up outside, like this:

String path = audioCursor
        .getString(audioCursor.getColumnIndex(MediaStore.Audio.Media.DATA));

Then lastly your blanks are off on this line:

s.setDuration( new Duration(duration) );

I'd say there is no reason to add them, it can even create confusion as now I start to think about the reason of the blanks, this is more clear:

s.setDuration(new Duration(duration));

Early exiting

Currently you have all your code in the if (audioCursor != null) statement like this:

if (audioCursor != null) {
    //your code
    return value;
}
return null;

This leads to clutter and less space to actually type code because of the indentation, the preferred way would be to do so:

if (audioCursor == null) {
    return null;
}
//your code
return value;

This way you exit early and the rest of your code is not impacted by this flow.

Variable naming

Most variable names look okay, except Context c and Song s, I see no reason to not use the full name like context and song, it will not harm anybody.
When taking a closer look, I actually noticed that album_id and trackid are also off, they are not consistent and neither in the recommended camelCase, they should be albumId and trackId.

Code safety

I would recommend to make Context context and String songPath final, I would say it is important for context, such that you cannot accidentally reassign the context variable.

Performance note

Currently you create a new String[] { * } on every method call, for maximum performance you could create a private final static String[] STAR_STRING_ARRAY = new String[] { * } and reference that one such that you do not need to create a new string array at every call. It depends on the amount of calls this method receives to see whether it is really worth it.

One more high level look

After analyzing the code I see it can be decomposed into two methods:

public static Song getSong(Context context, String songPath) { ... }
private static Song getSong(Cursor audioCursor) { ... }

Where the latter would be called once you successfully have obtained the audioCursor and that one would do the low level job.

Conclusion

My conclusion still is that the code overall is fine minus the coding style issues, but these improvements would improve it.
I think it is also better than a Singleton class, because this to me simply looks like an utility method, hence warranting a place in a AudioUtils class, but I do not see a reason for a Singleton class for this.


interface design for allowing custom parameter struct, falling back on defaults

It sounds like your primary problem right now is memory management — you're worried about how to use dynamic memory allocation without leaks or double-frees. C++ has a solution for that!

class FlyCamera {
public:
    FlyCamera(/* position, gaze, etc params */,
              std::unique_ptr<FlyCameraKeyParams> keyParams = nullptr) {
        if (keyParams == nullptr) {
            keyParams = std::make_unique<FlyCameraDefaultKeyParams>();
        }
        mKeyParams = std::move(keyParams);  // take ownership
    }

private:
    std::unique_ptr<FlyCameraKeyParams> mKeyParams = nullptr;
};

The destructor of unique_ptr<T> takes care of calling delete on the owned pointer (which will call the proper derived-class destructor as long as you've made the base-class destructor virtual).

However, for this particular problem, I don't see why you want a whole polymorphic class for FlyCameraKeyParams. Have you considered flattening things out into a more "C-like" style?

The name of the class should tip you off: I understand a desire for generic KeyBindings or something; but if your FlyCameraKeyParams are literally nothing more than Params to the FlyCamera, then you should make them params to the FlyCamera. Parameterizing the behavior of a concrete class is generally done by setting member variables.

Bonus: FlyCameraDefaultKeyParams describes the defaults of the key params of FlyCamera. So with C++11 member-variable-default-initializer syntax, we flatten that class away as well.

class FlyCamera {
public:
    FlyCamera(/* position, gaze, etc params */) { ... }

    void setFlyForwardKey(int k) { mFlyForwardKey = k; }
    void setFlyBackwardKey(int k) { mFlyBackwardKey = k; }

private:
    int mFlyForwardKey = 'W'; // Self-documenting defaults!
    int mFlyBackwardKey = 'S';
    // ...
};

Notice in passing that I removed your virtual destructor from FlyCamera and made the protected members private, just to discourage people from inheriting from it. If you really need to allow inheritance, go ahead and put the virtual stuff back.


Nitpicking
I find your table aliases to be difficult to follow. Take this with a grain of salt coming from an outsider to your organization. I find eact, eact3, eact4, etc. to be a bit confusing, for example. Granted, if there is an internal, consistent standard, disregard this part.
SELECT DISTINCT
This is a pretty expensive operation, and usually better to use GROUP BY instead. That way you run your uniqueness check on the result set instead of the source data set (which could be a LOT larger) and only on the columns you think/know may have duplicate values. For example:
GROUP BY est.id, est.trackingNumber, actTypes.NAME

Create a stored statement
Given the look of this whole script, this doesn't smell like an ad-hoc query to me. Assuming that's accurate, you would benefit from creating a stored statement, in this case likely a stored procedure. This commented line at the bottom kind of gave me a hint:
-- AND est.id = 6266

For example:
CREATE PROCEDURE FooBar
    @Establishment_ID INT
AS
BEGIN
/* your query here */
AND est.id = @Establishment_ID    -- your commented line
ORDER BY 'LatestCreatedOrModified' DESC
END;
GO

Then, whenever needed:
EXEC FooBar 6266;

This way, the execution plan will be stored after it is called for the first time, speeding up (sometimes dramatically) execution after it is ran once.
Compliments
I have to note that your formatting, capitalization and aliasing are consistent. Kudos for that.
The elephant in the room
To me, the slowness of this query could be largely due to multiple levels of nested subqueries, each with multiple join operations. It appears that you join the same tables over and over, and this could be mitigated to some extent by having your nested where clauses in your outer query, whenever possible.
This:
    FROM SACPAN_EstablishmentActivities eact3 --(1)
    INNER JOIN SACPAN_ActivityTypes at3 -- (2)
        ON eact3.activityType_FK = at3.code
    INNER JOIN SACPAN_Status stat3 -- (3)

That:
        FROM SACPAN_EstablishmentActivities est4 -- (1)
        INNER JOIN SACPAN_ActivityTypes at4 -- (2)

And the other:
INNER JOIN SACPAN_EstablishmentActivities eact -- (1)
    ON est.id = eact.establishment_FK
INNER JOIN SACPAN_ActivityTypes actTypes -- (2)
    ON eact.activityType_FK = actTypes.code
INNER JOIN SACPAN_Regions reg
    ON est.region_FK = reg.code --
INNER JOIN SACPAN_Municipalities mun
    ON est.municipality_FK = mun.code
INNER JOIN SACPAN_ContactEstablishments ce
    ON ce.establishment_FK = est.id
INNER JOIN SACPAN_Contacts con
    ON ce.contact_FK = con.id
--JOIN SACPAN_Status stat -- (3)

Notice I've commented out where you are joining all the same tables. You could more than likely work most these conditions into your where clause and avoid unneeded overhead. It's impossible for me to test it out, since I don't have access to your DB, but try to eliminate subqueries/CTEs as much as you can help it.


How can I refactor the validation code to minimize it?

Exception handling
You may want to consider reducing the try block to where the expected exception actually is raised.
try:
    app = App.objects.get(id=app_id)
except App.DoesNotExist:
    …

Possible bugs
This test does not consider the case, that only one of addr and secret is None. Is that permitted?
if addr is None and secret is None:
    …

These response dicts are never used:
if wallet.pk is None and wallet.pk > 0:
    response = {'status': 'OK', 'data': 'success'}
else:
    response = {'status': 'FAIL', 'data': 'Messed up'}

Deduplication
Regarding your concern of duplicated dicts: I see none.
Sure, they are similar, but there are no duplicates, since the error messages differ. Of course, you can outsource the generation to a function like
def make_response(data: str, success: bool) -> dict:
    """Returns a response dict."""
    return {'status': 'OK' if success else 'FAIL', 'data': data}

but it's up to you to decide if that's worth an extra function.


Creating a page number array for pagination

1. Review

The function needs a docstring to explain what it does, with maybe some examples. The explanation in your post is very good: this is exactly the kind of thing that should go into the docstring.
The number 5 is arbitrary, so I would make it a parameter to the function.
The implementation takes time proportional to the number of entries in the page range. It would be more elegant to compute the endpoints of the range directly, taking constant time.

2. Revised code

def page_range(page, last, span=5):
    """Return a range of page numbers around page, containing span pages
    (if possible). Page numbers run from 1 to last.

    >>> list(page_range(2, 10))
    [1, 2, 3, 4, 5]
    >>> list(page_range(4, 10))
    [2, 3, 4, 5, 6]
    >>> list(page_range(9, 10))
    [6, 7, 8, 9, 10]

    """
    return range(max(min(page - (span - 1) // 2, last - span + 1), 1),
                 min(max(page + span // 2, span), last) + 1)


Searching within a data model using an array matching multiple terms

You have picked a hard data structure and hard algorithm to solve it.  Specifically, you have your searchable list as a list of strings and need to parse and convert it for each search.  You then do linear searches.

If you are going to precompute or cache your search information, consider creating a dictionary where the keys are the words and the values are sets of item indices.  Then you search is anding the set of indices with the value of each word.

Alternately, if you are optimizing for code brevity, use a regular expression. If your search strings were like ':MyName:MyType:MyBatch:' You want to create an expression from your search like :(word1|word2|word3): and use

NSUInteger numberOfMatches = [regex numberOfMatchesInString:string
                                                    options:0
                                                      range:NSMakeRange(0, [string length])];

and make sure it matches the number of words.   Yes, more work if you want to avoid the, er, inventive user, searching for "MyBatch MyBatch MyBatch".

Keep trying to make it prettier :)


Determining if there is data left after fetching a page of data

You should be aware that

return (new ArraySegment<T>(data, 0, count), data.Length > count);

throws an exception if count > data.Count()

The normal Take() doesn't behave that way - it takes min(count, data.Count())

One way to go could be:

public static IEnumerable<T> TakeWithRemainder<T>(this IEnumerable<T> sequence, int count, out bool hasMoreData)
{
  bool moreData = false;

  IEnumerable<T> Iter()
  {
    int i = 0;
    foreach (T value in sequence)
    {
      if (i < count)
      {
        yield return value;
      }
      else
      {
        moreData = true;
        yield break;
      }
      i++;
    }
  }

  var result = Iter().ToList();
  hasMoreData = moreData;
  return result;
}

Another way could be:

public static IEnumerable<T> TakeWithRemainder<T>(this IEnumerable<T> sequence, int count, out bool hasMoreData)
{
  hasMoreData = sequence.Skip(count).Any();
  return sequence.Take(count);
}

Or if you want to take a sub sequence not at the start:

public static IEnumerable<T> TakeWithRemainder<T>(this IEnumerable<T> sequence, int skip, int count, out bool hasMoreData)
{
  sequence = sequence.Skip(skip);
  hasMoreData = sequence.Skip(count).Any();
  return sequence.Take(count);
}

Or if you want to take page number n of m:

public static IEnumerable<T> TakeWithRemainder<T>(this IEnumerable<T> sequence, int page, int count, out bool hasMoreData)
{
  sequence = sequence.Skip(page * count);
  hasMoreData = sequence.Skip(count).Any();
  return sequence.Take(count);
}


Coding style and best practice regarding exception-handling

The way you are handling the exception will result in the method returning normally whether or not the method has succeeded.  This is bad API design.  Better design would be to either return some special value to indicate failure or (better) to allow the exception to propagate, or throw a different one.

Catching Exception is usually a bad idea.  The problem is that you may end up catching all sorts of unexpected exceptions.

Unconditionally writing stacktraces to standard output is bad practice.  Use a logging system; e.g. java.util.logging, log4j, etcetera.

Here is an alternative version that avoids these problems:

public Comics add(Comics comics) throws ... {
    EntityManager em = EMF.get().createEntityManager();
    EntityTransaction tx = null;
    try {
        tx = em.getTransaction();
        tx.begin();
        em.persist(comics);
        tx.commit();
    } finally {
        try {
            if (tx != null && tx.isActive()) {
                tx.rollback();
            }
        } finally {
            em.close();
        }
    }
    return comics;
}


method to decide if two strings are anagrams

Bug
Your algorithm is not quite correct.  For example:
areAnagrams("abc",  "abc")  -> true  (correct)
areAnagrams("abc",  "abcd") -> true  (wrong)
areAnagrams("abcd", "abc")  -> false (correct)

The problem is that you are checking that the characters in s1 exist with the same frequency in s2.  But there can be characters in s2 that do not exist in s1 and you don't check for those.
An easy way to remedy this would be to check that both strings have the same length.  This plus the frequency check you are already doing should ensure that the strings are anagrams.


Beginner jQuery – Coding Fundamentals / Performance

A couple of things:

Anytime you compare to 0 (zero) you want to make sure you use the exactly equal operator === instead of ==.  What would make your code even more expressive is doing something like if(tar.val().length){} .  This way your code is saying is "if the value of tar is blank then do this"
I'd also bring the last line to the top of your function and place it under the var loc statement.  The functions will be hoisted above all that so they'll be there even if they are defined after the calls.
this could prob be re-factored into one function with a simple if/else statement checking the value of the field.
Instead of using the each to call the data function ,assuming you don't have any other events attached to blur event you could call blur explicitly at the end of your chain to invoke that functionality ...click(data).blur().
I would look into ANeves suggestions as well.


A case cursor == NULL does not free(out->data).
A test i > 1 is strange, and buggy. If i happens to be 1, you are leaking memory legend[0] points to.
Do not cast the result of malloc
Calling calloc in char *curstr = (char *) calloc(len+1, sizeof(char)); is an overkill:

sizeof(char) is guaranteed to be 1, and
the contents of curstr is immediately overwritten by strncpy, so its zero initialization was a waste of time.

The body of the loop spells out

    legend[i] = strdup(lgnd[i]);

in a very obfuscated way.
Given no context, it is very hard to see why do you need all that dynamic allocation at all.


Code to pass json data with WCF REST POST

Is my code is correct?

Yes, but it needs just some tweaks in some areas. The only part I need to noted is when you declaring a StringBuilder and you're creating multiple string objects then append them to the StringBuilder. for this, you misused the StringBuilder, and what you need to do, is to use StringBuilder directly, and don't create strings outside the StringBuilder. Everything else looks fine to me.

for the dynamic part, it's fine to use dyanmic then using strong typed objects if you know the exact structure of the returned JSON. You'll only lose some of debugging auto-complete feature (aka code IntelliSense), and everything must be written manually. If you don't use any castings (like what you've know), the datatype will be assigned at run-time (the compiler will decide it). But it'll be better to cast objects when needed.

  Are there any impact affect performance ?

Performance-wise, it actually performs almost same as strong typed objects with a slight margin of difference, you'll hardly even notice it. So, don't think too much about it.

  And if there are any advise or feedback for my code,

Yes, you can simplify it :

public void ImportJSON(Stream request)
{
    using (var reader = new StreamReader(request))
    {

        var model = JsonConvert.DeserializeObject<dynamic>(reader.ReadToEnd());

        var stringBuilder = new StringBuilder(string.Empty);

        foreach (var item in model.Headers)
        {
            stringBuilder.Append($"{(string)item.Header};");
        }

        stringBuilder.AppendLine();

        foreach (var item in model.Values)
        {
            stringBuilder.AppendLine($"{(string)item.value};");
        }

        var path = HttpContext.Current.Server.MapPath($"~/App_Data/tmp/{Guid.NewGuid().ToString()}.csv");

        // you can use it directly in new StreamWriter(HttpContext.Current.Server.MapPath($"~/App_Data/tmp/{Guid.NewGuid().ToString()}.csv"))

        using (var writetext = new StreamWriter(path))
        {
            writetext.WriteLine(stringBuilder);
        }

    }
}


db_data = {}

def create_info(db_data, …):
    …
    return db_data

new_db_data = create_info(db_data, …)

This feels plain wrong. Either your create_info function mutates data, or it generates some; but not both. Judging by the name, your function should create the dictionary it returns:

def create_info(data):
    …
    code = …
    return {'code': code}

db_data = create_info(my_dict)
print(db_data)

If you want to avoid passing data as a parameter to split_join and not use a lambda altogether, you can still define a nested function which will capture the needed variables:

def create_info(data):
    def split_join(field):
        return '_'.join(data.get(field).split()) if field in data else None
    …
    code = …
    return {'code': code}

db_data = create_info(my_dict)
print(db_data)

You can avoid calling split_join several times by using map:

def create_info(data):
    def split_join(field):
        return '_'.join(data.get(field).split()) if field in data else None
    name, first_name, last_name = map(split_join, ('name', 'first_name', 'last_name'))
    code = '_'.join(filter(None, [name, first_name, last_name])).lower()
    return {'code': code}

db_data = create_info(my_dict)
print(db_data)

What is interesting with that, is that you can feed the result of map directly to the filter:

def create_info(data):
    def split_join(field):
        return '_'.join(data.get(field).split()) if field in data else None

    code = '_'.join(
            filter(
                None,
                map(split_join, ('name', 'first_name', 'last_name'))
            )
    )
    return {'code': code.lower()}

db_data = create_info(my_dict)
print(db_data)

Last improvement would be to not rely on None being generated when there is no data available, but '' instead, since you’re only manipulating strings:

def create_info(data):
    def split_join(field):
        return '_'.join(data.get(field, '').split())

    code = '_'.join(
            filter(
                bool,
                map(split_join, ('name', 'first_name', 'last_name'))
            )
    )
    return {'code': code.lower()}

db_data = create_info(my_dict)
print(db_data)

Update According to your comment:

You can obviously remove the need for a nested function by switching back to a lambda:

def create_info(data):
    code = '_'.join(
            filter(
                bool,
                map(lambda field: '_'.join(data.get(field, '').split()),
                    ('name', 'first_name', 'last_name')
                )
            )
    )
    return {'code': code.lower()}

db_data = create_info(my_dict)
print(db_data)

But readability is becoming worse. In any case, it is often recommended to convert map + lambda into an explicit list-comprehension or generator expression instead. I’m choosing the generator expression here because we won't need an intermediate list:

def create_info(data):
    code = '_'.join(
            filter(
                bool, (
                    '_'.join(data.get(field, '').split())
                    for field in ('name', 'first_name', 'last_name')
                )
            )
    )
    return {'code': code.lower()}

db_data = create_info(my_dict)
print(db_data)


Optimizing Python loop with Numba for live load analysis

Just a few quick points on your code:

any future imports should be at the top of any code. Are you using this intentionally (2to3?) or this is leftover code?
your loop to generate test data overrides i in two secondary loops - this is bad coding practice.
you're using xrange, which is pretty much deprecated since Python 2.3. Are you really using Python 2.3 or you just have stuck with xrange?
no entry point aka if __name__ == "__main__": to demonstrate the start of your code, you have pieces of code scattered around your listing.
Your code as-is with the random function cannot prove Numba JIT nor caching will have any effect. My results for your functions show:

CacheInfo(hits=0, misses=665297, maxsize=0, currsize=0)
CacheInfo(hits=0, misses=1000, maxsize=0, currsize=0)

Which is to be expected with a random dataset. It's recommended to put a real dataset somewhere on the 'net for people to use.
SimpleSpanMoment uses a global variable L, you should rewrite the function to inject all variables (or create them inside the function) and not use global variables.
cstep_size is unused.

Hope this helps you move towards a better implementation, to solve the performance issue. Good Luck!


You could use an array of grades:

$grades = Array("F","F","F","F","F","F","D","C","B","A","A+");
if($_SESSION['numberQuestions'] == 10){
    if ($_SESSION['score'] <= 10 and $_SESSION['score'] >= 0) {
        $grade = $grades[$_SESSION['score']];
    } else {
        $grade = 'Unknown';
    }
}

Use the same method for the second test.


Is this a proper way to cancel an onMouseOver which uses setTimeout? (Vanilla JS)

Response to your prompt

  Due to my lack of knowledge in JS I would like to know if this is a proper solution.

This code sets attributes on the elements to store properties. While this works, it technically leads to invalid HTML1. Alternatives include using data attributes and setting properties on the variable representing the element. See responses to Custom attributes - Yea or nay? and  Associate Data With HTML Element (without jQuery)

Other review feedback

Many developers believe it is good to move all JavaScript code out of the markup. So instead of the onmouseover=... and onmouseout=... attributes, you could register those event handlers in the JavaScript using EventTarget.addEventListener()

document.addEventListener('DOMContentLoaded', function() {
  var image = document.getElementById('123');
  image.addEventListener('mouseover', rollover);
  image.addEventListener('mouseout', cancel);
});

With an approach like this, the this keyword inside the functions rollover and cancel refers to the element, so there isn't a need to accept the element as a parameter. If you did want to pass parameters to those functions, it could be achieved using partially applied-functions with Function.bind():

  //set context of 'this' to the image and pass string literal '123' as the first parameter
  image.addEventListener('mouseover', rollover.bind(image, '123'));

The id attribute can be used instead of .getAttribute('id').

So instead of this line:

var id = element.getAttribute("id");

the same can easily be achieved with:

var id = element.id;

This may make assigning that value to a new variable superfluous.

1https://stackoverflow.com/a/13041243/1575353


basically just cleaned up some redundant brackets, tags, added a comment and modified existing comments, fixed indentations etc. Then i ran it through JSLint(http://www.jslint.com/), enjoy :)!

$(document).ready(function() {
    $('nav a[href^="#"]').bind('click.smoothscroll',function (e) {
        e.preventDefault();
        var target = this.hash,
        $target = $(target);
        $('html, body').stop().animate({
            'scrollTop': $target.offset().top
        }, 900, 'swing', function () {
            window.location.hash = target;
        });
    });
    $('a[href=#top]').click(function(){
        $('html, body').animate({scrollTop:0}, 'slow');
        return false;
    });
    $(function() {
        $("nav select").change(function() {
            window.location = $(this).find("option:selected").val();
        });
    });

    //place ID's of all required fields here.
    required = ["name", "email", "message"];
    //if using an ID other than #email or #error then replace it here
    email = $("#email");
    phone = $("#tel");
    errornotice = $("#error");
    //the text to show up within a field when it is incorrect
    emptyerror = "Required field.";
    emailerror = "Invalid email.";
    nameerror = "Name";
    phoneerror = "Phone";
    messageerror = "Message";
    onlynumber = "Invalid phone.";

    $("#contact").submit(function(){
        //validate required fields
        for (i = 0; i < required.length; i++) {
            var input = $('#' + required[i]);
            if (input.val() == "" || input.val() == emptyerror || input.val() == nameerror || input.val() == messageerror) {
                input.addClass("needsfilled");
                input.val(emptyerror);
                errornotice.fadeIn(750);
            } else {
                input.removeClass("needsfilled");
            }
        }
        //validate the e-mail.
        if (!/^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/.test(email.val())) {
            email.addClass("needsfilled");
            email.val(emailerror);
        }

        //validate phone
        if(phone.val() != phoneerror) {
            if (!/\(?([0-9]{3})\)?([ .-]?)([0-9]{3})\2([0-9]{4})/.test(phone.val())) {
                phone.addClass("needsfilled");
                phone.val(onlynumber);
            }
        }

        //if any inputs on the page have the class 'needsfilled' the form will not submit
        if ($(":input").hasClass("needsfilled")) {
            return false;
        } else {
            errornotice.hide();
            return true;
        }
    });

    //clears any fields in the form when the user clicks on them
    $(":input").focus(function(){
       if ($(this).hasClass("needsfilled") ) {
            $(this).val("");
            $(this).removeClass("needsfilled");
       }
    });

    $(function(){
        $('input, textarea').each(function(){
            var txtval = $(this).val();
            $(this).focus(function(){
                $(this).val('')
            });
            $(this).blur(function(){
                if($(this).val() == ""){
                    $(this).val(txtval);
                }
            });
        });
    });
});


To me it looks like you should move the if (result) into each one of  promptUserToPickFromDuplicatePersons, selectPersonFromDuplicatePersonLookup and addAsParticipant and add a method:

function handleError(e( {
    console.log(e.stack);
    return self.createOdsPerson()
           .then(self.addAsParticipant.bind(self, redirect));
}

Then you can rewrite the code as:

self.getPotentialPersonDuplicates()
  .then(promptUserToPickFromDuplicatePersons)
  .then(selectPersonFromDuplicatePersonLookup)
  .then(addAsParticipant )
  .catch(handleError)
  .then($ui.stopWaiting);

You could also look at the Bluebird promise library


Approximate String Matching Interview Question

1.I would use something like "APPROXIMATE BOYER-MOORE STRING MATCHING" described here:

http://www.cs.hut.fi/~tarhio/papers/abm.pdf

2.The second option is the Suffix Tree Solution:

http://homepage.usask.ca/~ctl271/810/approximate_matching.shtml

The Suffix Tree approach to the k-mismatch problem is essentially the same as the approach taken when matching with wild-cards; though in this case k is the number of allowable mismatches rather than the number of wildcards. The algorithm proceeds by executing up to k constant-time lce queries for each position i in the text. If the the lce queries span the end of P, then P occurs starting at position i of the text.

for i = 1; i < m-n+1; i++
  1. j = 1, i′ = i, count = 0
  2. l = lce (P[j], T[i′])
  3. if j+l = n+1, P occurs in T at i with only count mismatches; continue next i;
  4. if count ≤ k, count++, j = j+l+1, i′=i′+l+1, go to 2
  5. if count = k+1, then a k mismatch of P does not occur at i; continue next i;

An alternate approach, when both k and the alphabet size are relatively small is to generate all permutations of P with up to k changes and then search for each of these permutations in the tree. This would run in time O(P′ + m), where P′ is the combined length of the permissible permutations of P.


Best way to do unknown number of nested v-for loops, or how to do while loops in VueJs (is there a "v-while"?)

There is no v-while, no. You can however use v-for over a computed property (which you can compute using while if you so wish).
Although I don't see a reason to use any while-loop. What you have is a data structure with topics and subtopics of any arbitrary length. Using a recursive component for this, which you have done here, is a good choice.
About the only thing that I would change is to, instead of using arritem[0] and arritem[1], using an object with properties name and children. This can possibly also help you determine if a component has any children or not.


Assign Specific Value If BitField Is True

This looks like a good candidate for a 'case' selection statement:

SELECT  @ct1 = case when TypeDaily = 1 then 1 else 0 end,
        @ct2 = case when TypeTerm = 1 then 2 else 0 end,
        @ct3 = case when TypePerformance = 1 then 3 else 0 end,
        @ct4 = case when TypeWeather = 1 then 4 else 0 end,
        .....
FROM    ReportTable
WHERE   ReportSelectionId = @ReportSelectionId;

Note, you seem to have an extra , at the end of your selection list.

Using the above system there is no need for the if-conditions.

An alternate syntax which reduces the process to arithmetic, would be:

SELECT  @ct1 = 1 * isNull(TypeDaily,0),
        @ct2 = 2 * isNull(TypeTerm, 0),
        @ct3 = 3 * isNull(TypePerformance,0),
        @ct4 = 4 * isNull(TypeWeather,0),
        .....
FROM    ReportTable
WHERE   ReportSelectionId = @ReportSelectionId;

In the past (before the case statement was available) I used to do calculations like the above, but depending on the circumstances, it can be less readable than the case. In this instance, I think the case is still better.