React breadcrumbs component implementation

Your code is looking pretty good. Here's a handful of suggestions you could try:
This part
{labels.map((label, idx) => <h5 key={idx} onClick={idx < breadcrumbPaths.length ? () => history.push(breadcrumbPaths[idx]) : null} className={"label2"}>{label}
)}

is a really long line of code. Try breaking it up, it makes it easier to read.
{labels.map((label, idx) => (
  <h5
    key={idx}
    onClick={
      idx < breadcrumbPaths.length
        ? () => history.push(breadcrumbPaths[idx])
        : null
    }
    className={"label2"}
  >
    {label}

))}

(I tend to prefer 2-space indentation with javascript and HTML as they both tend to be indentation heavy, and it seems to be a more common in the javascript community - so I'll use that in these examples)
Also, refrain from using an index for an element key when possible (the react docs talk about why). You could instead use the breadcrumbPath, as that would be unique to each element, and the keys would correctly change when the path changes.
{labels.map((label, idx) => (

    {label}

))}

You have some logic in there to calculate the number of backslashes a URL contains, but if you just wait a little bit on that early return, you will already have easy access to that number, as its the same as breadcrumbsPath.length + 1
if (breadcrumbPaths.length + 1 < labels.length) {
  return null;
}

On that note, this function won't handle the case correctly when there's a leading slash on the URL (i.e. 'example.com/a/b/') - that'll need to be taken care of. If you use the above code snippet, then you will only need to fix this issue in one place instead of two - where you create the breadcrumbPaths array.
To address your concern of having multiple returns: there's nothing wrong with having multiple returns like that in a function - in fact, it can often lead to cleaner code. Often, the alternative means large if-thens or flag variables, both of which are much harder to follow. I've heard that once upon a time a function with a single exit used to be something encouraged, but that's not the case anymore.
Now onto the part that you probably care about most - what to do about that chunk of logic with the c-style for loop, and multiple pathNameIdx--s.
First things first, I would probably break the meat of that logic out into a helper function. There's a lot of low-level work going on there that gets in the way of reading and understanding your component.
Here's how your component might look after doing that
import React from "react";
import { useHistory, useLocation } from "react-router-dom";

const RouteBreadcrumbs = ({labels = []}) => {
  const location = useLocation();
  const history = useHistory();
  const pathName = location.pathname;

  const breadcrumbPaths = ancestorPaths(pathName);
  if (breadcrumbPaths.length + 1 < labels.length) {
    return null;
  }

  return (

      {labels.map((label, idx) => (
        <h5
          key={breadcrumbPaths[idx]}
          onClick={
            idx < breadcrumbPaths.length
              ? () => history.push(breadcrumbPaths[idx])
              : null
          }
          className={"label2"}
        >
          {label}

      ))}

  )
};

function ancestorPaths(pathName) {
  let breadcrumbPaths = [];
  let pathNameIdx = pathName.length - 1;
  while (true) {
    while (pathName[pathNameIdx] !== "/") {
      if (pathNameIdx === 1) {
        return breadcrumbPaths;
      }
      pathNameIdx--;
    }

    const newPath = pathName.slice(0, pathNameIdx);
    breadcrumbPaths = [newPath, ...breadcrumbPaths];
    pathNameIdx--;
  }
}

Notice how there's a lot less low-level logic going on in the actual RouteBreadcrumbs component? It's a lot easier to read through it and get a good idea of what's going on - except for maybe the actual jsx getting returned - it's a little too nested for my liking, but it'll get simplified in a bit.
A couple other things I'll note with your original code:

Prefer string.slice() over string.substring() - it has fewer quarks
Good use of console.assert() there. The one thing I dislike about console.assert() is that it doesn't actually throw an error, it just logs one. Sometimes this isn't a big deal, here it is. If that assertion happened to come true, it would be stuck in an infinite loop, logging forever. You can just do if (condition) throw new Error(...) instead, or make your own assert function that actually throws an error.

Now lets look at simplifying our new ancestorPaths() helper function. It is possible to use regex to gather the indicies of all the slashes, which would work similar to how you have it, but greatly simplify the logic (see here). I'm going to instead just split on '/', build a list, and use a generator function, as follows:
function* iterAncestorPaths(pathName) {
  const parts = pathName.split("/").filter(x => x !== "");
  for (let i = 1; i < parts.length; ++i) {
    yield "/" + parts.slice(0, i).join("/");
  }
}

Note that the .filter() at the beginning will take care of both the leading / and a potential trailing slash.
One final thing: If your breadcrumb segments are links, why not make them actual links? it'll simplify some things.
Here's the final solution, with a couple other misc tweaks.
import React from "react";
import { Link, useLocation } from "react-router-dom";

const RouteBreadcrumbs = ({labels = []}) => {
  const pathName = useLocation().pathname;

  const ancestorPaths = [...iterAncestorPaths(pathName)];
  if (ancestorPaths.length + 1 < labels.length) {
    return null;
  }

  return (

      {ancestorPaths.map((path, idx) => (
        <Link key={path} to={path} className="label">
          {labels[idx]}
        </Link>
      ))}
      {labels[labels.length - 1]}

  );
};

function* iterAncestorPaths(pathName) {
  const parts = pathName.split("/").filter(x => x !== "");
  for (let i = 1; i < parts.length; ++i) {
    yield "/" + parts.slice(0, i).join("/");
  }
}


Is there a more elegant solution than this spaghetti code without completely revamping the whole page?

Your script is alright, there are just some minor issues:

1.) If string is enclosed inside "" then PHP interpreter checks whether there are some variables or not, if string is enclosed inside '' PHP interpreter does not check it.

2.) You forgot to declare $info variable, it is always good to declare your variables before doing some operations on them like .=.

3.) I don't like using this shorter syntax, because it can be source of bugs which are hard to find, in my opinion it is usually better to use {}:

if($counter == 0) $info .= "
Educational Background

";

4.) You don't need to repeat $info .= on every line, it can be replaced by ..

I rewrote the script in respect to previously mentioned points:

$degreeType = explode(',', $degreeType);
$major = explode(',', $major);
$issuingEstablishment = explode(',', $issuingEstablishment);
$yearReceived = explode(',', $yearReceived);

$counter = 0;
$info = '';
if($degreeType[0] != ''){
    foreach($degreeType as $dType) {
        if(!$counter) {
            $info .= '
Educational Background

';
        }

        $info .= "
$dType - "
            . (($major[$counter] != '') ? "$major[$counter], " : '')
            . $issuingEstablishment[$counter]
            . (($yearReceived[$counter] != '') ? ", $yearReceived[$counter]" : '')
            . '
'
        ;

        $counter++;
    }
    $info .= "
";
}


SciPy sparse: optimize computation on non-zero elements of a sparse matrix (for tf-idf)

I'm making a fair few assumptions about the internal format that may not be justified, but this works on the demo data I tried:

factors = csr.shape[1] / (1 + np.diff(csr.indptr))
xs, ys = csr.nonzero()

csr.data = np.log(csr.data + 1.0) * np.log(factors[xs])

All I do is work on the internal dense data structure directly.


Note that I'm not very familiar with C#, so the code that I write may not actually compile.

  Let's say I need to get 20 dates. Is there an easier way to do this, like only having one prompt per date?

There's a much easier way to do this, and that is to extract this to it's own separate method. This method should do just what your code is doing now: prompt the user for the day, the month, and the year, and should return a DateTime.

public static DateTime PromptDateTime()
{
    Console.WriteLine("Day: ");
    var day = Convert.ToInt32(Console.ReadLine());

    Console.WriteLine("Month: ");
    var month = Convert.ToInt32(Console.ReadLine());

    ... year...

    return new DateTime(year, month, day, 0, 0, 0, 0);
}

