This answer is just going to focus on what you asked for, how to speed up your code. I'm going to go through line by line and note anything that could be done to make it faster.

 Application.ScreenUpdating = False
 Application.DisplayAlerts = False
 Application.Calculation = xlCalculationManual

 Path = "PathToFolder" & "\"
 Filename = Dir(Path & "*.xl??")
 Set wsO = ThisWorkbook.Sheets("Sheet1")

You might want to add Application.EnableEvents = False.
Other than that, nothing to change here, this is about as fast as it's ever going to get.

Do While Len(Filename) > 0
     Set wbk = Workbooks.Open(Path & Filename, True, True)
     ws = wbk.Worksheets.Count
     For i = 1 To ws
     Application.ScreenUpdating = False
     Application.DisplayAlerts = False
     Application.Calculation = xlCalculationManual
     Set rRng = Range("b1:b20")

This is mostly fine, except why are you re-setting all the Application.Settings options to false? They haven't changed from 6 lines ago. Just cut them out.

An obvious way to speed things up is not to open every worksheet in every workbook in this folder, but I'm going to assume that they are all required.

Opening a workbook does take time. If you've got a lot of them to open, then this macro is going to take time to run no matter how much you optimise it.

     For Each rCell In rRng.Cells
         If rCell <> "" And rCell.Value <> "Not Tested" Then

         wsO.Cells(wsO.Rows.Count, 1).End(xlUp).Offset(1, 0).Value = rCell
         wsO.Cells(wsO.Rows.Count, 1).End(xlUp).Offset(0, 1).Value = rCell.Offset(0, -1)
         wsO.Cells(wsO.Rows.Count, 1).End(xlUp).Offset(0, 2).Value = Right(ActiveWorkbook.FullName, 15)
         End If
     Next rCell

By process of elimination, any performance problems not related to opening the workbooks will be found here.

Fortunately, there are many things to be improved.

My personal #1 rule of fast spreadsheet manipulations:

Thou shalt not directly manipulate data in worksheets

By this I mean, doing anything in a worksheet has huge computational overhead. In the VBA object heirarchy, worksheets are only 2 steps removed from the application object itself. There are layers upon layers of abstractions, events, handlers, objects (not to mention several Billion range objects) buried in a worksheet object, and any time you do something in it, it will trigger a cascade of operations to make sure that nothing in your worksheet gets messed up.

For this reason, you should interact with worksheets as infrequently as possible. If there is data in your worksheet that you need to analyse: access the worksheet once to read the data into an Array, then do all your computations on the Array, then access the worksheet once to read the data back (if applicable).

Your sub then goes like this:

Sub AbesLoop()

    Application.ScreenUpdating = False
    Application.EnableEvents = False
    Application.DisplayAlerts = False
    Application.Calculation = xlCalculationManual

    Dim targetBook As Workbook
    Dim targetSheet As Worksheet

    Dim sheetCount As Long
    Dim targetFilename As String

    Dim outputSheet As Worksheet
    Set outputSheet = ThisWorkbook.Sheets("Sheet1") '/ Get this out of the way until we need it later

    Dim sheetRange As Range
    '/ Note the *descriptive*, *unambiguous* names.

    '/================================================================================================================================================
    '/================================================================================================================================================
    '/ Create the main array object, define columns, insert headers.

    Dim testOutputData As Variant
    testOutputData = Array()

    Dim testOutputRowIndex As Long
    testOutputRowIndex = 1
    ReDim testOutputData(1 To 3, 1 To testOutputRowIndex) '/ Defined it in a transposed state (column, row) because when extending arrays, if you want to preserve the data, you can only extend the final dimension.

    Const CELL_VALUE_COLUMN As Long = 1
    Const ADJACENT_CELL_VALUE_COLUMN As Long = 2 '/ It would really help when naming to know what this data actually is that you need to copy.
    Const WORKBOOK_NAME_COLUMN As Long = 3

    testOutputData(CELL_VALUE_COLUMN, testOutputRowIndex) = "Cell Value"
    testOutputData(ADJACENT_CELL_VALUE_COLUMN, testOutputRowIndex) = "Cell Value in adjacent (to left) column"
    testOutputData(WORKBOOK_NAME_COLUMN, testOutputRowIndex) = "Workbook Name"

    '/================================================================================================================================================
    '/================================================================================================================================================

    Dim sheetData As Variant
    sheetData = Array()

    Dim i As Long, j As Long
    Dim cellValue As Variant, adjacentCellValue As Variant

    targetFilename = Dir(FOLDER_PATH & "*.xl??")

    Do While Len(targetFilename) > 0
        Set targetBook = Workbooks.Open(FOLDER_PATH & targetFilename, True, True)
        sheetCount = targetBook.Worksheets.Count

        For i = 1 To sheetCount
            Set targetSheet = targetBook.Sheets(i)

            Set sheetRange = targetSheet.Range("a1:b20") '/ include the adjacent column in our data
            sheetData = sheetRange

            For j = 1 To 20
                cellValue = sheetData(j, 2) '/ column "a" is in 1, so "b" is 2
                If cellValue <> "" And cellValue <> 0 And cellValue <> Null And cellValue Is Not Nothing And cellValue <> "Not Tested" Then '/ Check for other versions of [No Data]

                    adjacentCellValue = sheetData(j, 1)

                    testOutputRowIndex = testOutputRowIndex + 1
                    ReDim Preserve testOutputData(1 To 3, 1 To testOutputRowIndex) '/ add an extra row to the end

                    testOutputData(CELL_VALUE_COLUMN, testOutputRowIndex) = cellValue
                    testOutputData(ADJACENT_CELL_VALUE_COLUMN, testOutputRowIndex) = adjacentCellValue
                    testOutputData(WORKBOOK_NAME_COLUMN, testOutputRowIndex) = targetBook.Name

                End If
            Next j
        Next i

        targetBook.Close False
        targetFilename = Dir
    Loop

    '/ --> [Transpose data array back to (row, column) form]. You can find a function on the internet or write your own.

    '/ print final data array back to sheet
    Set sheetRange = outputSheet.Range(Cells(1, 1), Cells(testOutputRowIndex, 3))
    sheetRange = testOutputData

    Application.ScreenUpdating = True
    Application.DisplayAlerts = True
    Application.EnableEvents = True
    Application.Calculation = xlCalculationAutomatic

End Sub


Speeding up HTML Parsing

You can make some quick wins on the HTML parsing side by applying a SoupStrainer class allowing to parse only a part of the document containing the desired jobs:

parse_only = SoupStrainer('div', class_='job-item')
bs = BeautifulSoup(formatted_result, 'lxml', parse_only=parse_only)

jobs = []
for job in bs.select("div.job-item"):
    _company = job.strong
    try:
        company = _company.a.get_text()
    except AttributeError:
        company = _company.get_text()

    company = company.replace('\n', '').replace('\r', '').replace('\t', '')

    title = job.h3.a.string
    description = job.select_one("p.description").contents[0]
    link = base_url + job.select_one("a.job-link")["href"]
    jobs.append({
        "title": title,
        "description": description,
        "company": company,
        "link": link
    })

Don't forget to import SoupStrainer from bs4.

Speeding up Database Interaction

First of all, you should not be using str.format() to parameterize your query - it is highly discouraged. You are opening your code to SQL injections and have to deal with type conversions and quote balancing and escaping manually. Instead, properly parameterize your query via your database driver.

As far as improving the speed - you can actually use executemany() to insert jobs into the database in one go:

query = """
    INSERT INTO
        jobs (title, description, company, link)
    VALUES
        (%(title)s, %(description)s, %(company)s, %(link)s)
"""
db.executemany(query, jobs)

Other performance improvements

I would probably enforce the uniqueness of a link on the database level and handle/skip constraint violations on insert instead of doing it manually via grabbing the existing links first. If you still gonna continue with this approach, make sure to make links a set to improve the lookup speed.


I don't see why you want/need three functions to download the different quality videos. There is a bunch of repeated logic both in the functions and in the main loop.

Then, I would move all of the main specific code into the __name__ == __main__ section because that's the purpose of that section.

#!/usr/bin/env python3.5.2

import urllib.request, urllib.parse
import os

def get_sourcecode(url):
    return urllib.request.urlopen(url).read()

def get_info():
    return urllib.parse.parse_qs(get_sourcecode(url).decode('unicode_escape'))

def get_video_title_path():
    try:
        return os.path.join(directory, '{}.mp4'.format(get_info()['title'][0]))
    except KeyError:
        print('Parsing error, please rerun the code!')

def get_stream_map_list():
    video_links = []
    for video_stream in get_info()['url']:
        if "googlevideo" == video_stream.split('/')[2].split('.')[1]:
            video_links.append(video_stream)
    return video_links

quality_map = {'small': 0, 'medium': 1, 'high': 2}

def download_video(quality='medium'):
    k = quality_map.get(quality)
    map_list = get_stream_map_list()[k]
    title_path = get_video_title_path()

    print("Downloading {} -----------> {} in {} quality.".format(map_list, title_path, quality))
    return urllib.request.urlretrieve(map_list, title_path)

if __name__ == '__main__':
    print("\n                          * * * * * * * * * * * * * * *")
    print("                          *                           *")
    print("                          * Youtube Video Downloader! *")
    print("                          *                           *")
    print("                          * * * * * * * * * * * * * * *\n")
    # make sure to change directory path
    directory = r'C:\Users\SalahGfx\Desktop\DownloadedVideos'

    while True:
        try:
            url, quality = input(
                "Please type a youtube video url and its quality(choose between high, medium and small) and separate them with a space: ").split()

        except ValueError:
            print("Please type the right url and quality.");
            print("Make sure the url start with 'https://www.youtube.com/'");
            print("high - for downloading high quality video");
            print("medium - for downloading medium quality video");
            print("small - for downloading small quality video");
            continue

        if url.startswith('https://www.youtube.com/') and quality in quality_map:
            get_sourcecode(url)
            download_video(quality)
            break


Retrieve filename and ID with Google Drive API in C#

First of all let me clarify that I'm not familiar with the Google Drive API. I've done some refactoring but I haven't tested it (just make it compile).
If I can assume you are using greater C# version than 8 then you can refactor your code like this:
using static {YourMainNamespace}.Constants;

class Program
{
    static async Task Main(string[] args)
    {
        UserCredential credential = await AuthorizeAgainstGoogleDriveAsync();
        IList<Google.Apis.Drive.v3.Data.File> files = await GetFilesMetaInfoAsync(credential);
        DisplayFilesMetaInfoInTabularFashion(files);
        Console.ReadLine();
    }

