Your code does not follow naming conventions (private fields should be camelCased, and usually have an underscore prefix; parameters should be camelCased)
there is no need in private properties, use fields instead (ConnectionString)
It is not an asynchronous version of SQL access, it is multithreaded access. The difference is that you don't necessarily need to span new threads (and you should not, in fact) to make your code asynchronous.
Stopping a thread using Thread.Abort is discouraged, and in general is very dangerous as it may lead to leaked resources and a lot of other side effects. It was explained in a lot of places, e.g. How To Stop a Thread in .NET (and Why Thread.Abort is Evil)
Killing a previous SQL action upon running the new one is the best way to get random issues all over your application
You don't provide any means to control the execution of asynchronous request, so calling code has no idea whether SQL finished execution
And finally, AsyncSqlCall<T> method should not have Action<T> Callback parameter as it is a continuation action, you should return Task<T> instead (so that caller can add a continuation)

I don't like custom ORMs and would suggest you to use Entity Framework or NHibernate as a data layer, but as an exercise here are the fixes I would apply (.NET 4.5):

public class SqlAsync
{
    private readonly string _connectionString;
    public int Timeout { get; set; }

    public SqlAsync(string connstring)
    {
        _connectionString = connstring;
        Timeout = 30;
    }

    public Task<T> AsyncSqlCall<T>(string sp, Func<SqlDataReader, Task<T>> handleResult, Dictionary<string, object> parameters = null)
    {
        return AsyncSqlCall<T>(sp, (reader, token) => handleResult(reader), CancellationToken.None, parameters);
    }

    public async Task<T> AsyncSqlCall<T>(string sp, Func<SqlDataReader, CancellationToken, Task<T>> handleResult, CancellationToken cancellationToken, Dictionary<string, object> parameters = null)
    {
        using (SqlConnection conn = new SqlConnection(_connectionString))
        using (SqlCommand cmd = new SqlCommand(sp, conn))
        {
            cmd.CommandTimeout = Timeout;
            cmd.CommandType = CommandType.StoredProcedure;

            if (parameters != null)
            {
                foreach (KeyValuePair<string, object> kvp in parameters)
                    cmd.Parameters.AddWithValue(kvp.Key, kvp.Value ?? DBNull.Value);
            }

            await conn.OpenAsync(cancellationToken);

            using (SqlDataReader rdr = await cmd.ExecuteReaderAsync(cancellationToken))
                return await handleResult(rdr, cancellationToken);
        }
    }
}


Find a Id that contains all mentioned values

You can use a HAVING clause to filter your GROUP BY result.

SELECT CategoryId
FROM ModeTester
WHERE Mode IN ('H', 'W', 'R')
GROUP BY CategoryId
HAVING Count(CategoryId) = 3


You might want to check that the input of stringValuesToFloats is valid (that every row has the same number of columns).

If you do that, you should document this behavior in ReadFromCsv.

Replace all for foo, _ := range … by for foo := range …. When you're not using the second argument, you don't need to discard it explicitly.

But instead of iterating on values, you could iterate on stringValues, and the inner loop could be for colIndex, s := range …, and you could use s instead of stringValues[rowIndex][colIndex].

var err error = nil → var err error.
When a function returns something, error and you want to return an error, you usually return the default value of something along with the error. So in stringValuesToFloats, you would return nil, err rather than values, err. This helps you make sure that you're not going to use the return value when you return an error.
Instead of printing the error with fmt.Println, you probably want to use log.Errorf and add an error message. Or not print anything at all and let the callers deal with the error (after all, it's why you return it), possibly returning fmt.Errorf("stringValuesToFloat: couldn't parse value %s", err) instead of just err.
Close the file after usage. Add defer file.Close().
Use a csv.Reader with option TrimLeadingSpace instead of trimming whitespace by hand. Your CSV file shouldn't have space after values (arguably, it shouldn't have spaces anywhere).
On "does this look like Go", I'd say you have too much whitespace (empty lines in functions are seldom used), line returns (you never see them right after declarations (:=) or assigments (=)), and your variable names are Java-level verbose. In Go, you would use i instead of rowIndex, floatArray instead of make2dFloatArray, ConvertCSV instead of ReadFromCSV, etc.

And, no, there's no easy way to have something more dynamic that float64, unless you have a specific use case in mind (and then, you would use an interface, but this is out of scope for this question). See this for a detailed discussion on why Go doesn't have generics for now.


Callback/Promises implementation for a boolean check

Assuming you're using Node.JS v6.x, or lower but with babel (this is ES6 syntax):

function saveTask(req) {
  // Always return a promise.
  return new Promise((resolve, reject) => {
    // Build a task.
    const _id = mongoos.Types.ObjectId();
    const task = new Task({
      _id, // Not a mistake. it's valid ES6 code.
      taskname: req.body.name,
      teamid: req.body.team,
      content: req.body.content,
      createror: req.user.userId
    });

    // Save it.
    task.save((err) => {
      if (!err) {
        log.info('New task created with id: %s', _id);
        // Resolve promise with task.
        // If you don't actually need task, you could
        // resolve(req); // to pass req along.
        resolve(task);
      } else {
        log.error('Internal error(%d): %s', err.code, err.message);
        // Reject promise with err.
        reject(err);
      }
    });
  });
}

// Utility function to run a specific code sequence.
const postTask = (req) => valTeam.isMember(req).then(saveTask);
// If `valTeam` is not a module library, then this might be better:
// const postTask = (req, valTeam) => valTeam.isMember(req).then(saveTask);
// and call with `postTask(req, valTeam)`

And here's the isMember() function

/**
 * Utility function to replace:
 *
 * if (req.body.team) { ... }
 *
 * with a promise.
 */
const hasTeamId = (req) => new Promise((resolve, reject) => {
  if (req.body.team) {
    // Has team id. Pass `req`
    resolve(req);
  } else {
    reject(new Error('No team id provided'));
  }
});

// Function isMember() always returns a promise
module.exports.isMember = function (req) {
  const teamid = req.body.team;
  const userid = req.user._id;

  // Internal utility function to check if a given team it exists.
  const checkTeamExists = (req) => {
    // Execute query
    Team.findOne({'_id': teamid, $or:[{'creator': userid }, {'userlist': { $in : [userid]}}]}, function(err, result) {
      // On callback, solve the promise.
      if (!err && result) {
        // No error, and at least 1 document in results.
        // Resolve promise.
        resolve(req);
      } else {
        // 1) Either error, or
        // 2) No error, but empty results => Create a new error.
        // Reject promise.
        reject(err || new Error('404 - Not found'));
      }
    });
  };

  return hasTeamId(req).then(checkTeamExists);
};

Also, if you have Mongoose 4.x+ which supports Promises, better use this:

// ALTERNATIVE FOR MONGOOSE v4.x+
// Function isMember() always returns a promise
module.exports.isMember = function (req) {
  const teamid = req.body.team;
  const userid = req.user._id;

  // Internal utility function to check if a given team it exists.
  const checkTeamExists = (req) => {
    // Execute query ( In mongoose 4.x+, queries return Promises )
    return Team.findOne({'_id': teamid, $or:[{'creator': userid }, {'userlist': { $in : [userid]}}]})
      .then((result) => {
        // On callback, solve the promise.
        if (result) {
          //at least 1 document in results.
          return req;
        } else {
          // not found.
          throw new Error('404 - Not found');
        }
      });
  };

  return hasTeamId(req).then(checkTeamExists);
}

Finally, use the above like so:

postTask(req)
  .then((task) => {
    // Successfully saved task.
    // Handle task, if needed, otherwise just remove the `then()` branch.
  })
  .catch((err) => {
    // Some error occured, either in `isMember` or in `saveTask`
    // Handle error, if needed, otherwise just remove the `catch()` branch.
  });


Function to check truth value of a specific statement

Make the function return True or False.
You can use all and a generator comprehension instead of returning early.
You should make the range have the same input.

Putting these together you can get:

def check_truth(bits):
    return all(
        x + y == (x | y) + (x & y)
        for x in range(bits ** 2)
        for y in range(bits ** 2)
    )

print("{} for {} bits".format(check_truth(bits), bits))

The simplest way to prove:

$$x + y = (x \land y) + (x \lor y)$$

Is to think of integers as a bunch of wires that are passed to an infinite full adder. Due to how full adders work, they will not care how the bits are placed, as it makes no logical difference to its functionality.
So \$010 + 101 = 111 + 000\$, which means as long as we know there are the same amount of bits on each section of the equation, then we know they are the same.
Since we know \$a = x \lor y\$ and \$b = x \land y\$, we can test if there are any missing or new bits.
And so using the following 'table' shows that each level will have the same amount of bits:

$$
x, y, a, b\\
0, 0, 0, 0\\
1, 0, 1, 0\\
0, 1, 1, 0\\
1, 1, 1, 1\\
$$

And so to get the best performance we can re-write check_truth:

def check_truth(bits):
    return True

To make a more compelling argument, we could sub \$a\$ and \$b\$ into a full adder equation, and show there's no difference, but if you think about this logically you should notice it's always true.

$$
S = C \oplus (A \oplus B)\\
C_1 = ((A \oplus B) \land C) \lor (A \land B)
$$

Sub \$A = x \lor y\$ and \$B = x \land y\$:

$$
S = C \oplus ((x \lor y) \oplus (x \land y))\\
C_1 = (((x \lor y) \oplus (x \land y)) \land C) \lor ((x \lor y) \land (x \land y))
$$

Simplify some things:

$$
(x \lor y) \oplus (x \land y) = x \oplus y\\
(x \lor y) \land (x \land y) = x \land y
$$

Sub simplified versions into main function:

$$
S = C \oplus (x \oplus y)\\
C_1 = ((x \oplus y) \land C) \lor (x \land y)
$$

See that it works the same way.


Check deep object property and find duplicate value

A very fun question, which took way too much time to analyze ;) It would have helped tremendously if you could have given a sample JSON instead of a screenshot.

Regardless, if you are using lodash anyway, you might as well leverage it all the way. By trying the different functions provided by lodash you start thinking differently about data structures.

The code I proposes flattens the array you are getting so that you just have a list of entries. Then it gets the properties from the entries, which it flattens again to have a nice searchable array. Then it counts the paths and checks for dupes, then it checks whether any dupe was found.

Instead of having the full Promise code, I will provide the essence:

var configObj = [{
  "providers": [{
    "replace": {
      "path": "command1",
      "function": "updateResources",
      "method": "post"
    },
    "save": {
      "path": "test2",
      "function": "updateResources",
      "method": "post"
    }
  }]
}];

var providers = _.values(configObj);
var entries = _.flatMapDeep(providers, _.values);
var props = _.flatMapDeep(entries, _.values);
var counts = _.countBy(props, 'path');
var dupe = _.findKey(counts, count => {
  return count > 1;
});
console.log(dupe ? dupe : 'No dupe found');
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.14.1/lodash.min.js"></script>