Need to call this method twenty times? Go ahead (you'd probably want to use a loop though). With an extracted method like the one above, you won't have to worry about having cluttered code.

Validate Input

This is how you are getting input:

var dateDay = Console.ReadLine();
var dateDayInt = Convert.ToInt32(dateDay);

What if the user enters something like this?

  LOOK MA! NO VALIDATION

What's your code going to do? It's going to throw an error because Convert.ToInt32 doesn't quite know how to parse that.

To validate the user's input, you should use int.TryParse. This method takes a string and an output variable and attempts to parse the string into a number and puts the parsed number in the output variable. If the parse is unsuccessful, then this method returns false.

What this method could look like in action:

var input = Console.ReadLine();
var num;
if(int.TryParse(input, out num))
{
    Valid!
} else
{
   Invalid!
}

Of course, this is a little much to put inside this method you have (considering the fact that you'll have to keep looping to get the user's proper input). Therefore, you should extract this into a method.

public static int ReadInteger() {
    while(true) {
        var input = Console.ReadLine();
        var num;
        if(int.TryParse(input, out num))
        {
            return num;
        }
    }
}

The above method keeps on looping until proper input is receive. As you may notice, this is not very suitable for unit testing as STDIN is forced. However, as Dan Lyons commented:

  Console.WriteLine utilizes Console.Out for everything - if the method took in a TextWriter, he could use Console.Out in "production", but a StringWriter in test.

Now, with proper validation, your extracted method would look like this:

public static DateTime PromptDateTime()
{
    Console.WriteLine("Day: ");
    var day = ReadInteger();

    Console.WriteLine("Month: ");
    var month = ReadInteger();

    ... year...

    return new DateTime(year, month, day, 0, 0, 0, 0);
}

As svick mentioned, this is still technically not enough validation. What if, for the month, the user enters

  13

That doesn't make much sense, does it?

This, of course, can lead to some complications. Some months had 30 days and others have 31. Validation in general should be mostly simple; you just check that the month number is between 1 and 12 (or 0 and 11, but be consistent), and that the year number is between 1 and the current year (unless you want to handle BC/BCE, in which you'd have to do some extra checking).

However, this still doesn't solve the days-in-month problem. A solution could be to create a map/table showing the months and the corresponding amount of days and use that to look up whether the day number is valid. However, then you encounter February (yay!) with which you have to do further validation. Honestly, your best bet would be to go with Zack's solution as it is more idiomatic and would probably be easier to do parsing with (although, I don't know how it handles that days-in-month issue either).


Script for starting a rails app, with some peculiarities

This was an interesting one. Thank you :)

I dug around in the rails code and poked at webrick and rack for a while and this is what I came up with:

PROJECT_DIR     = ENV['PROJECT_DIR']     || '/path/to/app'
BROWSER_COMMAND = ENV['BROWSER_COMMAND'] || 'browser http://localhost:3000 &'
PORT            = ENV['PORT'].to_i       || 3000

require "#{PROJECT_DIR}/config/environment.rb"

thread = Thread.new do
  Rack::Handler::WEBrick.run Rails.application, Port: PORT
end

`#{ BROWSER_COMMAND }`

Rack::Handler::WEBrick.shutdown

thread.join

This approach is actually borrowed from rack's webrick handler.

I load the environment prior to actually starting the webrick server making any waits unnecessary for me. If that should be necessary for you, I'm sure you could add it.

Then I pretty much stuck to what you did, putting the actual server into a thread. The Handler already provides that neat shutdown method.

Oh, I also took the liberty of adding some ENV variables so you can put this script into a file and run it from where ever you want.

EDIT: In the comments Marcus pointed out, that in order to resolve the timing issue, one can set the closure (block variable) from WEBrick.run {|server|} to a thread-local variable that can be polled afterwards.

There might also be ways to exploit Celluloid for messaging between the different threads.


You were right on track with

no_start = str[1:]
no_end = no_start[:len(no_start) - 1]

In a first step, they can be combined:

return str_[1:len(str_)-1]

Note: I changed str to str_ because str is actually a datatype in Python.

The next thing to know about slicing, is that you can use negative indices to index from the back without specifically using the length of the string like so:

return str_[1:-1]

And since this also works for strings with a length equal to two, you can also get rid of the earlier check.

So your are now down to basically:

def without_start_end(input_):
    return input_[1:-1]

Again take note: input_ also has the trailing _, since, you guessed it, input is already taken.

A non-directly code relate side-note: the official Style Guide for Python Code (aka PEP8) recommends to use 4 spaces per indentation level, and most people seem to follow that recommendation. There are however exceptions, e.g. Google's TensorFlow framework uses 2 spaces per indentation level (see their style guide), although Google's own "general purpose" style guide for Python code sticks with 4 spaces.


We can move the while loop into another function.

def is_prime(candidate, primes):
    n = 0
    while primes[n]**2 <= candidate:
        if candidate % primes[n] == 0:
            return False
        n += 1
    return True

def sieve():
    primes = [2]
    for candidate in count(start=3, step=2):
        if not is_prime(candidate, primes):
            continue
        yield primes[-1]
        primes.append(candidate)

We can use itertools.takewhile to expose the while loop as an iterable.

def is_prime(candidate, primes):
    for prime in itertools.takewhile(lambda p: p**2 <= candidate, primes):
        if candidate % prime == 0:
            return False
    return True

We can use any to make is_prime easier to read.

If for any of the values, candidate % prime == 0, are true the result is true.
If none of them are then it is false.
Since we want it to be the other way around we can just use not.

def is_prime(candidate, primes):
    return not any(
        candidate % prime == 0
        for prime in itertools.takewhile(lambda p: p**2 <= candidate, primes)
    )

We can move is_prime back into the first function.

def sieve():
    primes = [2]
    for candidate in count(start=3, step=2):
        if not not any(
            candidate % prime == 0
            for prime in itertools.takewhile(lambda p: p**2 <= candidate, primes)
        ):
            continue
        yield primes[-1]
        primes.append(candidate)

We can swap the if to cancel the continue and a not.
We can swap the any and == 0, with not all.
We can cancel the double not.

def sieve():
    primes = [2]
    for candidate in count(start=3, step=2):
        if all(
            candidate % prime
            for prime in itertools.takewhile(lambda p: p**2 <= candidate, primes)
        ):
            yield primes[-1]
            primes.append(candidate)

At the expense of readability you can get the following trade offs.

There is a chance that using int(candidate ** 0.5).__ge__ is faster than the lambda.


Faster/Better Processing for SQL While Loop

Please update your questions with the relevant tags, although it is obvious you are using SQL Server here.

If you run an execution plan in your query window, you will be able to see which specific bits are taking a lot time and whether SQL Server is using any indexes etc.

It would be good if you gave a data sample and the table structure. Here are some ideas though.

Is there a reason why you are using a WHILE loop instead of a cursor ? The idea here is that you start with ID 1 and increment until you reach the max ID but there must probably be gaps in your table... the approach is possibly wasteful if you are trying to update rows that don't even exist.

Rather than work on the table Account directly (which may be in use or subject to locks), I would rather work on a partial copy using a temporary table.

Step 1: create a temporary table with all the records from Account you want to fix, matching some criteria eg country empty

SELECT *
INTO #Account
FROM Account
WHERE <add your criteria here>

Step 2: perform all your operations on that temporary table #Account

Step 3: update the original table based on the temporary table (UPDATE FROM):

UPDATE Account
SET
    Account.ShippingCountry = #Account.ShippingCountry,
    Account.BillingCountry = #Account.BillingCountry,
    ...
FROM #Account
WHERE
  #Account.id2 = Account.id2

Here I am assuming that id2 is indeed an identity column that uniquely identifies each record. If it isn't, but instead is some kind of unindexed integer value, then each UPDATE requires a full table scan and there is a performance hit here. Again, can't tell without knowing the table structure for sure.

If all this takes too much time, you can process the jobs in small chunks, for example pull 1000 records at a time using SELECT TOP 1000, and repeat until the table is cleaned.

In short, updating a large table can be very slow if you cannot rely on some index, using an appropriate WHERE clause.

Important remark regarding the temporary table approach: doing SELECT INTO creates a copy of the data but does not include the complete table structure, that is indexes, constraints. That mean the id column will be an ordinary integer and not a unique, indexed field. So I would add the index manually on that field to speed the UPDATE FROM.


Setting bgcolor in Ruby. What's the proper way to do it?

inline styles are bad practice

more elegant way would be assigning class to your  element based on debate properties, maybe creating a helper if this line is used frequently


Reduce or improve Linq query with nested from-where clauses

After a lot of setup, I arrived at this:

var extensionMethodQuery =
    from container in containers
    let items = container.GetItems()
    select items.GetItemDerivedTagItems
        (items.SelectInterestingItemTags()).FirstOrDefault();

Your original query looks pretty optimal, but it took a while to see why.  I broke it down into its component parts, and concluded that I'd concentrate on making it more reusable and readable.  Personally, I find lambda joins too verbose, so created two extension methods instead:

public static class Filters
{
    public static IEnumerable<ItemTag> SelectInterestingItemTags
        (this IEnumerable<Item> items)
    {
        return
            from item in items
            let tag = Tag.CreateTag(item)
            where Tag.IsInteresting(tag)
            select new ItemTag(item, tag);
    }

    public static IEnumerable<ItemDerivedTagItem>
        GetItemDerivedTagItems
        (this IEnumerable<Item> items, IEnumerable<ItemTag> itemTags)
    {
        return
            from itemTag in itemTags
            from item in items
            let derivedTag = Tag.CreateDerivedTag(itemTag.tag)
            where Tag.CreateTag(item) == derivedTag
            select new ItemDerivedTagItem(itemTag.item, item);

    }
}

You'll notice I needed to create two extra classes to enable this, ItemTag and ItemDerivedTagItem, that replace the anonymous classes.  Those names are probably awful, but not knowing the context, I did the best I could.  The IsInteresting and CreateDerivedTag methods were made static member methods of their classes, too.  The results were compared successfully via unit tests, against my dummy classes and dummy data, so hopefully you can verify that with yours.

As ever, the proof is in the profiling, and for me at least, the extension method query is 4 times faster.  I can supply the dummy classes and data I used if needed, but as mentioned in the comments, I'd much prefer those supplied next time please!


You have a bug. length doesn't return the length of a string, but the length of a vector. The function you need is nchar.
This problem reveals that you haven't tested your program enough.
Always look for corner cases and test well.

A minor thing, but when you reach a stop statement, the rest of the function will not be executed, so you could remove the else block,
making the code more "flat", which is typically more readable.

As far as good practices go,
in R, it's generally not recommended to use return statements,
especially when there is a single point of return from the function.
So I recommend to simply omit the return statement at the end of the function.

Putting the above tips together:

initials <- function(full.name) {
  # Returns initials of a full name
  # Input will contain only letters (uppercase and/or lowercase) plus
  # single spaces between words. Folks like Joseph Gordon-Levitt,
  # Conan O’Brien, and David J. Malan won’t be using your program. (If only!)
  if (nchar(full.name) == 0) {
    stop ("Valid name please")
  }
  isspace  <- integer(0)
  fn.split <- unlist(strsplit(full.name, fixed = TRUE, split = ""))
  isspace  <- which(fn.split == " ")
  init     <- toupper(fn.split[c(1, (isspace+1))])
  paste(init, collapse = "")
}


I rewrote your code, let me explain my changes line by line:

from random import randint

The same.

from itertools import count

You need to use modules in Python, itertools is incredibly useful and allows to avoid while and use instead the for loop (manual incrementing is terribly un-idiomatic in Python)

def number_guessing(minimum, maximum):

This is a function, you may use it as many times as you want, even in the same program with different arguments. Taking optional parameters for the messages for ultimate customization is left as an exercise for the reader.

randomNum = randint(minimum, maximum)

We use the parameters as literals in the call to randint, not just numbers.

for tries in count(1):

count() just counts, from 1 (the argument) to infinity. tries is just a number that counts the iterations of a loop, but automatically this time.

numPlayer = int(input("Guess the number({}-{})".format(minimum, maximum))

String interpolation, so the user sees a message that contains the appropraite numbers, not always 0 - 100.

    if numPlayer > randomNum:
        print ("My number is smaller"  )
    elif numPlayer < randomNum:
        print ("My number is bigger")

Using spaces around operators, removing unnecessary parentheses, and using messages that seem more understandable to me. (Your homework will make this messages fully customizable, so if you do not like my choices do not worry)

    elif numPlayer == randomNum:
        return tries

If the player guessed correctly our function halts and returns (gives back) how many tries it took for the user to guess the number.

print ("Well done you guessed my number in {} guesses".format(
    number_guessing(0, 50)))

We just call the function we wrote and print its result, that is how many tries it took.

Final code

Just to play around and implement the change I suggested:

from random import randint
from itertools import count

def number_guessing(minimum, maximum):
    randomNum = randint(minimum, maximum)
    for tries in count(1):
        numPlayer = int(input("Guess the number({}-{})".format(minimum, maximum)))
        if numPlayer > randomNum:
            print ("My number is smaller"  )
        elif numPlayer < randomNum:
            print ("My number is bigger")
        elif numPlayer == randomNum:
            return tries

print ("Well done you guessed my number in {} guesses".format(
    number_guessing(0, 2)))


Automating the installation and configuration of Vim

vim, vim_directories, vim_files and flags seem to be constants, so you should apply the naming conventions on them by capitalizing their names.

Reviewing the very first part of your function code

About the serious things, I would talk for the moment only about the very first part of your code, later I may come back (no promise though):

Within the try block, you should test only the code that is actually prone to raising an exception, nothing else. If you apply this rule, you will end up by coding short try blocks.
What may raise an exception here is rather the attempt to create a directory: os.mkdir(os.path.expanduser('~/' + sub)), the print() would not execute anyway if the attempt fails. If the directory creation succeeds, the else block should take care of the printing task. The try block should be concise and clean
I do not see the necessity of sys.exit(1) here. To be honest, in most cases it is useless, and in your typical case, I do not see how it could be useful, and you already print a message about execution failure.
As a reader of your code, I was curious to know why are you particularly interested errno.EEXIST but not other error codes? I was expecting that you are too meticulous and you decided to track down all the symbols of errno module, but I was mistaken. I think it is fair enough to write this instead:

except OSError as e:
     print('Error code: {}'.format(e.errno))
     print('Error message: {}'.format(e.strerror))

Besides, note that this code:

e.errno == errno.EEXIST:
    print('...')

is the same as:

e.errno == 17:
    print('...')

What I mean here, do you really want to include such fine grain details in a function which is rather more generic/high level?
If for some mysterious reason of your own, you find errno.EEXIST too sexy and attractive, I would still opt for a less brain nagging syntax: FileExistsError instead of errno.EEXIST (note that the later corresponds exactly to FileExistsError but, as you can see, it is more readable)
Given the elements mentioned so far, I would write the very first part of your code as follows:

for sub in vim_directories:
    try:
        os.mkdir(os.path.expanduser('~/' + sub))
    except FileExistsError:
        print("Directory " + vim + sub + " already exists.")
    except OSError as e:
        print('Error code: {}'.format(e.errno))
        print('Error message: {}'.format(e.strerror))
    else:
        print("mkkdir " + os.path.expanduser('~/' + sub))


Submit an array as an HTML form value using JavaScript

First of all, I'd make sure that supporting IE7 is actually required. It's a really old browser by now, and there are a lot of things that are much more difficult to do.

Anyway, as for sending multiple form values, there's a common - but informal - way of doing that without JSON. It's supported by some server-side languages/frameworks (notably PHP, where I think it started), so it might work for you.

It's all about naming your inputs using square brackets to namespace them.

Typically - again, this isn't a true standard, just an informal one - you would use a name like foo[bar] to specify that bar is a named sub-property of foo. Or you'd use the name foo[] multiple times to indicate that foo is an array (but this only works for plain value arrays).

Here, you need a little of both, something like this (I've skipped a lot of HTML just to make it clearer):

<form id="form">
    <input type="text" name="group_name">

    <div id="dynamic_form">
        <input type="text" name="members[0][name]">
        <input type="text" name="members[0][date]">

        <input type="text" name="members[1][name]">
        <input type="text" name="members[1][date]">

        <input type="text" name="members[2][name]">
        <input type="text" name="members[2][date]">
    </div>
</form>

E.g. what gets sent to the server would be something like:

group_name=SomeGroup
members[0][name]=Alice
members[0][date]=01/01/2015
members[1][name]=Bob
members[1][date]=02/01/2015
members[2][name]=Carol
members[2][date]=03/01/2015

This is roughly equivalent to a JSON structure like:

{
  "group_name": "SomeGroup",
  "members": [
    {
      "name": "Alice",
      "date": "01/01/2015"
    },
    {
      "name": "Bob",
      "date": "02/01/2015"
    },
    {
      "name": "Carol",
      "date": "03/01/2015"
    },
  ]
}

Again, I can't guarantee that how your server will understand it, but it's a common way to do things.

Even if your server-side code doesn't understand it automagically, it's still parseable; you just have to write a bit more code yourself.

The trick is of course to increment the number, when you add new fields. That can be done in many ways, though.

Alternatively, you simply name all your fields the same:

<input type="text" name="name">
<input type="text" name="date">
<input type="text" name="name">
<input type="text" name="date">
<input type="text" name="name">
<input type="text" name="date">

The browser will send all the values, but usually the server-side software has a rule for how to handle duplicate names, and keeps only the first or last one it sees. But again, you can access the raw request data, and parse it yourself, if you want. But there's a lot of work in doing that.

On a side-note: I'd avoid having duplication between the javascript and the HTML (right now, the page starts out with 1 set of member inputs in the HTML, and the rest get added using a string in the JavaScript. That means you have to keep both of them identical in order for things to work - not great.


Dynamically importing Python source modules from a given directory

I took @GarethRees's advice and subclassed importlib.abc.SourceLoader. After reading importlib's source code, I arrived at the following implementation:

import importlib.abc

def import_module(dir_path, module_name):
    filename = resolve_filename(dir_path, module_name)

    # I got test failures when I left this out, even though I thought it
    # was a responsibility of the loader.
    # If you know why this is, please enlighten me!
    if module_name in sys.modules:
        return sys.modules[module_name]

    return ASTFrobnicatingLoader(module_name, filename).load_module(module_name)

# in importlib, this function would be the job of the 'finder'
def resolve_filename(dir_path, module_name):
    filename = os.path.join(dir_path, *module_name.split('.'))
    if os.path.isdir(filename):
        filename = os.path.join(filename, '__init__.py')
    else:
        filename += '.py'
    return filename

class ASTFrobnicatingLoader(importlib.abc.FileLoader, importlib.abc.SourceLoader):
    def get_code(self, fullname):
        source = self.get_source(fullname)
        path = self.get_filename(fullname)

        parsed = ast.parse(source)
        self.frobnicate(parsed)

        return compile(parsed, path, 'exec', dont_inherit=True, optimize=0)

    def module_repr(self, module):
        return '<module {!r} from {!r}>'.format(module.__name__, module.__file__)

import_module now creates an instance of my custom loader and calls its load_module template method, which is provided by the abstract base class. By inheriting from both FileLoader and SourceLoader, I get a 'free' implementation of the whole protocol and I only need to override get_code.

In Python 3.4, SourceLoader provides a source_to_code method which you can override. It would've been ideal for my purposes (because the only thing I'm customising is the generation of the code object) but sadly I'm stuck with having to override the whole of get_code and calling get_source and get_filename manually.


As suggested by @netme in the comments, unless you need to write the permutation code yourself, it would be much better to use itertools.permutations, as so:

import itertools

for perm in itertools.permutations([1, 2, 3]):
    print(perm)

That code is more compact, memory-efficient and faster than yours. The itertools module has been deliberately honed to be fast (I think it’s written in C rather than pure Python) and is worth looking into if you haven’t used it before – it’s really useful.

Assuming that you're supposed to be writing your own permutation, here are some comments on that code.

(Given the self parameter and the self.insert_each_position in the second function, I’m assuming these are class methods. I put them in their own class for testing.)

Unless tuple unpacking makes the code cleaner or the variables are related, I'm generally inclined to split variable definitions over multiple lines. So I’d split the variable declarations over two lines in the start of each function.

I would then get rid of the len_of_nums variable. It’s much clearer just to use len(nums) directly in the two places where this variable is used.
You don’t mention whether you’re using Python 2 or 3. If you’re using 2, you should use xrange() instead of range(), which is slightly faster and more memory efficient.
There are no comments or docstrings. I had to guess how the function worked. You should explain what the code is trying to achieve, and why you wrote it that way – it will make it easer for me to review, and other people to use.

I would also suggest trying to pick better variable names. res and tmp are not particularly descriptive or useful.
My concern with your approach is that you gradually build up a list of all the permutations, which is going to be very memory inefficient and slow. Your program began to struggle when I asked it to permute range(10). It think it has exponential growth, but I’m not sure.

If you want something fast and you can’t use itertools, I suggest you consider looking at generators for yielding individual permutations. That’s a lot more memory efficient, and will be much faster.


That's a classic FizzBuzz solution.  I wouldn't try to do any clever optimization — it won't make any difference to performance.  One hundred iterations of anything is trivial for a computer.  Furthermore, most of the time will be dominated by the output routines, which you can't do much about.

The code formatting, on the other hand, could be improved.  The most glaring issue is the omission of the braces for the final else.  Why make your code ugly to save a couple of bytes?

Also note a de facto formatting convention: Put a space after if and for, and before any opening { brace.


Wet Chairs problem from Australian Informatics Olympiad

A O(N) algorithm would be the sliding window method. Sliding Window means that you keep track of 2 indexes, the front and the back of the "window".

Let every dry chair be a 1 and every wet chair be a 0. At first, let front = 1 and back = 0.

While front is not out of bound (i.e. not more than C, 1-indexed), check if the number of dry chairs in the window is equal to N-K. If so, update the minimum length of the window if needed and increment the back by one. Subtract 1 to the running sum of dry chairs if the chair "removed" is a dry chair.

If not, then increment front by one. Add 1 to the running sum of dry chairs if the chair "added" is a dry chair

A pseudo-code is shown below

while front <= C
if dry == N-K                                  //If there are enough dry chairs
    if front - back < min                      //Update minimum if necessary
        min = front - back
    back = back + 1                            //Decrease size of "window"
    dry = dry - chairs[back]                   //Update number of dry chairs

else                                           //If there are not enough dry chairs
    if (front == C) break
    front = front + 1                          //Increase the size of the window (Make sure that front does not go out of bounds!)
    dry = dry + chairs[front]                  //Update number of dry chairs

Why is it O(N)? Because front is incremented exactly N times  by the time the loop ends and back is incremented at most N times. You might want to check this link for another similar explanation

What is Sliding Window Algorithm? Examples?


Make C# Unity Script database methods more re-usable and concise

General
Good
Except for the non english part you are naming your methods and variables in a good way using the correct casing style.
You are using using statements to properly dispose the IDisposable's which is the way to go.
You are coding against interfaces rather then concrete implementations which is the way to go as well.
Not so good
You are using methods GetXXX but the methods returning type is void. If one read GetXXX or FetchXXX one expect that the method is in fact returning something.
Your "problem"
The first two methods are doing basically the same. They open a connection to a database, executing a SQL statement and using the value of the first column which is read by the reader as a string.
The easiest way would be to pass the SQL statement and the ID to a method which returns the read string which then can be assigned to the desired property of the doenca (whatever that is).

Because usually an ID is unique I expect that query will only return one item, so you should use ExecuteScalar() instead of having the while(reader.Read()) loop.
This could look like so
private string ExecuteScalar(string sqlQuery, string id)
{
    using(IDbConnection dbConnection = new SqliteConnection(connectionString))
    {
        dbConnection.Open();

        using(IDbCommand dbCommand = dbConnection.CreateCommand())
        {
            dbCommand.Parameters.Add(new SqliteParameter("@id", id));
            dbCommand.CommandText = sqlQuery;

            return ConvertFromDBVal<string>(dbCommand.ExecuteScalar());
        }
    }
}

where the ConvertFromDBVal<T>() method is
public static T ConvertFromDBVal<T>(object obj)
{
    if (obj == null || obj == DBNull.Value)
    {
        return default(T); // returns the default value for the type
    }
    else
    {
        return (T)obj;
    }
}

now the assignment of that properties could look like so
doenca.nome = ExecuteScalar("SELECT nome FROM doenca WHERE id = @id",  doencaId);
doenca.descricao = ExecuteScalar("SELECT descricao FROM descricao_doenca WHERE id = @id", doencaId);

If you want to hide that implementation you could add two more methods like so
private string FetchNomeById(string id)
{
    return ExecuteScalar("SELECT nome FROM doenca WHERE id = @id",  id);
}
private string FetchDescricaoById(string id)
{
    return ExecuteScalar("SELECT descricao FROM descricao_doenca WHERE id = @id",  id);
}

which results in assigning the properties like so
doenca.nome = FetchNomeById(doencaId);
doenca.descricao = FetchDescricaoById(doencaId);

but I would like to encourage you to use english for naming classes, methods and variables, because if Sam the maintainer isn't familiar with your language he/she will at least speak english because thats just what each developer does, so it would be easier for Sam to get what your code is about.

The second two methods are doing basically the same as well.  They open a connection to a database, executing a SQL statement and using the values of the first column. The difference is that they "return" different types so this is screaming for a generic version like so
private IList<T> FetchValuesOfSingleColumn<T>(string sql, string condition)
{
    IList<T> values = new List<T>();

    using (IDbConnection dbConnection = new SqliteConnection(connectionString))
    {
        dbConnection.Open();

        using (IDbCommand dbCommand = dbConnection.CreateCommand())
        {
            string sqlQuery = string.IsNullOrWhiteSpace(condition)
                            ? sql
                            : sql + " WHERE " + condition;

            dbCommand.CommandText = sqlQuery;

            using (IDataReader reader = dbCommand.ExecuteReader())
            {
                while (reader.Read())
                {
                    values.Add(ConvertFromDBVal<T>(reader[0]));
                }
            }
        }
    }
    return values;
}

which can be used to get all values from a single column without a condition as well.
Assuming doenca.sintomas is a List<string> the usage could of that method could then look like so
string condition =
IList<string> descratios = FetchValuesOfSingleColumn<string>("SELECT descricao FROM sintoma", condition);

doeanca.sintomas.AddRange(descratios);

where condition could be constructed like so
private string BuildCondition<T>(IEnumerable<T> values, string columnName, string @operator, string conditionType)
{
    IList<T> items = values.ToList();
    if (items.Count == 0) { return string.Empty; }
    if (conditionType==null) { throw new ArgumentNullException("conditionType)"); }
    if(string.IsNullOrWhiteSpace(conditionType)) { throw new ArgumentException("parameter may not be empty", "conditionType"); }

    var builder = new StringBuilder();
    string format = columnName + @operator + "{0}";
    string conditionTypeFormat = " " + conditionType + " " + format;

    builder.AppendFormat(format, items[0]);

    for (int i = 1; i < items.Count; i++)
    {
        builder.AppendFormat(conditionTypeFormat, items[i]);
    }
    return builder.ToString();
}

resulting in
string condition = BuildCondition<int>(listaIds, "id", "=","OR");
IList<string> descratios = FetchValuesOfSingleColumn<string>("SELECT descricao FROM sintoma", condition);
doeanca.sintomas.AddRange(descratios);

and for the other property assignment
string condition = BuildCondition<int>(new int[]{ doencaId }, "id", "=","OR");
IList<int> descratios = FetchValuesOfSingleColumn<int>("SELECT sintoma_id FROM doenca_sintoma", condition);
listaIds.AddRange(descratios);

The BuildCondition<T>() method will only work correctly with T being a numeric types because this types won't need quotes for the query.

If you need more queries with datamappings I would like to encourage you to dig into some object relational framework like for instance Entity Framework or any other relational mapping framework.


If you can, just use Path.GetFileNameWithoutExtension

  Returns the file name of the specified path string without the extension.

Path.GetFileNameWithoutExtension("asdasdasd.asdas.adas.asdasdasdasd.edasdasd");

With one line of code you can get the same result.

If you want to create one by yourself, why not just use this?

int index = a.LastIndexOf('.');
b = index == -1 ? a : a.Substring(0, index);

P.S Special thanks to @Anthony and @CompuChip to point me out some mistake i done, bad day maybe.

You take everything which comes from 0 (the start) to the last dot which means the start of the extension


Determine whether bitwise-OR of sub-array is odd

Code

#pragma GCC optimize("O2")

Normally we just pass that as a compiler flag, so we don't get "unrecognised pragma" warnings from other compilers.

    long int c,d,j,N,Q;

These are poor names - they tell us very little about what they are used for.
The number of array elements and the number of queries can't be negative.  I suggest size_t (from <stdint.h>) would be better than long for these.  Also consider what range is required for the other values (the challenge should state these bounds).  You might want to use the int_fastX_t and int_leastX_t families to ensure the required range.

    scanf("%ld %ld\n",&N,&Q);

Don't throw away the return value from scanf() like that.  It's important to know how many conversions were successfully performed before attempting to use the assigned values.
Algorithm
This is on average, much less computation than the naive brute-force algorithm, since we stop examining the array once we find an odd number.
Something to consider, especially for programming challenges, is that we often talk of average-case complexity using big-O notation, but it can be more helpful to think like an adversary: "What's the worst-case input this algorithm could be given?".  The test cases are likely to include some arrays which are all odd or all even - the former being very expensive for this algorithm.
If we have many queries, we can spend a little time creating a structure to make each query constant-time.  The way I would approach this is probably to have an array of size_t that stores the running count of odd numbers.  Then, given a query Q(m,n), look at odd_count[n]; if it's equal to odd_count[m], we have only even numbers in the range, else we have at least one odd number.  Note that we don't need to actually store the input array, as we'll only use the running total.  Obviously, adjust m and n before lookup if these are inclusive in the challenge (it's a little unclear in your summary, but I assume more rigorously defined in the original).


finding definite integrals in Python using Trapezium rule

First, there is an error where you have:

sum_y = (f(0)+f(b))

f(0) should be f(a). It doesn't matter on your example, because you start with 0, but would otherwise.

Another error is that you add f(a) 3x instead of just once. i=a+h should be the line before while.

Your while loop makes O(n) multiplications and twice as many additions. Instead you should have something like:

i = a+h
part_sum = 0
while i<b:
    part_sum += f(i)
    i += h
sum_y += 2*part_sum

Still same number of additions, but only one multiplication.

Using list comprehensions might be a bit faster, but you'd spend too much memory at scale where it matters.

print significantly slows your function. If you actually need to print this, then store intermediate results in array and then print them before final result with print "\n".join(intermediates).


Handling null exception when having multiple variables

Refactor into a method:

var name = this.GetVariable("Name");
var dueDate= this.GetVariable("Due Date");
.
.//more variables
.
var Title= this.GetVariable("Title");

private string GetVariable(string name)
{
    try
    {
        return item[name].ToString();
    }
    catch (Exception ex)
                        {
                            Console.WriteLine();
                            Console.WriteLine(name + " not found.");
                            Console.WriteLine();
                            return null;
                        }
}


Optimize function that returns length of a subarray

Specific suggestions:

In many situations it would probably be useful to return sub rather than len(sub). This makes the code somewhat simpler and gives the caller more information. Depending on the context that may or may not be useful, but it simplifies the code, which makes it easier to focus on the core issue.
The code iterates over all sub-lists, calculating min and max of each of them. This is a lot of duplicate work. You can instead iterate only once over the list (with some backtracking):

Set the longest sub-list to the empty list.
Set the working sub-list to a list containing just the first item in the input list.
Set working sub-list min and max to the first item in the working sub-list.
Move along the input list, updating min and max as long as the difference between them ends up being less than one and adding the current item to the working sub-list.
Once you encounter a number which makes the difference between min and max more than one (or the end of the list, at which point you'd terminate after this step), check if the working sub-list is longer than the longest sub-list and update the latter if so.
Once you encounter a number which makes the difference between min and max more than one you can't simply start the new working sub-list from that list item, because valid sub-lists may overlap (for example, [1, 1, 2, 3] has valid sub-lists [1, 1, 2] and [2, 3]). At this point you need to set the new working sub-list to include all the items at the tail end of the previous working sub-list which make a valid sub-list with the new item (if any).
Go to 3 until you reach the end of the list.

Tool support

black can automatically format your code to be more idiomatic, for example adding spaces around infix mathematical operators like +.

flake8 can give you more hints to write idiomatic Python beyond black:
 [flake8]
 ignore = W503,E203

I would then recommend validating your type hints using a strict mypy configuration:
 [mypy]
 check_untyped_defs = true
 disallow_any_generics = true
 disallow_untyped_defs = true
 ignore_missing_imports = true
 no_implicit_optional = true
 warn_redundant_casts = true
 warn_return_any = true
 warn_unused_ignores = true

In your case it looks like the type of arr should be Iterable[int] and the output is int.


jQuery plugin to detect Konami cheat code sequence

This is almost like code golf; this could probably be shortened.  You just need to keep track of i and when it's past the end of the array, you know all the keys were hit in the correct order.

jQuery.konami = function() {
    function KonamiCode(kFn, kCode) {
        var i = 0;

        $(document).keydown(function(e) {
            var char = typeof kCode === 'string' ? String.fromCharCode(e.which).toLowerCase() : e.which;
            i = char === kCode[i] ? i + 1 : 0;
            if (i === kCode.length) {
                kFn();
                i = 0;
            }
        });
    }
    return function(fn, code) {
        // ↑ ↑ ↓ ↓ ← → ← → B A
        kCode = code || [38, 38, 40, 40, 37, 39, 37, 39, 66, 65];
        new KonamiCode(fn, kCode);
    };
}();


Consider replacing Node<T> with:

typedef Node<T> node_t;

...

node_t node;

Consider making your implementation STL-enabled. If I were user of this class, the first thing I'd ask you is "how do I iterate over this list?". Doubly-linked lists are great when adding items in the middle, how do I do it? (it's about operations like insertBefore(), insertAfter()). How do I sort it? How do I check if item is on the list? How do I search using predicate?
Why do you call the method deleteNode if it's only argument is of type T? It's more to findNodeByValueAndDeleteIt(T).
What about assignment operator? You should either declare it private (if you don't support it), or implement it explicitly depending on semantics you want to support (deep copy (most likely what you want), reference, COW, etc):

YourList<int> a; // do something with a

YourList<int> b; // do something with b

a = b; // what is "a" here? what if I add nodes to a? will it affect b?

// imagine, scope ends here, dtor for b is called, everything's fine

// dtor for a is called - here you're going to crash, since

// both a and b were using the same memory and this memory is already

// free, since b's dtor has already been called at this point

For methods like void addNode(T data) - why do you pass data by value? Since you store item values by value, in either case you're going to call their copy-ctor. Copy-ctor requires const-reference, so you should consider replacing addNode with void addNode(T const& data).
using namespace std; - is it only for cout instead of std::cout in your main()?

Checked nothing from the "algorithmic" standpoint, C++ only.


Prime engine: generation, primality, factorization

This is excellent code for a beginner. It's neat, the methods are short, etc. However, there are a couple things I'm concerned with.

1) Your engine has a lot of state. It looks like this is mostly related to the generation of the next prime sequences, and any found primes are cached, so it shouldn't be too bad. However, you have to test that calling PrimesUntilValue followed by UniquePrimeFactors, for example, doesn't generate "duplicate" values or skip any.

2) Given that you are using an approximation for primes, your code is structured neatly. However, do note that actually generating the sequence might get a bit messier than this and don't expect to be able to swap it out neatly. Given that your class's state is solely used for generating the next prime and that all previously found values are cached, it shouldn't be an issue.

3) This code could lead to massive memory use in an application. Since you are already caching the values and all, you should consider making it a static class and making the cached collection a thread-safe hashmap. Then you have one instance of the prime engine and can do things like PrimeEngine.PrimesUntilRoot, etc. The hashmap would prevent duplicate primes from being entered into the collection.


Pythonic Ideas

Multiplication with lists

You can create an array of n + 1 zeros using the * operator:

dp = [0] * (n + 1)

Which seems a bit clearer (IMHO) than:

dp = [0 for i in range(n+1)]

General solution with no base case

You could get rid of the base case n == 1 if you do:

def climbStairs(self, n):
    """
    :type n: int
    :rtype: int
    """
    dp = [0] * max(3, n + 1)
    dp[1] = 1
    dp[2] = 2
    for i in range(3,n+1):
        dp[i] = dp[i-1] + dp[i-2]
    return dp[n]

Computing Fibonacci

Your solution is one of the fastest (and most obvious) ways to compute fibonacci with a running time of \$O(n)\$. However, there's a \$O(\log{}n)\$ solution using an interesting property of fibonacci numbers. Here's a proof and an in depth explanation.

Basically if you know F(n) and F(n-1) you can find F(2n) and F(2n-1) following these two formulas:

\begin{aligned}F_{2n-1}&=F_{n}^{2}+F_{n-1}^{2}\\F_{2n}&=(F_{n-1}+F_{n+1})F_{n}\\&=(2F_{n-1}+F_{n})F_{n}.\end{aligned}

Using this, you can double your way to the fibonacci number you need (or recursively half your way down)

def fibonacci(n):
    memo = {
        0: 0,
        1: 1,
        2: 1,
        3: 2
    }
    def recurse(n):
        if not n in memo:
            if n % 2 == 0:
                k = n // 2
                memo[k] = recurse(k)
                memo[k - 1] = recurse(k - 1)
                memo[n] = (2 * memo[k - 1] + memo[k]) * memo[k]
            else:
                k = (n + 1) // 2
                memo[k] = recurse(k)
                memo[k - 1] = recurse(k - 1)
                memo[n] = memo[k]**2 + memo[k -1]**2
        return memo[n]
    return recurse(n)

Note: While the closed form solution is interesting, it's not computationally practical since it requires infinate precision of \$\phi\$.


Is this an efficient implementation?

Yup. It calls map exactly once per item, and otherwise does nothing but the regular range calls. A specialized implementation could be more efficient in some cases (but probably only if using vector instructions), as could a parallel implementation, but neither of these have the genericity that your code does.

  Is it readable?

Absolutely, it's some of the most readable code I've seen. The content of the loop is somewhat dense. You could perhaps make it less dense like this:

    auto front = tuple!("elem", "map")(r.front, map(r.front));
    auto min = front;
    auto max = front;

    r.popFront;
    foreach (e; r) {
        front = tuple(e, map(e));
        if(front.map > max.map) max = front;
        if(front.map < min.map) min = front;
    }
    return tuple!("min", "max")(min.elem, max.elem);

Apart from that, I got nuthin'.

  Any general feedback is appreciated.

As hinted at in the section above, instead of while (!empty), you might want to use foreach. This reduces your code by one line (r.popFront()), and makes it clearer that you're going to iterate over every element of the range. It shouldn't change the performance of the code in any way.

You should put an if (is(typeof(unaryFun!pred))) constraint on the template, so the user of the function gets an error message on the line where he or she tries to instantiate it with arr.minMax!"invalid string".

Also, the name pred is wrong - a predicate is a boolean-valued function, like equal, same color or contains bees. I'd call it Fn or Fun.

As a minor nit, I'd also change the name of map, probably to fn or fun (note the difference in capitalization). This because I kept conflating your map with std.algorithm.map. The concept is correct, but essentially the name is already taken.

All in all, very good - my only comments are essentially nitpicks.


Python Combinatory Algorithm - A Binomial Coefficient application with n mutable and k fixed to 2

If you just want the length of the list, your code can be reduced to one line:
result = len(to_do) * (len(to_do) - 1)

Also, you're comments are, at the very least, excessive. You should really only use comments to explain a design choice or a complicated equation/algorithm. Comments like #if the condition is satisfied just clutters your code.
As explained in a comment, actual computations need to be made. This can be done using itertools.permutations.
import itertools
from typing import List

def func(nums: List[int]) -> List[int]:

    return list(set(
        x * y for x, y in itertools.permutations(nums, 2)
    ))

While this doesn't avoid the extra computations, it's a short and sweet solution. And below is how you would use it:
to_do = [1, 2, 3, 4, 5]
func(to_do)


Converting input containing special character to float

For reading a fraction such as "97/100", you can use the fractions library.

For example:

from fractions import Fraction

f = Fraction("97/100")

print(float(f)) # prints 0.97

And because the constructor also takes a float, we can remove the check for /. Therefore, the final code is:

from fractions import Fraction

def toNum(interest):
    f = Fraction(interest)
    f = float(f)

    if f > 1:
        f /= 100

    return f

print(toNum("97/100")) # prints 0.97
print(toNum(0.97)) # prints 0.97
print(toNum(9)) # prints 0.09


Not really about performance, but this is more about clarity of the code.

Attach onload handlers first, for readability. Appending the src starts the loading process. If you saw code that loaded something, expect to do something, but haven't found the handler to do it makes it a bit confusing.
Declare one handler function in a persistent scope and have the onload refer to it, rather than create one handler for each onload, or creating the function everytime the whole routine executes.
Instead of find(), use jQuery function's second parameter, context. With this, jQuery finds the elements with the given selector under the jQuery object that is on the second parameter.
If the images are children of data.content, use children() instead of find() to avoid deep DOM traversal. Also, the lower you are in the DOM, the less deep find() has to dive and find your elements.
Use strict comparison as much as possible.
Don't forget to declare the variables and use var. You'd be declaring globals if you didn't.

And so:

var $images = $('img', data.content),
  imagesLength = $images.length,
  imageLoadingIterator = 0,
  img, i;

function onImageLoad() {
  if (++imageLoadingIterator === images.length) _continue();
}

for (i = 0; i < imagesLength; i++) {
  img = new Image();
  img.onload = onImageLoad;
  img.src = $images[i].src;
}

However, these advices might have a very negligible gain in performance, and might be unnecessary since the compiler might be optimizing them in some way.


How can I display the results of mysql_fetch_assoc in a dynamic table?

Aren't you forgetting something, called ?

Try

<?php

// Configure connection settings

$db = 'scorecard';
$db_admin = 'root';
$db_password = '********';
$tablename = 'scoreboard';

// Title

//echo "DIV!";

// Connect to DB

$sql = mysql_connect("localhost", $db_admin, $db_password)
or die(mysql_error());

mysql_select_db("$db", $sql);

// Fetch the data

$query = "SELECT * FROM $tablename";
$result = mysql_query($query);
echo mysql_error();

echo "
\n";

// Return the results, loop through them and echo

while($row = mysql_fetch_assoc($result))
{
    echo '
'."\n";
    echo "{$row['codcliente']}	\n" . "{$row['nombre']}	\n" . "{$row['ejecutivo']}	\n" . "{$row['banca_as400']}	\n" . "{$row['banca_real']}	\n" . "{$row['ingresos']}	\n" . "{$row['ciiu']}	\n" . "{$row['division']}	\n" . "{$row['actividad']}	\n" . "{$row['riesgo_industria']}	\n" . "{$row['riesgo_cliente']}	\n" . "{$row['fecha']}	\n" . "{$row['analista']}	\n";

    echo '
'."\n";
}

echo "
\n";

?>


Don't use a lambda

This code:

std::for_each(first, last, [&result, comp] (ValueType curr) {
    if (comp(result, curr)) result = std::move(curr);
});

is just a lot messier than the non-lambda equivalent:

for (; first != last; ++first) {
    ValueType cur = *first;
    if (comp(result, cur)) {
        result = std::move(cur);
    }
}

I don't see the advantage in the lambda.

Avoid the copy

Once you advance an input iterator, all earlier iterators are invalidated. But you can dereference the same one multiple times. In this case, you're incurring an unnecessary copy of ValueType, you can just write:

for (; first != last; ++first) {
    if (comp(result, *first)) {
        result = std::move(*first);
    }
}

Move iterators

Dereference likely returns a const T& - so you probably want to wrap the iterators in std::make_move_iterator first. That will actually let you move-from the iterator, instead of looking like you're moving from and actually copying from.

advance is excessive

You can just write:

ValueType result{*first++};

Or:

ValueType result{*first};
++first;

There's no need for advance() - you know operator++ is supported.

Throwing on empty range

Honestly, I'd prefer it just be undefined behavior and avoid the first check. Let the user deal with it. That's just a personal preference though.

Additionally, you could return an optional<ValueType>, returning none if the range is empty.

Defer to std::max_element?

Since std::max_element is more efficient than yours for forward iterators, it'd be nice to defer to it if you're given a forward iterator:

template <class It, class Cmp>
typename std::iterator_traits<It>::value_type
max_input(It first, It last, Cmp mp) {
    // possibly check empty range and throw here, if that's what you want
    return max_input(first, last, cmp, typename std::iterator_traits<It>::iterator_category{});
}

template <class It, class Cmp>
typename std::iterator_traits<It>::value_type
max_input(It first, It last, Cmp cmp, std::input_iterator_tag) {
    /* your implementation */
}

template <class It, class Cmp>
typename std::iterator_traits<It>::value_type
max_input(It first, It last, Cmp cmp, std::forward_iterator_tag) {
    return *std::max_element(it, last, cmp);
}

Excessive commenting

Avoid this sort of commenting style:

#include <iterator>   // std::iterator_traits, std::advance
#include <stdexcept>  // std::logic_error
#include <algorithm>  // std::for_each
#include <functional> // std::less
#include <utility>    // std::move

It's just verbose and provides no value.


Pseudo-random generation able to regenerate backwards

Dispose of IDisposable objects with the using statement. For example, objects of type Rijndael, MemoryStream, and CryptoStream. Follow C#'s capitalization conventions, in particular camelCase for parameters (and though not specified in the link, for local variables).


Scraping reviews from Google Play using JavaScript

Use scraping as last resort. I suggest you find available APIs for that. It's more robust, and  easy to work with. One issue with scraping is that it fetches the static HTML generated by the url. You can't fetch what is loaded via JS. Although there are ways to do it, it's just adds too much complexity.

In terms of hacking the code, you could check out how Google Play loads the rest of the comments. It should be an AJAX call, check the network tab of your browser. You checkout that url, the response and modify it to your needs.

As for your script: You're using jQuery, use it all the way!

// Cache as well as put configurables here
var input = $('#input');
var output = $('#output');
var noodleUrl = 'http://example.noodlejs.com/?';

var query = {
    // You should check if the url ends with parameters. Otherwise, this fails.
    url: input.val() + '&hl=en',
    type: 'html',
    selector: '[class=review-body]',
    extract: 'text'
};

// $.param
var request = noodleUrl + $.param({
  q : JSON.stringify(query),
  callback : '?'
});

$.getJSON(request, function (data) {
    output.html('<pre>' + JSON.stringify(data, null, 4) + '</pre>');
}


A program that reads 8763x2 values from a CSV file and initialises an array and few other variables

You don't really mention what are the values used for. You'll always have a tradeoff between speed and memory (in this case memory amounts to how many digits you have).

Some issues with your code:

1) You're casting your decimal.Decimal(line[0]) as float, that should negate the advantage of using Decimal. And this might be a reason why you see the unexpected inconsistency. You have two options (in my opinion), you drop the use of numpy in favor of array from the standard library or you drop the pretense of using Decimal and use a pure numpy solution. But this will depend on what exactly you're doing.

2) Looping over the CSV Reader is a way to read out the data, but numpy implements better ways to load a csv. See the last example in the documentation here.