    static async Task<UserCredential> AuthorizeAgainstGoogleDriveAsync(
        string sourceRelativePath = Authorize.RelativeFilePath.Source,
        string targetRelativePath = Authorize.RelativeFilePath.Target)
    {
        using var stream = new FileStream(sourceRelativePath, FileMode.Open, FileAccess.Read);

        var credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(
            GoogleClientSecrets.Load(stream).Secrets,
            Authorize.Scopes,
            Authorize.User,
            CancellationToken.None,
            new FileDataStore(targetRelativePath, true));

        Console.WriteLine($"Credential file saved to: {Authorize.RelativeFilePath.Target}");

        return credential;
    }

    static async Task<IList<Google.Apis.Drive.v3.Data.File>> GetFilesMetaInfoAsync(
        UserCredential credential,
        string applicationName = GetFiles.ApplicationName,
        int pageSize = GetFiles.PageSize,
        string fields = GetFiles.Fields)
    {
        var service = new DriveService(new BaseClientService.Initializer()
        {
            HttpClientInitializer = credential,
            ApplicationName = applicationName,
        });

        FilesResource.ListRequest listRequest = service.Files.List();
        listRequest.PageSize = pageSize;
        listRequest.Fields = fields;

        var fileList = await listRequest.ExecuteAsync();

        return fileList.Files;
    }

    static void DisplayFilesMetaInfoInTabularFashion(IList<Google.Apis.Drive.v3.Data.File> files)
    {
        Console.WriteLine("Files:");
        Console.WriteLine($"{DisplayFiles.Name}{new string('\t', 6)}{DisplayFiles.Id}{new string('\t', 8)}{DisplayFiles.ModifiedTime}");

        if (files == null || files.Count <= 0)
        {
            Console.WriteLine(DisplayFiles.NoFileMessage);
            return;
        }

        foreach (var file in files)
        {
            Console.WriteLine($"{file.Name,-56}{file.Id,-36}{file.ModifiedTime}");
        }

    }
}

static class Constans
{
    public static class Authorize
    {
        public const string User = "user";
        public readonly static string[] Scopes = new[] { DriveService.Scope.DriveReadonly };

        public static class RelativeFilePath
        {
            public const string Source = "credentials.json";
            public const string Target = "token.json";
        }
    }

    public static class GetFiles
    {
        public const string ApplicationName = "GoogleDriveFileManager";
        public const int PageSize = 1000;
        public const string Fields = "nextPageToken, files(id, name)";
    }

    public static class DisplayFiles
    {
        private const string prefix = "file.";
        public const string Name = prefix + nameof(Name);
        public const string Id = prefix + nameof(Id);
        public const string ModifiedTime = prefix + nameof(ModifiedTime);
        public const string NoFileMessage = "No files found.";
    }
}

Let me give you some context for each part:
Main
static async Task Main(string[] args)
{
    UserCredential credential = await AuthorizeAgainstGoogleDriveAsync();
    IList<Google.Apis.Drive.v3.Data.File> files = await GetFilesMetaInfoAsync(credential);
    DisplayFilesMetaInfoInTabularFashion(files);
    Console.ReadLine();
}

I've made your Main async (supported since C# 7.1) to be able to use async-await
I've split your logic into three smaller functions to make your Main short and concise

If the scope of the application is this small then you can use shorter names of course, like

AuthorizeAsync
GetFiles
DisplayFiles

Constants
using static {YourMainNamespace}.Constants;

...

static class Constans
{
    public static class Authorize
    {
        public const string User = "user";
        public readonly static ImmutableArray<string> Scopes = new[] { DriveService.Scope.DriveReadonly }.ToImmutableArray();

        public static class RelativeFilePath
        {
            public const string Source = "credentials.json";
            public const string Target = "token.json";
        }
    }

    public static class GetFiles
    {
        public const string ApplicationName = "GoogleDriveFileManager";
        public const int PageSize = 1000;
        public const string Fields = "nextPageToken, files(id, name)";
    }

    public static class DisplayFiles
    {
        private const string prefix = "file.";
        public const string Name = prefix + nameof(Name);
        public const string Id = prefix + nameof(Id);
        public const string ModifiedTime = prefix + nameof(ModifiedTime);
        public const string NoFileMessage = "No files found.";
    }
}

I've put all of the hardcoded values into a hierarchical structure

Because I'm unfamiliar with the domain I've organize them based on the usage
In normal cases you should organize them based on their semantics

I've used const (which is implicit static) to prevent modification
In case of Scope I've used ImmutableArray to prevent modification

Here I can't use const but it could (and should) be marked as readonly

I've used using static to avoid prefixing with Constants each and every time

AuthorizeAgainstGoogleDriveAsync
static async Task<UserCredential> AuthorizeAgainstGoogleDriveAsync(
    string sourceRelativePath = Authorize.RelativeFilePath.Source,
    string targetRelativePath = Authorize.RelativeFilePath.Target)
{
    using var stream = new FileStream(sourceRelativePath, FileMode.Open, FileAccess.Read);

    var credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(
        GoogleClientSecrets.Load(stream).Secrets,
        Authorize.Scopes,
        Authorize.User,
        CancellationToken.None,
        new FileDataStore(targetRelativePath, true));

    Console.WriteLine($"Credential file saved to: {Authorize.RelativeFilePath.Target}");

    return credential;
}

I've made the source and target file paths configurable (but with default values)

If you wish you can make the same with user and scopes

One can argue whether the Console.WriteLine should belong here or inside the Main

I've put it here to make the main as concise as possible
But from reusability point of view it should not belong here

I've used using declaration (which is a C# 8 feature) to avoid the block operator ({ ... })

GetFilesMetaInfoAsync
static async Task<IList<Google.Apis.Drive.v3.Data.File>> GetFilesMetaInfoAsync(
    UserCredential credential,
    string applicationName = GetFiles.ApplicationName,
    int pageSize = GetFiles.PageSize,
    string fields = GetFiles.Fields)
{
    var service = new DriveService(new BaseClientService.Initializer()
    {
        HttpClientInitializer = credential,
        ApplicationName = applicationName,
    });

    FilesResource.ListRequest listRequest = service.Files.List();
    listRequest.PageSize = pageSize;
    listRequest.Fields = fields;

    var fileList = await listRequest.ExecuteAsync();

    return fileList.Files;
}

I've made this API call to async (Execute >> ExecuteAsync) to make use of the async non-blocking I/O
I've declared the function with three optional parameters to be able to customize the request if needed
I've realized that you are not making use of the nextPageToken but I did not remove it

I've assumed that the implementation of paging will be your next step

DisplayFilesMetaInfoInTabularFashion
static void DisplayFilesMetaInfoInTabularFashion(IList<Google.Apis.Drive.v3.Data.File> files)
{
    Console.WriteLine("Files:");
    Console.WriteLine($"{DisplayFiles.Name}{new string('\t', 6)}{DisplayFiles.Id}{new string('\t', 8)}{DisplayFiles.ModifiedTime}");

    if (files == null || files.Count <= 0)
    {
        Console.WriteLine(DisplayFiles.NoFileMessage);
        return;
    }

    foreach (var file in files)
    {
        Console.WriteLine($"{file.Name,-56}{file.Id,-36}{file.ModifiedTime}");
    }
}

This operation is tightly coupled to the request

It highly relies on the retrieved fields
So, it might make sense to it make more dynamic if needed

I've used new string instead of new String

I suggest to read this article

I've reverted the if statement to use the early exit pattern

With this the main logic (foreach) is not indented

I've also used the capabilities of string interpolation to avoid calls like PadRight


Good randomness in Python code for a lottery-like game

According to the Python documentation random.SystemRandom() uses os.urandom() which

  [...] returns random bytes from an OS-specific randomness source. The returned data should be unpredictable enough for cryptographic applications, though its exact quality depends on the OS implementation.

Given that your system does a good enough job, the output of random.SystemRandom() should be indistinguishable from true randomness, and thus be good enough for your purpose.

Also, if the randomness provided by your system is indistinguishable from true randomness, shuffling does not add anything to the randomness of your output (even if you had also used a cryprographically secure RNG for shuffling).

In this case your code could be reduced to

import random

def randomWeightedSelection(choices, weights):
    rng = random.SystemRandom()

    indices = list(range(len(choices)))

    selected_index = rng.choices(indices, weights = weights, k = 1)[0]

    return [choices[selected_index], selected_index]


Simplifying the code with same list comprehensions

As far as I can tell, the difference between the conditional branches is only whether or not to avoid KeyError occurring at additional_images[_key] when key does not exist. This code should have the same behavior:

@staticmethod
def decorate_sort_images(primary_images, additional_images, get_uri_text, marker=False):
    srt_keys = sorted(primary_images)
    new_result = OrderedDict()
    allow_key_error = additional_images and not marker
    for _key in srt_keys:
        new_result[_key] = [get_uri_text(iter_el) for iter_el in primary_images[_key]]
        if allow_key_error or _key in additional_images:
            new_result[_key] += [get_uri_text(iter_el) for iter_el in additional_images[_key]]
    return new_result

When additional_images is empty, _key in additional_images is always False, so we don't need the first if statement any more.

Note that I also removed a redundant .keys() from sorted(primary_images).


Your function is slow because it is O(n2): each element being added to new_seq has to be compared against every previously added element.

To deduplicate a sequence, use a set.  Constructing the set is only O(n) because it uses hashing.

Then, to obtain the size of the set, use len().

def unique(seq):
    return len(set(tuple(element) for element in seq))


Small method that runs various processes

I'd first start with naming conventions. Prefixes are usually avoided and method name is PascalCase:

public void RunProcess(string path, string fileName, string fileExtension)

Honestly I'd accept just one parameter with full path and I'd split it inside this method but you might not be able to change this then I won't comment about it.

First I'd extract a method to create the StartupInfo leavinig in this method only invocation and parameters validation:

if (path == null)
    throw new ArgumentNullException(nameof(path));

// More validations...

using (var process = Process.Start(CreateStartupInfo(path, fileName, fileExtension)))
{
    process.WaitForExit();
}

Then, moving to CreateStartupInfo() implementation, I'd first drop those if in favor of a Dictionary or a plain list because it's much easier to extend and it might come from a configuration file (no need to change code to support more file types.)

For the moment keep the if in-place but consider:

Do not perform string comparison with ==. It's a current culture aware case sensitive comparison, it's not obvious and it's not probably what you want. Use String.Equals() specifying the right StringComparer/StringComparison value.
Do not manually build paths, there is Path.Combine() for that. Let's see an example where for simplicity I have as input the full file path.

Given this holder:

sealed class KnownFileType
{
    public KnownFileType(string type,
        bool useShellExecute,
        Func<string, string> interpreter,
        Func<string, string> interpreterCommandLine)
    {
        // ...
    }

    public string Type { get; }
    public Func<string, string> Interpreter { get; }
    public Func<string, string> InterpreterCommandLine { get; }
    public bool UseShellExecute { get;  }
}

We can declare a list of known file types like this (note that his can be outside the method and static):