The nice thing about this approach is that if you wanted to change the functionality and log all the dupes at once, you could.


Script that retrieves trending topics from Twitter

Structure: Cache Class

You already noted it yourself, you have some duplication. You could get rid of it by introducing some loadTweetFromCache function, but ideally, you would extract the whole cache handling code to its own class (and maybe have an additional twitter specific cache function or class).

Right now, if you want to change how the cache works, you would need to do that all over the place. And if you want to cache other things, you would again duplicate code.

So instead, create a Cache class that can load and store cache entries.

Structure: Logic

  Wouldn't it be better if the code tried to get the trending topics directly from Twitter, resorting to the cache if it can't right off the bat?

It really depends. You would still spam twitter with requests if you handled it like that, so it's probably not the best approach.

Still, it takes a while to see when what is happening in your code, because of the nested ifs, the exit, and the check for the trends variable.

Because of this nesting, it's also easy to miss errors. For example: If your cache file doesn't exit, and the rate limit is exceeded, nothing happens. There is no feedback for this at all.

I would probably go with a structure like this:

// the used variables are either class variables or just passed as arguments
function getTwitterTrends() { // throws some kind of exception if trends could not be loaded from cache
    if (!$twitterCache->isStale()) {
        return $twitterCache->getTrends();
    }
    try {
        $trends = $twitterAPI->getTrends();
    } catch (RateLimitException $rle) {
        return $twitterCache->getTrends(); // couldn't retrieve new trends, use stale cache
    }
    $twitterCache->storeTrends($trends);
}

Now it's pretty clear when what is happening (of course, you have a lot more function calls, but the code clarity should be worth it).

Security

You are open to directory traversal via location-code.

In your case, that isn't all that bad, but it should still be fixed. What can happen is:

An attacker can read parts of files that have a .data extension and properly deserialize (not likely).
An attacker can check for the existence of any .data files (which may gain them some system knowledge or may aid in further attacks, but which isn't that serious).
If you have a file upload that allows the uploading of files with a .data extension an attacker can gain object injection (which may be serious, depending on the rest of your code).

Note that the .data extension limitation does not apply to old PHP versions that are vulnerable to null byte poisoning or path truncation.

Also, your echo is vulnerable to XSS.


You are making your class variables readonly which is good because they won't change.

what I don't like is your mixing of the bracing style. Sometimes you use the Allman style, sometimes the K&R and sometimes another style.
Usually in C# one would expect to see Allman style only. If you want to use another style, that is pretty fine as long as you stick to it.

the exception handling like you are doing it is superfluous and is destroying the stacktrace. Please read: is-there-a-difference-between-throw-and-throw-ex
Because you are never handling the exceptions you could just remove the try..catch completely.


I'd look at python decorators as something, that accepts function and returns function, which is usually original function wrapped in another function and some added behaviour.

Change signature of your "decorator" functions to match that and you got something like decorators. Don't have much time at the moment to write examples, but you get the idea :-)

Edit:
I took a closer look at your code, but it seems very specific to your framework and I can't make complete sense of it to dare refactoring (doesn't mean it's bad code). At least here are some examples of wrapper functions to help you started:
https://gist.github.com/harrylove/1230566/d064e5c216384d3846f73ed555e9899be02e8f98


Your implementation is quite fine. Some minor improvements are possible.

The insertionsort method doesn't need to return the array. It's not required by the problem, and it's pointless anyway, as the method modifies the input array.

In the main method you called the array array. That's not a very useful name, too generic.  Inside insertionsort it's even worse just the letter a. A better name in both places would be for example nums.

The inner while loop would be better as a for loop. The reason is, with a for loop it's easier to not forget to decrement the loop variable:

for (; j >= 0 && nums[j] > key; --j) {

Also, you set j = i - 1, and then you have to remember to use a[j + 1] in two places. It would be slightly simpler to use j = i and rearrange the rest accordingly.

Lastly, the printing of the array really belongs to a separate helper method.


You have a few challenges here.

As you say, pagination will be wonky if a user's status/score changes between page requests. You could use fragment caching to cache the rendered pages, and serve the same content to all users for a fixed period of time. But this has a different drawback: Rendering is lazy, so page 2 (or 3, or N) will only be cached if someone requests it. So that's the same problem as before; sorting may change. Also, if the cache updates between page views, it doesn't matter that you're using a cache, since it's not that same cache version as was used in the previous request.

So what you'll want to do is run something that periodically rebuilds/-queries the entire list, a multi-version cache, and a way to lock a user into a specific version for his/her subsequent page views.

The tradeoff (besides more work) is that the list will be stale after a while.

An example of this is stackexchange's rep leagues tables which, while based on score, lags a bit behind actual score. You can decide whether that's worth the tradeoff.

Now, for querying periodically, I'd recommend

using an ActiveJob task to do the querying at fixed intervals
storing multiple versions of the query results as a hash in Rails.cache, using a timestamp as key for simplicity
a way of cleaning out old results, so stuff doesn't keep accumulating
adding a param to page requests to identify the active cache version/timestamp (if blank, serve the latest)
some means of telling the user "we're serving you a snapshot of this list as of [time and date]" - and a way of saying "the snapshot you requested is too old, and we've thrown it away"

In the end, it's simpler to only show unpaginated (but limited to top-N) lists with no caching. Or show lists that use a (more) stable sorting parameter (e.g. user name).


Here's my two cents:

Do not using namespace std;.  It causes serious problems and is considered bad practice.  See Why is using namespace std; considered bad practice?.
Consider wrapping your class in a header so that it can be reused.  Use an include guard.
MinHeap is a common name that may cause name clash.  Consider placing it in a namespace.
MinHeap only supports ints.  You can make MinHeap a template.
Right now MinHeap can only be default initialized to empty.  Consider adding a constructor to initialize the MinHeap with a list of values.
Your comments apply to the function, instead of the first line of the function body.  They should really go outside the function.

// this function foos the bar
void foo(int bar)
{
    ...
}

You use int for indexes.  This is not good because int may be too narrow — INT_MAX may be as small as 32767.  Use std::size_t instead.
All of your functions that return an index have the suffix _index, except get_min_child.  I would suggest renaming it to min_child_index to be consistent.
Don't write the whole branch on the same line.  This decreases readability.  Instead of

if (2*index + 2 < heap.size()) return 2;
else if (2*index + 1 < heap.size()) return 1;
else return 0;

Do

if (2*index + 2 < heap.size())
    return 2;
else if (2*index + 1 < heap.size())
    return 1;
else
    return 0;

In left_child_index and right_child_index, ind can be computed in the if statement.  (C++17)
You swap(heap[0], heap.back()) then immediately heap.pop_back().  You are not doing heap sort, you are popping the value.  Just heap[0] = heap.back().
Incidentally, the standard library offers a couple of heap operations, and also priority_queue.  Maybe you can use them to simplify your implementation.


Recursive component JSON configuration builder

Good things

This code uses const for variables that don't get re-assigned.

The functions are concise, though some of the lines are a bit long due to ternary operators.

Suggestions

Bear in mind that functional programming is typically slower than imperative because each iteration leads to a function being added to the call stack. This would be noticeable with large data sets. Having the function addResult() seems like an excess step since it is only called in one spot. The lines to ensure the object at the given key is an array and push an element to that array could simply exist in the callback to the _.reduce() call.

Also, instead of either creating a new array with the data item or pushing it into an existing array, it could create an empty array when appropriate and then always push the data. This may be slightly less performant but requires fewer lines of code than storing the data in a temporary variable.

function createConfiguration(configuration) {
  return _.reduce(configuration.components, (result, data) => {
    const component = data.$ref ? getComponentByReference(data) : data;
    if(!result[component.key]) {
      result[component.key] = [];
    }
    result[component.key].push(component.components ? { ...component, components: createConfiguration(component) } : component)
    return result;
  }, {});
}

Unless you fully understand the ways Automatic semicolon insertion can be broken by certain statements, add semi-colons to terminate the lines.


View model using different datetime component

First of all I would advice to use DateTimeOffset instead of DateTime.

Use the time, date, datetime2 and datetimeoffset data types for new work. These types align with the SQL Standard. They are more portable. time, datetime2 and datetimeoffset provide more seconds precision. datetimeoffset provides time zone support for globally deployed applications.
Source: https://docs.microsoft.com/en-us/sql/t-sql/data-types/datetime-transact-sql?view=sql-server-ver15

Besides that; If you have to do a lot of mapping I would use AutoMapper.
The mapping profiles (where you can do some mapping configuration) would look like this:
  public class MeetingEventProfile : Profile
  {
    public MeetingEventProfile()
    {
        CreateMap<MeetingEvent, MeetingEventViewModel>()
            .ForMember(x => x.StartDateDayName, x => x.MapFrom(_ => _.StartDateTime.DayOfWeek))
            .ForMember(x => x.StartDateMonth, x => x.MapFrom(_ => _.StartDateTime.Month))
            .ForMember(x => x.StartDateDay, x => x.MapFrom(_ => _.StartDateTime.Day))
            .ForMember(x => x.StartDateYear, x => x.MapFrom(_ => _.StartDateTime.Year))
            .ForMember(x => x.EndDateDayName, x => x.MapFrom(_ => _.EndDateTime.DayOfWeek))
            .ForMember(x => x.EndDateMonth, x => x.MapFrom(_ => _.EndDateTime.Month))
            .ForMember(x => x.EndDateDay, x => x.MapFrom(_ => _.EndDateTime.Day))
            .ForMember(x => x.EndDateYear, x => x.MapFrom(_ => _.EndDateTime.Year));
    }
  }

You only see some specific mappings for properties that don't match by name (or require some conversion/etc). Property names that match you don't have to explicitly map; although there is a lot of configuration possible here!
In your logic (which is not poluted with mapping anymore) you would do something like this:
public class MyClass{
  private readonly IMapper _mapper;

  public MyClass(IMapper mapper){
    _mapper = mapper;
  }

  public void MyMethod(){
    var meetingVms = _mapper.Map<MeetingEventViewModel[]>(Meeting);
  }
}

The performance impact by using AutoMapper is very low; I did quite some benchmarks with high performance requirements and the impact was very low.
My example assumes you are using dependency injection. AutoMapper is very easy to implement. Otherwise you have to create the Mapper instance yourself which isn't hard too. The docs are well written: https://docs.automapper.org/en/stable/Dependency-injection.html


Perhaps or macro could be used here:

(defn get-data [query]
   (or (get-data-from-cache query)
       (get-data-service-1 query)
       (get-data-service-2 query)
       (get-data-service-3 query)))

or short-circuits, so the first match will return and the rest will not be evaluated


The search' could could be written more idiomatically (but not necessarily faster) as

search' [] = []
search' (x:xs) | goal x    = x : search' xs
               | otherwise = search' (succ x ++ xs)

The Eq constraint on searchDfs seems to be unused.
In succN, you are calculating sum+i'^d twice (unless the compiler optimizes that away, but it’s better not to rely on that). Also, it will calculate it for all values of i' until goal, although you probably want to abort early. Maybe using takeWhile would be better:

 succN (sum,i,d, goal) =
     takeWhile (\(s,_,_,_) -> s <= goal)
               [( sum+i'^d, i', d, goal) | i' <- [(i+1)..goal]]

It looks as if the d and goal field of your Nodes is always the same. Then you shouldn’t have it as part of the Node, but rather pass it around explicitly. You can do that without modifying searchDfs!


flvPlayerRef?
In the constructor, you have
this.myRef = React.createRef();
this.flvPlayerRef = element => {
  this.flvPlayerRef = element;
};

This is pretty confusing. The property is either a function or an element, depending on whether it was called as a function before, and either way, it's not a ref, so it's also misnamed. It also isn't used anywhere else in the code, and consumers of the instance already can get a reference to the <video> element through the myRef property.
I'd remove flvPlayerRef completely, and also rename the less-than-informative myRef property name to videoRef or to flvPlayerRef.
At that point, you can make things concise by using class fields instead of a constructor:
class ReactFlvPlayer extends Component {
  videoRef = React.createRef();

  componentDidMount() {
    // ...

You can also consider using a functional component instead of a class-based component, as React tentatively recommends for new code - but that's not required.
Destructured props
This line is hard to read:
const {type , url, isLive, enableStashBuffer, stashInitialSize, hasAudio, hasVideo, handleError, enableWarning, enableError} = this.props;

When there are more than 2 or 3 properties to be destructured, I'd recommend putting each on a separate line
const {
  type,
  url,
  isLive,
  // ...
} = this.props;

But, in this case, a significant fraction of the properties are used only to be passed into flvjs.createPlayer later. Consider using rest syntax to collect those options into a single object, without having to specify each one individually:
const {
  enableStashBuffer,
  stashInitialSize,
  handleError,
  enableWarning,
  enableError,
  ...createPlayerOptions
} = this.props;

The enableError variable is not used. If that's deliberate, best to not extract it from the props in the first place. Or maybe you meant to assign it to LoggingControl? Change
flvjs.LoggingControl.enableError = false;

to
flvjs.LoggingControl.enableError = enableError;

Nicer indentation Rather than creating another indentation block after checking if flvjs is supported, you can consider returning early if it's not supported:
componentDidMount() {
  if (!flvjs.isSupported()) {
    return;
  }
  const {
    enableStashBuffer,
    stashInitialSize,
    handleError,
    enableWarning,
    enableError,
    ...createPlayerOptions
  } = this.props;

  const flvPlayer = flvjs.createPlayer(
    createPlayerOptions,
    {
      enableStashBuffer,
      stashInitialSize
    }
  );
  // etc

Returning early is pretty nice, especially with more complex logic which would otherwise require multiple levels of indentation, which can get pretty hard to read.
Spacing There are a few places where I'd expect to see a space but don't see any given the code style in the rest of the script, or where I see spaces where there probably shouldn't be any, like const {type , url,, },{, (err)=>{, const { height, width, (do you want leading/trailing space when destructuring and with objects, or no?).
Whatever you want your code style to be, it would be good to be consistent - consider using ESLint to keep your style consistent, to fix things automatically, and warn you of potential bugs before they turn into runtime errors.


Should I be trying to imitate the control flow in this example R code?

In my opinion, this function is a nice example of R code. Your interpretation of the code is correct. One unnecessary command is y == 0 since the information is redundant given that x == "H" is already known. In this case, y == 0 is identical to c(TRUE, !(x == "H"), TRUE).

The code can be simplified. The object wz can be created more easily:

calc_streak <- function(x){
  wz <- c(1, which(x == "M") + 1, length(x) + 2)
  streak <- diff(wz) - 1
  return(streak)
}

Alternatively and probabily even more efficiently, you can create a logical index indicating the positions of the "M"s in the vector and calculate streak more directly:

calc_streak <- function(x){
  idx <- x == "M"
  streak <- c(!idx[1], diff(which(idx)) - 1, !tail(idx, 1))
  return(streak)
}

The ! sign indicates logical not. If numeric and logical values are combined in one vector, the logical values are cast into numeric values. TRUE becomes 1, FALSE becomes 0.


Updating register_globals code for importing $_GET and $_POST data

This seems a bit complex for relatively little benefit. Personally, from these two choices, I would go with the isset approach for simplicity and slightly improved performance.

But I do see your point about the default value, and the readability of the array structure. If you actually do have a lot of parameters which have a default value, your approach might have merit.

But since you are going through the trouble of updating legacy code anyways, you could also think about choosing a different approach and create an Input class. It would also result in readable code, and you could add input filters, increasing your security. The structure is really a matter of preference, but it might look something like this:

class Input {

    function getRaw($value, $default) { ... }
    function getInt($value, $default) { ... }
    function getSafeHTML($value, $default) { ... }
    function getFiltered($value, $default, $regex) { ... }
    ...

    function postRaw($value, $default) { ... }
    function postInt($value, $default) { ... }
    function postSafeHTML($value, $default) { ... }
    function postFiltered($value, $default, $regex) { ... }
    ...

    ...
}

It's then used like this:

$x  = Input::getInt('x', $xdefault);
$ab = Input::postCleanHTML('ab', $abdefault);

It's a bit more work, but it's readable, well structured, and provides additional security; filtering input should never be your main line of defense, but it is highly recommended as defense in depth (depending on the input of course; some input you want unaltered, which is why the getRaw method is there).

Misc

There's no need to pass the arguments by reference to _export. It gives off the impression that the function will change the values, which it does not (and should not, especially for $_GET).
if you are updating legacy code anyways, I would check if REQUEST is really needed. If it is not, change it to GET or POST to increase the security of the code even further.


Specify table data in code, reference objects

This class doesn't have any responsibilities, it just holds a group of static variables.  It is unclear what the purpose of these variables are.  I am sure there is a better way to achieve your goal as I doubt you actually need to be storing these details here.


Initialize a hash with all 0 values based on two arrays

Conceptually, that's the way to go. I'd just propose some small changes:

Use Array#to_h instead of Hash#[]
This line is too long, split it in multiple lines.

So I'd write:

scores = people.map do |person|
  person_scores = subjects.map { |subject| [subject, 0] }.to_h
  [person, person_scores]
end.to_h


Pretty fun little bit of code. Very neatly written as well. Only thing I would suggest would be to use .charAt(x) instead of using array indexers for your strings when you're comparing characters. Not a big deal but will improve compatibility among browsers and is a bit easier to read IMHO.

// Compare the two chars.
if (text.charAt(i) !== tumbleText.charAt(i))

Good stackoverflow post covers it in more detail here.


File upload in AngularJS causes browser out of memory error

Marshaling the file contents as a byte array is obviously problematic.

Browsers can easily upload files through HTML forms, with

<form method="POST" enctype="multipart/form-data">
  <input type="file">
</form>

Adapt the server to handle file uploads using that mechanism, then develop a replacement AJAX client.


Your code is lacking comments that explain the why, ideally every non-trivial math programme should include a brief description of the algoritmh used.


Pythonic way to select element in a list window

Write functions, improvements can range from faster code to the ability to reliably time or profile your code.
You don't need to use else if you're just using pass in that block.
Your code is WET, so it's not DRY. Instead of duplicating the code, you could instead assign to a variable in the if and else, to check against.
You may want to get into a habit of using if __name__ == '__main__':. In short, if you import the file it won't run the code.

This can get you:

def rename_me(l, seuil):
    new_l = []
    index = []
    for i, elt in enumerate(l):
        bound = 1 if elt > seuil else seuil
        try:
            if (l[i-1] and l[i+1]) > bound:
                new_l.append(elt)
                index.append(i)
        except IndexError:
            pass
    return index, new_l

A couple more things:

I think you have a bug, (l[i-1] and l[i+1]) > bound probably isn't doing what you think it is. It's only checking if l[i+1] is greater than bound. As 1 and 2 == 2 and 0 and 2 == 0 are both true. Instead you may want to use l[i-1] > bound < l[i+1].
I don't see why you'd need the indexes and the elements from the original list, and so you could instead just return one or the other.
You can change the function to be a generator function, as this reduces memory usage.
You could use a modified itertools.pairwise, to remove the IndexError.

from itertools import tee

def rename_me(l, seuil):
    a, b, c = tee(l, 3)
    next(b, None)
    next(c, None)
    next(c, None)
    for index, (i, j, k) in enumerate(zip(a, b, c), 1):
        if i > (1 if j > seuil else seuil) < k:
            yield index


Generate dictionary of points on n-sphere

Style
Following PEP8, the official Python style guide, you should use snake_case for your variables and functions names. You should also put a space after comas.
I would also rename the function sphere_points as the "get" is implied by the fact that you call a function (to get a result).
You also happen to not use the dim parameter and, looking at your description, the last one is just len(pList). Unless this length is common to a lot of calls and there is a real benefit to cache it, you can drop 2 out of 3 parameters.
numpy
numpy has vectorized functions  for your main operations: numpy.fabs (or numpy.absolute if you're dealing with complex numbers) and numpy.linalg.norm. Using these might speed things up. Unfortunately, going back into pure Python realm (dict + zip) can't be speed up that way.
However, as pointed out by @200_success in a comment, these answers suggest using np.sqrt(pt.dot(pt)) or np.sqrt(np.einsum('i,i', pt, pt)) for faster results than np.linalg.norm. As always, profile and choose what's best for your use case.
Cache function access
In Python, local symbols are faster to resolve. Which means np.linalg.norm is kinda slow, but norm is faster. And granted you performed norm = np.linalg.norm somehow before, it will produce the same result.
But caching a complex lookup within the same call you use it does not add much, since the complex lookup still need to be performed.
One way to efficiently do it is to use default values for arguments as the lookup will be performed only once and the speedup will occur at each call.
Proposed improvements
import numpy as np

def sphere_points(keys, random_gen=np.random.standard_normal, absolute=np.fabs, norm=np.linalg.norm):
    pt = absolute(random_gen(len(keys)))
    pt = pt/norm(pt)

    return dict(zip(keys, pt))


Is there any better way to fetch two tables in one statement or query?

SQL:

This is just a simple join.

SELECT e.Votes, e.Views, e.id, u.username
FROM election as e, userinfo as u
WHERE e.id= u.id WHERE e.ElectionId=?
ORDER BY e.id ASC

Now you can iterate over all lines and every time e.id is changing you know that you have to display a new group.

Are there really multiple users per Votes and Views pair? I guess Votes and Views are counting columns so your model is kind of strange. Maybe you can find better names, so it is easier to get an idea what you want to do.

PHP:

usually classes are starting with a capital letter.
usually methods are starting with a lower case letter.
there is something missing in your output, some echos?
it is best practice to skip the ?> at the end, do avoid sending whitespace in case you will change the page header later.
$call and world are really strange names


Bitmasking and searching consecutive 1's

<bits/stdc++.h> (like everything in your compiler's bits/ subtree) is not a standard header and therefore not portable.  Even if you're willing to sacrifice portability, it's a poor choice, as it will slow compilation down compared to simply including what you use.

using namespace std; is poor practice.  It makes your code less clear, and it may even silently change its meaning.

Don't use the preprocessor to name constants.  Use a properly scoped, strongly typed C++ constant:

constexpr std::size_t max = 100000;

When using input streams, always check that operations succeed before using their results.

Variable names should be more descriptive.  I have no idea what n, q, and k are supposed to be storing.  In fact, these names are so useless that I gave up reading at this point - it's not at all clear what this is supposed to be doing.


Generic error handler function for POSIX shell scripts

I'm a big fan of tput, which many script authors seem to overlook, for generating appropriate terminal escapes.  Perhaps my enthusiasm started back in the early '90s, when using idiosyncratic (non-ANSI) terminals, but it still glows bright whenever I run a command in an Emacs buffer or output to a file.

A style point, on which you may disagree: I prefer not to enclose parameter names in braces unless it's required (for transforming the expansion, or to separate from an immediately subsequent word).  So [ "$#" -ne 3 ] rather than [ "${#}" -ne 3 ], for example.  The braces aren't wrong, but do feel unidiomatic there.

A simple improvement: you can save a lot of doubled-backslashes in the printf format strings by using single quotes rather than double quotes (this also protects you against accidentally expanding variables into the format string).  I also find it easier to match arguments to format if I make judicious use of line continuation.  Example:
    printf '%s%b()\n\n\t%s%b%s\n\nexit code = %b%s\n' \
           "$bold_yellow" "$2" \
           "$nocolor" "$3" "$bold_red" \
           "$1" "$nocolor" >&2

The definition of is_number isn't shown in your example function, but something similar is written in full here:
# check if the first argument is a number
# if not, print out an internal error without colors
if ! [ "${1}" -eq "${1}" ] 2> /dev/null
then

I think it makes sense to have is_number for that test; it would certainly reduce the need for comments:
if ! is_number "$1"
then    # print out an internal error without colors

It probably makes sense to redirect output to the error stream once at the beginning of print_error_and_exit, since we won't be generating any ordinary output from this point onwards:
print_error_and_exit()
{
    exec >&2

That saves the tedium of adding a redirect to every output command, and neatly avoids the easy mistake of missing one.

When we test that tput succeeds, perhaps we should tput sgr0 without redirecting to null, so that the output device is in a known state (thus killing two birds with one stone)?
If tput works at all, then when its argument can't be converted, its output is empty, which is fine.  If we want to be really robust when tput doesn't even exist, then we could test like this:
tput sgr0 2>/dev/null || alias tput=true

Then we don't need a separate branch for the non-coloured output (we'll just output empty strings in the formatting positions).  That won't quite work as I've written it, unless we specifically export the alias to sub-shells, but we can more conveniently just use a variable:
tput=tput
$tput sgr0 2>/dev/null || tput=true

We might also choose to test that the output is a tty (test -t 1, if we've done the exec I suggested, else test -t 2).

$bold_yellow saves no typing compared to $bold$yellow, and it's only used once anyway, so it can easily be eliminated.  Same for $bold$red.

Modified code
Applying my suggestions, we get:
is_number()
{
    test "$1" -eq "$1" 2>/dev/null
}

print_error_and_exit()
# expected arguments:
# $1 = exit code
# $2 = error origin (usually function name)
# $3 = error message
{
    # all output to error stream
    exec >&2

    if [ "$#" -ne 3 ]
    then    # wrong argument count - internal error
        printf 'print_error_and_exit() internal error\n\n\tWrong number of arguments has been passed: %b!\n\tExpected the following 3:\n\t\t\$1 - exit code\n\t\t\$2 - error origin\n\t\t\$3 - error message\n\nexit code = 1\n' \
               "$#"
        exit 1
    fi

    if ! is_number "$1"
    then    # wrong argument type - internal error
        printf 'print_error_and_exit() internal error\n\n\tThe first argument is not a number: %b!\n\tExpected an exit code from the script.\n\nexit code = 1\n' \
               "$1"
        exit 1
    fi

    # if tput doesn't work, then ignore
    tput=tput
    test -t 1 || tput=true
    $tput sgr0 2>/dev/null || tput=true

    # colors definitions
    readonly bold=$($tput bold)
    readonly red=$($tput setaf 1)
    readonly yellow=$($tput setaf 3)
    readonly nocolor=$($tput sgr0)

    # highlight the error origin and the exit code
    printf '%s%b()\n\n\t%s%b%s\n\nexit code = %b%s\n' \
           "${bold}$yellow" "$2" \
           "$nocolor" "$3" "${bold}$red" \
           "$1" "$nocolor"

    exit "$1"
}


R Function to Generate Predictions from Ratings and Save Results

So after a lot of testing I found something that significantly reduces calculation time. Converting the format of my dfm to a different sparse format saves significant time when subsetting my main matrix (dfm).

dfm<-as(dfm,"dgCMatrix")

This took my calculation time from approximately 11-12 seconds per line, to .2 seconds per line. As I understand it, this is because dgCMatrix format is optimized for subsetting by columns/column operations which is the first subsetting operation in my function. If you were wanting to subset by rows the optimal format would be RsparseMatrix, optimized for rows.

dfm<-as(dfm,"RsparseMatrix")


How could this be written using continuation passing style?

I would like to slightly rewrite the problem before making it continuation based because it will make it clearer and avoid duplication:

defmodule BTree do
  defstruct tree: nil
  def new(e), do: %BTree{tree: {e, nil, nil}}

  def insert(%BTree{tree: root}, element) do
    %BTree{tree: do_insert(root, element)}
  end

  defp do_insert(nil, element) do
    {element, nil, nil}
  end

  defp do_insert({e, l, r}, element) when e > element do
    {e, do_insert(l, element), r}
  end

  defp do_insert({e, l, r}, element) when e < element do
    {e, l, do_insert(r, element)}
  end

  defp do_insert({_, _, _} = tuple, _element) do
    tuple
  end
end

BTree.new(10) |> BTree.insert(5) |> BTree.insert(15) |> IO.inspect

The previous code was generating a BTree for every node. Instead, we simply treat each node as a tuple with three elements (the node item, left and right). When inserting an element, we traverse the tree until we reach nil. We can make it tail recursive by passing a function and invoking the previous one at each step:

defmodule BTree do
  defstruct tree: nil
  def new(e), do: %BTree{tree: {e, nil, nil}}

  def insert(%BTree{tree: root}, element) do
    do_insert(root, element, &%BTree{tree: &1})
  end

  defp do_insert(nil, element, fun) do
    fun.({element, nil, nil})
  end

  defp do_insert({e, l, r}, element, fun) when e > element do
    do_insert(l, element, &fun.({e, &1, r}))
  end

  defp do_insert({e, l, r}, element, fun) when e < element do
    do_insert(r, element, &fun.({e, l, &1}))
  end

  defp do_insert({_, _, _} = tuple, _element, fun) do
    fun.(tuple)
  end
end

BTree.new(10) |> BTree.insert(5) |> BTree.insert(15) |> IO.inspect

Note though I find this code much harder to understand and I don't think you would get any benefit in practice.


Getting the grandparent directory of the current code

This will be short one, but as we all know, in most cases, "explicit is better than implicit".

Indeed, the second one is ugly and not easily understandable at the first sight. Doing something like this might be better:

from os.path import dirname, realpath

filepath = realpath(__file__)

dir_of_file = dirname(filepath)
parent_dir_of_file = dirname(dir_of_file)
parents_parent_dir_of_file = dirname(parent_dir_of_file)

OFC that's in no way simpler than your first solution, altough it might be clear what the end-result will look like.

More, from here:

  os.path.abspath doesn't validate anything, so if we're already
  appending strings to __file__ there's no need to bother with
  dirname. Just treat __file__ as a directory and start climbing:

# climb to __file__'s parent's parent:
os.path.abspath(__file__ + "/../../")

Climbing more than two levels starts to get ridiculous.

  But, since we know how many levels to climb, we could clean this up
  with a simple little function:

uppath = lambda _path, n: os.sep.join(_path.split(os.sep)[:-n])

# __file__ = "/aParent/templates/blog1/page.html"
>>> uppath(__file__, 1)
'/aParent/templates/blog1'
>>> uppath(__file__, 2)
'/aParent/templates'
>>> uppath(__file__, 3)
'/aParent'


The main thing you are missing is that when total is 0 (a multiple of 101), you can stop the recursion and just make all other operators be *, as you already reached a multiple of 101 and product will keep it like that.

As for the order of operators in the recursive function, the right choice is to put * at the end, which seems to be what you have right now. The main reason is that 101 is prime, so you won´t get a multiple of 101 by the products of numbers. So it´s better to leave that choice for last, as + or - have higher chances of generating a multiple of 101 quicker.

Update: I have tried your resursion solver with the stopping when reaching to 0 remainder but it still gives time out in a few cases, so ended up trying a different approach: dynamic programming.

The trick is that 101 is small, so the possible remainders are only between 0 and 100. The idea is that when looking at the ith number, you don´t really care if the accumulated result from previous operations is 2 or 103 or 204, you only care that its remainder with 101 is 2.

With that in mind, we can make a boolean array where we will store the remainders that can be generated by a combination of operations using the previous numbers.

So for each of these remainders we can get with the previous numbers (0 to i - 1 ), the remainders we could possibly get in the ith step are the same but adding, substracting and multiplying the ith number by that remainder.

I decided to keep a 2 dimensional array, where the first dimension is the step and the second one the remainder: boolean[][] remainders = new boolean[10000][101];

So for each number in the array, if we are on the ith step we iterate remainders[i - 1] and look for the true values. For those, we set the new remainders[i][j + array[i]], remainders[i][j - array[i]], remainders[i][j * array[i]] to true.

Note that we need to add modulo to that to keep it between 0 and 100.

The complexity of this is N * 100. Considering worst case, 10^4 * 100 = 10^6 which should fit nicely in the given time.

With this done, we know for each step what remainders we can get. So according to the problem, remainders[array.length - 1][0] should always be true as it can always be obtained.

There is still the problem that we don´t know what operation we used for each step so we can´t reconstruct the operations just by storing these values in remainders. I suggest you to think over how to do this.

If you still can´t manage, here is my full code that passed the tests. I don´t usually use java so my code surely has some improvements to make.

          import java.io.;
        import java.util.;
        import java.text.;
        import java.math.;
        import java.util.regex.;

        public class Solution {

            static int array[];

            public static void main(String[] args) {
               Scanner s = new Scanner(System.in);
               int n = s.nextInt();
               array = new int[n];
               for (int i = 0; i < n; i++)
                   array[i] = s.nextInt();
               System.out.println(solve());
            }

            public static String solve () {
                boolean[][] remainders = new boolean[10000][101];
                Character[][] operators = new Character[10000][101];
                int[][] previousRemainder = new int[10000][101];

                remainders[0][array[0]] = true;

                for (int i = 1; i < array.length; i++) {
                    int num = array[i];

                    if (remainders[i - 1][0]) {
                        remainders[i][0] = true;
                        operators[i][0] = '';
                        previousRemainder[i][0] = 0;
                    } else {
                        for (int j = 0; j < 101; j++) {
                            if (remainders[i - 1][j]) {
                                remainders[i][Math.floorMod(j + num, 101)] = true;
                                operators[i][Math.floorMod(j + num, 101)] = '+';
                                previousRemainder[i][Math.floorMod(j + num, 101)] = j;

                                remainders[i][Math.floorMod(j - num, 101)] = true;
                                operators[i][Math.floorMod(j - num, 101)] = '-';
                                previousRemainder[i][Math.floorMod(j - num, 101)] = j;

                                remainders[i][Math.floorMod(j * num, 101)] = true;
                                operators[i][Math.floorMod(j * num, 101)] = '*';
                                previousRemainder[i][Math.floorMod(j * num, 101)] = j;
                            }
                        }
                    }

                }

                String result = Integer.toString(array[0]);
                Integer currentRemainder = 0;
                String[] operatorsResult = new String[10000];

                for (int i = array.length - 1; i >= 1; i--) {
                    operatorsResult[i] = Character.toString(operators[i][currentRemainder]);
                    currentRemainder = previousRemainder[i][currentRemainder];
                }

                for (int i = 1; i < array.length; i++) {
                    result += operatorsResult[i] + Integer.toString(array[i]);
                }

                return result;

            }
        }


Writing a proper (and simple) auth/login class in PHP

At the first look, no big hole shines through. Some points that can be considered, on the order of appearance:

Instead of directly using the $_POST, you can take these as parameters, thus making it look like more of an API. Example usage: when you want to directly log in people who have just  registered. You will not be tied to some particular $_POST parameters.
Crypt::hash ...: Not seeing the interior of this, one can't comment much but from the looks, the salt seems constant, unless you are querying the users table again inside this. A different (and preferably with a length matching the password) salt for each user is generally the way to go in security-conscious developer environments.
Similar to the #1, you can use a wrapper class for $_SESSION usage.
else if($_SESSION['authenticated'] && $_SESSION['userid'] > 0 && !empty($_SESSION['user'])): Instead of directly querying the $_SESSION, you can make another function like $this->isLoggedIn(), so you'd be more resistant to future session and log in changes (along with some other benefits).
redirect($_SERVER['REQUEST_URI']); Relying on a $_SERVER variable always looked insecure and unstable to me. You can use some checks here or use some of your internal navigation variables instead, in case you don't want to make it completely generic in this way.


What's this?

public XMLCreator() {
    if (this.xml == null) {
        this.xml = new HashMap<Integer, String>();
    }
    if (this.roots == null) {
        this.roots = new HashMap<Integer, String>();
    }
    if (this.sB == null) {
        this.sB = new StringBuilder();
    }
}

The null checks are always true, where should a value come from?

Why

this.child = "<" + child + ">" + "</" + child + ">";

and not

this.child = "<" + child + "/>";

?


int.Parse(key.Attribute("id").Value)

XAttribute (and XElement) supports implicit cast to int (and other types), this means you can write just:

(int)key.Attribute("id")

One more advantage of this approach is that it uses the invariant culture, unlike the Parse() methods, which use the current culture by default. This is especially important for decimal values, since many cultures use , as the decimal separator, not ..

And if you're going to use casts for numeric types, you might want to use them for string too for consistency, instead of accessing Value.

var tasks
var tasks2
var tasks3
var tasks4

Those are not very good variable names, try to make names more descriptive, like accountStatusTasks.

Also, it's hard to advise more about the structure of the code when you don't use all those tasks in any way, except to wait for them. I assume that's not all they're good for.

There are not many cases where ContinueWith() is useful, when you can use await. Here, I would make the Select() lambda async, which also means you can use await Task.WhenAll() instead of Task.WaitAll(), which blocks a thread unnecessarily:

var tasks2 = keys.Select(async key =>
{
    var keyInfo = await EveOnlineClient.GetAPIKeyInfoAsync(key.ID, key.VerificationCode);

    var characters = keyInfo.Characters;

    // Get the sheet for each character in each API key
    var tasks3 = characters.Select(character => EveOnlineClient.GetCharacterSheetAsync(key.ID, key.VerificationCode, character.ID));

    // Get skill in training for each character in each API key
    var tasks4 = characters.Select(character => EveOnlineClient.GetSkillInTrainingAsync(key.ID, key.VerificationCode, character.ID));

    await Task.WhenAll(tasks3.Concat(tasks4));
});

Quite often, code that makes many requests to a single server in parallel is limited by ServicePointManager.DefaultConnectionLimit, which by default is set to just 2. But if you decide to change this, make sure to follow any guidelines about rate limiting of the API you're using; otherwise, you might easily end up blocked.


Doubly linked list with different dependencies

Task depends on Dependency (not very troubling in itself) :

public class Task {
    private List<Dependency> parents = new ArrayList<Dependency>();

Also Dependency depends on concrete class Task (somewhat more troubling):

public interface Dependency {
    Task getTask();

Although dependency cycles of size 2 are not intrinsically a problem, in this case interface Dependency is pretty much useless, [if we look at the implementation, which is a hybrid holder and wrapper for Task]. Too generic a name and getters and setters on the interface are also signs that this interface does not pull its weight.

If the problem model is a graph it is expected that class that represents the node of that graph should be depend on itself. Dependency cycles of 1 is generally better than 2.

My Suggestion

The only methods that contain logic in the implementation of Dependency is setBackwards and setForwards. But when we read them we see that they manipulate the insides of Task, and therefore should be moved into that class. After the said move you can remove Dependency and EA, and directly use Task instead.


Basic abstract graph implementation in Java

Thinking about naming...

When I see a single capital letter, it makes me think of generic type.  I find your usage misleading.
Single letter variable names can be OK when it's obvious what they are, such as indexers in loops, I would suggest avoiding them for anything with larger scope, particularly at the field level.
int V;  // Number of vertices, why not just call it numberOfVertices?  You don't need the comment and the rest of the code is that little bit easier to interpret?
edges(): Typically in Java I'd expect this type of method to be called getEdges, it's really just returning the field.  In fact, when I first saw it, I thought it would be returning some collection of edges, but it doesn't it just returns a count.  Consider renaming it to match what it returns.
LinkedList<Integer> llOne = new LinkedList<>();.  Generally, avoid embedding the type information (ll) in the variable name.  Think about what the list is representing and call it that, rather than 'one' and 'two'.


Search in a 2D array to find if there is a row or a column that contains the word “error” in every cell of that row or column

My Java is a bit rusty but I'm not seeing any logical issues with the code doing what you want it to.

Since you return just the row or column index, the caller can't tell from that if the match was a row or a column.


Add To Query Based Off Date Picker Or Drop Down List

I'm not familiar with Joomla's database library, so forgive me if some details below are suboptimal. But this is how it looks like you could start cleaning the script up.

// Query the dates.
$records = QueryDates();

// If we didn't get any dates...
if($records == null)
{
    echo "Please check the selection criteria and process again.";
}
else
{
    // Do something.
}

// Put your logic in a function that can be called wherever you need.
// You'll eventually want your PHP logic to be in a different file from
// your presentation markup.
function QueryDates()
{
    $bgin = $_POST['bgin'];
    $end  = $_POST['end'];

    if (isset($_POST['daterange']))
    {
        $datecriteria = $_POST['daterange'];
    }

    // Wrap our database interactions in a try-catch for safety.
    //
    // You might want to comment out the try-catch when first debugging.
    try
    {
        // Connect to the database.
        //
        // Is $option defined somewhere?
        $db = JDatabase::getInstance($option);

        // Get a new query object.
        $query = $db->getquery(true);

        // SELECT * FROM table_name ...
        $query->select('*');
        $query->from($db->quoteName('table_name'));

        // Get a quoted version of our datefield column.
        $datefield_name = $db->quoteName('datefield');

        if (isset($bgin) && isset($end))
        {
            $query->where("$datefield_name >= " . $db->quote($bgin), 'AND');
            $query->where("$datefield_name <= " . $db->quote($end));
        }
        elseif (isset($datecriteria))
        {
            // Make sure the data is well-formed.
            if ($datecriteria != 10
                && $datecriteria != 20
                && $datecriteria != 30)
            {
                return null;
            }

            // Calculate our range.
            $min_date = DateAdd(day, $datecriteria * -1, getdate());

            $query->where("$datefield_name >= " . $db->quote($min_date), 'AND');
            $query->where("$datefield_name <= " . $db->quote(getdate()));
        }
        else
        {
            return null;
        }

        // Execute the query.
        $db->setQuery($query);
        $results = $db->loadObjectList();

        return $results;
    }
    catch (Exception $e)
    {
        // Could return something more useful, based on what
        // is containe din $e.
        return null;
    }
}

You'll notice a few things here. Let's break them down:

I put your logic into a function. It's a good habit to get into, as
you start to learn more about PHP and web development. You'll start
to out-grow the mode of putting all your PHP code in the same file
as your HTML markup and will start to write functions you want to
call from multiple pages.
I changed your query from being a string to a series of function
calls. Joomla appears to utilize an abstraction library where you
build queries out of function calls against a query object. It also
appears to use quoteName for input sanitation.

That last part sounds iffy, to me. If Joomla has query parameters,
I'd recommend you use those, instead. But, as in the intro, I'm not
familiar with the Joomla db library so this is what their
documentation seems to suggest doing.
https://docs.joomla.org/Selecting_data_using_JDatabase

In either case, don't simply pass a POST parameter into the query. You'll be
opening up your entire database to anyone who knows basic SQL Injection
(including the droves of SQL Injection bots that will find your site).
I have the new function return null whenever something goes wrong. This
allows you to check for the bad output after the function call and handle it
there, however you need to. Again, if you were to call this function from
different pages, each might have its own way of dealing with the bad output.

The Joomla documentation doesn't say if loadObjectList() returns something
like null or false if the query fails. If it does return null, you might
need to change all my "return null;"s to be something like "return false;",
so you don't confuse the two outputs.
Finally, I set a try-catch block around your database interaction. This is
good practice in production, as it will avoid nasty errors from hitting your
users. But it may be troublesome while you're developing the code (as it
will prevent you from seeing when something goes wrong). I'd recommend
commenting out the try-catch until you do publish the site to your
production environment.

As for speed, most of those 3 seconds for loading is likely network flight time (though, I assume you're running this locally) and the interaction with your database. There's not a lot you can do to speed up the traffic of sending the query and receiving the data, outside of environmental changes (eg. getting a faster hard drive on the server).

The one thing you can do is make sure your database schema is structured to facilitate speedy queries. For instance, if you're constantly querying against this "datefield", you might consider putting an index on it.

Depending on the data being returned, you can also tweak the cache. For instance, if users are frequently querying the same data, ensure that the cache is actually storing that data (rather than saying it's too big and dumping it or having the cache outright turned off).

If you expect a bunch of users to be using the page, you might also want to put stricter limits on the range of dates that can be queried. Having someone try to dump your entire database could cause slowdowns for other users.

But a lot of this is up to details you haven't given us.


Code-Style: Good
Functionality: no problem seen
Potential Bugs: only one I can see
Android-Expert-Level: I am not an android expert.
Android-Basic-Level: Everything looks sane

Bug (in jest):

People can play 1.9 seconds of angry birds, swap to a different app, and then swap back ;-)

Suggestions:

There is only one improvement I can suggest.

   private BroadcastReceiver screenReceiver = null;

This line is out-of-place. The only place it is used is in your registerScreenReceiver method. You may as well declare it in that method.

I would be tempted actually to pull the declaration out of the method and make it a final in-initialization anonymous instance:

 private final BroadcastReceiver screenReceiver = new BroadcastReceiver(){
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
                Log.i("ScreenReceiver", "Screen off");
                screenOn = false;
            } else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
                Log.i("ScreenReceiver", "Screen on");
                listenForAppStarts();
                screenOn = true;
            }
        }
    };


I agree with both of your suspected issues:

Pointless iteration through @items hash: As you suspected, iterating through all entries of a hash defeats the purpose of a hash.  That takes O(I * S) time — the number of items times the number of specials.   Why not iterate through @specials, then look up the item by name?  That's only O(S).
while loop: The loop can be replaced with arithmetic.

In addition, I would like to point out some more problems:

Surprising side-effect in getter: By convention, any method named get_*() is assumed to have no side-effects.  However, get_discounts() alters @items, reducing their quantity.  If that is intentional, you should rename the method to apply_discounts() or something even more suggestive that there is a side-effect.
Abuse of instance variable: @discounts is assumed to be pre-initialized to an empty array before get_discounts() is called.  get_discounts() populates the array, then calls determine_discount(), which converts it into a scalar.  That indicates that @discounts is not storing the state of the object, so using an instance variable for that purpose is abuse.

Here is a revised version of the code:

def get_discounts
  discount = 0
  @specials.each do |special|
    if item = @items[special.sale_item]
      multiples = (item[:quantity] / special.quantity).floor
      discount += multiples * special.discount

      # Suspicious side-effect...
      # item[:quantity] -= multiples * special.quantity
    end
  end
  return discount
end


Finding the percentile corresponding to a threshold

If I understand your question, you are asking to determine the percentile value of the first value that exceeds the threshold. The thing to do is the following:

Specify the number of random.normal deviates in the call and pre-sort the array. That way you can just look at each element in the array, knowing that the next one is bigger than the last.
Just count the number of values that fail to exceed the threshold, stopping after you find one that exceeds it. No need to continue beyond this point.
Then, do the arithmetic.

my_vals = sorted(np.random.normal(0.05, 0.02, 60000))
count_vals = 0
for i in my_vals:
    count_vals += 1
    if i > threshold_val:
        break
percentile_val = 100 * (count_vals/len(my_vals))
print('{0:0.6}'.format(percentile_val))

As a check, you could then calculate the value of the element at that percentile using np.percentile.

print(np.percentile(my_vals, percentile_val))

Even easier is to do the counting this way:

count_vals = sum(i > threshold_val for i in my_vals)
percentile_val = 100 * (count_vals/len(my_vals))


I'd suggest to filter out unneeded elements, instead of replacing them by -1. Keeping and processing all the -1 is unnecessary:

sieve_once :: [Integer] -> Integer -> [Integer]
sieve_once seq p = filter (\x -> x `mod` p /= 0) seq

-- a list of all prime numbers
sieve :: [Integer]
sieve = unfoldr (\(p:rest) -> Just (p, sieve_once rest p)) [2..]


Fine tuning of an informative replacement for rm

Bonus question: Does ls -C help?

-C     list entries by columns

You need -r to remove directories, so do you intend to impose this check as well when directories are specified?

plural="s"
if [ $count -eq 1 ]; then plural=""; fi

That can be rewritten as

[ $count -eq 1 ] && plural="" || plural="s"

Is the use of _ really necessary here?

if [ "_$?" != "_0" ]; then exit 1; fi
if [ "_$REPLY" = "_y" ]; then

edit: Bonus question, round 2...

You could try this for du_colored:

du_colored() {
    du -sh "$@" | awk -F'\t' -v COL=4 \
        '{if(++c>COL){c=1;print""}("ls -Ad --color \""$2"\"")|getline entry;
        printf "%6s %s\t",$1,entry}END{print""}' | \
    column -s $'\t' -t
}

Instead of parsing ls output carefully to feed into du, I started from the output of du and then replacing each entry with its ls --Ad --color output. COL is used to fix the number of 'columns' we want column to pick up afterwards, which is in turn used to print the appropriate newlines.

Finally, I feed the output to column as a final attempt at pretty-printing. \t is used as the delimiter throughout.

It still doesn't look as nice as the default non-piped ls output, but at least it's something I suppose...

edit 2: Bonus question, round 3...

I hope this is what's required... :)

du_colored() {
    awk -F'/' 'NR==FNR{k=$0;gsub(/\x1B\[[;[:digit:]]*m/,"",k);s[k]=$0}
        NR!=FNR{l=$0;for(i=3;i<=NF;i+=2){v=$i;gsub(/[ ]+$/,"",v);sub(v,s[v],l)};
            gsub("/"," ",l);print l}' \
    <(ls -Ad --color "$@") \
    <(du -sh "$@" | awk -F'\t' -v C=4 '{if(++c>C){c=1;print""}printf "/%6s/%s\t",$1,$2}
        END{print""}' | column -s $'\t' -t)
}

Get both the output of ls -Ad --color "$*" and du -sh "$@" ... using bash process substitution to pass into awk.

The du -sh command is in turn piped to an 'internal' awk command, similar to my earlier suggestion, for column to render properly. What's crucial to note here is that the start, the size and the file/directory entry are delimited using the / character, which is the safest delimiter as files and directories cannot have that (nested directories yes though).

The 'main' awk command uses / to split each line into 1 + C * 2 columns (C=4 used above). By using the combination of NR==FNR/NR!=FNR conditions, we can specify different handling for the two 'files'.

For the ls output, i.e. NR==FNR, we construct a map from the file/directory (by stripping away the color codes - gsub(/\x1B\[[;[:digit:]]*m/,"",k)) to its colored output.
For the du output, we then substitute the file/directory in the appropriate fields (after trimming the extra spaces behind - gsub(/[ ]+$/,"",v)) with the colored output from the mapping.
After substituting each / character back to a  character, we reprint the entire line, which now contains the colored output.

This is arguably more efficient as both ls and du are performed once on the arguments. The lesson learned here is that column doesn't play ball with most control characters (seemingly \t is the only exception here). For some reason, sort-ing on du's output is still introducing minor quirks in my own testing, so I'm leaving that out for now.


You are storing all of the A and B inputs in sorted vectors, basically doing an insertion sort.  A few observations (two minor, one major):

The if (c == 1) special case should be eliminated.
Flag variables (founda and foundb) suck.  You would be better off writing two separate for loops.
Each time you insert a value, all values beyond the insertion point need to be shifted over to make room for the insertion.  That means that constructing as and bs takes O(N2) time altogether — which is unacceptable, since N can be very large.

However, there are only 100 possible values of A and B.  So, do a counting sort instead, building a histogram with 100 buckets.  That would be a much more efficient way to represent the same information, using O(N) time and a fixed amount of space.


You're creating a bunch of unnecessary vector copies. Try passing iterators into FindMaximumSubarray instead of a vector.

You can find the max of an initializer list of numbers using std::max.

You don't need to pass ints as const refs.

Are you sure this is more performant than a linear solution? What is your reasoning? Can we see your linear version?

Your code looks like it might have potential overflow errors. Maybe that's not important.


This is correct code. It could go into production.

You don't need the memory barrier because SetEvent will do that for you (if it didn't a lot of code would be broken).

You could change this to use futures (provided that you have some C++ lib that supports them. I don't really know C++ well):

var data = PrepareData();
var boringComputation = StartSomeFuture([&data] { ... });
var funComputation = ComputeFun(data);
var boringResult = boringComputation.ResultAndWait();

Much better.


Non-nullable reference type default parameters in C# 8

My take on this is that the function signature should not lie.
So if it can handle a null passed in, as it can, it should use

Bar? bar = null

Another approach could be to overload the function with another which only takes a single parameter. Something like ...

Task FooAsync(
   Bar bar,
   CancellationToken ct = default)
{
    ...
}

Task FooAsync(
   CancellationToken ct = default)
{
    return FooAsync(new Bar(), ct);
}


Learn Python the Hard Way #48 — lexicon exercise

verb=['go','kill','eat']
direction=['north','south','east','west']
noun=['bear','princess']
stop=['the','in','of']

There is not a lot of point in storing these in separate variables only to stick them inside vocab just put the list literals inside vocab

vocab={'verb':verb,'direction':direction,'noun':noun,'stop':stop}

Python convention say to make constant ALL_CAPS. I'd also not abbreviate the names. Code is read more then written, so make it easy to read not to write.

def scan(sentence):
    wordlist=sentence.split()
    result=[] #initialize an empty list

Pointless comment. Assume you reader understand the language. You don't need to explain what [] means.

    for word in wordlist:

I'd use for word in sentence.split():

        found=False

Boolean logic flags are delayed gotos. Avoid them when you can

        for key,value in vocab.items():
            if word.lower() in value:  #convert to lower case so that we can handle inputs with both cases

Your dictionary is backwards. It maps from word types to lists of words. It'd make more sense to have a dictionary mapping from word to the word type.

                result.append((key,word))
                found=True
                break
        if not found:

Rather then this, use an else block on the for loop. It'll be execute if and only if no break is executed.

            try:
                word=int(word)
                result.append(('number',word))

Put this in the else block for the exception. Generally, try to have as little code in try blocks as possible. Also I wouldn't store the result in word again, I'd put in a new local.

            except ValueError:
                result.append(('error',word))

    return result

My approach:

WORD_TYPES = {
   'verb' : ['go', 'kill', 'eat'],
   'direction' : ['north', 'south', 'east', 'west'],
   'noun' : ['bear', 'princess'],
   'stop' : ['the','in','of']
}
# invert the dictionary
VOCABULARY = {word: word_type for word_type, words in WORD_TYPES.items() for word in words}

def scan(sentence):
    tokens = []
    for word in sentence.split():
        try:
            word_type = VOCABULAR[word]
        except KeyError:
            try:
                 value = int(word)
            except ValueError:
                 tokens.append( ('error',word) )
            else:
                 tokens.append( ('int', value) )
        else:
            tokens.append( (word_type, word) )
     return tokens

Alternately, using some regular expressions:

classifications = []
for word_type, words in WORD_TYPES.items():
    word_expression = '|'.join("(?:%s)" % re.escape(word) for word in words)
    expression = r"\b(?P<%s>%s)\b" % (word_type, word_expression)
    classifications.append(expression)
classifications.append(r"\b(?P<int>\d+)\b")
classifications.append(r"\b(?P<error>\w+)\b")
parser = re.compile('|'.join(classifications))

def scan(sentence):
    return [(match.lastgroup, match.group(0)) for match in parser.finditer(sentence)]

EDIT

If your version of python is to old to use the dict comphrensions you can use:

dict((word, word_type) for word_type, words in WORD_TYPES.items() for word in words)


At first sight, your code is short and there is nothing wrong with it.

At second sight, there are a few things to improve:

Your semicolons are all over the place; you have both missing and pointless semicolons.
There is no point in declaring id in all since you clearly will not use it
ngPost is an old skool constructor, it's name really should start with an uppercase

These things I gleaned from JSHint, you should use it.

Furthermore, I could be wrong, it seems that you are mixing functions which I would put in posts together with functions which I would put in post. I am not sure that is the best approach.


Generating numbers that are a product of consecutive primes

Ok so I figured this one out, by doing the nested loops recursively as a generator. Below is a MUCH nicer code that yields the same answer.

def loop(n,depth):
    """generates numbers containing "depth" primes, up to n"""
    if depth==0:            #generates the powers of two
        num1=1
        while num1<n/2:
            num1*=pr[0]
            yield num1
    else:
        for i in loop(n,depth-1):           #generates all numbers containing the first n prime numbers
            num_depth=i                     #number containing all previous primes
            while num_depth<n/pr[depth]:
                num_depth*=primes[depth]            #successively multiplies the nth prime
                yield num_depth

def admissiblenums(n=1e9):
    """generates a set of all admissible numbers not exceeding 1e9"""
    admissibleset=set()
    for i in range(len(pr)):
        nth_admissible_prime=set(loop(n,i))
        admissibleset|=nth_admissible_prime     #union of admissibles up to nth prime
    return admissibleset

def pseudofortunate(n):
    """returns the pseudofortunate number of n
    (the difference between n, and the first prime larger than or equal to n)"""
    prime_candidate=n+3#defined as prime larger than n+1, so starting the search for a prime at n+3, since admissible numbers are always even
    while True:
        if is_prime(m):
            return prime_candidate-n        #returns the difference(pseudo-fortunate number) if prime_candidate is prime
        prime_candidate+=2      #check odd numbers
t1=time()
primes=generate_primes(24)      #the primes less than 24, since the primorial needs to be less than 1e9
pseudofortunates=set()
for i in admissiblenums():
    pseudofortunates.add(pseudofortunate(i))    #adds psuedo-fortunate numbers to set
print sum(pseudofortunates)     #sum of unique pseudo-fortunate numbers
t2=time()
print t2-t1


Count patterns that start and end with "1", with 0's in between

Although the other 2 answers currently given are technically correct. I find it more logical to search for a 1 followed by any number of 0's ending with another 1 which we cannot consume yet (as it can be used again in the following match).

So the pattern should look like 1[0]+(?=1)

Which turns the method implementation to this:

static int patternCount(String s) {
    Pattern pattern = Pattern.compile("1[0]+(?=1)");
    Matcher matcher = pattern.matcher(s);
    int count = 0;
    while (matcher.find()) {
        count++;
    }
    return count;
}


You have comments in the definition of RingBuffer on the value limits for some members, but there is nothing in the code that enforces that or checks to see if those limits are exceeded.

Why does TryRead take its parameter by const int&?  The reference is unnecessary.  Just pass in the int.

Why is MAX_SIZE a macro?  It should be a constexpr (if your compiler supports it) or static const int if not.

In the RingBuffer constructor, you can combine the reserve and assign calls into one, and include it in the member initializer list.

Push will happily and silently overwrite things that have been added to your ring buffer but not consumed.

The way your Push is set up, you can have multiple threads write to the same memory location (if, for instance, there are enough other calls to Push so that the value calculated for index wraps back around).

It is also possible for mMaxReadIdx to indicate a slot is available for reading when it isn't.  For example, thread A starts a Push, and gets a write index.  Thread B then starts another Push, gets a write index, stores its value and increments mMaxReaddx before thread A has stored its message.  The slot used by thread A will be readable by a TryRead but won't have data in it yet.

TryRead can return the same message to multiple consumers, since each consumer has its own idea of where the bottom of the buffer is.

RingBuffer::RingBuffer(int pNumOfConsumers): mVector(MAX_SIZE, nullptr)


Simulate a person who is working in a quarry with classes

Before worrying about delegates, there are some very basic notions we should review! :)

Never, ever getting back together expose your fields. They should be private. Use properties like you did in your Quarry class instead.
This pattern is called encapsulation and is an important practice in the software development process.

In general, an instance (like new Quarry()) shouldn't deal with static fields. Why is that? Imagine the following scenario where you have 2 quarries.

Quarry quarry = new Quarry();
quarry.stone -= 100; //Somebody's been working hard
Quarry quarry2 = new Quarry();
Console.WriteLine(quarry.stone);

What is printed? Is it 9900? Nope, because your instance constructor resets the static field. The stone field shouldn't be static. Each Quarry should have its own number of stones. Maybe the number of stones could be customized with a parameter in the constructor?

public class Quarry
{
    public int Stones { get; set; }

    public Quarry(int stones)
    {
        Stones = stones;
    }
}

This way each of your Quarry is independant.

Next problem, there is no relation between your Person and your Quarry. This is bad. A Person works in a Quarry (in your example, we'll keep it simple), but in your code, we don't see this relation. To keep it simple, we'll say that a Person Works with a Quarry. What does it mean? It means that the Work method should receive a Quarry parameter.

public class Person
{
    public int stone;
    public int money;

    public Person()
    {
        stone = 0;
        money = 0;
    }

    public void Work(Quarry quarry)
    {
        stone += 1;
        quarry.Stones -= 1;
        if (this.stone >= 20)
        {
            ChangeStonesToMoney(ref this.stone, ref this.money);
        }
    }

    public void ChangeStonesToMoney(ref int stone, ref int money)
    {
        stone -= 20;
        money += 1;
        Console.WriteLine("One Person has now {0} dollar.", this.money);
    }
}

Notice that stones isn't the best variable name you can use. Perhaps workedStones would be better. Or something like this.

Also, you use Thread.Sleep(300); in your main loop, but I assume that it's the person's work that takes 300 milliseconds (damn those persons are fast!). So maybe the sleep should be in the Work method. Using Thread.Sleep() is unorthodox and is usually not recommended, but for your example I get why you're using it! :)

I noticed you were using ref. That's bad. I mean, you used it in a "good" scenario, as you want to modify an int by reference, but you don't need to do this and you shouldn't include ref everywhere just for the kick of it.

You already have access to stone and money, so why pass them as parameter?

public void Work()
{
    stone += 1;
    Quarry.stone -= 1;
    if (this.stone >= 20)
    {
        ChangeStonesToMoney();
    }
}

public void ChangeStonesToMoney()
{
    stone -= 20;
    money += 1;
    Console.WriteLine("One Person has now {0} dollar.", this.money);
}

Now, I don't have time to go for a longer review, but I suggest you think about the following points :

Why is the Person class responsible for knowing how many stones are worth a dollar? Shouldn't another class be responsible for this?
Shouldn't a Quarry have a list of Person that works for it? Instead of having different people work on a quarry once in awhile like it is actually done at the moment.
Are these people under the minimum wage?

Otherwise, there's some good stuff in there, you've done a good job for a first little application :)


There is nothing really wrong with this but using a simple hash may be easier:

module App
    @@settings = {
        :console => true,
        :file => []
    }
    def self.settings
        @@settings
    end
end

Your following code would then become:

p App.settings[:console]
App.settings[:file] << "afile.rb"
p App.settings[:file]

There are several advantages to this approach:

Hashes are easy to serialise and store in files using yaml/json/etc.

require 'yaml'
p App.settings.to_yaml

You can reference App.settings in a local variable to avoid writing it out:

s = App.settings
#do stuff with s

Hash has many convenience methods for iterating over its values.

App.settings.each do |key, value|
    #do something
end

You can add to/update it succinctly using the merge! method.

App.settings.merge! :console => false, :newsetting => 'value', :etc => '...'

To get functionality like this in your method would require you to write lots of methods yourself. It's better to just use the built in functionality that Ruby has instead of reinventing the wheel.


Instead of returning an rvalue reference, it's better to return bv by value:

template<typename T>
ByteVector operator<< (ByteVector && bv, T data)
{
    return bv << data;
}

C++ compilers perform return value optimisation, which means that the return value won't be copied in this case.

An alternative approach is to ignore the advice not to subclass standard library containers, and implement your operators as member methods.  That will remove the need to overload for rvalue types, and I believe it's safe to do so for this use.


Efficiently checking if a number is divisible by 3

Computers aren't humans.  A human might find it easiest to apply a divisibility rule.  A computer, though, doesn't care.

The simplest code would be to check n % 3 == 0.  The modulo operator uses the JVM opcode irem, which is about as efficient as you can get.

On an Intel CPU, irem is probably implemented using the IDIV (signed divide) instruction.  On most modern x86-compatible processors, IDIV with a 32-bit operand uses 10 to 30 micro-operations and has a latency of 20 to 61 clock cycles.  More importantly, the trend on newer and more powerful hardware is for IDIV to take fewer clock cycles.  In other words, writing the program as if it were a RISC processor is a counterproductive "optimization" — it would be better to let the hardware perform the division operation to its full potential.

For comparison…

javap -c DivThreeEfficiently

public final class DivThreeEfficiently {
  public static boolean isMultipleOfThree(int);
    Code:
       0: iload_0
       1: ifge          7
       4: iload_0
       5: ineg
       6: istore_0
       7: iconst_0
       8: istore_1
       9: iconst_0
      10: istore_2
      11: iload_0
      12: ifeq          46
      15: iload_0
      16: iconst_1
      17: iand
      18: iconst_1
      19: if_icmpne     25
      22: iinc          2, 1
      25: iload_0
      26: iconst_1
      27: ishr
      28: istore_0
      29: iload_0
      30: iconst_1
      31: iand
      32: iconst_1
      33: if_icmpne     39
      36: iinc          1, 1
      39: iload_0
      40: iconst_1
      41: ishr
      42: istore_0
      43: goto          11
      46: iload_1
      47: iload_2
      48: if_icmpne     55
      51: iconst_1
      52: goto          56
      55: iconst_0
      56: ireturn
}

Div3MoreEfficiently.java

public class Div3MoreEfficiently {
    private Div3MoreEfficiently() {}

    public static boolean isMultipleOfThree(int n) {
        return n % 3 == 0;
    }
}

javap -c Div3MoreEfficiently

public class Div3MoreEfficiently {
  public static boolean isMultipleOfThree(int);
    Code:
       0: iload_0
       1: iconst_3
       2: irem
       3: ifne          10
       6: iconst_1
       7: goto          11
      10: iconst_0
      11: ireturn
}


Translating month number into month name

Like I said in my comment: If you want to know which is faster, write a benchmarking script, it's that easy:

$start = microtime(true);
//if-hell approach
$ifs = microtime(true) - $start;
$start = microtime(true);
//switch
$switch = microtime(true) - $start;
$start = microtime(true);
//array
$array = microtime(true) - $start;

Then compare and echo the results in any way you like.
My gut tells me that in this case, the switch will probably be the faster option. Considering a switch construction is sort of like labeling blocks of code, and then do some sort of eval-go-to thingy.
Branching (if) is faster in terms of compilation, perhaps, but for the month of december, you'll end up performing all if statements.
The array approach, for this example, doesn't look like the fastest approach you can take in this case, because it's constructing an array, performing a HashTable lookup, evaluate the result of that lookup, then perform the same lookup again, or return an empty string. HashTable lookups are as fast as it gets, of course, but still, you're having to do 2 of them, just after you've constructed the HashTable. The other approaches don't construct to then perform a lookup.

Mind you, This is micro-optimization of the worst kind. It's completely pointless and the speed difference won't be noticeable. Especially if you use some form of OP-Code caching (APC, for example). That should be the first port of call if you're trying to optimize some code.

What code should you use?:
This is the better question to ask. The efficiency of some snippet of code isn't just determined by the time it takes to execute. Efficient code is good code (is stable, performant, error and notice-free) and is easy to read, update and maintain.
If your determining the name of the month then it's pretty obvious the data-set is limited to 12 valid strings. But in most cases, you might end up with an ever growing switch or if-elseif-else tree. That's not efficient coding. The moment you have to scroll to see a single block of code, you can safely say it's time to think about refactoring your code.

That's why I'd either use the array approach (works just as well when data is coming from a query, so you can create a function that you can reuse). Or, if you are working on dates, I'd give way to normalization, and use the DateTime class. when I see new DateTime or $d = DateTime::createFromFormat, I know what to exepct. Even more so when I see:

[public] function doStuff(DateTime $date)
{
}


Fastest way to find dataframe indexes of column elements that exist as lists

itertuples
When traversing over the rows of a DataFrame, using itertuples is generally faster than iterrows. The latter makes a new Series for each row, the former a namedtuple, which is generally faster.
defaultdict
Appending items to a list on a key is typically done with a defaultdict.
from collections import defaultdict
result = collections.defaultdict(list)
for row in X.itertuples():
    idx = row.Index
    for item in row.B:
        result[item].append(idx)

The method you use to combine the values in the dictionary is meant to include empty items as None. Here you add them, and then filter them out, so using a defaultdict will simplify this up a lot.
naming
Try to follow pep-8.

snake_case for variables, etc.
spaces around operators
...

timings
dummy data
def make_dummydata(rows, max_length, seed=0):
    letters = string.ascii_letters
    np.random.seed(seed)
    random.seed(seed)
    col1 = np.random.randint(0, 10, size=rows)
    items_per_row = np.random.randint(0, max_length, size=rows) + 1
    col2 = [random.choices(letters, k=amount) for amount in items_per_row]
    return pd.DataFrame({"A": col1, "B": col2})

benchmark method
import timeit

def benchmark(cases, functions):
    for rows, max_length in cases:
        df = make_dummydata(rows, max_length)
        for name, function in functions.items():
            result = timeit.timeit(
                stmt=f"function(df)",
                globals={"df": df, "function": function},
                number=1,
            )
            yield rows, max_length, name, result

results
cases = [(10, 2), (100, 10), (1000, 40), (10000, 200)]
functions = {
    "OP": find_op,
    "maarten": find_maarten,
    "jezrael": find_jezrael,
}
list(benchmark())

[(10, 2, 'OP', 0.001344002000003286),
 (10, 2, 'maarten', 0.0003913850000003549),
 (10, 2, 'jezrael', 0.005293956000002709),
 (100, 10, 'OP', 0.027166392000005146),
 (100, 10, 'maarten', 0.0004795910000012782),
 (100, 10, 'jezrael', 0.013824836999994261),
 (1000, 40, 'OP', 0.3434149869999956),
 (1000, 40, 'maarten', 0.0032574399999987236),
 (1000, 40, 'jezrael', 0.018533767000000978),
 (10_000, 200, 'OP', 33.48681208600001),
 (10_000, 200, 'maarten', 0.10972772499999905),
 (10_000, 200, 'jezrael', 0.7631061700000004),
 (350_000, 1000, 'maarten', 22.097186581000003),
 (350_000, 1000, 'jezrael', 516.128048978)]

The method using defaultdict is a lot faster. This only says something about the run-time, not the memory usage, where my method does not create a large intermediary DataFrame.


Calculations to position a text box next to another object

This is a definite candidate for using rect / point structures, but I don't know what the rest of your code-base looks like, so just talking about the algorithm alone, one approach would be:

void FindNonOverlappingPosition(
    uint canvasWidth, uint canvasHeight,
    uint x1, uint y1, uint width1, uint height1,
    uint width2, uint height2, uint spacing,
    uint* outX, uint* outY)
{
    // Position above if possible, below otherwise
    if (y1 >= height2 + spacing)
        *outY = y1 - (height2 + spacing);
    else
        *outY = y1 + height1 + spacing;

    // Position left-aligned if content is closer to the left of the canvas, right-aligned otherwise
    if (x1 < canvasWidth - width1)
        *outX = x1;
    else
        *outX = (x1 + width1) - width2;

    // Ensure that the box being positioned fits on the canvas
    if (*outX < 0)
        *outX = 0;
    else if (*outX + width2 > canvasWidth)
        *outX = canvasWidth - width2;
}

This fails in cases where an alignment according to those rules is impossible, such as the content taking up the entire height of the screen, or the text box being wider than the screen.  You could check for those cases and return an error code if desired.


Ok, so there's a lot to cover here.

get_user_array is a terrible name. What does "getting a user array" mean? Is it an array of users? A user's array? Be descriptive.
Why all the instance variables (@...)? This method is a simple helper that has no need to persist state between invocations. Don't use instance variables for this!
You appear to be laboring under a lot of misunderstandings of, well, fairly basic things to be frank.

Don't use #map unless your intention is to transform an array 1-to-1 into a new array. You're using #map a lot, but only once for an actual mapping operation.
You're doing a lot of pointless conversion back and forth. For instance, Array(a).count when a is already an array.
You also do stuff like Date.parse(u.created_at.strftime("%F")) which means you're taking a Date, making it into a String, and then back to a Date again. I'm guessing you may be doing that on purpose to drop the time-part, but doesn't it strike you as an incredibly complicated way of doing that? Why involve strings when going from Date to Date? This sort of thing should cause you to reexamine your approach, because it just doesn't smell right.
User.all.reject{|u| !u.valid? } for one, what you want is #select - not #reject. Right now you're saying "do not give me users that are not valid"; with #select, you'd be saying "give me valid users". I.e. User.all.select(&:valid?).
However, you should really be doing neither! Selecting a subset of records based on given criteria is what databases are for. Your User model should ideally have a scope that'd allow you to just get valid users in one go, e.g. User.valid.all.
However, you don't really want that either, since you're still pulling every single user for every single week that's passed since mid-June 2016. That's crazy. If you have ~500 user records and it's now been ~7 weeks since your zero-day, you're instantiating 3,500 records only to discard the vast majority with a #reject call! As time passes and user base grows, this gets worse in a hurry. Yes, Rails is smart enough to cache some stuff, but jeez! Doesn't that strike you as a fundamentally bad approach?

Luckily, you can do more stuff in the database. Most, in fact (probably all of it, with more SQL, but I'll leave that for someone better qualified to figure out).

Supposing your User model has a valid scope that restricts queries to only valid records (thus avoid the horrendous #reject stuff), you could do:

START_DATE = "2016-06-15".freeze

# ...

per_week = User
  .valid
  .where("created_at >= ?", START_DATE)
  .order("created_at")
  .group("FLOOR(DATEDIFF(created_at, '#{START_DATE}') / 7)")
  .count

Note: I couldn't get proper query interpolation to work in the group call, so it's just plain string interpolation. Only use this when you 100% control the value to be inserted, otherwise you'll leave yourself open to injection attacks.

This will produce a SQL query that

Calculates the number of weeks between the created_at timestamp, and the start date
Groups rows sharing the same week
Counts the number of rows in each group

The result you get back is something like:

{
  0 => 1,
  1 => 4,
  2 => 4,
  3 => 13,
  4 => 12
}

To then do the cumulative summation you can do:

sum = 0
cumulative_per_week = per_week.map(&:last).map { |_, count| sum += count }

Now, cumulative_per_week will be [1, 5, 9, 22, 34].

I'd also recommend splitting logic into two methods: One for sign-ups per week, and one for cumulative sign-ups per week:

START_DATE = "2016-06-15".freeze

def signups_per_week
  User
    .valid
    .where("created_at >= ?", START_DATE)
    .order("created_at")
    .group("FLOOR(DATEDIFF(created_at, '#{START_DATE}') / 7)")
    .count
    .values
end

def signups_per_week_cumulative
  sum = 0
  signups_per_week.map { |count| sum += count }
end