Thus, in the end the question back is, what for do you want the numbers to be a accurate as possible? Keep in mind that the values in the file are already "wrong" as they most likely come already from a float type, so in my opinion, you don't gain anything by using Decimal in this case. A different scenario would be if the values are integers and then in your program you're doing some divisions or multiplications, in that case, you have from the beginning control of the floating-point values and then using Decimal might be what you want to do.

Keep in mind, that highly sophisticated scientific research and their calculations use 64-bit floats and they do just fine.


Attempt at the Most dynamic FizzBuzz possible in Java

The most important problem I have with your code is, that it totally fails to achieve the goal you set yourself. This is not dynamic at all. Basically, you take the "normal" method body and put it into a lambda, but this lambda now is a complex function, which contains all of the business logic.

Dynamically, you'd need a collection (probably list for being ordered) of lambdas, which each check a single input value and return an appropriate string representation (i.e. "fizz" or "buzz" or "whatever" or the empty string) and a method to apply this complete list on a single input, accumulate the results and perform the final check whether to output that string or the integer itself.

Thus, start out with something like:

Function<Integer, String> fizz = i -> i % 3 == 0 ? "fizz" : "";
Function<Integer, String> buzz = i -> i % 5 == 0 ? "buzz" : "";
Function<Integer, String> barz = i -> i % 7 == 0 ? "barz" : "";
List<Function<Integer, String>> fizzBuzzList = Arrays.asList(fizz, buzz, barz);

