Sort a linked-list with only three distinct values

Algorithm

The algorithm linked in the post is a peculiar implementation of counting sort. I'm not sure why splicing and chaining is used, but I believe blunt counting into an array of three elements is much more effective. Your algorithm would be written in generic and comprehensive manner, as ints are always copy constructible.

Code

As mentioned in the comments, this is ANSI C. I've actually tried it on ideone and it worked perfectly. I also established that your code works correctly for small inputs (haven't tested others). I'm not sure if reimplementing linked list is part of the task, but I'll suggest you standard library alternatives for the code you've written:

Reading:

Not everybody might agree with me, but I like this usage:

unsigned int size{};
std::cin >> size;
std::list<int> values;
std::copy_n(std::istream_iterator<int>{std::cin}, size,
            std::back_inserter(values));

As you can see, everything is handled for us. Starting from looping size times, to push_backing items in. It is better to write declarative code that is also efficient. It is not always possible, but this case is easy enough to be handled by declarative code.

printing:

Here is what people usually prefer:

for (int value : values)
    std::cout << value << ' ';
std::cout << '\n';

But I prefer:

std::copy(values.begin(), values.end(),
          std::ostream_iterator<int>(std::cout, " "));
std::cout << '\n';

It is much harder to say which one is more expressive, thus this is more a matter of taste.

sorting:

C++ algorithms on containers are usually written using iterators. Do note though that sometimes iterators get in the way, like when you'll try to implement heap sort (e.g. heavy use of indices is needed). In this case, iterators are pretty good.

Lets start from the signature:

using iterator = std::list<int>::iterator;

void terse_sort(iterator start, iterator end)

Most of the range algorithms are declared like that: start and end of the range. Do note that end is one past the end. Here is an example: if your range is {1, 0, 1, 2}, start will point to leftmost 1, and end will point to "uncertainty" after 2. With that out of the way, lets get to the most interesting part of the algorithm:

counting:

As name of the algorithm implies, use counting:

unsigned int occurence_count[3] = {0};

auto count_pos = start;
while (count_pos != end)
    ++occurence_count[*count_pos++];

Thw while loop is the same as (p != NULL) in the code. For every index 0, 1, 2, occurence_count will tell how many of those occured in the list. Now, lets put the values in the correct places:

for (unsigned int value = 0; value < 3; ++value)
    for (unsigned int i = 0; i < occurence_count[value]; ++i)
        *start++ = value;

As it can be observed, for index 0, it is gonna write 0 from the start, occurence_count[0] times. The same for indices 1 and 2.

The algorithm mentioned in the linked post

I actually thought about it a little. The thing is that it doesn't perform any swaps! So, if blunt counting sort performs copies (e.g. doesn't regard cases where key!=value), the mentioned algorithm preserves relative order and regards keys not being the same as value. I found it really peculiar, thus decided to implement somewhat more generic version:

#include <map>

template <template <typename ...> typename List, typename ValueType, typename ... Rest>
void splice_sort(List<ValueType, Rest...>& list)
{
    std::map<ValueType, List<ValueType>> locomotives;
    while (list.size() != 0)
    {
        auto locomotive_end = locomotives[list.front()].cend();
        locomotives[list.front()].splice(locomotive_end, list, list.begin());
    }

    //no elements left in list,
    //put it back in the correct order
    for (auto&& locomotive : locomotives)
        list.splice(list.cend(), locomotive.second);
}

Since the algorithm is designed for types that are heavy to swap, they are probably not ints, but std::arrays or some other weird swappable type.

A bit of trivia.

Why locomotive?