var fileTypes = new KnownFileType[]
{
    new KnownFileType(".py", false, x => "python.exe", x => $"\"{x}\""),
    new KnownFileType(".exe", true, x => Path.GetFileName(x), x => $"\"{x}\""),
    new KnownFileType(".vbs", false, x => "cscript.exe", x => $"/B \"{x}\""),
};

Do you need to add new known file type? Add one line here. If those values come from a configuration file then you might want to use String.Format() instead (be careful if configuration can be tampered.) Because I dislike escape sequences I'd introduce an helper method:

private static string Quote(string text) => '"' + text + '"';

Using it I may simplify above code to:

new KnownFileType(".py", false, x => "python.exe", x => Quote(x))

To create the ProcessStartupInfo you just need to:

string extension = Path.GetExtension(fullPath);
var fileType = fileTypes.First(x => String.Equals(x.Type, extension, StringComparison.InvariantCultureIgnoreCase));

return new ProcessStartInfo
{
    UseShellExecute = fileType.UseShellExecute,
    FileName = fileType.Interpreter(fullPath),
    Arguments = fileType.InterpreterCommandLine(fullPath),
    WorkingDirectory = Path.GetDirectoryName(fullPath)
};

Note that here I used a plain array but if you opt for a Dictionary<string, KnownFileType> (with the proper case insensitive comparer for keys) then code may be slightly simplified to:

var fileType = fileTypes[Path.GetExtension(fullPath)];
// ...


Naming convention: classes should normally use PascalCase.
Requests best practices: if you want to use the requests library, you can see my answer about requests usage.
Speeding up your script:

Threading: you can use the threading standard library to get data from URLs and process that data.
Concurrent Futures: this approach exists from Python 3.2, there is a good example on the docs page. But you may have problems with using requests with the concurrent.futures library, so take a look at standard.
Scrapy: modern Python for scraping data from websites. It provides lots of built-in functionality: from scrapping to storing results in a way you wish.

Logging: it is a good practice to use logging while doing any actions, e.g. scrapping.
Exceptions: adding exception handlers is good practice. At the moment, if your script fails in any line, it stops all execution.


Instead of using a ConcurrentDictionary as a cache, and having to cast, you can use an embedded generic static class. The static construction is lazy and threadsafe by design. To make it work you have to create and open delegate (an instance method with no "this") for the mapper function:

public class Mapper
{
    public Mapper()
    {
        // dependencies are injected in the constructor
        // not shown here for simplicity
    }

    public object Map<T>(T item)
    {
        var mapper = MapperCache<T>.Map;
        return mapper(this, item);
    }

    // example methods
    public object Map(SomeObject item) { return new object(); }

    public object Map(SomeTotallyDifferentObject item) { return new object(); }

    public object Map(Guid item) { return new object(); }

    private static class MapperCache<T>
    {
        public static readonly Func<Mapper, T, object> Map;

        static MapperCache()
        {
            var mapMethod = typeof(Mapper).GetMethod("Map", BindingFlags.Public | BindingFlags.Instance, null, new[] { typeof(T) }, null);

                Map = mapMethod != null ? (Func<Mapper, T, object>)Delegate.CreateDelegate(typeof(Func<Mapper, T, object>), mapMethod)
                                        : (mapper, item) => { throw new InvalidOperationException($"{nameof(Mapper)} cannot map from {typeof(T).Name} to object"); };
        }
    }
}

The first time you reference the static property, Map, the MapperCache<T> for the given type T will be initialized. By setting up the delegate creation in the static constructor you guarantee that it will only run once for each T. If any exceptions are thrown in the static constructor the type will fail to load and cannot be used at runtime.

The same trick is used in System.Data.DataRowExtensions (source) to cache converters.


Of course this can be improved. Look at all the repetition... then, factor it out into a function. You'll end up with something like this:
pseudomoves.push_back_if_legal(row, col, row-1, col+2);
pseudomoves.push_back_if_legal(row, col, row-2, col+1);
pseudomoves.push_back_if_legal(row, col, row+1, col+2);
pseudomoves.push_back_if_legal(row, col, row+2, col+1);
pseudomoves.push_back_if_legal(row, col, row+2, col-1);
pseudomoves.push_back_if_legal(row, col, row+1, col-2);
pseudomoves.push_back_if_legal(row, col, row-2, col-1);
pseudomoves.push_back_if_legal(row, col, row-2, col-1);

As a bonus, it is now relatively obvious where the bug is!


I am not particularly a python expert but can offer some feedback from a fairly generic perspective.

There are no useful (plain English) comments until line 105. There is definitely room to improve the commenting of this code.
Unless StackExchange is affecting the formatting, this doesn't appear to adhere to PEP 8 (the definitive Python style guide). For example, you are using three spaces per indentation level, not four.
As @200_success spotted in a comment, you are calling main() twice at the end: is this intentional? I cannot understand why this would be.
foobar() does not sound like a sensible name for a function: it gives me absolutely no clue as to what the function's purpose is.
What is the significance of "WordsWeNeverSee"? This might be well documented in the Telnet library but it might be helpful to offer a brief explanation here, so somebody can follow this code without knowing that library well.  Failing that, at least a reference to the main documentation would be good.
Your main game engine architecture smells funny to me. When main() first calls readBoard(), this can then lead to readBoard() being called recursively, and/or control passing to foobar() which then calls readBoard() again. This feels like it might lead to a deeply-nested call stack. Without following the logic through carefully I have no idea what the rationale is for this, but it seems unlikely to be the best design approach.
Relatedly, your key functions readBoard() and selectMove() take no input and return no output. They are operating on data structures that exist globally, aside from their function scope - i.e. they are having side effects. This also seems unlikely to be the best approach; I'm not really qualified to say what the best or most-pythonic way might be, but a more object-oriented approach could be one way to go.
readBoard() seems to have two blocks of identical code, inside the first if and following elif. In other words, you're saying: if len(tLines)==13, then do some stuff; if len(tLines)==14, then do the same stuff; else do something different.  Can you see the quick way to simplify this code?


I'm happy to use EcmaScript 6 features

Try array comprehensions!

var vals = range(0, 3);
return [ [i, j, k, l] for (i of vals) for (j of vals) for (k of vals) for (l of vals) ]

Still, it translates to the same nested loops. If you need a variable nesting level, you  can use a recursive solution.


Msbuild batch - if any build fails than skip the last one

You probably want to localize any environment changes.

You should initialize your variables to a known state at the beginning, otherwise you could get the wrong result.

You have a lot of redundant code that can be eliminated by using a CALLed subroutine

You can use the || operator to conditionally execute code if the previous command failed. I find it simpler than using IF ERRORLEVEL.

You can save a bit of typing by storing code in a variable to be used as a simple macro.

@echo off
setlocal
set "failed32="
set "failed64="
set "build=call :build"

%build% Win        32 my-proj1
%build% X          64 my-proj1
%build% ManagedWin 32 my-proj1
%build% ManagedX   64 my-proj1
%build% Win        32 my-proj2
%build% X          64 my-proj2
%build% Win        32 my-proj3
%build% Win        32 my-proj4
%build% Win        32 my-proj5

if not defined failed32 msbuild /target:setup32 my-last.proj

%build% X          64 my-proj3
%build% X          64 my-proj4
%build% X          64 my-proj5

if not defined failed64 msbuild /target:setup64 my-last.proj
exit /b

:build  target  size  proj
msbuild /target:%1%2 %3.proj || set failed%%2=1
exit /b


Counting duplicate tags in a string of many tags

I has been a long time since I used PHP, but what you want are multisets that are basically sets with a value -> number-of-occurrences mapping. I believe you can accomplish this in PHP via associative arrays as below:

$tags1 = "red blue green yellow colors blue red green yellow yellow";

function addTags($param) {

    // tagsArray should be a global variable
    // but put as local variable for illustration only
    $tagsArray = array();

    if($param == ""){ // no tags
        return;
    }
    $explode = explode(" ",$param);

    foreach ($explode as $value) {
       $val = 0;
       if (array_key_exists($value, $tagsArray)) {
          $val = $tagsArray[$value];
       }

       $tagsArray[$value] = 1 + $val;
    }

    // sort the array
    arsort($tagsArray);

    // for illustration purposes only
    foreach ($tagsArray as $key => $value) {
       echo $key.':'.$value.', ';
    }
}

addTags($tags1);


Here are some of my suggestions:

Declare static things at the top. i.e. var ch = ['success','default']; it is declared twice.
Duplicate code should be pulled into functions (see below).
Be consistent: el.removeClass('btn-default').addClass('btn-success'); and el.removeClass('btn-'+ch[1]).addClass('btn-'+ch[0]); Either make use of ch or get rid of it (I suggest the first).

Duplicate code:

var el = $(el);
var name = el.html();
var ch = ['success','default'];
if(!chosen[name]) ch.unshift(ch.pop());
el.removeClass('btn-'+ch[0]).addClass('btn-'+ch[1]);
chosen[name] = !chosen[name];

Something like:

var ch = ['success','default'],
    toggleElement = function (el) {
        var el = $(el),
            name = el.html();

        if(!chosen[name]) ch.unshift(ch.pop());
        el.removeClass('btn-'+ch[0]).addClass('btn-'+ch[1]);
        chosen[name] = !chosen[name];
    };

Your case 0 and case 1 statements could be made into a function as well as they're identical (other than the true/false).


Leap year functionality in Ruby and JavaScript

Unfortunately, the two pieces of code are not equivalent, so definitely not idiomatic. Javascript does not have classes like other languages, so it has a unique way of creating class equivalents.

Let's look at what your Javascript code does first, so we can understand how to fix it.