And try to come up with code that operates on such a list. Note: Function is the standard function type with an integer as an input and a string as the output. No need to define your own interface.

If you have achieved this, you can easily add another function to the list to check another value, and then you have achived something that might be considered dynamic.


Some notes:

var myList: Don't use generic names like myList. My list of what? Variable names are very important, they should inform about the nature of their content, not their type (although it's indeed important to use singular variable names for single elements and plurals for collections).
var myList = list.getElementsByTagName("li");. What if list is null? no checks?
myList[i].innerHTML = a[i];. You are overwriting HTML contents, it would probably be better to move DOM elements instead.

I'll leave a pure Javascript re-write to others, if you are interested in solutions that use external libraries, using jQuery and underscore I'd write:

var sorted_lis = _.sortBy($("#list li"), function(li) { return li.innerText; });
$("#list").empty().append(sorted_lis);

The original ten lines reduced to two (one actually, but it's good to break things a bit and give names to intermediate values), thanks to functional style (underscore) and easy DOM manipulation (jQuery).


This may be a good case for generator functions.  And splitting it into two parts might make things more flexible: first, remove the stopwords; and second, handle the punctuation.

Also, str.maketrans and str.translate can do the punctuation mapping.

def remove_stopwords(text_iterable, stopwords):
    for word in text_iterable:
        if word.lower() not in stopwords:
            yield word

def handle_punctuation(text_iterable, table):
    for word in text_iterable:
        yield word.translate(table)

# format is ("chars", "replacement")
mappings = (("/-'", ' '),
            ('&', ' & '),
            ('?!.,"#$%\'()*+-/:;<=>@[\\]^_`{|}~' + '“”’', None))

table = str.maketrans({c:v for k,v in mappings for c in k})

stopword_free = remove_stopwords(text, stopwords)
cleaned_text = handle_punctuation(stopword_free, table)

cleaned_text is a generator, use list(handle_punctuation(stopword_free, table)) if you need an actual list of words.


General
As example code, there is a fair amount to comment on. For an eclipse plugin, I would at least expect you to select-all and Ctrl-Shift-F ....

consistent use of braces (on the end of the line, not start of the new line)
consistent spacing between values and operators jsonResponse+=line; to jsonResponse += line;

The formatted code looks like:

    HttpURLConnection httpconn = null;
    BufferedReader breader = null;
    try {
        URL url = new URL(this.web_service_url);
        httpconn = (HttpURLConnection) url.openConnection();
        httpconn.setRequestMethod("GET");
        System.out.println(httpconn.getResponseMessage());
        if (httpconn.getResponseCode() == HttpURLConnection.HTTP_OK) {
            breader = new BufferedReader(new InputStreamReader(
                    httpconn.getInputStream()));
            String line = null;
            while ((line = breader.readLine()) != null) {
                jsonResponse += line;
            }
            // System.out.println(jsonResponse);
            // display_json_results(jsonResponse);
        }
    } catch (MalformedURLException e) {
        MessageDialog.openError(Display.getDefault().getShells()[0],
                "Invalid URL", e.getMessage());
    } catch (ProtocolException e) {
        MessageDialog.openError(Display.getDefault().getShells()[0],
                "Invalid Protocol", e.getMessage());
    } catch (IOException e2) {
        Log.info("Failed to access the data" + e2.getMessage());
    } finally {
        try {
            breader.close();
        } catch (IOException e) {
            Log.info("Failed to release resources" + e.getMessage());
        }

    }

Working with the formatted code now:

Why do you have an active System.out.println(httpconn.getResponseMessage()); in the code? That should be commented out. Use the Log for that.
Why are the HttpURLConnection and BufferedReader declared outside the try-block? There is no need.
The BufferedReader should be opened with a try-with-resource block to perform the auto-close.
you are losing newlines on the BufferedReader's readLine(). You should use a different system, or alternatively add the newline back in... unless you are using some other mechanism to reformat thte JSON.
you should be appending to a StringBuilder, not doing String concatenation (jsonResonse += line; == BAD)
why have commented-out code in example code? Get rid of the println's and the display_json_results

Exception Handling
This exception-handling has a lot of problems I can see.

you are throwing away all stack traces.... you do not report them! Why?

you have different forms of exception naming in your handlers. Two of them call the exception e. The third is called e2. Use meaningful names, or use consistent names. The mix is.... mixed up.

Calling Log.info("Failed to access the data" + e2.getMessage()); is ... poor. If you have the Log available, it should at least be a warning! Also, you should pass the full exception to the Log, and log the full trace. Finally, you do not have a space between the 'data' and the e2.getMessage() in the output... .... access the data" should be ... access the data: "

When there is an exception, you should help the user by indicating what data was causing the exception. In this case, the errors/dialogs should contain this.web_service_url since that was the source of the problem.

Since you have the log, not only should you be outputting the exception message for the URL formats to the Display, but also to the Log.

Quick reformat
I messed with the code, and got the following:
  try {
        URL url = new URL(this.web_service_url);
        HttpURLConnection httpconn = (HttpURLConnection) url.openConnection();
        httpconn.setRequestMethod("GET");
        //System.out.println(httpconn.getResponseMessage());
        if (httpconn.getResponseCode() == HttpURLConnection.HTTP_OK) {
            try (BufferedReader breader = new BufferedReader(new InputStreamReader(
                    httpconn.getInputStream()));) {
                String line = null;
                while ((line = breader.readLine()) != null) {
                    jsonResponse.append(line).append("\n");
                }
            }
            // System.out.println(jsonResponse);
            // display_json_results(jsonResponse);
        }
    } catch (MalformedURLException mue) {
        Log.warn("Invalid URL " + this.web_service_url, mue);
        MessageDialog.openError(Display.getDefault().getShells()[0],
                "Invalid URL " + this.web_service_url, mue.getMessage());
    } catch (ProtocolException pe) {
        Log.warn("Protocol Exception " + this.web_service_url, pe);
        MessageDialog.openError(Display.getDefault().getShells()[0],
                "Invalid Protocol " + this.web_service_url, pe.getMessage());
    } catch (IOException ioe) {
        Log.warn("Failed to access the data " + this.web_service_url, ioe);
    }

}