By Marcus Wong Wongm [GFDL (http://www.gnu.org/copyleft/fdl.html) or CC BY-SA 4.0 (https://creativecommons.org/licenses/by-sa/4.0)], from Wikimedia Commons

In countries of post-Soviet era, the trains led by locomotives are commonplace, especially just after the collapse of Soviet union. When reading about the algorithm, I recalled my travels on those when I was a kid. The algorithms behaves like merge of trains: trains with lower value are appended to ones which have next bigger value, and so on until all trains are merged into one. Also the splice sort preserves relative order and regards keys not being values, like people in wagons are not their priorities, and vice versa.

Full code to play with

#include <map>

template <template <typename ...> typename List, typename ValueType, typename ... Rest>
void splice_sort(List<ValueType, Rest...>& list)
{
    std::map<ValueType, List<ValueType>> locomotives;
    while (list.size() != 0)
    {
        auto locomotive_end = locomotives[list.front()].cend();
        locomotives[list.front()].splice(locomotive_end, list, list.begin());
    }

    //no elements left in list,
    //put it back in the correct order
    for (auto&& locomotive : locomotives)
        list.splice(list.cend(), locomotive.second);
}

#include <list>
using iterator = std::list<int>::iterator;

void terse_sort(iterator start, iterator end)
{
    unsigned int occurence_count[3] = { 0 };

    auto count_pos = start;
    while (count_pos != end)
        ++occurence_count[*count_pos++];

    for (unsigned int value = 0; value < 3; ++value)
        for (unsigned int i = 0; i < occurence_count[value]; ++i)
            *start++ = value;
}

#include <iostream>
#include <algorithm>
#include <iterator>
#include <sstream>

void terse_sort_demo(std::istream& in)
{
    unsigned int size{};
    in >> size;
    std::list<int> values;
    std::copy_n(std::istream_iterator<int>{in}, size, std::back_inserter(values));

    std::copy(values.begin(), values.end(),
              std::ostream_iterator<int>(std::cout, " "));
    std::cout << '\n';

    terse_sort(values.begin(), values.end());

    std::copy(values.begin(), values.end(), std::ostream_iterator<int>(std::cout, " "));
    std::cout << '\n';
}

void splice_sort_demo(std::istream& in)
{
    unsigned int size{};
    in >> size;
    std::list<int> values;
    std::copy_n(std::istream_iterator<int>{in}, size, std::back_inserter(values));

    std::copy(values.begin(), values.end(),
        std::ostream_iterator<int>(std::cout, " "));
    std::cout << '\n';

    splice_sort(values);

    std::copy(values.begin(), values.end(), std::ostream_iterator<int>(std::cout, " "));
    std::cout << '\n';
}

int main()
{
    const std::string input = "6\n"
        "2 0 0 2 1 1\n";
    std::istringstream input_stream(input);

    std::cout << "splice sort:\n";
    splice_sort_demo(input_stream);
    std::cout << "\n\n";

    input_stream.str(input);
    std::cout << "raw counting sort:\n";
    terse_sort_demo(input_stream);
}

Demo on Wandbox.


Methods to check form validity and to count invalid form fields

If you are using Google's guava, I would suggest:

@Override
public boolean isValid() {
  // Firstly, flat your Iterable<Iterable<Component>> getFormSections()
  // into Iterable<Component>.
  // Then we use a Predicate to check whether there is any match.
  return Iterables.all(
    Iterables.concat(getFormSections()), validComponents());
}

@Override
public int countErrors() {
   return Iterables.size(
      Iterables.filter(Iterables.concat(getFormSections()), Predicates.not(validComponents()));

}

// - Positive names is always preferable
// - This method is static simply because it does not access to any instance varibles. It is easier to extract it out into another class.
private static Predicate<Component> validComponent() {
  new Predicate<Component>() {
      @Override
      public boolean apply(Component input) {
        return // your logic here
      }
    };
}


just implemented multiprocessing and queue demo, wonder if there are any improvements?

You should pass the url_q queue to the constructor instead of using it as a global variable.


One could consider at least the following points:

Instead of including <stdlib.h>, I'd include <cstdlib>.
In getRandDart(), it might in this case be more readable to do static_cast<double>(rand()) / RAND_MAX; instead of multiplying by 1.0.
In the for loop, all of x, y and d can be const, so I'd make them const. This has the potential to protect the programmer from unintended mistakes, and can sometimes allow the compiler to optimize better.
When you increment by one (in countInSquare += 1;), it makes more sense to use the ++ operator, i.e., to just write ++countInSquare. This is more idiomatic and protects us from unintended mistakes: ++ conveys the meaning of increment (by one), whereas with += we might accidentally write += 2; and that would be perfectly valid (but not what we wanted).
Regardless of the above point, notice that during the for-loop, it holds that iteration == countInSquare. So strictly speaking, the variable countInSquare is unnecessary and could be replaced by just iteration when needed.
You could consider making the number of iterations and the second operand of the % operand constants to allow for easier modification and perhaps to slightly improve readability.
Instead of typing (4.0 * countInCircle / countInSquare) twice, we could make a function that takes the two variables as parameters. This would allow us to save some typing, and again to protect us from unintended mistakes.


Serialization/Unserialization of a list of strings - C++

Looks like it will work fine.
You preserve the string integrity in the file by maintaining its length as a separate entity that you can check independently. So it should work fine.

Not sure why you copy it to intermediate arrays.
Why not copy directly from input to file then from file to output?

You implement most of the other loops so precisely. But the main loop to read from the file is a bit a bit bulky and messey. With an extra class you can make it look just like the others.

std::vector<std::string> output;
std::ifstream in("out.txt", std::ios::in);
MyStringReader    reader;

while(in >> reader)
{
    output.push_back(reader);
}
in.close();

So now you just need to define the MyClassReader

struct MyStringReader
{
    std::string   data;
    operator std::string const&() {return data;}  // This is used in the line
};                                                // output.push_back(reader) and converts
                                                  // the reader object into a string before
                                                  // it is pushed

std::istream& operator>>(std::istream& stream, MyStringReader& value)
{
    size_t length;
    char   sep    = 'X';

    // Use the stream operators to get the size (and separator)
    // Much nicer than using tha atoi() function.
    //
    if ((stream >> length >> sep) && (sep == '|'))
    {
        // Resize the string to the correct size and put the word into it.
        value.data.resize(length);
        stream.read(&value.data[0], length);
    }
    return stream;
}


If you are allowed to, I would strongly suggest using https://github.com/pathikrit/better-files to do this. The code would look like :

import better.files._
class GetFileCount {
  def getFilesCount(dir: String):Int = {
    File(dir).glob("**").count(_.isRegularFile)
  }
}

If you can't or won't use better-files, you can probably improve your code using just nio:

import java.nio.file.{ FileSystems, Paths, Path, Files }
import java.util.function.Predicate
import java.util.stream.Stream
object GetFileCount{
  val regularFilePredicate = new Predicate[Path] {
    override def test(path: Path) = Files.isRegularFile(path)
  }
}
class GetFileCount {
  import GetFileCount._
  def getFilesCount(dir: String): Int = {
    val path: Path = FileSystems.getDefault.getPath("/tmp/d1")
    val filter: Stream[Path] = Files.walk(path).filter(regularFilePredicate)
    filter.toArray.length
  }
}


Fixed space between two dynamically sized blocks

I guess this is the proper way to have fixed space between to half-fitted blocks, but maybe later you'll have small issuer with container DIV, because child elements are absolute position and parent - relative, so it will not follow heights of child elements.

for example: http://jsfiddle.net/XfStv/3/

.

------UPDATE------

You can also use table property for objects, but it's not supported by IE 7:

here is example of tabled version code: http://jsfiddle.net/zur4ik/ehGRk/


+1 to @Gilbert Le Blanc's comment. Creating

I'd consider extracting out methods like createOpenMenuItem(), createSaveMenuItem(), createPrintMenuItem() for better readability and higher abstraction:

private JMenuItem createOpenMenuItem() {
    JMenuItem openMenuItem = new JMenuItem("Open");
    openMenuItem.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {

        }
    });
    return openMenuItem;
}

Then the setUpFileMenu would be a lot cleaner:

private void setUpFileMenu() {
    fileMenu = new JMenu("File");

    // File menu items
    fileMenu.add(createNewMenuItem());
    fileMenu.add(createOpenMenuItem());
    fileMenu.add(createSaveMenuItem());
    fileMenu.add(createSaveAsMenuItem());
    fileMenu.add(createPrintMenuItem());

    add(fileMenu);
}

A maintainer would be helpful, it's easier to get an overview what the method does (without the details) and you can still check them if you are interested in. For example, finding code of save menu is much faster than before.

  Now, each JMenuItem obviously needs an ActionListener,
  so I just gave each one a different ActionListener.
  I'm skeptical about this because I know it can be kind of disorganized looking.

I've found this practice easier to work with than having one ActionListener for multiple components (with a switch-case inside).

  Basically, I just want somebody to let me know
  if this practice is all right, or if there is a better
  alternative that doesn't involve me making 20 new classes.

Having a lot of classes doesn't hurt if they have clear responsibilties.


It's pretty nice IMO but can be improved.

If your project uses apache commons (this library is often included), you should consider using the FieldUtils class to get the fields : https://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/reflect/FieldUtils.html

Notably, the getFieldsWithAnnotation method would reduce your code complexity by a bit.

That's up to you though ;)

This part :

try {
    String value = field.get(object).toString();
    string += varName + "=" + value + ", ";
} catch (IllegalAccessException e) {
    e.printStackTrace();
    string += varName + "=" + "{Unavailable}, ";
}

may fail if your field is null, you should exploit the String + operator to avoid it like this :

string += varName + "=" + field.get(object) + ", ";

string is really a bad name for your variable, maybe rename it as res or something ?

I'm no big fan of the printStackTrace, you should consider using the various logging utilities proposed by java : https://docs.oracle.com/javase/9/docs/api/java/util/logging/Logger.html or slf4j.

I think those 4 modifications will already make the code neater but we can do a bigger refactoring :
instead of using a String that we concatenate bit by bit and then remove the final comma, you should consider using a Stream over the fields array and generating the result with the Collectors#joining method.

In the end, you'd have the following method :

private static final String SEPARATOR = ", ";

public static String format(Object object) {
    final String className = object.getClass().getSimpleName();
    final String prefix = className + "[";
    String res = Arrays.stream(FieldUtils.getFieldsWithAnnotation(object.getClass(), Formatted.class))
        .map(field -> {
        String varName = field.getName();
        try {
            return varName + "=" + field.get(object);
        } catch (IllegalAccessException e) {
            log.severe(e.toString());
            return varName + "=" + "{Unavailable}";
        }
    }).collect(joining(SEPARATOR));
    return prefix + res + "]";
}


You can always break it down in multiple lines to make it more readable. You can also use named groups which take the "magic" out of the group numbers (4 == whisper, 3 == normal, etc).

        var regex = new Regex(@"^\[(?<TimeStamp>\d{2}:\d{2}:\d{2})\]\s*" +
            @"(?:" +
                @"(?<SysMessage>\[System Message\])?\s*" +
                @"<(?<NormalWho>[^>]*)>|" +
                @"(?<Whisper>(?<WhisperWho>.+) Whisper You :))\s*" +
            @"(?<Message>.*)$");

        string data = @"[02:33:03] John Whisper You :  Heya
[02:33:03] John Whisper You :  How is it going
[02:33:12] <John> [02:33:16] [System Message] bla bla
[02:33:39] <John> heya
[02:33:40] <John> hello :S
[02:33:57] <John> hi
[02:33:57] [System Message] <John> has left the room
[02:33:57] [System Message] <John> has entered the room";

        foreach (var msg in data.Split(new char[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries))
        {
            Match match = regex.Match(msg);
            if (match.Success)
            {
                if (match.Groups["Whisper"].Success)
                {
                    Console.WriteLine("[whis from {0}]: {1}", match.Groups["WhisperWho"].Value, msg);
                }
                else if (match.Groups["SysMessage"].Success)
                {
                    Console.WriteLine("[sys msg]: {0}", msg);
                }
                else
                {
                    Console.WriteLine("[normal from {0}]: {1}", match.Groups["NormalWho"].Value, msg);
                }
            }
        }


Rather than using timing intervals, you may want to consider using promises/deferreds to process your queue. By doing this, you don't have wasted time gaps where you are not doing work. You could also experiment with the number of items you process of the queue at a given time to find the right balance between execution time and resource consumption.


Updates list in haskell to remove duplication

It is better to use records instead of tuples here:

data Rating = Rating
  { user :: String
  , rate :: Int
  } deriving Show

data Film = Film
  { title    :: String
  , director :: String
  , year     :: Int
  , ratings  :: [Rating]
  } deriving Show

Thus you get self documenting code and all of pull* functions for free (for each field compiler generates accessor function with the same name).

This also leads to more concise implementation of other functions:

-- Find films by name
getFilm :: String -> [Film] -> [Film]
getFilm search = filter ((== search) . title)

Note that in Haskell there is no single element tuple, so parentheses around Film are redundant ([Film] but not [(Film)]).

newRating :: Rating -> [Rating] -> [Rating]
newRating r = (r :) . filter ((/=user r) . user)

I switched arguments in newRating because this allows to define function more concisely and it is also correlates with update/insert from Data.Map: they have collection as a last argument.

Now it is possible to skip directly to rateMovie and implement it in couple of lines:

rateMovie :: String -> Rating -> [Film] -> [Film]
rateMovie mTitle nRating database
  = [m {ratings = newRating nRating (ratings m)} | m <- matchingMovies]
  ++ database'
  where
    (matchingMovies, database') = partition ((==mTitle).title) database

(Btw, why "movie"? we were talking about "films" all the way.)

I'm using partition from Data.List to extract matching movie(s) from database.

Also there is funny syntax I'm using to update movies:

m {ratings = ...}

You can read more about it here.

And of course it is better to use Data.Map instead of simple lists if the code is full of lookups.


Updating a JavaFX ListView after service update

Found a better way myself:

saveButton.setOnAction( event -> {
            // Save the updated note with the service
            Note selectedItem = listView.getSelectionModel().getSelectedItem();
            selectedItem.setTitle( titleField.getText() );
            selectedItem.setContent( contentField.getText() );
            noteService.updateNode( selectedItem );

            // First update the item in the model
            listView.getItems().set( listView.getSelectionModel().getSelectedIndex(), selectedItem );
            // Trigger a sort of the items. Could be avoided by checking if the title really did change
            listView.getItems().sort( new NoteComparator() );

This avoids getting the full lists of notes from the service again each time.


Your code is really good, so there's not much to improve on, that I can see, but nonetheless:

You shouldn't have whitespace before, or inside your brackets unless required:

   $return = $input[ array_search($element, array_column($input, 'id')) ];
                    ^                                                  ^
   $str [] = $return ['name'];
       ^            ^
   if($return ['parent'] != 0) {
             ^
       $str [] = path($return ['parent'], $input);
           ^                 ^

All these lines above have unnecessary whitespace, however the line below is missing whitespace after the comma in path().

var_dump(path(13,$in));
                 ^

You really ought not to name your variables $return or $str, because the first is a system keyword, and the second is undescriptive & possibly confusing as it's really an array, not a string.

The implode string -> could also be -> with an extra space, or even a unicode long (or not long) rightwards arrow: ⟶, along with the extra space, visually output would be more readable, and better looking.

13 - Anniversary -> New arrives -> Discount // With added space
13 - Anniversary ⟶ New arrives ⟶ Discount // With added space and long rightwards arrow


Is this a proper use of a services project and an ASP.NET MVC controller?

My first instinct is to suggest using built-in ASP.NET Roles. This is handled at the ASP.NET level, so in general you can redirect to the appropriate View. You may have roles for 'Anon' 'Read' and 'ReadWrite' and possibly more. This will help with the first pass authorization, not at the specific database record level, but at a high level based on user type, aka role. However, its not required and the per record, per user access will work just as well.

If you have specific access requirements on a 'per record, per user' basis, you have a couple options.

A) Do what you're doing now, pass the User object to the Services layer, and let the services sort it out and return an appropriate error code. In this case, the service probably selects all of the data required to service the request, so if you expect a high level of authorization failures, this is probably not ideal because you'll waste a lot of database IO on requests that are going to fail. If in your list views, you arleady eliminate records the user doesn't have access to, and are your record level security is to prevent people from Uri snoopting (/Entity/Detail/#### for example) this might be sufficient.

B) Implement a method or two in your services layer which accepts a UserID and an EntityID. It then does the minimum database selection to determin if the UserID provided has access to the EntityID and it simply returns true/false. This is a good option if you expect that high number of requests for entities will fail authorization, since in the failed instances, you'll only select a few bits of data from the database and not the entire request; however, for requests that are permitted, you end up doing two selections. Only you can decide if this is worth it or not. But it does make the code a bit more simple:

if(! services.UserEntityAccess(userID, entityID))
{
    return View("NoAccessView");
}

return View(services.ReadEntity(entityID));

C) Hybrid of A and B, when you initialize a new instance of your service layer, make sure that your User object is a parameter in the constructor of the service, then your service can is always operating from within the "context" of a specific user. This is probably the way I would go, and internally, you can decide which of option A or B works best, based mostly on how many failed authorizations you expect, the advantage here is that if you guess wrong, it's easy to change, because its handeled internally to the class, and you wont need to change any calling code.

public ActionResult Get(int id)
{
    var svc = new ServicesLayer(GetUser());
    var entResponse = svc.GetEntity(id);

    if (entResponse.Error != null)
    {
        return View("ErrorView",entResponse.Error);
    }

    return View(entResponse.Entity);
}


I'm not sure if I understand your input data correctly, since I don't get this $queue.pop(start.to_i), but:

I won't mention codestyle issues -- I'll talk about algorithm.
Looks like your search is really Depth-first, since it doesn't find the shortest path:

$h = {?0=>[?1,?2,?3], ?1=>[?3], ?3=>[?4]}
p find_path ?0,?4
=> ["0", "1", "3", "4"]

it is because:

it calls recursion immediately before iterating the rest of child nodes
in real Breadth-first you have to store a lot of paths at the same time

Use Set instead of Array for visited, since it looks up immediately instead of searching the value from the beginning of the list.
The easiest way to implement both of these searches with no risk of stack overflow is to use stack of the next states, that we should analyze instead of recursion. Also in this way we don't need global variables or other namespace tricks, since we just do the loop, where path is used instead of $queue and returnArray:

Take this code:

def find_path start, endpoint
  require "set"
  visited = Set.new
  stack = [[start.to_s]]
  until stack.empty?
    path = stack.shift
    start = path.last
    get_next_paths(start).each do |i|
      return path.push i if i == endpoint.to_s
      next if visited.include? i
      visited << start
      stack.push path+[i]
    end
  end
end

And run this:

$h = {?0=>[?3,?2,?1], ?1=>[?5], ?3=>[?4], ?5=>[?4], ?2=>[], ?4=>[]}
p find_path_ ?0,?4

The fun thing is how it is now easy to switch between Depth and Breadth by just replacing .shift with .pop:

["0", "3", "4"]
["0", "1", "5", "4"]


Substitution cipher algorithm performance boost

You should use memoization on findNextPossible(), otherwise your algorithm has exponential complexity.

Also: the optimization obtained by looking for '0's will be no more useful once you use memoization... so the resulting code should become much, much smaller.

This is a possible implementation:

#include <string>
#include <map>
#include <iostream>
#include <cassert>

using namespace std;

int ways(std::string s) {
  static map<string,int> cache;
  map<string,int>::const_iterator f = cache.find(s);
  if (f!=cache.end()) return f->second;
  //  cout<<"ways("<<s<<")"<<endl;
  if (s.size()==0) return 1;
  if (s[0]=='0') return 0; // no way the first digit is 0
  if (!isdigit(s[0])) return 0;
  if (s.size()==1) return 1; // only one possibility for a single digit
  // here we have at least 2 digits
  if (!isdigit(s[1])) return 0;
  int n = 10*(s[0]-'0')+(s[1]-'0');
  if (n>26) return cache[s] = ways(s.substr(1)); // cannot merge first two digits.
  return cache[s] = ways(s.substr(1)) + ways(s.substr(2)); // two possible interpretations
}

const char *tests[]={"1213","12","214","205",0};

int main() {
  for (int i = 0; tests[i]; ++i) {
    cout<<tests[i]<<": "<<ways(tests[i])<<endl;
  }
}


Adding an attribute to a class after the documentation comment trivia

Look into the WithAnnotation(Formatter.Annotation) member.  This should create a new node with the correct leading indentation.

var newClassNode = classNode.AddAttributeLists(attributeList)
                            .WithAnnotation(Formatter.Annotation)


Filling in gym membership prices by joining PANDAS dataframes

Consider a left side merge to match member data with corresponding prices by contract type and date. No for loops or external list needed for this approach:

df = pd.read_excel(location)
df_prices = pd.read_excel(location2)
df_prices.fillna(method='ffill',inplace=True)

finaldf = pd.merge(df, df_prices, left_on=['Date-Joined','Contract Type'],
                   right_on=['Date','Description'],
                   how='left')[['Member Nbr','Date-Joined','Contract Type','Amount']]

finaldf.to_excel(location, index=False)


Linked list in Python which gets values from keyboard

I don't see anything glaring, except for the size method. It has 2 major flaws:

Every time you want to check the size, you must traverse the entire list, giving it a time complexity of O(n) (linear). This would likely be an unacceptable complexity for real world use. I'd expect that a size method would be O(1), meaning the length of time the operation takes  has nothing to do with the number of elements in the list. What if your list contained a million elements and you needed to repeatedly get the size of it?
It prints the size instead of returning it. Rarely should a method print its result; unless that's the sole purpose of the method. Return the result instead of printing it directly so the returned size can actually be used instead of just seen. If you want to print the data, print the return of the function instead. Let the caller of the function decide how the data is used instead of forcing it to be printed.

How can these points be fixed? Instead of calculating the size, give your list an n_nodes (or similar) field, and increment it inside of insert:

def insert(self,data):
    data = input("Add an element:")
    node = Node()
    node.data = data
    node.next = self.head
    self.head = node
    self.n_nodes += 1 # Here

Then just change your size method to return n_nodes. Notice that the number of elements in the list has no effect on the time this method will take to finish:

def size(self):
    return self.n_nodes

Then just print the size at the call site:

...
elif menu == 3:
    print(MyList.size())

Now that I've looked over your insert method though, it suffers from a similar problem: needless use of side-effects. Why ask for the data inside the method via input instead of passing the data in? What if you want to insert data that came from the internet, or from the disk?

Use the data parameter of the insert method to pass the data in, and get rid of the call to input. The data can still come from input, just ask for it outside of the method.


Reporting success or failure of a child process

In your original post, you wrote

The variable result is an integer representing the exit code of a command line process that was run via Groovy code. An exit code of 0 means the process was successful and an exit code from 1-255 means a failure. Then this line is executed:
println result ? "The command failed." : "The command succeeded."

I find it interesting you had to explain it so much.  I imagine if this were real code you may have to attach a similar code comment.
Personally I prefer to write code that requires no comments, if possible, and no explanation, by using well-crafted symbols.  So for example if you wrote it as
boolean success = (exitCode == 0);
println success ? "The command succeeded." : "The command failed.";

...you wouldn't have to explain that a exit code of 0 indicates success, and it wouldn't require a second glance to figure out the reversed ternary expression.
Any compiler worth its salt will optimize out the working variable and emit exactly the same executable code, so the increased readability costs you nothing.


Working and calculating with geographic positions

There are some temporary variables that you might not use, such as fLatTarg_deg and fLotTarg_deg: you can commit the operation along with the function call.

Also, the variables (which are actually costants, probably) _RADIUS_EARTH_m and _PERIMETER_EARTH_m are breaking the standard C++ naming conventions.


Creating two output files from two formatted files

All in all I can understand it OK, it reads fairly well. There are a few structures I would recommend you change.... for a start, I would separate the category definitions from the counters, as it would be easier to maintain:

Note, I am defining @categories as a simple array, not a nested array here.... so it is a different thing from yours:

my @categories = ('RMA Request', 'Product Info Request', 'Dealer Locator (New or Resupply)',
                  'Order Request', 'Order Status', 'Wireless Activation/Deactivation',
                  'Pricing', 'Account Setup/Registration', 'Other');

my %catcounts;
foreach (@categories) {
    $catcounts{$_} = 0;
}

OK, this does three things, it makes adding/changing the categories easy, and it separates the count setup from the category setup. It also sets up a hash fro the counter, so you don't need to loop through them all but can do it by key, so the code:

        if ($line =~ /^"(.+)"$/) {
            foreach my $cat (@categories) {
                if ($1 eq $cat->[0]) {
                    $cat->[1]++;
                    $match = 1;
                }
            }
        }
        # Add case to 'Other' if no match was found
        if (not $match) {
            $categories[8]->[1]++;
        } else {
            $match = 0;
        }

can become:

        if ($line =~ /^"(.+)"$/ && defined $catcount{$1}) {
            $catcount{$1}++;
        } else {
            $catcount{'Other'}++;
        }

This will be much faster because it uses the hash lookup instead of the array loop to find the category.

you will need to adapt the output to loop through the @categories, but print out the %catcount


Singly linked list implementation in Scala

A list is just a wrapper for an element that also contains a pointer to another list, thus its definition is straightforward:

scala> abstract class MyList[+A]
defined class MyList

scala> case class MyCons[A](head: A, tail: MyList[A]) extends MyList[A]
defined class MyCons

scala> case object MyNil extends MyList[Nothing]
defined object MyNil

scala> val xs = MyCons(1, MyCons(2, MyCons(3, MyNil)))
xs: MyList[Int] = MyCons(1,MyCons(2,MyCons(3,MyNil)))

scala> xs.head
res2: Int = 1

scala> xs.tail
res3: MyList[Int] = MyCons(2,MyCons(3,MyNil))

This list is completely immutable. Because of the polymorphic type A it can take any type of element and because it is covariant +A, it can also take the subtypes of an element:

scala> trait T
defined trait T

scala> class X extends T
defined class X

scala> val xs: MyList[T] = MyCons(new X, MyNil)
xs: MyList[T] = MyCons(X@56a13ea6,MyNil)

The covariant nature of type A also allows the definition of MyNil, which would not be possible otherwise because it is parameterized with type Nothing, Scalas bottom type.

This single linked list definition is also the actual implementation of type List in the stdlib of Scala, although this implementation contains some more optimization details and MyCons is called ::.

If you also want to access the members head and tail when you only have type MyList instead of the more concrete type MyCons then you have to declare them directly in the supertype:

abstract class MyList[+A] {
  def head: A
  def tail: MyList[A]
}

case class MyCons[A](head: A, tail: MyList[A]) extends MyList[A]

case object MyNil extends MyList[Nothing] {
  def head = throw new NoSuchElementException("MyNil.head")
  def tail = throw new NoSuchElementException("MyNil.tail")
}


For 2.x and 3.x compatibility, I would explicitly use eval(raw_input(...)); you can then use:

import sys

if sys.version_info[0] > 2:
    raw_input = input

This makes more sense if you're writing for 2.x first, and is slightly easier than shoehorning eval onto 3.x's input everywhere you need it (which also makes life more difficult everywhere you don't).

Also for compatibility, print is a function in 3.x. You can import from __future__, or just use

print("{}\n".format(math))

in both.

You could make the constants class attributes:

class Parser(object):

    PROMPT = "..."
    ERR_MSG = "..."

    def parse_math(self):
        ...

These are still accessible via self, so your other code doesn't change. Note that now there are no instance attributes, you don't need __init__. In fact, you could take this further and make parse_math a class method, then you don't need to create an instance to call it.

Try giving the user a way to escape the loop. Perhaps:

while True:
    math = raw_input(self.PROMPT)
    if math.lower() == "done":
        break
    try:
        math = eval(math)
    except (NameError, SyntaxError):
        print(self.ERR_MSG)
    else:
        print("{}\n".format(math))

Note here also

Splitting input and evaluation to allow pre-evaluation checking;
Catching specific errors (see e.g. here); and
Using the else to minimise the code in the try block.

Finally, your code has no documentation. This is simple enough to not really need it, but it's a habit worth getting into. See e.g. PEP-257.


Here are a few minor suggestions:

Use uninterned symbols instead of keywords in defpackage (e.g., #:neg instead of :neg) to avoid polluting the keyword package.
Fix your indentation.
Add a defgeneric with docs for each defmethod (you can fold defmethod inside defgeneric)
Decide if your objects are read-only; if they are, replace :accessor with :reader, if they are not, add mutator functions (e.g., scale in-place)
Rename norm to normalize (norm in math refers to the length of the vector)
Use (plusp x) instead of (> x 0)
Use (/ x) instead of (/ 1 x)
In the else clause in norm can just return the argument or (create-vector3 0 0 0) for clarity


To start off, I have no idea what a SoC.DAL.Role is. Your namespaces are short abbreviations. This is quite hard to follow for people not really into your project.

Your role can add itself to a repository. This is not behaviour that I would expect. I would have a simple repository class (RoleManager?) that is capable of adding roles.

Role role = new Role(...);
new RoleManager().AddRole(role);

As such, you have 4 layers. One data access layer, one model layer, one domain layer and one GUI layer.


Export Hero information and list of his items to excel sheet/csv

hero.getLevel()+""

Use an explicit cast instead of implicit one:
Integer.toString(hero.getLevel())

```java
new Date().toString(),
// ...
hero.getGold().toString()

Which might or might not be the format you want in the final file. Ideally you'd define explicit formatting rules.

There are a few approaches to serialization of data like in your case.
POJOs are Serializable
The first approach is to teach your POJOs how they are being serialized. That means that they implement some interface, like CsvSerializable which defines the method `serialize(CSVWriter csvWriter).
This has the upsides that the the objects themselves know how to serialize themselves. The downsides are that your data is now bound to CSVWriter and that you need to thing about where and how to put the header.
Adapters
The second possibility is to use "adapters", which means that you have Hero and HeroSerializer classes. The later has a method like serialize(Hero hero, CSVWriter csvWriter).
This has the upside that your data classes are fine on their own, the downside is that you need two classes per class (that's 100% more class per class) and that the logic you already have is not that much improved.
Monolithic serializer
That's basically that approach that you already have. With some minor changes (like encapsulating more logic into separate methods, for example the writing of each different item type into its own method) it's actually a very good approach. It keeps your data classes on their own, but you have an ever growing monolith.
Reflective serialization
Fields
Now comes the fun one, you could use reflection to access the fields at runtime. That means that your ITEM_LIST_HEADER actually becomes the key to serialization of your objects. That approach is more complicated, but means a little bit more flexibility. The downside is that your fields always must be the same than the headers...well, if you consider that a downside.
So what you could be doing is something like this:
private void writeLine(CSVWriter csvWriter, Object object, String[] fieldNames) {
    Map<String, Field> fields = getFields(object.getClass());
    String[] values = new String[fields.length];

    for (int index = 0; index < fieldNames.length; index++) {
        String currentFieldName = fieldNames[index];
        Field field = fields.get(currentFieldName);

        if (field != null) {
            values[index] = Objects.toString(field.getObject(object));
        } else {
            values[index] = "-";
        }
    }

    csvWriter.writeNext(values);
}

private Map<String, Field> getFields(Class<?> clazz) {
    // Could be cached for each class if performance is important.
    Map<String, Field> fields = new HashMap<>();

    for (Field field : clazz.getDeclaredFields()) {
        // Maybe add some checks, like if the field is static or not.
        field.setAccessible(true);
        fields.put(field.getName(), field);
    }

    return fields;
}

Untested and without exception handling, but I guess you see where this is going.
Getters/Setters
Like above, you can access the Getters/Setters reflectively. It is close to the same solution as above, with the difference that you don't need the set the fields accessible. However, you must be slightly more selective with what methods you expose in that case, and you need to convert the names.


Determine whether path A→B→C on a plane constitutes a left or right turn

Welcome to Haskell (and Code Review). Your ADT Direction is a good approach for the result. However, top-level functions should have a type, as it will make type errors easier to read and give other users an idea how to use your function:

type Point2 = (Double, Double)

findDirection :: Point2 -> Point2 -> Point2 -> Direction
findDirection (x, y) (x1, y1) (x2, y2)

While isn't necessary—GHC can infer it—it can at least act as a minimal documentation.

Next, we should tackle the names. We have x, x1 and x2. Those seem arbitrary. Why don't we start with x1? The names (ax,ay), (bx,by) and (cx,cy) would be more suitable, since we're talking about the coordinates of three specific points, a, b and c:

findDirection :: Point2 -> Point2 -> Point2 -> Direction
findDirection (ax, ay) (bx, by) (cx, cy)

However, as vnp said, you should use the cross product. While the cross-product is only defined for three dimensions, we can simply embed your points into \$\mathbb R^3\$ and then take the Z-component of the resulting vector:

type Vector2 = (Double, Double)

-- See https://en.wikipedia.org/wiki/Cross_product#Computing_the_cross_product
cross :: Vector2 -> Vector2 -> Double
cross (ax, ay) (bx, by) = error "Implement this as an exercise"

With yet another function, we can then get the two vectors from our original three points:

diff :: Point2 -> Point2 -> Vector2
diff (ax, ay) (bx, by) = (bx - ax, by - ay)

Now we really end up with an elegant solution:

findDirection :: Point2 -> Point2 -> Point2 -> Direction
findDirection a b c =
    case cross (a `diff` b) (b `diff` c) `compare` 0 of
        GT -> LeftTurn
        EQ -> Straight
        LT -> RightTurn


Should I moved the foreach loops in the model?

Yes, definitely.

Currently, you have SQL in the model and the controller, which isn't a good idea. It makes it hard to make out what the actual query will be, and splitting up one functionality (database lookup in this case) in multiple classes is not a good idea in general. SQL should be part of the user model (or DAO), so create a method called searchBy($keywordsArray) there and use that.

Security

You are completely open to SQL injection, as you put $_POST values directly into your query as column name and like clause. When putting variable content into queries, you should always use prepared statements to defend against SQL injection if possible.

When it's not possible, for example with variable column names, then you should prepare a whitelist of your columns, and check if the user input is in it.


Converting string elements of an array to upper and lower case, maintaining names of keys

Is there any possible way to somehow use implode and explode to get around this (convert to string while somehow keeping key names in memory)?

You can get all the keys using array_keys then combine them with array_combine.

$upperCase = array_combine(array_keys($Color), explode(',', strtoupper(implode(',', $Color))));
print_r($upperCase);

But why do all these efforts? Your solution is perfect, you could not do better.

  should this sort of operation be done with one function rather than the two

If you have no need to do anything else but convert the text in lowercase/uppercase, then just call

print_r(array_map('strtoupper', $Color));

  Is it good practise to implement such guard conditions in my own code at this point?

It is advisable when you do not know the data you're working. It is not in this case.


Find more appropriate data structures

  This question has been asked for other languages, but I haven't seen it for C++.

Getting timeout usually indicates an inefficient algorithm.
The language doesn't matter, because algorithms are language agnostic.
Some of the posts you linked mention the word "performance",
and they shed light to the problem,
with suggestions that could be applied here too,
even if the language is different.

The first thing to ask when a solution is too slow,
what's the time complexity of the algorithm?

   quadratic: \$O(n^2)\$

That's not so good. Looping over all elements is a linear operation (\$O(n)\$),
and checking if an element is in a vector is also a linear operation.

In other words, the weak spot is using a vector to store the elements already seen.
A vector doesn't provide a fast way to search for random elements.
Other data structures can provide faster than linear performance to lookup elements:
a tree set can do it in logarithmic time (\$O(\log n)\$, making the overall complexity of your algorithm log-linear \$O(n \log n)\$),
or a hash set can do it in constant time (\$O(1)\$, making the overall complexity of your algorithm linear \$O(n)\$).

Coding style

The name newVector is not great, for several reasons:

What's "new" about it?
Including the name of the data structure in the name of the variable usually doesn't give much new information to the reader, and therefore doesn't help understand its purpose.

This vector is used to store elements already seen. I would have called it seen.

The name a is even worse: it tells nothing to the reader about what it is.

The main loop goes over indexes of the input vector.
You could loop over the values of the input,
which would read more natural:

for (int value : a) {
    if (std::find(newVector.begin(), newVector.end(), value) != newVector.end()){
        return value;
    }
    newVector.push_back(value);
}


This looks pretty decent for a beginner. Some suggestions:

Making a variable space instead of using the literal directly is actually a kind of nice idea. You can improve the code by marking the local const.
Why is pos an integer? it only has two values, and you are using it to test a condition. Use a bool instead.
For that matter, why have pos in the first place? Pos tells you the same thing as pig1.Length == 0.
Any time you write a comment, ask yourself did I add this comment because the code was unclear? and then can I write the code so clearly that I don't need the comment?  You say

string pig2 = ""; // First letter

Dude. If the name of the variable is firstLetter then you don't need the comment.
pig2 is just one letter, so it can be a char instead of a string. You can say:

char firstLetter;
...
firstLetter = word[0];

You're using pig1 as an accumulator; you're accumulating the final result piece by piece. This is totally fine for small strings. If that string was really big then this is not an efficient technique; you should use StringBuilder instead if you want to make an accumulator for a large string.
Finally, like I said, this is fine for a beginner, walk before you run, and so on. To give you a sense of how an expert would write this code, I'd write it like this:

string pigLatin = string.Join(" ",
  engword.Split()
         .Select(word => word.Substring(1, word.Length - 1) + word[0] + "ay"));

Which is nicely compact.


Dynamically-resizable array implementation, for use in a game-dev-related library

Use a memory checker
There's a clear bug, identified by running the test program under Valgrind:
==21190== Invalid free()
==21190==    at 0x48369AB: free (in /usr/lib/x86_64-linux-gnu/valgrind/vgpreload_memcheck-amd64-linux.so)
==21190==    by 0x109320: cg_mem_list_remove (215759.c:64)
==21190==    by 0x109388: main (215759.c:94)
==21190==  Address 0x1fff0006a8 is on thread 1's stack
==21190==  in frame #2, created by main (215759.c:82)

This is where a local variable, not allocated with malloc() has been passed to free().
There's also a leak:
==21190== 16 (8 direct, 8 indirect) bytes in 1 blocks are definitely lost in loss record 2 of 2
==21190==    at 0x48356AF: malloc (in /usr/lib/x86_64-linux-gnu/valgrind/vgpreload_memcheck-amd64-linux.so)
==21190==    by 0x4837DE7: realloc (in /usr/lib/x86_64-linux-gnu/valgrind/vgpreload_memcheck-amd64-linux.so)
==21190==    by 0x1091F8: cg_mem_list_add (215759.c:36)
==21190==    by 0x109366: main (215759.c:88)

This is only partially mitigated if we add a call to cg_destroy_mem_list, because the individual items still don't get reclaimed (that's what the "8 indirect" refers to).
Other issues
We need to include <stdlib.h>, to use malloc() and family.
We're completely missing the (necessary) error checking when we call malloc() and realloc(), both of which can return null pointers.  Remember to check the result of realloc() before overwriting the old pointer (which is still valid if realloc() failed).


Project Euler #7 in C: find 10001st prime using something like Sieve of Eratosthenes

Your code is using trial division (i % primes[j] == 0) and thus it is not at all similar to the Sieve of Eratosthenes - or any prime sieve, for that matter.

The core idea of prime sieves is that you have some sort of array with a flag for each of the candidate numbers - the sieve - and that all the non-primes in that array get struck off in some fashion so that whatever is left must be prime.

The hallmark of Eratosthenean sieving is the avoidance of multiplication and/or division during the striking-off process; multiples of a number are enumerated by repeated addition of that number. That's why it can be several orders of magnitude faster than the alternatives.

There's nothing wrong with trial division as such, as long as you find it fast enough for your purposes. Had the Euler problem description asked for the 100,000,001st prime then things would look different, though, and you'd need a lot of patience for approaches based on trial division. So much so that you'd be faster programming a nice sieve instead of waiting for the trial divider to finish...

Next time, start with the simplest, most straightforward implementation of your idea and leave out the supposed optimisations. Don't start 'optimising' until you have proof that it's necessary, and keep optimisations only if the measured improvement significantly outweighs the resulting uglification of your source code. If you do some measurements then you'll find that only appreciable effect of your current 'optimisations' is to make the code unreadable.

Starting with the simplest, cleanest rendering of your algorithm might help you avoid mistakes like trial dividing by the primes 2 .. 13 twice (first explicitly in a branch statement, then again implicitly when checking against the array of found primes).

Also, in order to prove the compositeness of a number you only need to check potential factors up to the square root of the number. You are checking all primes less than that number (i.e. all primes found so far), which is a lot more than necessary.

Note: explicitly trial-dividing by a handful of the smallest primes is indeed a valid optimisation that can also be found in industrial-strength code. It works because dividing by constants enables compilers to pick more efficient means than actual division, like using multiplication and shifting, or testing bit 0 for computing x % 2. However, like all optimisations it needs not only the proof of validity but also the proof of necessity in order to make the cut.


Find the product of digits at odd/even places

Program structure

Separate I/O from the calculation and keep the main function short:

public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    int dist = sc.nextInt();
    if (dist < 0) {
        // ... report error and terminate  program.

    }

    int bonus = calculateBonus(dist);
    System.out.println("The bonus is " + bonus);
}

That makes the program structure clearer, makes the functions reusable, and allows to add test cases easily.

Handle invalid input

By convention, error messages are written to the standard error output, and a nonzero exit code indicates an abnormal program termination. Instead of "Invalid Input" I suggest to print a message indicating the correct usage:

if (dist < 0) {
    System.err.printf("Input must be a non-negative integer.");
    System.exit(1);
}

Miscellaneous

Inconsistent white space here:

int bonus=0;
int prodOdd = 1;

It can be difficult to choose a good variable name, but I am sure that you'll find something better here:

int lol = counter;

Declare variables at the nearest scope where they are used. As an example, currDigit is only used inside the for-loop:

for (int i = 0; i < lol; i++) {
    int currDigit = dist % 10;
    // ...
}

Simplifiying the program

The calculation of

    if (prodOdd == prodEven)
        bonus = 2 * prodOdd;
    else
        bonus = prodOdd > prodEven ? prodOdd : prodEven;

does not change if we exchange the even and the odd product. Therefore it does not matter if we count even and odd position from the most significant (decimal) digit or from the least significant digit.

As a consequence, we can process the digits starting with the least significant one, and it is not necessary to calculate the number of digits beforehand.

Instead of the counter, a boolean variable is sufficient to keep track of even and odd positions.

So the countDigits() function is obsolete, and calculateBonus() could be implemented like this:

public static int calculateBonus(int dist) {
    int prodOdd = 1;
    int prodEven = 1;
    boolean evenPosition = true;

    while (dist > 0) {
        int currDigit = dist % 10;
        if (evenPosition) {
            prodEven *= currDigit;
        } else {
            prodOdd *= currDigit;
        }

        dist /= 10;
        evenPosition = !evenPosition;
    }

    return prodOdd == prodEven ?
        2 * prodOdd :
        prodOdd > prodEven ? prodOdd : prodEven;
}


Aho-Corasick algorithm to scan through a list of strings

This code is slow because:

It builds a new keyword tree for each test case. Just build it once, using all the genes.
It builds a list of all the matching keywords. KeywordTree.search_all() is a generator, just loop over it directly. And,
It loops over the list of genes to find the gene index, so that it can find the health.
Instead, build a dict with the genes as keys and an (index, health) tuple for the value.

Something like this (untested):

import math
from collections import defaultdict
from ahocorapy.keywordtree import KeywordTree

def geneshealth(genes, health, testcases):

    # build the kwtree using all the genes
    kwtree = KeywordTree(case_insensitive=True)
    for gene in genes:
        kwtree.add(gene)
    kwtree.finalize()

    # build a dict that maps a gene to a list of (index, health) tuples
    index_and_health = defaultdict(list)
    for gene, data in zip(genes, enumerate(health)):
        index_and_health[gene].append(data)

    min_dna_health = math.inf
    max_dna_health = -math.inf

    for case in testcases:
        start, end, dna = case.split()
        start = int(start)
        end = int(end)

        dna_health = 0

        # search the dna for any genes in the kwtree
        # note: we don't care where the gene is in the dna
        for gene, _ in kwtree.search_all(dna):

            for gene_index, gene_health in index_and_health[gene]:

                # only genes that are within the testcase limits
                # contribute dna_health
                if start <= gene_index <= end:
                    dna_health += gene_health

        # keep the min/max weight
        if dna_health < min_dna_health:
            min_dna_health = dna_health

        if dna_health > max_dna_health:
            max_dna_health = dna_health

    return(min_dna_health, max_dna_health)


Making a pool of coroutines seems not to be the way why we invented coroutines. Coroutines means to be lightweight, so that they can be created in very large numbers. Rather than limiting the number of coroutines, I think the right way to do this is to limit the running coroutines, and:

use an asyncio.Semaphore

async def worker(semaphore, coro):
    async with semaphore:
        await coro()

async def scheduler(corotines):
    tasks = []
    semaphore = asyncio.BoundedSemaphore(pool_size)
    for coro in corotines:
        tasks.append(loop.create_task(worker(coro))
    await asyncio.gather(*tasks)

loop.run_until_complete(scheduler(coroutines))
loop.close()

check out this article for a full example.


DRY - Don't Repeat Yourself:

1) change this block into an method:

switch Model.sharedInstance.levelPassed[0] {
    case 1:
        level1.setBackgroundImage(image, for: .normal)
    case 2:
        level1.setBackgroundImage(image2, for: .normal)
    case 3:
        level1.setBackgroundImage(image3, for: .normal)
    default:
        break
}

into this (assuming you can access thee image1 to image 3:

func applyImage(button: UIButton, level: Int){
    switch Model.sharedInstance.levelPassed[0] {
        case 1:
            level1.setBackgroundImage(image, for: .normal)
        case 2:
            level1.setBackgroundImage(image2, for: .normal)
        case 3:
            level1.setBackgroundImage(image3, for: .normal)
        default:
            break
    }
}

so you can call it this way:

applyImage(level_1,1)
applyImage(level_2,2)
applyImage(level_12,12)

2) avoid the switch:

arrays are zero based, so you decrease the level by 1

let images = [image1,image2,image3]

func applyImage(button: UIButton, level: Int, images: [UIImage]){
    button.setBackgroundImage(images[level-1], for: .normmal)
}
applyImage(level_1 , 1, images)
applyImage(level_2 , 2, images)
applyImage(level_12,12, images)

3) use IBOutletCollection and .tag property

because the order of an IBOutletCollection is not guaranteed you should use the tag property to ensure it shows the right information:

@IBOutlet var buttons: [UIButton]!

let images = [image1,image2,image3]

for button in buttons {
    button.setBackgroundImage(images[level-1], for: .normmal)
}

PS: all code is untested pseudo code - but it should show you the idea how to improve your code


Someone posted an answer which had some great points, but they deleted it.  I am only going to mention a couple of points that they made as well as some new ones, but they should definitely put their answer back up!

I am no Javascript expert but I have used it before.  Despite this, I am having great difficulty understanding what your code does.  You say you think the code is pretty good, so I'll have to take your word for it that it does what you are expecting it to do.  It is very hard to understand, though!

I'll just go through and point out things as I see them.

    var CameraX = 0,
        CameraY = 0;

Personally for this I would just say var CameraX; and var CameraY; on separate lines.  I don't see what you are really gaining by omitting the second var.  I know that it is legal to do it your way in Javascript, so it's not that it's wrong, but in my opinion it just causes a potential reader of your code to have to pause and reread it to fully understand.

for(var yChunks = 0; yChunks < NumYChunks; yChunks++)

You are iterating based on yChunks, but the fact that you have it plural just makes it confusing.  I would suggest simply yChunk, but I will talk about that more in the next paragraph.  The name NumYChunks is also a bit confusing.  Is it the max number of y chunks?  If so, I would call it MaxYChunks instead.

To elaborate on my earlier point, your naming is all over the place and completely inconsistent.  You say things like ChunkY, Finalychunk, yChunks, NumYChunks, all in different places and they all mean different things.  This makes the logical flow of your program very hard to follow.  At the very least, all of these things need to have a similar format, so if you are going to have Y capitalized and at the end of the variable, always do that.  So for example FinalyChunk would be FinalChunkY.  But an even better approach is to minimize the number of similar names, so try to come up with better, more descriptive names whenever possible.

A related point, I would suggest that you follow the variable naming conventions in whatever language you are writing in, so for Javascript that would be camelCase.

You use many magic numbers in the code, such as

ChunkCameraY = yChunks * 4294967296;
ctx.fillText("ID: " + index, FinalxChunk + 10, FinalyChunk + 20);
ctx.rect(NewCeldX, NewCeldY, 80, 40);

What is 4294967296?  What do 10 and 20 represent?  What are 80 and 40?  By declaring these as variables somewhere in the code, such as rectangleXSize = 80; rectangleYSize = 40; you will be accomplishing two things.  First, it will be much easier to read and understand your code.  Second, you will have a much easier time trying to modify the code at a later time, because at the top of the function you will see those values declared.  Otherwise you will have to search through the code to find the numbers you want to change.

The main logic of the function is where things get the most confusing, at least for me.  You have a four level deep for-loop structure, which is a sign that the design needs to be reevaluated.  Any time you have to have that many for loops to accomplish something, there is usually a better approach.  Additionally, I would break as much as possible out of the for loops and into smaller functions.  This will improve the readability of your code and make the logic easier to follow and easier to change later.  If you use descriptive function names, it will also be self documenting.

Finally I will echo the other (now deleted) answer and say that you should have more comments in your code.  You might even be forgiven for a deeply nested for loop if you have comments that explain what is happening at each stage.  At the very least, it will be a lot easier for you to understand in the future if you ever try to look at the code again!


Scraping HTML via async controller & classes + HTML agility pack

public async Task<ActionResult> UpdateHandicap()

We add the Async suffix to methods that are marked with the async keyword. This is a naming convention that as you'll see in a moment Entity Framework follows too.

var results = db.Users.ToList();

You can use the Users directly in the loop, you don't have to call ToList first.

foreach (Users user in results)
{
    user.Index = await Calculations.GrabIndexValue(user.GHID);
    db.Entry(user).State = EntityState.Modified;
    db.SaveChanges();
}

The async calls are incomplete. SaveChanges would still block so you also want to use the

await db.SaveChangesAsync();

but do you really need to call SaveChanges in a loop? This could be bad for the performance. I think you should do it after the loop:

foreach (var user in db.Users)
{
    user.Index = await Calculations.GrabIndexValue(user.GHID);
    db.Entry(user).State = EntityState.Modified;
}
await db.SaveChangesAsync();


My first time here providing code review on stackexchange. I randomly clicked a link and arrived here. Anyway, here's how I'd improve your code:

#!/usr/bin/env python

import datetime

DATE_FORMAT = "%d/%m/%y"
DATE_FORMAT_FOR_HUMANS = "DD/MM/YY"
TIME_FORMAT = "%H:%M:%S"
TIME_FORMAT_FOR_HUMANS = "Hour:Minute:Second"

def prompt_for_user_input():
    return int(
        input(
            """Please choose one of these options below and type it in the prompt:
1 - To know the date ({DATE_FORMAT_FOR_HUMANS})
2 - To know the time ({TIME_FORMAT_FOR_HUMANS})
3 - To know both date and time. ({DATE_FORMAT_FOR_HUMANS} {TIME_FORMAT_FOR_HUMANS})
"""
        )
    )

def print_datetime_from_input(user_input, datetime_value):
    formatted_date = get_formatted_date(datetime_value)
    formatted_time = get_formatted_time(datetime_value)

    if user_input == 1:
        print(formatted_date)
    elif user_input == 2:
        print(formatted_time)
    elif user_input == 3:
        print(formatted_date, formatted_time)
    else:
        print("You didn't type in 1, 2 or 3!")

def get_formatted_time(datetime_value):
    return datetime_value.strftime(TIME_FORMAT)

def get_formatted_date(datetime_value):
    return datetime_value.strftime(DATE_FORMAT)

def main():
    now = datetime.datetime.now()

    print("Welcome to Date and Time!")

    user_input = prompt_for_user_input()
    print_datetime_from_input(user_input, now)

if __name__ == "__main__":
    main()

And here's why:

It's good practice to separate logic into smaller functions as it makes it easier to run tests against smaller parts of a system. For the above, I could have wrote three separate tests, one that ensures that for a given user input, the right date gets displayed. Another test for the the formatting of the date and time, another one for the main execution.

If you're curious about tests, I recommend you to search online why do we write unit tests and how to write tests in python. This helped me a lot in writing better code.

Separating into smaller function helps for reusability. In the given example, I tried to separate the logic from the user input and the display.
I used an IDE to auto indent and format. The above follows PEP8.
I extracted the formats into DATE_FORMAT and TIME_FORMAT. Again, we are not reusing anything, but imagine you'd like to reuse the formats somewhere else. It also makes it easier to change the formats as you only need to change one line to see a different result.
I've split the input into multi line string which makes it easier for readability. I also moved the displayed format for the user beside the format used by the code to display it, this way, if you change one of the formats, you can update the prompt for the user more easily.
I've added a main function and a if __name__ == "__main__": condition to call main. In this case, it will execute the main function if the script is invoked directly. Imagine your script is called ask_for_time.py, you could now import ask_for_time.DATE_FORMAT and the main execution won't be executed on import time.
The first line #!/usr/bin/env python is called a shebang, it's used to tell the shell what to use to execute the script in case it is invoked directly (example: ./ask_for_time.py instead of python ask_for_time.py.

You should always try to use the DRY principle.

For the datetime formatting, you can refer to the following documentation: http://strftime.org/

As an exercise, I suggest you to try and write unit tests to make sure the code you write does what you intend it to do.
Good luck and have fun learning python ✌


Insert an array[4] to an array[8] (C++, SSE)

Storing

Are there other (better) ways to insert data from s2 into last four elements of peak_dB (AVX excluded)?

Yes, actually you already used that way: it's _mm_store_ps. For example:
    s2 = lin2db(s2);
    _mm_store_ps(peak_dB + 4, s2);

Maybe you prefer &peak_dB[4] instead of peak_dB + 4, that works just fine too.
_mm_store_ps takes a pointer to wherever you want to store the data, that pointer does not have to point to the start of an array.
Loading
An other problem here is the use of _mm_set_ps. Though it accepts variable arguments, it is mostly meant for constant arguments, and good code is far from guaranteed if it is used differently. In the code on Godbolt, you can see the effect. Here I removed the code from lin2db from it that got "interleaved" into it:
    movss   xmm1, DWORD PTR float * channelsPeak+12
    movss   xmm0, DWORD PTR float * channelsPeak+8
    movss   xmm2, DWORD PTR float * channelsPeak+4
    movss   xmm4, DWORD PTR float * channelsPeak
    unpcklps xmm2, xmm1
    unpcklps xmm4, xmm0
    unpcklps xmm4, xmm2

And this is seen for the other similar instance of _mm_set_ps as well:
    movss   xmm1, DWORD PTR float * channelsPeak+28
    movss   xmm0, DWORD PTR float * channelsPeak+24
    movss   xmm2, DWORD PTR float * channelsPeak+20
    movss   xmm3, DWORD PTR float * channelsPeak+16
    unpcklps xmm3, xmm0
    unpcklps xmm2, xmm1
    unpcklps xmm3, xmm2

Avoid this pattern, try to use _mm_load(u)_ps if possible. That's easy in this case:
s1 = _mm_loadu_ps(channelsPeak);
// later
s2 = _mm_loadu_ps(channelsPeak + 4);

Zeroing
Initializing local variables of type __m128 like this is fine:
__m128 s1 = _mm_setzero_ps();

There's no serious problem with that, but it does not do anything useful in this code, it's just redundant. Of course if the value of zero is used as an input to something, then it should be done. But here it can just as well be skipped, declaring the variable only when you have a value to assign to it, for example:
__m128 s1 = _mm_loadu_ps(channelsPeak);


This code is a non-static C# class for rolling a number of dice

I have few tips:

Infinite recursion.
The app would never finish until you call Environment.Exit because you have infinite recursion. The result of the infinite recursion is always StackOveflowException, sooner or later. Take the trigger: if you forced to use Environment.Exit to stop the app, then something went wrong. About correct usage of the recursion: on some level of calling the recursive method must return not make a recursive call again. Then the recursion would finish normally. Btw, you need no recursion here.

Naming
Give all the items: classes, namespaces, variables, fields, etc. names that explains its purpose or containing value. It would make the code maintaneable. Also I use the following standard.
private int _fieldName;

public int PropertyName { get; set; }

public void DoSomething()
{
    int localVariableName = 0;
}

It allows explicitly differ fields and local variables in a code even if I'm reading the code outside of IDE editor.

Incapsulation.
The OOP principle that helps you in development to avoid popular mistakes. What method should I call when I create an instance of RollDice class? All the methods are public. Leave public only that class components which you allow to access outside of the class.

Small tips.
Remove inheritance class RollDice : Program, it does nothing. Let the methods and classes do some single job. (see S in SOLID principles for details).

Here's some alternative implementation of the same to play.
class Program
{
    static void Main(string[] args)
    {
        RollDice dice = new RollDice();
        dice.Run();
        Console.ReadKey();
    }
}

public class RollDice
{
    private const int maxDice = 100;
    private const int minDice = 1;
    private const int maxSides = 100;
    private const int minSides = 2;

    private Dice[] _dices;

    private List<string> _menuItems = new List<string>
    {
        "Exit.",
        "Setup Roll Dice.",
        "Roll!"
    };

    public void Run()
    {
        Console.Write("Welcome to Roll Dice!");
        while (true)
        {
            ShowMenu(_menuItems);
            switch (ConsoleHelper.ReadInteger("Enter your selection: ", 0, _menuItems.Count - 1))
            {
                case 1:
                    Setup();
                    break;
                case 2:
                    Roll();
                    break;
                case 0:
                    Console.WriteLine("Bye.");
                    return;
                default:
                    Console.WriteLine("Error: Unexpected menu input!"); // this would never happen
                    break;
            }
        }
    }

    private void Roll()
    {
        if (_dices == null)
        {
            Console.WriteLine("Please setup the Roll Dice first.");
            return;
        }

        Console.WriteLine("Rolling...");
        for (int i = 0; i < _dices.Length; i++)
        {
            _dices[i].Roll();
        }
        Console.WriteLine($"You rolled: {string.Join(", ", (object[])_dices)}");

        int total = 0;
        for (int i = 0; i < _dices.Length; i++)
        {
            total += _dices[i].Value;
        }
        Console.WriteLine($"Total sum rolled is {total}");
    }

    private void Setup()
    {
        int diceCount = ConsoleHelper.ReadInteger("How many dice do you want to throw? ", minDice, maxDice);
        int sides = ConsoleHelper.ReadInteger("How many sides does each dice have? ", minSides, maxSides);
        _menuItems[1] = $"Change Roll Dice setup. (currently {diceCount} dice of {sides} sides).";
        _dices = CreateDice(diceCount, sides);
    }

    private Dice[] CreateDice(int diceCount, int sides)
    {
        Dice[] dices = new Dice[diceCount];
        for (int i = 0; i < diceCount; i++)
        {
            dices[i] = new Dice(sides);
        }
        return dices;
    }

    private void ShowMenu(List<string> items)
    {
        Console.WriteLine();
        for (int i = 1; i < items.Count; i++)
            Console.WriteLine($"[{i}] {items[i]}");
        Console.WriteLine($"[0] {items[0]}");
    }
}

public class Dice
{
    private static Random rndGen = new Random(); // one random generator for all dices would be enough

    private int _sides;

    public int Value { get; private set; }

    public Dice(int sides)
    {
        _sides = sides;
    }

    public void Roll()
    {
        Value = rndGen.Next(0, _sides) + 1;
    }

    public override string ToString()
    {
        return $"[{Value}]";
    }
}

public static class ConsoleHelper
{
    public static int ReadInteger(string prompt, int min, int max)
    {
        while (true)
        {
            Console.Write(prompt);
            if (int.TryParse(Console.ReadLine(), out int option) && option >= min && option <= max)
                return option;
            Console.WriteLine($"You need to enter a valid number from {min} to {max}!");
        }
    }
}

Note for other reviewers: I'm not including const or readonly warnings in the review to leave it as simple as possible.
No recursion above.


Send Data from DynamoDB to Lambda (C#) and to Azure Queue

If the connection and queue name are not changing per record then there is no reason to be creating a new client for each record in the loop. Especially for the amount of times stated in the original post.

Move that to the constructor of the class.

public class Function {
    private static readonly JsonSerializer _jsonSerializer = new JsonSerializer();
    private readonly IQueueClient client;
    private const string connectionString = "QUEUE END POINT";
    private const string queueName = "QUEUE NAME";

    public Function() {
        ServiceBusConnectionStringBuilder builder = new ServiceBusConnectionStringBuilder(connectionString);
        ServiceBusConnection connection = new ServiceBusConnection(builder);
        client = new QueueClient(connection, queueName, ReceiveMode.PeekLock, RetryPolicy.Default);
    }

    public async Task FunctionHandler(DynamoDBEvent dynamoEvent, ILambdaContext context) {
        var logger = context.Logger;
        logger.LogLine($"Beginning to process {dynamoEvent.Records.Count} records...");

        foreach (var record in dynamoEvent.Records) {
            logger.LogLine($"Event ID: {record.EventID}");
            logger.LogLine($"Event Name: {record.EventName}");

            string streamRecordJson = SerializeStreamRecord(record.Dynamodb);
            await SendAsync(streamRecordJson);

            logger.LogLine($"DynamoDB Record:");
            logger.LogLine(streamRecordJson);
        }

        context.Logger.LogLine("Stream processing complete.");
    }

    private Task SendAsync(string body) {
        var message = new Message(Encoding.UTF8.GetBytes(body));
        return client.SendAsync(message);
    }

    private string SerializeStreamRecord(StreamRecord streamRecord) {
        using (var writer = new StringWriter()) {
            _jsonSerializer.Serialize(writer, streamRecord);
            return writer.ToString();
        }
    }
}


is it good practice (as per optimization) to write separate loops.

That depends on the logic you need to implement. For example, if you have two loops iterating over the same range and having the same body, then it would be good to combine them to eliminate the code duplication. But that's not the case here, as the two loops can have distinct ranges. By combining the loops, you extend the range, and evaluate some condition more than necessary.

Take for example the input 256 and target 1. There's no need to evaluate the first condition more than once. After one check, it's enough to evaluate the second condition repeatedly until you reach the target number.

It's very often not possible to separate the conditions like this, effectively serializing the operations. For example if you have an unordered collection of users and you want to filter out those under age 20 and above 60, you have no choice but iterate over the entire collection, and to avoid two loops with identical bodies, it will be good to combine the conditions. You cannot just iterate while users are under 20 and then continue while users are above 60, since the collection is not known to be ordered that way. If it was, you would benefit from splitting the loop, reducing the number of evaluated conditions.

By the way, a funny thing about the challenge in question is that you could even flip the order of those two loops, for example this will work too:

while(a>b){
        a>>=1;
        count++;
}
while(a&(a-1)){
        a>>=1;
        count++;
}

The point is,
in this example the loops don't operate on the same range.
They each reduce the range,
and they can do that independently to get the same result.

Code review

Keep in mind that using namespace std is considered bad practice. A practical alternative:

using std::cin;
using std::cout;

Some other minor improvements:

It's better to declare variables where you use them, in the smallest scope
The code would be more readable if you put spaces around operators
The indentation is inconsistent
It's recommended to have one statement per line
No need for return 0 at the end of the main method, the compiler adds it automatically

Like this:

#include <iostream>

using std::cin;
using std::cout;

int main() {
    int testCases;
    cin >> testCases;
    while (testCases--) {
        unsigned long int a, b;
        cin >> a >> b;

        int count = 0;
        while (a & (a - 1)) {
            a >>= 1;
            count++;
        }
        while (a > b) {
            a >>= 1;
            count++;
        }
        while (a != b) {
            a <<= 1;
            count++;
        }

        cout << count << "\n";
    }
}


Long multiple choice decisions in python work well as dictionaries, rather than elifs.

def handle_event(event):
    OnKeyDown = {K_w:(0, 4), K_s:(0,-4), K_a:(-4, 0), K_d:(4,0)}
    OnKeyUp = {K_w:(False, True), K_s:(False, True), K_a:(True, False), K_d:(True, False)}

    if event.type == KEYUP:
         delta = OnKeyDown[event]
         movex += delta[0]
         movey += delta[1]
    elif event.type == KEYDOWN:
         delta = OnKeyUp[event]
         if delta[0]: movex = 0
         if delta[1]: movey = 0

   x += movex
   y += movey


Reducing time limit for prime number program

For this SPOJ problem with (1 <= m <= n <= 1000000000, n-m<=100000) limits you will have to use an offset sieve of Eratosthenes.

Since n <= 10^9, to sieve any range under n it is sufficient to have just the primes below its square root, 31622, pre-calculated. There are only 3401 such primes, the biggest being 31607.

So, A. pre-calculate the 3401 primes below 31622.

Since n-m<=100000, you can B. have one array of 100000 booleans preallocated, and sieve it by those primes, as in sieve of Eratosthenes, for each pair m,n.

As an easy optimization, use that sieve segment to represent just odds, without evens: an entry at position i will represent odd(m) + 2*i where odd(m) is the lowest odd number not below m in value. Sieve this segment by odd primes only. No even number above 2 is ever a prime:

for i = 3, 5 ... √n in primes:
   for j = i^2, i^2+2*i, i^2+4*i ...   inside the segment  m ... n:
      A{j} := false


Unit testing for a blog post model on Google App Engine

try:
    p = test_model()
    key = p.put()
    result = True
except:
    result = False

self.assertFalse(result)

This except clause catches any exception. What you probably intend to test was whether a specific exception occured, so catch that exception and none else.

If you want to make full use of the unittest library (which is what I assume you're using), you can rewrite this block with assertRaises as follows:

with self.assertRaises(YourExpectedException):
    p = test_model()
    key = p.put()

Now, the test__get_coords method doesn't make any sense to me. It unconditionally returns some JSON before it has any chance to assert anything at all. And even after removing the return statement, the code still asserts that some JSON is a dict object. Something is really finshy here!

test__make_secure_val is along the same lines. You're not actually testing the function but implementing it again, which is then what you test. You should probably change it to something like this:

def test__make_secure_val(self):
    test_result = make_secure_val(val)

    self.assertEqual("test|e91f3aaeb48b71fc68bddc8ea34dda24", test_result)

If you want to pass the secret to make_secure_val, add it to the parameter list:

def make_secure_val(val, secret):
    return '%s|%s' % (val, hmac.new(secret, val).hexdigest())


Pure JS countdown clock not converting millisecond time correctly

The plunker has this code at the top of the CountDown function:

let options = {
    // ...
    },
    lastTick = null,
    intervalsBySize = ["year", "week", "day", "hour", "minute", "second"],
    TIMESTAMP_SECOND = 200,
    TIMESTAMP_MINUTE = 60 * TIMESTAMP_SECOND,
    TIMESTAMP_HOUR = 60 * TIMESTAMP_MINUTE,
    TIMESTAMP_DAY = 24 * TIMESTAMP_HOUR,
    TIMESTAMP_WEEK = 7 * TIMESTAMP_DAY,
    TIMESTAMP_YEAR = 365 * TIMESTAMP_DAY,
    elementClassPrefix = "countDown_",
    interval = null,
    digitConts = {};

... but that states that there are 200 milliseconds in a second. Obviously there are 1000 of them. So the line in question should be:

TIMESTAMP_SECOND = 1000,

This solves the issue. However, your setInterval also uses this variable for the length of the interval, and it might make sense to have more than one tick per second. So for that interval you should probably use a new variable that would indeed have the value 200.

Nice work though on the CSS side!


In fairness, this task is relatively simple, and your solution is actually pretty good.

Shell scripts are often just a hack to solve a specific task, and, your script is much better than many that I see that do that.

There are two things to consider in your script. The first is whether it can be improved. The second is whether there's a better way.

Now, about improving it. I would:

remove the need for the second parameter
name the parameters,
include the / in a different place
use quotes around variables in specific places.
reverse the if-blocks to get rid of the 'negate' condition.

Consider the following:

deploy () {
    local dir="$1"
    for file in $(ls "$dir/" ); do
        # Fully qualified file
        fqfile="$dir/$file"
        if [ -d "$fqfile" ]; then
            deploy "$fqfile"
        else
            echo "$fqfile"
        fi
    done;
}

Introducing the fqfile allows the simplifcation of other variables too.

Now, having said all that, your command could easily be solved with the find command:

find . -type f -exec echo {} \;

The above command will recursively find all files below ., and echo them.


Get list of unique parents from childrens list

Your use of var is good, but names like temp is meaningless. It's a temp what exactly? A more descriptive name is in order here.

The call to ToList appears to be redundant. Hashset's constructor takes an IEnumerable<T> and Linq queries that return collections already return one.

I would also break the query away from the ctor for readability purposes.

var parents = from child in program.Children
                 select child.Parent;

var distinctParents = new HashSet<Parent>(allParents);

However, it's all kind of moot if you use the method syntax snippet that @RobH posted.

var parents = program.Children.Select(c => c.Parent).Distinct();


Are these C# and Python code snippets functionally identical?

This section seems wrong:

//The next 2 lines are for parsing the short, equivalent(?) to struct.unpack('h', byte)
i <<= 8;
i += file.ReadByte();

you're shifting the value in i 8 bits left and then reading another byte. I'm guessing because the original code read it in 2 bytes at a time. If your file isn't the right length then this will break it here. what about:

i <<= 8;
int secondByte = file.ReadByte()
if(secondByte != -1)
{
   i += secondByte ;
}

Whats with this? It is casting an int to a byte to a char and it is truncating.

byte b = (byte)i;
char c = (char)b;

so you're better off ignoring the first byte and instead everything after tick = !tick;
could be:

i = file.ReadByte();

char c = (char)(i ^ (key & 255));
builder.Append(c);

In Python chr() will throw an exception if the value is greater than 255 anyway.

And IMHO it is a bad idea to roll your own encryption/decryption like this. Use a trusted known solution instead.

Question: I only want to know if I have translated the function correctly to C# so it does the same as in Python

Answer Its more of a transliteration rather than a translation but they should give the same output. If I were to re-write the python into c# it would look different as it seems inefficient to me.


Doing a roll back with multiple MySQLI prepared statement

function CreateNewAccount(&$newRegistrationDataArray){ ///note the &

    /* variable needed */
    $memberId = $this->generateMemberId(); // a private function that generate member id

    // that is lots of repetitive code, lazy way is use extract,
    // although can be dangerous if you can't trust data in $newRegistrationDataArray
    extract($newRegistrationDataArray);

//    $date = $newRegistrationDataArray['date'];
//    $name = $newRegistrationDataArray['name'];
//    $address = $newRegistrationDataArray['address'];
//    $country = $newRegistrationDataArray['country'];
//    $occupation = $newRegistrationDataArray['occupation'];
//    $emailAddress = $newRegistrationDataArray['emailAddress'];
//    $usename = $newRegistrationDataArray['usename'];
//    $password = $newRegistrationDataArray['password'];
//    $salt = $newRegistrationDataArray['salt'];
//    $secretQuestion = $newRegistrationDataArray['secretQuestion'];
//    $secretAnswer = $newRegistrationDataArray['secretAnswer'];
//    $transactionCode = $newRegistrationDataArray['transactionCode'];
//    $perfectMoneyAccount = $newRegistrationDataArray['perfectMoneyAccount'];
//    $egoPayAccount = $newRegistrationDataArray['egoPayAccount'];
//    $payeerAccount = $newRegistrationDataArray['payeerAccount'];
//    $okPayAccount = $newRegistrationDataArray['okPayAccount'];
//    $bitcoinAccount = $newRegistrationDataArray['bitcoinAccount'];
//    $upline = $newRegistrationDataArray['upline'];
//    $userRegistrationIp = $newRegistrationDataArray['userRegistrationIp'];
//    $status = $newRegistrationDataArray['status'];
    /* variable needed */

    try
    {
        /* set autocommit to off */
        $this->dbConnection->autocommit(FALSE);

        $stmt1=$this->dbConnection->prepare("INSERT INTO `members` (date,name,address,country,occupation,emailAddress,memberID,usename,password,salt,secretQuestion,secretAnswer,transactionCode,perfectMoneyAccount,egoPayAccount,payeerAccount,okPayAccount,bitcoinAccount,upline,userRegistrationIp,status) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)");
        $stmt1->bind_param('sssssssssssssssssssss',$date,$name,$address,$country,$occupation,$emailAddress,$memberID,$usename,$password,$salt,$secretQuestion,$secretAnswer,$transactionCode,$perfectMoneyAccount,$egoPayAccount,$payeerAccount,$okPayAccount,$bitcoinAccount,$upline,$userRegistrationIp,$status);

        // failure is unexpected, so lets use exceptions to handle it
        if ($stmt1->execute() == false) {
            throw new Exception('Statement 1 Failed');
        }

        $stmt2=$this->dbConnection->prepare("INSERT INTO `membertotalfinancialstatus` (memberId) VALUES (?)");
        $stmt2->bind_param('s',$memberId);

        if ($stmt2->execute() == false) {
            throw new Exception('Statement 2 Failed');
        }

        // tidy up
        $stmt1->close();
        $stmt2->close();

        // is it normal to close connection at this level? or do you leave it open for other requests
        $this->closeDBConn;
    }
    catch(Exception $e)
    {
        // any sort of exception and we should rollback?
        // either that or subclass exception and handle each exception type differently
        $this->dbConnection->rollback();

        // whats the point of this, just re-throw the same exception?
        // $error=$e->getMessage();
        // throw new Exception($error);
        throw $e;
    } finally {
       // if you have php 5.5 you can do your tidy up here, although if
       // an exception has occured, you probably don't care about freeing stmt's as
       // they all end up in the garbage anyway

        // tidy up
        //$stmt1->close();
        //$stmt2->close();
    }

}


This is only micro optimization, I don't think it will make a difference, but here you go anyway:

b=[]
for i in range(int(input())):
    s=sum([pow(-1,j)/(2*j+1) for j in range(int(input()))])
    b.append("{0:.15f}".format(s))
for x in b:print(b)

Instead of 3 loops, there is only one
Removed unnecessary intermediary variables
Removed int(j), j is already int
Removed extra brackets, for example (2*int(j))+1 is the same as 2*j+1
Removed an unnecessary s=0

You could of course write the whole thing on a single line, but now that's starting to hurt readability...

for x in ["{0:.15f}".format(sum([pow(-1,j)/(2*j+1) for j in range(int(input()))])) for i in range(int(input()))]:print(x)


Adding a class to an element in a plugin

You can use the addClass method on all the elements instead of creating a new jQuery object for each item:

return this.addClass('editable').each(function () {
  var baseEditable = $(this).editable(saveUrl, settings);
  $(this).data('baseEditable', baseEditable);
});


Haskell: rndFile and [Char] vs IO String error

Congratulations on your progress, :) Welcome to monads

First thing you have to keep in mind is to restrict the time spent in imperative world. So take out as much stuff as you can from the do ..., and refactor them into smaller non-IO code.

import System.Environment (getArgs)
import System.Random
import Control.Monad

Another advice is to avoid magic numbers in your code. If there are any, they should be declared in a highly visible area along with their purpose rather than buried deep in the code.

minLen = 10000

main = do
    args <- getArgs
    writeFile (getFileName args) =<< rndStr (getFileSize args)
  where getFileSize [] = minLen
        getFileSize (x:xs) = read x :: Int
        getFileName [x] = x ++ "-output.txt"
        getFileName (x:y:[]) = y

As you can see, the reason you can't use rndStr directly is that rndStr uses IO. So it cannot be directly used as a function. You can think of it this way. rndStr returns some thing that is wrapped in a box. You need special constructs to unbox it, and the special construct is either <- . You might also notice that main has the same kind of signature.

That isn't a really good analogy, and I am not the best teacher :). So if you really want to understand what happens, it might be better to read any simple monad tutorial.

rndStr :: Int -> IO String
rndStr n  = sequence . replicate n . randomRIO $ (' ', '~')

Try this approach if it makes better sense to you. When you start ghci, use this flag

ghci -XImplicitParams

On the prompt after loading your program, try to execute writeFile which was not accepting (rndStr number) earlier, but this time, instead of that expression, replace it by ?check

> writeFile (getFileName ["5"] ) ?check

You will get back some thing like

<interactive>:0:32:
  Unbound implicit parameter (?check::String)
    arising from a use of implicit parameter `?check'
    In the second argument of `writeFile', namely `?check'
    In the expression: writeFile (getFileName ["5"]) ?check
    In an equation for `it': it = writeFile (getFileName ["5"]) ?check

Ignore every thing except the second line, the Unknown implict .. tells you that ghc expected any exprssion in place of ?check would be a string.

Now try finding the type of our expression (rndStr number)

> :t rndStr 5
rndStr 5 :: IO String

As you can see, rndStr number has a different type IO String than the expected String. This is the reason you cant use rndStr number there, and why we have to do all that above.

Note that my statement writeFile (getFileName args) =<< rndStr (getFileSize args) is really same as

do
str <- rndStr (getFileSize args)
writeFile (getFileName args) str

Try to work out how it is so.


Improve performance of math function applied to arrays

Well, some things I noticed:

    # Define factors.
    a_01, a_11 = max(elem[1], 1e-10), max(elem[3], 1e-10)
    a_02, a_12 = array2[:,1], array2[:,3]

a_02 and a_12 are static across the loop, no need to redefine them every time. a_01 and a_12 could be defined array-wise using np.maximum:

a_01 = np.maximum(array1[:,1], np.array(1e-10 for _ in xrange(len(array1))
a_11 = np.maximum(array1[:,3], np.array(1e-10 for _ in xrange(len(array1))

However, these are trivial improvements; function call overhead is often blamed for much in the Python optimisation world, but there is no way that removing 2n calls to max will improve things here. With that said, following the static data path further, we come across an instance of

a_0 = a_01**2 + a_02**2
a_1 = a_11**2 + a_12**2

If we instead define

a_022 = a_02**2
a_122 = a_12**2

at the beginning of the function, we can avoid n multiplications by replacing later occurrences of a_02**2 with a_022 (and likewise for a_12), which reduces the running time of the program by about 5% on my machine. That isn't too impressive, though I'm sure you should be able to knock that down a fair bit by doing more thing using numpy functions. However, my numpy skills evaporate when it comes to 2d arrays, so I can't help.

It is worth mentioning that the algorithm you are using is O(n^2) at least, so wouldn't get your hopes up too high. Otherwise, I'd recommend looking at Cython as this seems like a problem it would excel at, though you've mentioned that parallelism isn't an option, so I assume using C extensions won't be either. However, if it is, I think you will find great time savings there.

This was the final code I came up with:

def func2():
    lst = []
    # Define factors.
    a_02, a_12 = array2[:,1], array2[:,3]
    a_022 = a_02 ** 2
    a_122 = a_12 ** 2
    e10 = np.array([1e-10 for _ in xrange(len(array1))])
    a_01 = np.maximum(array1[:,1], e10)
    a_11 = np.maximum(array1[:,3], e10)
    for i, elem in enumerate(array1):
        # Combine the factors defined above.
        a_0 = a_01[i]**2 + a_022
        a_1 = a_11[i]**2 + a_122
        Bs, Cs = -0.5/a_0, -0.5/a_1
        # Perform operations.
        A = 1./(np.sqrt(a_0*a_1))
        B = Bs*(elem[0]-array2[:,0])**2
        C = Cs*(elem[2]-array2[:,2])**2
        ABC = A*np.exp(B+C)
        lst.append(max(ABC.sum(), 1e-10))
    return lst

N = 100
func_time = timeit.timeit(func, number=N)
print "Original\t", func_time / N
print "-" * 50

func2_time = timeit.timeit(func2, number=N)
print "Revision 1\t", func2_time / N
print "Improvement\t", str(int((func_time - func2_time) / func_time * 100)) + "%"
print "-" * 50


Some of your functions behave a bit unconventionally.

checkEnglish() only returns 1 or 0.  It would be clearer to return True or False, and rename the function to isEnglish().

getPage() won't allow retrieval of HTTPS URLs.  I would avoid trying to be "helpful" by automatically mangling the URL, unless such mangling was really smart and thorough (as good as the intelligence in your browser's address bar).  By the way, URI schemes are case insensitive (RFC 3986 Sec 3.1).

In getPage(), you swallow exceptions.  That's not good practice, but if you're going to do it, do it succinctly:

def getPage(url):
    print "Checking the site ", url
    req = urllib2.Request(url)
    try:
        response = urllib2.urlopen(req)
        return response.read()
    except:
        return None

In getPtag() and getDescription(), avoid nesting:

def getPtag(webPage):
    if webPage is None:
        return None
    match = re.search(r'<p\W*(.+)\W*</p>', webPage)
    if not match:
        return None
    return match.group(1)

In general, HTML is case insensitive, so use case-insensitive regular expression matching (or an HTML parser).

Your checking() function could use some improvement:

Returning strings '1', '0', or 'NULL' is really weird.  Returning True, False, or None would make more sense.
The name of the function is weird.  It should be something like isEnglishUrl().
Prefer to return early, and express the cascade more simply.

def isEnglishUrl(url):
    pageText = getPage(url)
    if pageText is None:
        return None
    return isEnglish(getDescription(pageText)) or \
           isEnglish(getPtag(pageText)) or \
           isEnglish(pageText)

If getPage() hadn't swallowed exceptions in the first place, then isEnglishUrl() wouldn't have to deal with that pesky if pageText is None.  Instead, it could just let the exception propagate and let its caller deal with it, for more flexibility with less code.

Since Python 2.5, the preferred way to open and close files is using a with block:

RESULT_STR = { True: '1', False: '0', None: 'NULL' }
with open('sample_domain_list.txt') as f:
    with open('newestResult.txt', 'w') as s:
        for line in f.readlines()[:20]:
            url = line.split(',')[1][1:-1]
            eng = isEnglishUrl(url)
            s.write("%s,%s\n" % (url, RESULT_STR[eng]))