var Year = function( number ) {

Going ok so far. We could also simply declare Year as a function: function Year(number) {..., but this is acceptable.

  this.number = number;

Also good. When we say new Year(2014), we'll assign it to the number property of the instance.

  function isLeap() {
    return isDivisibleBy(400) || ( isDivisibleBy(4) && !isDivisibleBy(100));
  }

Ok, so the method body is fine, but this is not being assigned as a method on the object, so we won't be able to do something like yearInstance.isLeap(). Instead, isLeap can only be used from the context of this method.

  function isDivisibleBy(a_number) {
    return this.number % a_number == 0
  }

This is meant to be a private method. Unfortunately, Javascript does not have a traditional concept of private scope. More on this later.

  return isLeap();
}

This return statement is...tricky. In Javascript, we can return an object from a constructor, and the value returned would be that object and not an instance of the function we are instantiating. I'll admit, that's confusing. Here's an example:

function A() {
    return new B();
}

Now, if we call new A(), we actually get back a new B. But there are caveats. If the return value is not an object (so a primitive like a boolean or a number not boxed), then we will not get back the return value, we'll get the object we are trying to instantiate. So now back to your code. From the constructor, we return the result of a call to isLeap. First, isLeap is not being called on any object, so it will always return false. Because false is a primitive, the result is discarded, and we end up exactly with what we expect. Because of the trickiness of Javascript constructors and returns, even if we get what we want, we should still not have a return statement. It is inappropriate in a constructor, and can lead to unexpected bugs. For more, see this StackOverflow answer.

Now we can break this code down to be more idiomatic.

function Year(number) {
    this.number = number;
}

Year.prototype.isLeap = function() {
    return this.isDivisibleBy(400) || (this.isDivisibleBy(4) && !this.isDivisibleBy(100));
}

Year.prototype.isDivisibleBy = function(aNumber) {
    return this.number % aNumber === 0;
}

Here, we've broken out the methods from the constructor. Because Javascript is a prototypical language, we create methods by adding them to the prototype of the constructor, Year.prototype in this case. We see isLeap is now a property on the Year prototype, meaning we can now call it like yearInstance.isLeap(). isDivisibleBy is also a property on the Year prototype. This means that, here, it's a public method as well. Like I said before, Javascript does not have the same concept of private visibility.

We can't make a private method as a property on the object. There are a few ways around this. The simplest is to prepend the method name with an underscore (like Year.prototype._isDivisibleBy). This does not make the method uncallable, but is a common convention to indicate that the method is meant to be private.

An alternate way (which I am not going to show) is to use a closure to hide the function.

Inside isLeap, all of the calls to isDivisibleBy must now be prefixed with this. because it is now a method.

Inside isDivisibleBy, we now see == is replaced with ===. This is not required in any way, and can sometimes boil down to personal preference (see JSLint). Basically, it compares value and type when checking for equality. Also, a_number has been changed to aNumber. Generally, I find that Javascript following similar camelCasing conventions as Java.


Avoid making multiple calls to express server, you can return filtered data from the POST call. Use single AJAX POST call. As your calls are being made parallel there is no way to know if the make and color would be set when you make the GET request.
Use === to strict-compare values
Array.filter()
returns a filtered array so you can remove the newList. Look into Destructing

readJSONFile('cars.json', (err, json) => {
    if (err) {
        res.status(400).json({
            error: err
        })
    }
    const items = json.cars
        .filter((item) =>
            item.type.toLowerCase() === make || item.color.toLowerCase() === color
        );
    res.send(items);
});

Convert the callback functions to promise and chain for readability. Promisify


Is there better alternative to making an optional set of elements from iterable in java?

Both optional collection and a collection of optionals are anti-patterns. There is no scenario where returning Optional<Set<X>> or Set<Optional<X>> is preferable to returning a Set<X> that can be empty.

As @AJNeufeld mentions, a guard condition is a good way to start. In your case. If incoming usersIds are null then return an empty set.

public Set<TenantDTO> getAllTenantsOfUsers(Set<Long> usersIds) {
    if (usersIds == null) {
        return Collections.emptySet();
    }
    // ...
}

Its really confusing when you mix Optional.map and Stream.map in a single call chain. But since the usersIds == null case is handled, you don't need Optional.ofNullable anymore. You can simplify this to just operations over your ids and Tenants.

Something like this:

public Set<TenantDTO> getAllTenantsOfUsers(Set<Long> usersIds) {
    if (usersIds == null) {
        return Collections.emptySet();
    }
    return tenantRepository
            .findAll(QTenant.tenant.users.any().id.in(usersIds))
            .stream()
            .map((tenant) -> tenantMapper.toDto(tenant))
            .collect(Collectors.toSet());
}

Now that getAllTenantsOfUsers returns Set(possibly empty Set), all clients of this code can use it directly instead of caring about handling and unwrapping optional.


Actually in the last part, during the iteration over list named rest, its O(N^2), so, its not working.
Refer to Geeksforgeeks for O(n).


theme_movies_data and newdict are bad variable names, change them to ones easier to read. This will reduce the amount of comments you need in your code.
You can simplify your code if you stop using range and use dict.iteritems more.
You shouldn't need your try. You would know this if you use range less.
You don't need dict.fromkeys(mylist_n).keys() it's just useless.

new_dict = {}
for key, themes in movie_themes.items():
    a = []
    for theme in themes:
        if theme in movie_sub_themes:
            a.append(movie_sub_themes[theme])
    new_dict[key] = a

theme_movies = {}
for key, movie_groups in new_dict.iteritems():
    theme_movies_data[key] = [
        movie
        for movies in movie_groups
        for movie in movies
    ]

print(theme_movies)

You can remove the need for the second loop if you use a.extend.
You can change the creation of a to a comprehension.
You can change the creation of theme_movies to a dictionary comprehension.

theme_movies = {
    key: sum(
        movie_sub_themes.get(theme, [])
        for theme in themes
    )
    for key, themes in movie_themes.iteritems()
}

print(theme_movies)

Alternately if you don't like sum:

theme_movies = {
    key: [
        movie
        for theme in themes
        for movie in movie_sub_themes.get(theme, [])
    ]
    for key, themes in movie_themes.iteritems()
}

print(theme_movies)


Finding the given word from jumbled letters

Your code is hard to read, please use correct indentation and brackets.

For example your for loop:

for(var i = 0; i< word.length; i++)

confused me at the start! Code shouldn't be confusing! Use brackets ;)

I believe the code will work (hypothetically), perhaps add some comments to make it a bit more clearer.
However your solution has a complexity of \$O(n²)\$, I would suggest to improve it.

A simple possible solution is to sort both strings alphabetically and run over them linear, this way you don't need to check if they are both of equal length, there is no need for 2 nested loops and it will run in linear time (sorting not included).

Example:

word: 'potato'
jumbled: 'otpato'

sorted word: 'aooptt'
sorted jumbled: 'aooptt'

run with one for loop over it and check if both match.

Goodluck!


It looks pretty good to me, but I see a few minor things that might be improved.

Specify which perl to run

I'd recommend not leaving it to chance as to which instance of perl is run.  Instead, for both safety and consistency, it might be better to do this:

PERL=/usr/bin/perl
##...
@$(PERL) -e '$(HELP_FUN)' $(MAKEFILE_LIST)

Allow multiword category tags

With a slight change in your regex, multiword categories could be supported. If the second line is changed to this:

if/^(\w+)\s*:.*\#\#(?:@([^@]*)@)?\s(.*)$$/}; \

It will support multiword categories, delimited with @,

nothing:         ##@Odds & ends@ Do nothing, but gracefully

Sort the keys for printing

On my machine, I get a different ordering each time I run make help which is a little confusing.  To fix that, sort the keys, rendering the last line:

@{$$help{$$_}},"\n" for sort keys %help

Note that you shouldn't have a line continuation there, and you don't need the trailing semicolon (although you may prefer one for style reasons).

Omit declaration of hash

Because %help is unambiguously used, you don't need to predeclare it.  It will automatically be created as an empty hash, so the first line can become:

while(<>){push@{$$help{$$2//'options'}},[$$1,$$3] \


This looks pretty solid. I don't have any major comments. Just lots of minor ones.

Unique or Shared

Why unique_ptr as a design choice over shared_ptr? The latter would let you be able to take shallow copies to your lists without having to have references everywhere. I'm not saying that shared_ptr is strictly better, more than it's something worth considering if you have not already. Either way, both are strictly better than raw pointers, so you're already on the right track.

std::unique_ptr<List<T>>

That is a huge mouthful to type every time. And it is the only type that matters. So let's just alias it:

template <typename T>
using FList = std::unique_ptr<List<T>>;

Alternatively, rename List<> to Cons or Node so that the alias can be named List. To avoid confusion, I will use FList throughout the rest of this review.

cons()

The standard name for a list structure that is a value and a list is a "cons" cell. As in construct. Just for consistency, you should rename your add() to cons():

template<typename T>
FList<T> cons(const T& t, FList<T>&& xs)
{
    return {new List<T>{t, std::move(xs)}};
}

Now, this is less usable than it could be, simply because you can't do something like:

FList<long> x = ...;
cons(4, std::move(x)); // error

For that, let's loosen the restrictions:

template <typename T,
          typename U,
          typename = std::enable_if_t<std::is_constructible<T, U&&>::value>
          >
FList<T> cons(U&& u, FList<T>&& xs)
{
    return {new List<T>{std::forward<U>(u), std::move(xs)}};
}

You'll note that I changed your variable from l to xs. 1 is a terrible variable name as it's very easy to mistake for l. So easy to mistake that you probably didn't notice that I wrote one the first time and el the second time.

list()

Going on the theme of loosening restrictions, let's do that here too:

template<typename T>
FList<T> list()
{
    return {}; // shorter
}

template<typename T, typename U, typename...Us>
FList<T> list(U&& u, Us&&... us)
{
    return cons(std::forward<U>(u),
                list<T>(std::forward<Us>(us)...)
                );
}

That will let you write:

auto nums = list<int>(1, '4', 5ull);

Checking for empty list

In your functions, you tend to start with:

if (l == list<T>())

But std::unique_ptr is usable in a boolean context as-is. So all of those checks you can write much simpler:

template<typename T>
FList<T> copy(const FList<T>& xs)
{
    if (!xs)
    {
        return {};
    }
    else
    {
        return cons(xs->head, copy(xs->tail));
    }
}

Note that in the interest of being functional, we also probably want:

template <typename T>
T const& car(FList<T> const& xs) { // or T& if you want mutability
    return xs->head;
}

template <typename T>
FList<T> const& cdr(FList<T> const& xs) {
    return xs->tail;
}

So that this becomes:

return cons(car(xs), copy(cdr(xs)));

filter()

Could avoid some code duplication here:

template<typename T, typename Filter>
FList<T> filter(const FList<T>& xs, Filter f)
{
    if (!xs) {
        return {};
    }

    auto tail = filter(cdr(xs), f);
    return f(car(xs))
           ? cons(car(xs), std::move(tail))
           : tail;
}

sort()

This function deserves a comment solely for:

    return merge(sort(filter(l->tail, [&](const T &t){return t < l->head;})), add(l->head, sort(filter(l->tail, [&](const T &t){return t >= l->head;}))));

It's like you never want anybody to read your code. So you're basically trying to do a sort of quicksort based on partitioning the head. Let's just write that in more than one line of code (and rename it to sorted to mimic python and make it sound less like you're sorting in place):

template<typename T>
FList<T> sorted(const FList<T>& xs)
{
    if (!xs) return {};

    auto left = filter(cdr(xs), [&](const T& val){ return val < car(xs); });
    auto right = filter(cdr(xs), [&](const T& val){ return !(val < car(xs)); });

    return merge(sorted(left),
                 cons(car(xs), sorted(right)));
}

I find that a ton easier to read. The reason I wrote the second filter with ! is that it naturally lends itself to adding a custom comparator:

template <typename T, typename Comp = std::less<T>>
FList<T> sorted(const FList<T>& xs, Cmp cmp = {})
{
    if (!xs) return {};

    auto left = filter(cdr(xs), [&](const T& val){ return cmp(val, car(xs)); });
    auto right = filter(cdr(xs), [&](const T& val){ return !cmp(val, car(xs)); });

    return merge(sorted(left, cmp),
                 cons(car(xs), sorted(right, cmp)));
}


Grabbing resolution and offset from xrandr

Cleaner is very much in the eye of the beholder.
Your regex is fine - although for the digits part - I would use \d+ because you expect at least 1 digit.  And \< only works in GNU sed (not on OSX for instance).
Alternative you can look at it differently .. e.g only print the lines you care about, and on those lines drop everything you don't care about).
sed -n -e '/connected/ { s/ (.*$//; s/^.*ected //; s/^primary //; p; }'


Instead of this block:

foreach ($a as $key => $value) {
    if($value == ''){
        unset($a[$key]);
    }
}

You could simply use array_filter() without the second parameter:

$a = array_filter($a);

And also your method system/core/Security::sanitize
(I suppose that would be $this->security->sanitize in your code above):

strip_tags does simply nothing after htmlspecialchars, because all the tags like <b> got replaced with &lt;b&gt;.
If that should secure you from cross site scripting it's definitely applied at the wrong place. You should only escape the html tags before outputting them, not directly after retrieving them, because some methods (like HTML parsers) would then parse the string wrongly.


Generic extension method that will attempt to parse a string and return it's value or default(T)

For starters, I feel inclined to go meta and question the design. One possible shortcoming of your method is that it falls back to the default value, which - for primitives - isn't null. So "blah blah" would evaluate to (int) 0 or (bool) false, and unlike TryParse, your method won't tell me if this result actually came from the input, or whether it only reflects the inability to convert it. This could lead to issues with invalid data getting swept under the rug, and as such it's sort of buggy by design (especially when handling dates).
The biggest no-no though is that you're not handling exceptions. That's quite a leap of faith when invoking a method by reflection, especially as it's only loosely identified by its signature. I wouldn't blindly trust the return type, or that the method we happened to find actually does what we hope it does.

Given that the name of the method promises to fall back to default if parsing is impossible, I would say not handling an exception breaks the principle of least surprise here.
var MethodInfo = type.GetMethods().FirstOrDefault(MI =>

How do you know the method you're looking for will always come up first on the list returned by GetMethods? If you only expect one, use SingleOrDefault. But FirstOrDefault indicates you consider the possibility that more than one method matches your given criteria. So, do we have some guarantee it would always be the first one in our way, or are we just "feeling lucky"? :) This looks pretty fragile to me.
This is subjective of course, but I have to say that since this method is actually less functional than TryParse and the implementation is rather brittle, I would personally veto this extension in a peer review, since I don't believe whatever readability improvement it brings to the table justifies the trade-offs.

I think this is a textbook example of what Jon Skeet calls evil code. It's not wrong as in "doesn't work", it's sort of clever, its "magic" can even have some appeal to it, but it's fundamentally unclear and dangerous. I highly recommend this talk: https://youtu.be/lGbQiguuUGc.
If you really want such syntactic sugar, I'd ditch generics and reflection-based approach, and replace it with hardcoded extensions for bool, DateTime, int - come on, it's not like there's dozens of use-cases anyway. Oh, and have them return a Nullable to distinguish between input actually converted to the default value, and not converted at all. Like so:

public static bool? ToBoolOrNull(this string str)
{
    bool result;
    return Boolean.TryParse(str, out result) ? result : (bool?) null;
}

And analogically for these few other types.

PS. Note that in C# lower-case names should be used for parameters and variables - so it would be this string value, methodInfo, mi etc. And I believe you don't really need ReturnedValue.


You could do with learning some of the more powerful tools in Python, such as pathlib.

Tracing control flow, instead of

torrents_folder = r'C:\users\user\torrents\folder'
torrents = os.listdir(torrents_folder)

for torrent in torrents:
    if torrent.endswith(".torrent"):
        ...

you can do

torrents_folder = Path(r'C:\users\user\torrents\folder')
for torrent_path in torrents_folder.glob("*.torrent"):
    ...

Then to get the date you can do just

datetime.date.fromtimestamp(torrent_path.stat().st_ctime)

Before I leave this, though, I should warn that your

text.replace(text[a:b], "")

to remove a slice is error-prone if that slice ever appears elsewhere. Instead try something like

text = text[:a] + text[b:]

Your if after

month = [month for month in months if month in new_date][0]
if month in new_date:

looks strange - of course it will be True since you've just checked for it.

Anyway, this can now be avoided entirely since we have a date object.

You run torrent_remover(date) (although you call it month in the call signature!), but you also need the torrent_path. It turns out you're passing this as a global! That's bad!

Instead, add another parameter so you have

def torrent_remover(path, date):

Your checks can then just be

end_date = date + days_to_wait
today = dt.datetime.today()

if end_date <= today:
    ...
else:
    ...

Your

print("Removing: ", torrent, "\tTorrent expired on", end_date)
torrent_files = os.path.join(torrents_folder, torrent)
os.remove(torrent_files)

Is misnamed (you only remove one file), but now can be just

print("Removing: ", torrent_path, "\tTorrent expired on", end_date)
torrent_path.unlink()

and your other path looks wrong:

print("Nothing to remove")
exit()

since exit quits the process entirely.

days_to_wait is a global constant, so should be uppercase. However, I would put the code in a main function and just pass it to the remover.

I would let torrent_remover get the date itself, simplifying the main loop.

Finally, your printing adds spaces between every part. One way to fix that is

print(a, b, c, sep="")

but it seems better to use formatting here:

print("{}{}{}".format(a, b, c))

This all gives

from datetime import date, timedelta
from pathlib import Path

def torrent_remover(path, shelf_life):
    created_on = date.fromtimestamp(torrent_path.stat().st_ctime)
    expired_on = created_on + shelf_life

    if expired_on <= date.today():
        print("Removing: {}\tTorrent expired on {}".format(torrent_path, expired_on))
        torrent_path.unlink()

def main():
    shelf_life = timedelta(days=14)
    torrents_folder = Path(r"C:\users\user\torrents\folder")

    for torrent_path in torrents_folder.glob("*.torrent"):
        torrent_remover(torrent_path, shelf_life)

if __name__ == '__main__':
    main()

which I hope you'll agree is simpler. To add a check for if any file has been removed, try something like

from datetime import date, timedelta
from pathlib import Path

def torrent_remover(path, shelf_life):
    created_on = date.fromtimestamp(torrent_path.stat().st_ctime)
    expired_on = created_on + shelf_life

    if expired_on <= date.today():
        print("Removing: {}\tTorrent expired on {}".format(torrent_path, expired_on))
        torrent_path.unlink()
        return True

    return False

def main():
    shelf_life = timedelta(days=14)
    torrent_paths = Path(r"C:\users\user\torrents\folder").glob("*.torrent")
    removed = sum(torrent_remover(path, shelf_life) for path in torrent_paths)

    if not removed:
        print("Nothing to remove")

if __name__ == '__main__':
    main()

This is untested.


Slight improvement in the sieve.
I doubt it is significant for max.

prime_table(integer num) {
    integer max = ceil(sqrt(num));
    std::vector<char> table(max, false);   // Making this char rather than bool
                                           // probably makes a tiny difference in speed.
                                           // Don't do an extra re-size do it all up
                                           // front in one allocation.

    // Initialize with the first 2 primes.
    // We don't need to mark multiples of 2 and 3 in the table as true.
    // because of the way we increment in the loop. We basically skip
    // all cells in table {for table[x] where (x%2 ==  0 || x%3 == 0)}
    // so we don't even consider multiples of 2 and 3.
    primes.push_back(2);
    primes.push_back(3);
    int inc = 4;

    // Increment by 2 then 4 (repeat)  (represented by `inc`)
    // This effectively ignores all multiples of 2 and 3.
    for (int i = 5; i < max; i += inc) {
        inc = 6 - inc;
        if (!table[i]) {
            primes.push_back(i);
            for (integer temp = 2 * i; temp < max; temp += i)
                table[temp] = true;
        }
    }
}

You needed the smallest prime here:

integer prime_factor(integer input) {
    for (int i = 0; primes[i] * primes[i] <= input; i++)
        if (input % primes[i] == 0)
            return prime_factor(input / primes[i]);
    return input;
}

This may result in a lot of wasted work (if primes[0] works you did not need the other primes). To only do as much work as you need you may want to try and implement a lazy sieve. That way you only calculate as many primes as you actually need. That being said the sieve is already fast so the extra code and complexity may outweigh the advantages of being lazy.

But to facilitate your tests (to see if a lazy sieve is worthwhile) you could update the code to use std::begin() and std::end() on the primes container. That way it can use your current technique. But if you change the container for primes into something that calculates primes on the fly you don't need to modify your code.

integer prime_factor(integer input)
{
    for (auto prime: primes)   // use std::begin() and std::end in the background (I think)
    {
        if ((prime * prime) > input) {
            break;
        }
        if (input % prime == 0) {
            return prime_factor(input / prime);
        }
    }
    return input;
}

Here is an attempt at a Lazy prime Sieve. Maybe that will help.

class LazyPrime
{
    std::vector<integer>    primes;
    integer                 max;
    std::vector<char>       table;
    integer                 inc;
    integer                 lastPrimeFound;

    struct LazyPrimeIterator
    {
        LazyPrime&   parent;
        std::size_t  current;
        LazyPrimeIterator(LazyPrime& p, int v) : parent(p), current(v) {}
        LazyPrimeIterator& operator++()     {current = parent.next(++current);return *this;}
        integer            operator*()      {return parent.primes[current];}
        bool               operator!=(LazyPrimeIterator const& rhs) const
        {return current != rhs.current;}
    };

    public:
        typedef LazyPrimeIterator           iterator;
        LazyPrime(integer num)
            : max(ceil(sqrt(num)))
            , table(max, false)
            , inc(2)
            , lastPrimeFound(5)
        {
            primes.push_back(2);
            primes.push_back(3);
            primes.push_back(5);
        }

        std::size_t next(std::size_t current)
        {
            if (current < primes.size())
            {    return current;
            }

            // Assume primes retrieved in order.
            assert(current == primes.size());

            for (integer temp = 2 * lastPrimeFound; temp < max; temp += lastPrimeFound){
                table[temp] = true;
            }

            // Increment by 2 then 4 (repeat)  (represented by `inc`)
            // This effectively ignores all multiples of 2 and 3.
            for (integer temp = lastPrimeFound + inc; temp < max; temp += inc) {
                inc = 6 - inc;
                if (!table[temp]) {
                    lastPrimeFound = temp;
                    primes.push_back(lastPrimeFound);
                    return current;
                }
            }
            lastPrimeFound = max - inc;
            return -1; // Same as end.
        }

        iterator begin() { return LazyPrimeIterator(*this, 0);}
        iterator end()   { return LazyPrimeIterator(*this, -1);}
};


A short review;

You probably want to cache this.content.length
That check for the end of array is clunky
separator will change from 0 to "", an unlikely edge case, but it could happen
Why are array elements in this.content ? I would have gone for this[i] instead
string is not very evocative, I went with out

Obligatory rewrite;

Array.prototype.myJoin = function stringMyJoin(separator) {
    separator = separator || "";
    let out = this[0];
    const length = this.length;
    for (let i = 1; i < length; i++) {
        out += separator + this[i];
    }
    return out || "";
}

console.log([].myJoin(","), [].myJoin(",") === "");
console.log(["apple"].myJoin(","));
console.log(["apple","bear","bananers"].myJoin(","));


Counting occurrences of a character in a string

So, performance. Let's list off things that are commonly done wrong that you do in your code:

print statements in a loop
line-by-line parsing of input
mid-list removals of values (removeAll())
not enough functions

The performance can be significantly improved by doing batch operations on the input, processing, and output.

Additionally, the last point is important. Java compiles code essentially on a method-by-method basis. By keeping all your code in the main method you are reducing the possibility for Java to compile and optimize it.

Read the whole file in, split the lines out in one operation, write all the results out as one string.

That will likely remove more than half your execution time... but your actual algorithm is slow as well.

Since you use regular expressions to split the characters, you may as well use one to just clean up the whole URL... and strip all vowels that way.

Here's a scratch-up of what I would consider given this task. It shows the ideas I was mentioning, and also uses some Java 8 features:

public static void main(String[] args) throws IOException {
    for (String infile : args) {
        System.out.println(processSource(Paths.get(infile)));
    }
}

private static String processSource(Path path) throws IOException {
    List<String> alldata = Files.readAllLines(path);
    Iterator<String> it = alldata.iterator();
    final int size = Integer.parseInt(it.next());

    String[] results = new String[size];
    for (int cnt = 0; it.hasNext() && cnt < size; cnt++) {
        results[cnt] = computeRatio(it.next());
    }

    return String.join("\n", results);

}

private static final Pattern DISCARD = Pattern.compile("(^www\\.)|[aeiou]");

private static final String computeRatio(String url) {
    int limit = url.lastIndexOf('.');
    String clean = DISCARD.matcher(url.substring(0, limit)).replaceAll("");
    // include the URL for debug:
    // return String.format("%d/%d -> %s", clean.length() + url.length() - limit, url.length(), url);

    // simple result
    return String.format("%d/%d", clean.length() + url.length() - limit, url.length());
}


I would suggest to add comments (Javadoc-style, but probably best if much lighter) to describe the intent of each method. Even the most simple ones. I found it especially useful in JavaScript to describe:

the type and range of arguments expected
which arguments are optional and what are the default values
the type of the result value, if any
what is the result when provided arguments do not match expectations

Otherwise I agree with your inline comment "this needs some refactoring, it creates bound and unbound", corresponding code should be extracted into a separate function, which will also reduce nesting, which seems to be one of your worries.

Regarding the code itself, I would rename wrap() to bind() to match the bind() function added in ECMAScript 5 and I would rename l to length in the for loop as letter l is easily confused with number 1.

I have doubts about this portion of the code:

if (is('Function', ext)) {
    return ext.extend(proto); // holy closure!
}

In my understanding: you check first that ext is a funciton before calling the extend() method, but:

extend() is not defined in JavaScript, it is one of your custom methods, so there is no guarantee that you will find this property on the function. You should probably add a check.
I do not understand the intent: an inline comment would help :)

All in all, I think it's fine that the code is a bit hairy because adding support for classes in JavaScript is no simple matter, but a lot more inline comments (up to one comment per line of code for the most complex stuff) would improve the code readability immensely.


My implementation of bubble sort using Python

Your bubble sort algorithm has way too many variables. You don't need to keep track of the right and left item. All you need to do is compare two values, and swap if one is bigger than the other.
def bubble_sort(nums):
    length = len(nums)
    for i in range(length - 1):
        for j in range(0, length - i - 1):
            if nums[j] > nums[j + 1]:
                nums[j], nums[j + 1] = nums[j + 1], nums[j]

After benchmarking, this code is substantially faster than your original code.
Benchmarks:
Array size bubble_sort_op       3000    1.87206s
Array size bubble_sort          3000    0.67218s
Array size bubble_sort_op       3200    2.24581s
Array size bubble_sort          3200    0.78276s
Array size bubble_sort_op       3400    2.41464s
Array size bubble_sort          3400    0.87018s
Array size bubble_sort_op       3600    2.69006s
Array size bubble_sort          3600    0.96319s
Array size bubble_sort_op       3800    2.99190s
Array size bubble_sort          3800    1.09713s
Array size bubble_sort_op       4000    3.48652s
Array size bubble_sort          4000    1.24830s


Efficiently filter a large (100gb+) csv file (v1)

Write code that does the conversion with a small portion of your data defined in the python module. That makes you focus on the data structures and if they fit to the problem. If you remove the code for file handling, logging - all that is not specific to your conversion problem - only a couple lines of code remain. That is what needs your attention and ours attention.

If that simple conversion work, add code that reads the data from external sources to populate the functions for your conversion code. Instead of splitting strings prefer code that is made for this common format: use built-in csv module. Separate file handling code from any algorithms.

Next create code that writes your intermediate output to external sources - again use csv module.

Separate any part/idea into their own place and give them names that makes readers understand their purpose. This is actually the main problem for any reader of your code.

What will make your code faster?

use generators to keep memory usage low and list comprehension for beauty and awesome filtering

What will make you solve it right?

If you split the problem into many parts, you can test any part itself. What makes you think your conversion is done properly at a scale of 2GB input files and large output files? Did you verified every line in output?
Apply testing with smaller data, gives you confidence for larger data.

What will make you giant leaps?

Go get IPython notebook. Write smaller parts and test execution time.

If you have understood your problem, use python libraries made for your problem and write the necessary glue code.

csvkit, pandas

Learn from similar questions/answers on CodeReview

Find the peak stock price for each company from CSV data


Note: this is intended to be a Community wiki since it was taken from a deleted answer by yannis; The suggestion to do this was here

mysql_* functions
Stop using them, immediately! They are essentially deprecated, as they refer to MySQL before version 4.1. They are not removed as to not brake backward compatibility, but there's no point in using them.
The drop in replacement is myslqi_* functions, which are based around a newer MySQL driver that works better with MySQL 5.x. You can easily replace most references to myslq_* functions by just adding the extra i.
But a far better solution is PDO, an object oriented database agnostic interface. Since you are starting out in object oriented PHP you'll definitely appreciate the object orient part, and as for the database agnostic part, it means that you can easily switch databases (with minor modifications).
Verbatim copy from another one of my reviews.
Long if, small else
Instead of:
if( condition ) {
    // blah
    // blah
    // blah
    // blah
    // blah
    // blah
    // blah
    // blah
    // blah
} else {
    // blah
}

consider refactoring as:
if( !condition ) {
    // blah
    exit();
}

// blah
// blah
// blah

It's a bit more readable.
Player, you've been played
You get $player from a post variable:
$player = $_POST['Player'];

and then you go and feed it to the database:
$query1 = "INSERT INTO `".$dbname."`.`".$dbtable."` (`player`, `item`) VALUES ('".$player."', '".$input."')";

and, sooner or later, you're dead. Read everything you can about SQL injection on Wikipedia and the manual. Tips:

User input is unsafe, and it includes everything that comes from the environment ($_POST, $_GET, $_SESSION, $_COOKIE, $_SERVER, etc).
Always validate and sanitize user input. Not only when you feed it to a database, always.

For this instance, your best bet would be to go with PDO and prepared statements, that's how the cool kids do it anyway. Additionally, use the Filter extension.
Error suppression operator
$ip=@$REMOTE_ADDR;

First of all, where does $REMOTE_ADDR come from and why do you suppress errors? What exactly are you doing there and what can go wrong.
In any case, forget all about the error suppression operator, it's evil and it must die.


Changing text with a click event: how to restore default state of text in jQuery if/else statement

as a first step I would rewrite the last if statement

else if ((clicked =! "Text1") && (clicked != "Text2") && (clicked != "Text3") )
    {
        $("#ActText, #AdaptText, #PlanText").css("opacity", "1");  // return to default state
    }

After that you could rewrite it as a switch statement: http://www.w3schools.com/js/js_switch.asp

edit : this would be better...

var textArray = new Array("Text1","Text2","Text3");
if($.inArray(clicked,textArray){
    $("#Text2, #Text3").css("opacity", "1");
}
else {
 $("#" + clicked).css("opacity", "0.2");
}


#include <condition_variable>
std::condition_variable cv;

#include <iostream>
#include <random>

#include <mutex>
std::mutex mtx;

#include <thread>

Don't mix includes and code, makes it easy to miss those globals you're defining in the middle. Keep the headers by themselves sorted in some order or grouped logically/by function as you prefer.

throw std::runtime_error(...);

You're missing <stdexcept>, your code could fail to compile.

int count = 0, buff_size = 0;
char* buff;

What are these? Why are they global? Why initialize two explicitly and not the third?

int random_int(int lower_bound) {
    std::random_device seed;
    std::mt19937 generator(seed());
    std::uniform_int_distribution<int> dist(lower_bound, std::nextafter(26, DBL_MAX));

    return dist(generator);
}

This isn't good. You're seeding a generator each time you generate a new random number - that's not how you're supposed to do it. You're supposed to seed a generator once, then use it repeatedly.

std::nextafter(26, DBL_MAX)

You're missing <cfloat> for DBL_MAX, and I really don't understand what this is for, or why 26 appears magically here with no warning (no indication in the function name, no comment). nextafter/before are really meant for floating point numbers (or template code where you don't know if you'll get ints or floats). If it's a plain int constant, just code it in. Actually, don't put that magic constant at all and allow the user to pass the lower and upper bound.

char random_char(int lower_bound) {
    return 'A' + (random_int(lower_bound) % 26);
}

(This only works for encodings where the letters are consecutive. This isn't guaranteed, but chances that your code will run on something with e.g. EBCDIC are small.)

Why %26 if your RNG already gives you values in the right range? The % trick is likely to ruin your distribution's statistical properties. So again, just pass the min and max to your random generating function (e.g. return myrand('A','Z');).

Here's one way to fix this:

// bounds are inclusive
char rand_char(char lower_bound, char upper_bound)
{
  thread_local std::random_device rd;
  thread_local std::mt19937 gen(rd());
  thread_local std::uniform_int_distribution<int> dist(lower_bound,
                                                        upper_bound);
  return static_cast<char>(dist(gen));
}

Then you can call:

rand_char('A', 'Z');

thread_local gives each thread its own generator and distribution, initialized only once per thread on first call of the function.

/* Producer

Randomly generates letters at (pos > buff_size & pos <= 26),
inserts them at the next available position in the buffer,
and then prints out the lowercase form of the inputted letter.

*/

This comment does not match the code, the code doesn't contain a pos at all. There's a job parameter, but it is not used. There does not appear to be any "next available" concept in the code. There is no "inputted letter" either. And if pos > buff_size, generating something at buff[pos] would be an overflow. So fix that comment (and fix the code to match it) or remove it. Bad comments are worse than no comment at all.

int buff_size = 0;
// ...
int main() {
  int buf_size = 0;

That's just evil! Are you running in an underhanded C++ contest? :-) Really that's a terrible choice of variable names.

std::cout << "The Producer-Consumer Problem (in C++11!)" << std::endl << "Enter the buffer size: ";
std::cin >> buf_size;
if (buf_size > 0 && buf_size <= 26) {
  // ...
} else {
  // rage quit
  panic("The range must be > 0 and <= 26.");
}

Bad user experience: inform about the limits before asking for the input.

buff = new char[buff_size];

Where's the delete[]? If your comment above produce was what you intended, you'd need to initialize too, otherwise your producers could read uninitialized data (which leads to undefined behavior). Use a std::vector instead to avoid the leaks and initialize all values to a sane default (e.g. a space).

As for the whole producer/consumer thing: your code is completely serial. There can only be one active thread, whether it is a producer or a consumer. Multiple produce threads could run one after the other without a consumer running in between, so you're "losing products" and it is likely that you'll see the same "product" output multiple times.

You should change your code so that the producers produce something predictable (e.g. "produce" and print out their job number) so that you can actually visually verify whether things are working. Then test your code with starting all the consumers first (and waiting a tiny bit), then the consumers. Then do the opposite. Run it several times, always checking that the output is correct. Increase the concurrency. Use sanitizers if you can (-fsanitize option for recent-enough GCC and clang for instance).


Some comments:

Converting to a binary string and then operating on the string is much slower and more laborious than operating on the bytes directly.
There is no need to collect all counts and then take the largest as we can just calculate the largest as we go.
Give your class and method appropriate names.
Check the precondition that the input is positive in the beginning of the method.

Here is a streamlined but untested solution:

class BinaryGapCalculator {
    static int binaryGap(final int n) {
        if (n <= 0)
            throw new IllegalArgumentException("n must be positive; was " + n);
        final int start = Integer.lowestOneBit(n), end = Integer.highestOneBit(n);
        int curRun = 0, longestRun = 0;
        for (int bitmask = start; bitmask != end; bitmask <<= 1) {
            final int bit = n & bitmask;
            if (bit == 0)
                ++curRun;
            else {
                longestRun = Math.max(longestRun, curRun);
                curRun = 0;
            }
        }
        return Math.max(longestRun, curRun);
    }
}

Regarding big-O, all solutions are technically O(1) because there are finitely many inputs. But if we were to pretend that an int could store arbitrarily many bits, the optimal solution would be θ(b) where b ~ log(n) is the number of bits of n. This is because the algorithm I wrote is θ(b) and the optimum must be at least as efficient as my algorithm; also there is no tighter bound than θ(b) because asymptotically, at least half of the input has to be seen. So my algorithm is optimal (up to a constant).


Division without using addition, multiplication or division

First of all, please keep your indentation consistent; it's all over the place here.  Java code is supposed to be indented by four spaces.  Also, try not to put whitespace in random places.  Keep things consistent.

Also, here are some additional cleanliness tips:

Don't declare or initialize multiple variables on a single line:

boolean isNeg=false,sign=true,bothNegative=false;

Have each variable on separate lines, which helps with maintenance and readability:

boolean isNeg = false;
boolean sign = true;
boolean bothNegative = false;

If you ever need additional boolean variables, having more lines would be better than having a longer single line across the screen.
Your bitwise operations can be simplified a bit:

a=a^b;
b=(a^b)&b;
b=b<<1;

If you're doing a bitwise (or a mathematical) operation where the same variable is on both sides of the = sign, you can simply them as such:

a ^= b;
b &= (a^b);
b <<= 1;


You don't need to "cache" the drawables yourself. Android does that internally, as can be seen in the source code.

    Drawable dr = getCachedDrawable(isColorDrawable ? mColorDrawableCache : mDrawableCache, key);

    if (dr != null) {
        return dr;
    }

Therefore, you're actually not saving any memory at all. (Technically you're wasting memory by creating a map for it, but that's so little memory it barely counts)

Instead of creating a LayerDrawable you might want to use setBackgroundResource() and setImageResource() (assuming you're using ImageViews)

As for the name CellDrawableProvider, I don't see what would be wrong with it. It's purpose is clear: A provider for cell drawables.


This should be interesting. The fastest way I can think of is to pluck all the courses_needed arrays out of Student, group them together, and count them:

course_hash = Student.where.not(courses_needed: nil).pluck(:courses_needed).
  flatten.group_by { |c| c }.map { |k, v| [k, v.size] }.to_h

Essentially, I grab all students that actually have courses_needed, I then grab just all the courses needed from students. Flatten the course arrays so that all courses are within the same array, then I group them by course. After that I map again to replace the values (just the list of all same courses) with the number of times each course is listed. Then I do to_h to turn each [course, number] into a course => number hash that you can access easier.

So pluck returns:

[[course, course2, course3], [course, course2]]

Flatten makes this:

[course, course2, course3, course, course2]

Group_by turns it into:

{course => [course, course], course2 => [course2, course2], course3 => [course3]}

Map does:

[[course, 2], [course2, 2] , [course3, 1]]

Then to_h:

{course => 2, course2 => 2, course3 => 1}

At that point you can access the course hash and get the number.

course_hash[course]
# 2

Now that we have the hash we can update the needed column in Course:

Course.find_each do |course|
  course.update_attributes(needed: course_hash[course].to_i)
end

The to_i is used so that if course_hash does not contain the course it returns nil, then to_i will turn nil into 0.


Optimal change with only with two euros coins and five and ten euros bills

The only way of making an odd total is with a five euro bill.  There is no point ever having more than 1 five euro bill, as you could replace pairs with a ten euro bill.  So, you should start off checking for the odd total.

if (change >= 5  &&  change % 2 == 1) {
    c.bill5 = 1;
    change -= 5;
}

At this point, you can simply compute the number of ten euro bills, and remaining 2 euro coins.

c.bill10 = change / 10;
change = change % 10;

c.coin2 = change / 2;

The only thing you have to watch out for is a total change amount of 1 or 3 euros (or negative), which is not possible to make.  Handle those as a special case.

Your optimalChange() creates a change object, and if dealWithChangeLike31Euros() methods is called, it creates its own Change object, and the first object is abandoned.  You shouldn't create the object if it isn't going to be used.  Options include passing the change object to the dealWithChangeLike31Euros() method, or delaying the creation.

Multiple return points is sometimes a code smell.  optimalChange() has 3:

return dealWithChangeLike31Euros(change);
return null;
return c;

If you initialized Change c = null;, and only created the Change object when needed, you could have just the one return c; at the end.  Less returns may reduce the complexity.


Some remarks :

your combine function is in fact List.zip, you might want to explore the Array and List sections of the standard library, they are full of very useful functions that will speed-up your development.
createRandomBoard is not a function and thus will always be the same array (arrays being mutable, you might come across some unwanted side effects if you use it twice in the same code). It could be rewritten using Array.init :

let createRandomBoard () =
   let rnd = new Random(10)
   Array.init size (fun _ -> if rnd.NextDouble() < 0.2 then 1 else 0)

you are using '0' and '1' to model your two states, why not booleans ? It would eliminate the need for some tests.
Array.set ar ind x can be rewritten as ar.[ind] <- x (but, as Foggy Finder said, you would lose some type inference if ar has not been identified as an array before)
forms such as :

[1..n] |> List.iter f

are indeed functional but inefficient and, I believe, not as readable as using a loop. F# is especially powerful because it is a hybrid language (and not a purely functional one) : don't hesitate to leverage arrays and loops when it makes sense.


When in doubt, profile. We may theorize about possible optimizations, but only the profiler can definitely say where the program does spend time.
That said,

the first/second spot logic looks suboptimal. Consider

if ((firstSpot & mask) != 0) {
    secondSpot |= mask;
} else {
    firstSpot |= mask;
}

(using else may also be redundant).

It is unclear (to me) how for (char c : chars) over the char array fares against other techniques. This could be an entertaining reading.

Yet again, profile.
Strictly speaking, the challenge only says the string contain only lowercase letters, but does not specify the locale.


Determining what functions should be implemented in this user-authentication class

The Single Responsibility Principle is a good thing to aim for, for many classes. It doesn't always mean that each class only does one thing (though it can), but that it is responsible for a small amount of tightly-related functionality.

That said, the job of some classes is to collect together a number of responsibilities. User may well be one of these, but the individual responsibilities can still be delegated to other classes - e.g. you could always give User an instance of a Credentials class that deals with the password checking.

You almost certainly don't want your database-related functions in User as if you write any tests for User, many of them are likely to have a need to hit the database when they run.


I would start by making your ip_list easier to understand. You could write a class for this, but using a collectins.namedtuple is a lot easier here:

from collections import namedtuple

Client = namedtuple("Client", "ip username passwd root_passwd")

clients = [Client("192.168.11.44", "root", "****", "****"),
           Client("192.168.11.8", "root", "****", "****"),
           Client("192.168.11.30", "root", "****", "****"),
           Client("192.168.11.6", "****", "****", "****")]

For the hard_disks, you could use the string module for all lowercase letters:

import string

HARD_DISKS = ['sd{}'.format(c) for c in string.ascii_lowercase[:19]]

For your repeated stuff, you could write a function:

def ssh_cmd(cmd, *args, root_passwd=None, **kwargs):
    stdin, stdout, stderr = ssh.exec_command(cmd, *args, **kwargs)
    if root_passwd is not None:
        stdin.write(root_passwd + "\n")
    return stdout.readlines()

This makes the rest slightly nicer to read. However, I would go further and put the other stuff in dedicated functions as well, which can then be put into a utils.py:

import string
from collections import namedtuple

Client = namedtuple("Client", "ip username passwd root_passwd")

HARD_DISKS = ['sd{}'.format(c) for c in string.ascii_lowercase[:19]]

def get_os(client):
    for line in ssh_cmd("cat /etc/*release", root_passwd=client.root_passwd):
       if any(x in line for x in os_check_list):
           # check for the obvious stuff first
           return line.split("=")[1]
    for os in ssh_cmd("cat /etc/system-release"):
       return os

def print_hard_disks(client, hard_disks=HARD_DISKS):
    for line in ssh_cmd("sudo -k udisksctl status", get_pty=True, root_passwd=client.root_passwd):
        if any(hd in line for hd in hard_disks):
            print(line)
        elif "command not found" in line:
            print("udisksctl not installed on target server")

def print_dmi_version(client):
    for line in ssh_cmd("sudo dmidecode -t 0 | grep -i version", get_pty=True, root_passwd=client.root_passwd):
        if "Version" in line:
            print(line)
        elif "command not found" in line:
            print("dmidecode not installed on target server")

It can then be imported in your main script:

import paramiko

from utils import Client, get_os, print_hard_disks, print_dmi_version

BANNER = """

******************************************************************

   IP ADDR = {}                SYSTEM INFO

******************************************************************"""

CLIENTS = [Client("192.168.11.44", "root", "****", "****"),
           Client("192.168.11.8", "root", "****", "****"),
           Client("192.168.11.30", "root", "****", "****"),
           Client("192.168.11.6", "****", "****", "****")]

def main(clients):
    ssh = paramiko.SSHClient()
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())

    for client in clients:
        ssh.connect(client.ip, username=client.username, password=client.passwd)

        print(BANNER.format(client.ip))
        print(" Operating System is {}" .format(get_os(client)))
        print_hard_disks(client)
        print_dmi_version(client)

if __name__ == "__main__":
    main(CLIENTS)


Java background server class that might be called from ui thread

Disclaimer: This answer uses the lambda-feature for java 8. Assuming non-availability of java 8, the expressions can be easily converted to Runnables.

You're completely overexerting yourself. Use inbuilt features of Java with a little composition and your server becomes by far easier:

public class Server {
     private final ExecutorService threadPool = Executors.newFixedThreadPool(1);

     public Server() {}

     public void start() {
         threadPool.execute(() -> handleStart()); //Runnable
     }

     public void stop() {
         threadPool.execute(() -> handleStop());
         threadPool.shutdown(); //depends a little on your functionality
     }
     //rest can remain unchanged
}

The Thread-Pool can be expanded manually. Additionally I'd recommend to override finalize() to shut down your executor.


Console-like printing of message JavaScript

Your code is really easy to understand, and there's not much wrong with it.

I promise I'll go easy on you.

Right on the first lines, something bothers me...

You have this:

var text = document.getElementById('text');
var greeting = ['Hello. I am a console wannabe.',
                'All systems are functioning.',
                'I like pie.'];
text.innerHTML = '▮';

What's wrong? The names!

text implies some actual text, but you have a
. greeting is alright, but it is actually text. And that  is a prompt.

I propose the following rewrite:

var screen = document.getElementById('screen');
var text = ['Hello. I am a console wannabe.',
                'All systems are functioning.',
                'I like pie.'];
screen.innerHTML = '&marker;';

It all makes sense, except for the class, which I will explain later on.
And please, use the HTML entities, to avoid problems with file encodings.
Also, don't use  for this, since it will have problems when the animation is stopped.
The best would be to move the prompt to the HTML and ignore that line.

Lets analyse the function greet().

You have the following code:

(function greet() {
    if (greeting.length > 0 && greeting.length < 3) {
        text.insertBefore(document.createElement('br'), text.lastChild);
    }
    var line = greeting.shift();
    if (!line) {
        return;
    }
    line = line.split('');
    (function type() {
        var character = line.shift();
        if (!character) {
            return setTimeout(greet, 2000);
        }

        text.insertBefore(document.createTextNode(character), text.lastChild);
        setTimeout(type, 300);
    }());
}());

Huh? The greet() function is preparing to type the text? And only works for this example? Well, let me re-write this for you.

function type(text, screen) {
    //You have to check for lines and if the screen is an element
    if(!text || !text.length || !(screen instanceof Element)) {
        return;
    }

    //if it is not a string, you will want to make it into one
    if('string' !== typeof text) {
        text = text.join('\n');
    }

    //normalize newlines, and split it to have a nice array
    text = text.replace(/\r\n?/g,'\n').split('');

    //the prompt is always the last child
    var prompt = screen.lastChild;
    prompt.className = 'typing';

    var typer = function(){
        var character = text.shift();
        screen.insertBefore(
            //newlines must be written as a `<br>`
            character === '\n'
                ? document.createElement('br')
                : document.createTextNode(character),
            prompt
        );

        //only run this again if there are letters
        if( text.length ) {
            setTimeout(typer, 300);
        } else {
            prompt.className = 'idle';
        }
    };
    setTimeout(typer, 300);
};

Wow, some fine German Overengeneering going on there!

You can pass it a string or an array of strings, and a 'screen', where the message will be added.

Now, enough of Javascript, lets talk about CSS!

It is a pretty straightforward CSS, without many complications.
But, remember that it suffered a rewrite.

Replace your i CSS with this:

#prompt{
    font-style: unset;
    font-size: 1em;
}
#prompt.idle {
    animation: blink 1100ms linear infinite;
    -webkit-animation: blink 1100ms linear infinite;
}

On your HTML, simply change the id.

Remember, we re-wrote it:

&marker;

Final result:

And now, all together:

function type(text, screen) {
 //You have to check for lines and if the screen is an element
 if(!text || !text.length || !(screen instanceof Element)) {
  return;
 }

 //if it is not a string, you will want to make it into one
 if('string' !== typeof text) {
  text = text.join('\n');
 }

 //normalize newlines, and split it to have a nice array
 text = text.replace(/\r\n?/g,'\n').split('');

 //the prompt is always the last child
 var prompt = screen.lastChild;
 prompt.className = 'typing';

 var typer = function(){
  var character = text.shift();
  screen.insertBefore(
   //newlines must be written as a `<br>`
   character === '\n'
    ? document.createElement('br')
    : document.createTextNode(character),
   prompt
  );

  //only run this again if there are letters
  if( text.length ) {
   setTimeout(typer, 300);
  } else {
   prompt.className = 'idle';
  }
 };
 setTimeout(typer, 300);
};

window.onload=function(){
 var screen = document.getElementById('screen');
 var text = [
  'Hello. I am a better console wannabe.',
  'All systems are functioning.',
  'I like pie.'
 ];

 type(text, screen);
};
body {
 background-color: #000000;
 color: #99ffcc;
 font-family: Courier;
}
#prompt {
 font-style: unset;
 font-size: 1em;
}
#prompt.idle {
 animation: blink 1100ms linear infinite;
 -webkit-animation: blink 1100ms linear infinite;
}

@keyframes blink {
 49% {opacity: 1;}
 50% {opacity: 0;}
 89% {opacity: 0;}
 90% {opacity: 1;}
}
@-webkit-keyframes blink {
 49% {opacity: 1;}
 50% {opacity: 0;}
 89% {opacity: 0;}
 90% {opacity: 1;}
}

&marker;

To ressemble a little more a console, the animation is only applyed when there's no typing.

With minor changes, it is possible to make it work with keypresses on the keyboard. And with a write queue. But that's left as an exercise for the O.P.

Also, one cool thing you can try is to use a random timeout, to create a varying effect on the writting, to simulate real typing! You can even add an extra interval to special characters, to be more human-like:

function type(text, screen) {
 //You have to check for lines and if the screen is an element
 if(!text || !text.length || !(screen instanceof Element)) {
  return;
 }

 //if it is not a string, you will want to make it into one
 if('string' !== typeof text) {
  text = text.join('\n');
 }

 //normalize newlines, and split it to have a nice array
 text = text.replace(/\r\n?/g,'\n').split('');

 //the prompt is always the last child
 var prompt = screen.lastChild;
 prompt.className = 'typing';

 var typer = function(){
  var character = text.shift();
  screen.insertBefore(
   //newlines must be written as a `<br>`
   character === '\n'
    ? document.createElement('br')
    : document.createTextNode(character),
   prompt
  );

  //only run this again if there are letters
  if( text.length ) {
   var delay, next = text[0];
   //based on a querty pt-PT keyboard, there delays are subjective
   if(next.match(/[a-z\d\t\-\.,º]/)){
    //fastest characters
    delay = 50;
   } else if(next == ' ' || next == '\n' || next.match(/[\\\|\!\"\#\$\%\&\/\(\)\=\?\'»\*ª_:;>A-Z]/)) {
    //medium-slow keys
    delay = 100;
   } else if(next.match(/[\@\€\£\§\{\[\]\}\~\´]/)) {
    //slow keys
    delay = 150;
   } else {
    //Yes, that slow!
    delay = 250;
   }
   //repeated characters are types faster
   if(next == character) {
    delay -= 25; //reduces the delay by 50
   }

   setTimeout(typer, delay + (Math.random() * 50));
  } else {
   prompt.className = 'idle';
  }
 };
 setTimeout(typer, 50 + (Math.random() * 50));
};

window.onload=function(){
 var screen = document.getElementById('screen');
 var text = [
  'Hello. I am a better console wannabe.',
  'All systems are functioning.',
  'I like pie.',
  'É só pra teste (just for testing).',
  'ASCII PARTY!"#$%&/()=?!!!!!'
 ];

 type(text, screen);
};
body {
 background-color: #000000;
 color: #99ffcc;
 font-family: Courier;
}
#prompt {
 font-style: unset;
 font-size: 1em;
}
#prompt.idle {
 animation: blink 1100ms linear infinite;
 -webkit-animation: blink 1100ms linear infinite;
}

@keyframes blink {
 49% {opacity: 1;}
 50% {opacity: 0;}
 89% {opacity: 0;}
 90% {opacity: 1;}
}
@-webkit-keyframes blink {
 49% {opacity: 1;}
 50% {opacity: 0;}
 89% {opacity: 0;}
 90% {opacity: 1;}
}

&marker;


Future "callbacks" can be simplified by using the for comprehension to compose futures. More information can be found here http://docs.scala-lang.org/overviews/core/futures.html#functional_composition_and_forcomprehensions

I'm not a Scala expert, but this is how i would replace the flatMap and map with a for

object Application extends Controller with securesocial.core.SecureSocial {

  val inboxSlurper = Akka.system.actorOf(Props[InboxSlurper], name = "inboxSlurper")

  def index = SecuredAction.async { implicit request =>
    implicit val timeout = Timeout(10 seconds)
    val user = request.user.asInstanceOf[User]

    for {
      emailFeed <- (inboxSlurper ? OauthIdentity(user.email.get, user.oAuth2Info.get.accessToken))).mapTo[Enumerator[Message]]
      str <- emailFeed |>>> Iteratee.fold[Message, String]("")((result, msg) => result + msg.getSubject())
    } yield Ok(views.html.index("Subject: %s".format(str)))
  }

}

The example demonstrates the sequential composition of futures, str will be calculated when emailFeed has retrieved the data for the inboxSlurper actor. After all futures have been completed then a result can be returned with yield.

Because everything is a expression in Scala for {} yield Ok() will be returned as result for the Action, which is a Future[SimpleResult].