Database schema for a products and bugs aggregator

CATEGORIES VARCHAR(255),
TAGS VARCHAR(255),

Take care with plural named fields. It's very, very likely that any plural field is secretly a multi-valued field. You might want to extract a "Category" and "Tag" table out of this, so searching for them is easier.

PRODUCT_ID INTE GER,

You've got a space there. Not sure if SQL is okay with that.

Lastly, I think you should put some NOT NULL in there - are you sure every field except the primaries can be NULL? You also seem to be missing foreign keys from one table to another.


I think you expect addNodes to be called exactly once, and expect it to be called before any other method.

Therefore, remove the addNodes method, and move the Set<T> nodes parameter to the constructor.

The next thing you want to do is define all edges. To do that you expect the user to call addEdges repeatedly (one for each node).

A simpler way to do that might be to pass in a list of all edges. If you do the following then you only need to call the method once (because the List can contain all edges for all nodes):

public class Edge<T>
{
    T node1;
    T node2;
    Double d;
}

public void addEdges(Iterable<Edge> allEdges) {
    for (Edge edge : allEdges) {
        addEdge(edge.node1, edge.node2, edge.value);
        addEdge(edge.node2, edge.node1, edge.value);
    }
}

private void addEdge(T node1, T node2, Double value) {
    if (!graph.containsKey(node1))
        graph.put(node1, new HashMap<T, Double>());
    HashMap<T, Double> map = graph.get(node1);
    if (map.containsKey(node2))
        throw new DuplicateEdgeException("Duplicate " + node1 + " to " + node2);
    map.put(node2, value);
}

Your Set<T> nodes is only used for assertions. I'm not sure how useful that is.

Also I don't understand your comment about a "god constructor". A constructor initializes the object using input data: that is something to love.

In summary, perhaps a class like the following. This constructs an arbitrary graph, using only a collection of edges as its input; it supports an isComplete method to test whether the resulting graph is complete (which, you could call as an assertion in the constructor):

class Graph
{
    public class Edge<T>
    {
        T node1;
        T node2;
        Double d;
    }

    private final Map<T, HashMap<T, Double>> graph;

    public Graph(Iterable<Edge> allEdges) {
        graph = new HashMap<T, HashMap<T, Double>>();
        for (Edge edge : allEdges) {
            addEdge(edge.node1, edge.node2, edge.value);
            addEdge(edge.node2, edge.node1, edge.value);
        }
    }

    private void addEdge(T node1, T node2, Double value) {
        if (!graph.containsKey(node1))
            graph.put(node1, new HashMap<T, Double>());
        HashMap<T, Double> map = graph.get(node1);
        if (map.containsKey(node2))
            throw new DuplicateEdgeException("Duplicate " + node1 + " to " + node2);
        map.put(node2, value);
    }

    public bool isComplete()
    {
        int count = graph.size();
        for (HashMap<T, Double> map : graph.values())
            if (count != (map.size() + 1))
                return false;
        return true;
    }

    public Map<T, Double> getAdj (T nodeId) {
        if (!graph.containsKey(nodeId)) throw new IllegalStateException("The graph is not populated with " + nodeId);
        return graph.get(nodeId);
    }
}


Semantic implementation of the structure of a web page with header, main, and footer

I myself am also a beginner in the world of web development (So any comments about my answer are more than welcome!)
But maybe my tips can still be useful in one way or another. ;-}
The first thing that came to mind is your header and footer element question about grouping them together that way in CSS because they have things in common...My short answer is no, I would change my HTML element for these, or better said, add a class or id attribute, and group it together this way.
Example:
 .....
         .....

CSS example:
 .header, topAndBottom {
.......
}

I personally prefer the class attribute over the id, because you can use it more often in your HTML, the id attribute is once or maybe twice acceptable in your HTML(Not my rules)
Or you can only style your
 inside your header and the
 inside your footer, I would recommend this if it is mainly text that you want to style.
And one tiny comment about the order in your CSS, and this is purely personal, but maintain the order from your HTML in your CSS for better reading, especially when your code will be more advanced and complex.
Good luck with your learning for web development! I started also not long ago and I am addicted!


I suspect that performance with 15k images will be bad no matter what you do. You might want to rethink your UI.

If you want to know which is the fastest solution you will have to measure them. Though I would guess the second is faster. You could test a direct document.querySelector though jQuery should be passing the query through pretty much as is. The one suggestion I would make is instead of interpolating your image_id each time give all of the images a class and use a class selector.

As to your last question, I don't know of anyway to do it using pure css and there would probably be little advantage anyway.


Using TinyMCE with responsive file manager PHP and Javascript

How you want to arrange your JS files depends also on your build processes too, and whether you want to utilise the cloud version of TinyMCE, or a self-hosted one.
If you're sticking with self-hosted, I find it easier to move external plugins out of the TinyMCE folder - this just makes updating the TinyMCE core easier. You can replace an entire TinyMCE folder with a new version, and know that the Responsive File Manager is not lost.
I would recommend splitting any external plugins (like Responsive File Manager, or anything else you write yourself too) to a separate folder outside of the TinyMCE folder - in the long run, just makes it easier to maintain.
Alternatively, you could use the TinyMCE cloud version - which means you don't need to host it yourself, and you would get the minor point updates as they come out (which for the 5 version have had some really nice features added). To do this, you can visit tiny.cloud and sign up for an API key, which is free. They offer premium plugins at a cost if there are features that you want to use.
For the config.php file, that all looks fine - it's about tweaking it to suit your folder structure.
In your init.js file, I'm assuming you have two different TinyMCE configs? If that is not the case, and you only have one configuration, then you don't need your second init call - the one that references "demoBaseConfig" could be removed.
The first call is initialising TinyMCE on any textarea, using the plugins and toolbar as stated, and hooking in to the Responsive File Manager.
If you wanted to clean it up, you could slim down your plugins array to only include those that you're actually using. There are some plugins here that you don't have in your toolbar, so could slim down the configuration further.
One thing I have done when using TinyMCE is have a number of JS objects that store different configurations, with a selector of "textarea.simple" or "textarea.full" (for two editor types).
The two configurations here are a simple editor (such as maybe basic text choices, adding links, etc) where as the full is a more feature-rich experience too. There are times when you may want to give your users a HTML editor but without too many options (such as for a bio or small snippet) and others where they need a full suite of options (like an article editor). This is more about UX, but just something to be aware of - not every TinyMCE instance needs to look the same.
If you were to go down this path, you would have one init call per configuration option, such as:
tinymce.init({
    selector: "textarea.simple",
    ...
    [whatever simple config options you need]
});

tinymce.init({
    selector: "textarea.full",
    ...
    [whatever full suite config options you need]
});

Just remember to add the appropriate class to your textarea and you'll be good to go.


I wrote the following code to read a config file line by line and split each line into 2 parts and store them separately.

So there are two parts on each line, the stuff before the =, which is stored as a string, and the stuff after the =, which shall be parsed as an integer and stored as a long long.

Thus you can handle each line on its own completely, without using a flag to determine at which part of the line you currently are:

for (int i =0; i<linesOfConfigFile.size(); i++)
{
    std::stringstream singleLine(linesOfConfigFile[i]);

    // get first part of the line
    std::getline(singleLine, currentItem, delimeter);
    // store it
    RHS.push_back(currentItem);

    // Now get the next part of the line
    std::getline(singleLine, currentItem, delimeter);
    // parse it
    long long orderbookId = 0;
    <some library class>::toNumeric(currentItem, orderbookId);
    // and store the result
    LHS.push_back(orderbookId);

    // done with this line :D
}

This supposes of course that the config file is well-formed, and the format requires that each name = value is on a separate line.

If the config file is malformed, or the file format is not as simple, this version may fail where yours wouldn't (for example

name =
value

would work with yours), but neither version does robust error handling, and both would fail on most malformed inputs. Config files can generally be assumed to follow the required format, so the absence of error handling probably isn't a serious problem.


Coderbyte SimpleSymbols challenge in Javascript

How about this logic?

if the first character or last character is a letter it's false
then go through the array and look for the letters

skip it if is a = or a +
if it isn't a = or a + then check that the character before and after is a +

So something like this:

var simpleSymbols = function (s) {
    if (s[0] != "+" && s[0] != "=") {
        return false;
    } else if (s[s.length - 1] != "+" && s[s.Length - 1] != "=") {
        return false;
    } else {
        for (var i = 1; i<s.Length - 1; i++) {
            if (s[i] != "+" && s[i] != "=") {
                if (s[i-1] != "+" || s[i+1] != "+") {
                    return False;
                }
            }
        }
    }
    return true;
}

This code is cleaner than what you have.

With this block of code:

it's more readable
it exits if the first or last character is a letter, immediately preventing unnecessary iterations in a for loop.
it's easier to read
it's easier to follow (in my opinion)

Bottom Line

Your code is not efficient.  All of the if statements fire every iteration until the end of the string is met or a return is met.

if the last character is a letter, will return false and not loop through the whole string.
will not perform a "before and after check" unless the character is a letter

It may not make a difference in smaller strings, but if you have a huge string to parse, it will make a difference.

I have been told the the CoderBytes challenge will include numbers that don't need to be surrounded by +'s, and I wanted to steal a little of @Konijn's answer as well.

All of my above points still stand for this code block as well.

var simpleSymbols = function (s) {
    if (s[0] >= 'a' || s[s.length -1] >= 'a') {
        return false;
    } else {
        for (var i = 1; i<s.length - 1; i++) {
            if (s[i] >= 'a') {
                if (s[i-1] != "+" || s[i+1] != "+") {
                    return false;
                }
            }
        }
    }
    return true;
}

NOTE

This code is the most efficient way to perform this task.

It exits if the first or last character is a letter because you can't have a + before the first character or a + after the last character, thus failing the filter.
It only checks the before and after characters if the character is a letter.  This prevents unnecessary if statements from being performed
All the other answers so far will check every character and the before and after character until it returns.  This could be an issue if the string is say 500,000 characters long,  you would see a definite decrease in performance.
This code will not loop through the whole string if there is a letter in the last character position, which would make it a lot more efficient in those cases.


An if inside the loop is usually counterproductive. Consider highlighting the choice afterwards:

    for (int index{}; index < n_items; ++index) {
        mvwprintw(win, 3 + index, 2, items[index]);
    }
    wattron(win, A_BOLD);
    mvwprintw(win, 3 + selected, 2, items[selected]);
    wattroff(win, A_BOLD);

It is very unclear what the 3 and 2 offsets stand for. Apparently they have something to do with the visual layout. Consider giving them some meaningful names.

Since you are writing in c++, you'd be in much better shape operating on vector<char *> rather than a raw array.


It is certainly better. You can improve it further:

Use early exits to reduce arrow code.
Use a JSON initializer for the result.
Prefix boolean names with 'is'.
Fix the 'user.lastEdited' bug.

.

function processResponse(data) {
    if (!data.query || !data.query.users || !data.query.users[0]) return {};

    var user = data.query.users[0];

    return {
        isInvalid: 'invalid' in user,
        isMissing: 'missing' in user,
        groups: user.groups || [],
        editCount: ('editcount' in user) ? user.editcount : null,
        registration: ('registration' in user) ? parseDate(user.registration) : null,
        isBlocked: 'blockexpiry' in user,
        gender: ('gender' in user && user.gender != 'unknown') ? user.gender : null,
        lastEdited: (data.query.usercontrib
                             && data.query.usercontribs[0]
                             && data.query.usercontribs[0].timestamp)
                        ? parseDate(data.query.usercontribs[0].timestamp) : null
    };
}


You loop from the first element to the last, and in each iteration you check if a next element exists or not. This check will only be false on the last element, it will be true for all elements before that. In other words, most of the time the check is unnecessary.

To get rid of this redundancy, you could start the iteration from the second element, and make comparisons with the previous one, which always exists. No more redundant checks.

More importantly, keep in mind that you don't need to read the entire input into memory to find the most frequent repetition. You don't need a vector. You could just parse the input word by word, always keeping only the last word in memory for comparisons. That way you will drastically reduce the memory footprint of the program.


You should use Ruby's Numeric#divmod function:

writing, integer = integer.divmod(1_000_000)

Your function parameter claims to accept an integer, so you should also handle negative inputs.  (It shouldn't be hard to prepend "negative " and flip the sign.)


Stateless Maximum Beauty of String implementation

How can I remove the state in the reducer for mapLettersByCount?

Return a new object on each iteration. Not optimal, but we're talking functional anyways. You can use object destructuring to do a shallow copy of the object. A more verbose version would be Object.assign. Then use computed keys to assign a dynamic key.

function mapLettersByCount(sentence) {
  return sentence.split(EMPTY_STRING)
                 .filter(letter => LETTERS_ONLY.test(letter))
                 .map(letter => [letter.toUpperCase(), 1])
                 .reduce((letterCount, [key, count]) => ({
                   ...letterCount,
                   [key]: (letterCount[key] || 0) + count
                 }), {});
}

  How can one use generators without assigning it to a variable? (see points variable in the maxBeauty function) Is this even considered state in this situation?

I believe that it is stateful since one call to points.next() does not return the same result as the next call. But I may be wrong.

One way you could do this is compute the points by subtracting the reducer's index from a constant 26. I believe it won't violate the rules of functional programming because

this 26 is a constant value
it's technically a closure scenario, similar to your other constants and
index is provided as an argument to the callback.

And it would look like this:

const POINTS = 26;

export function maxBeauty(sentence = "") {
  return Object.values(mapLettersByCount(sentence))
               .sort()
               .reverse()
               .reduce((score, count, index) => score + count * (POINTS - index), 0);
}


Billing and recurrent payment db structure

Consistency

I like the naming convention of the auto-incrementing primary keys to be prefixed with the table name. This allows the use of using (keyname) when joining tables.
Some tables are created with IF NOT EXISTS, other aren't. Is there a strategy behind this?

Design

I am missing tables user and business.
Table business_product has a column product_type which overrides that of the referenced table product_type. Is this as designed?
Perhaps table user_authorized should be renamed to user, update the name of the primary key and referenced foreign keys along. (This has an impact on the constraints below)

Constraints

Table product_detail is missing a foreign key to product.
Table business_product is missing a foreign key to product, user and business.
Table billing is missing a foreign key to user and payment_method.
Table billing_detail is missing a foreign key to billing, product and business.
Table user_authorized is missing a foreign key to user and payment_method.


Get a list of indexes for list A based on criteria in list B in Python

Consider doing this only with a single for loop, i.e. zip the two
lists, sort them by IDs and Yes/No (Yes first so those end up in
front in each block), enumerate and then, while keeping track of the
current block ID, simply always take the first element from each block
and append it to c.  E.g.:

a=[1,1,1,2,2,3,3,1]
b=['No','Yes','No','Yes','No','No','No','No']

d = list(enumerate(zip(a, b)))

def compare(x, y):
    same_ids = cmp(x[0], y[0])
    return -cmp(x[1], y[1]) if same_ids == 0 else same_ids

d.sort(cmp=compare, key=lambda x: x[1])

c = []
last = None
for i, (x, y) in d:
    if last != x or last == None:
        c.append(i)
    last = x

At the price of more memory consumption you could also just do a linear
scan and keep a dictionary around that records the best choice per ID so
far.  E.g.:

from itertools import izip

a=[1,1,1,2,2,3,3,1]
b=['No','Yes','No','Yes','No','No','No','No']

known = {}
for i, (x, y) in enumerate(izip(a, b)):
    current = known.get(x)
    if not current or y == 'Yes' and current[1] == 'No':
        known[x] = (i, y)

c = [i for (i, _) in known.itervalues()]


public void Lock(string key, int timeout = 60, int tick = 100)
    {
        ...
        //timeout = ConvertTimeoutToTicks(timeout, tick);
        ...
        timeout = 600;

Looks like you didn't finish tidying up the code.

        //timeout is specified in seconds, tick in milliseconds

Why perpetuate the common mistake in the standard libraries? TimeSpan exists: use it! I wish Microsoft would [Obsolete] every method in .Net which takes an int or a long for a timespan and replace it with a version taking a TimeSpan.

        var counter = 0;
        do
        {
            ...
        } while (counter++ < timeout);

Ok, now I'm even more confused. Is timeout supposed to be a timeout or a multiplier of tick?

            if (!Keys.Contains(key))
            {
                lock (Keys)
                {
                    if (!Keys.Contains(key))
                    {
                        Keys.Add(key);
                        return;
                    }
                }
            }

Just no. .Net's memory model fixes the subtle double-checked locking problem in Java, but only where the test is a simple boolean field. HashSet cannot guarantee that multi-threaded access will work correctly if one of the threads modifies it, so the unlocked test must be removed. However, I can offer an improvement which should compensate: use the return value of Add:

            lock (Keys)
            {
                if (Keys.Add(key))
                {
                    return;
                }
            }

Similarly, Unlock should wrap the current body in a lock statement.

What's the lifecycle of that ManualResetEvent? It's IDisposable, so you should take care of tidying it up yourself, probably with a using statement.


Other reviews already provided some pretty good points, so I'll just mention a few other things and reiterate on some already mentioned ones.

I would advise against function prototypes in this case. Since this is a single source file program, you could declare all functions before main() and avoid the prototypes. The problem with function prototypes is code duplication. If you change one function, at least two updates are mandatory, instead of just one. Avoid this extra maintenance overhead if you can.
For decimal division to work properly, you'll need a to use a floating-point type. My suggestion would be to use double instead of float. The float type is only recommended for storage and memory saving. Most CPUs operate natively on doubles and will convert a float to double when operating on a value. Since you don't have storage constraints, double is the best option.
Don't write noisy and obvious comments. The overall rule about code commenting is to use them to explain why you solved a problem in a given way, or to give any extra information (web links, mathematical formulas, etc) that will aid the understanding of a piece of code. Explaining what a code is doing should not be necessary if the code is well written. Well written code is self explanatory.
Arguably personal preference, but I find it better to properly space expressions and parameter list in function calls.

printf("\n%d + %d = %d\n",num1,num2,addition(num1,num2));

Better spacing:

printf("\n%d + %d = %d\n", num1, num2, addition(num1, num2));


Are you more worried about memory, speed or maintainability?   if the lists are long enough that you worry about them filling up your available memory, write them out one at a time. If not, process them in bulk.

in either case, a list-of-lists is better than maintaining 6 copies of identical code.  You could use a dictionary to store the different lists with their output filenames and avoid the duplication:

 lots_o_data = {
     'list1': [.....],
     'list2': [.....],
     'list3': [.....]
 }

 for eachfilename, eachlist in lots_o_data.items():
     with open(eachfilename, 'wb') as csvfile:
          writer = csv.writer(csvfile)
          for line in eachlist:
              writer.writerow(line)

If the data is interleaved - stuff from different ouput lists comes up intermingled - you have to collect it all before writing. If it's sequential you can do it read A - write A - read B - write B style. Ordinarily the total time won't change much - reading and writing the data will be way slower than whatever you do in the processing.

One thing you don't want to do is open the same source file multiple times if you don't have to - that will add extra time. Only do that if you're worried about memory.