texts:
Goal: create a new OrderedDict instance's keys in such way that keys in the specified order list appear first. If some keys in order list are not present in OrderedDict, ignore them.

Additionally, reordering should be "stable", that is, if some keys were not specified in order list, they should keep their original order from the old OrderedDict.

In other words:

o = OrderedDict([('a',1), ('b',2), ('d', 5), ('c',3), ('f', 6)])
reorder_ordereddict(o, ['c', 'a', 'x'])

produces:

OrderedDict([('c', 3), ('a', 1), ('b', 2), ('d', 5), ('f', 6)])

Code:

def reorder_ordereddict(od, new_key_order):
    odkeys = od.keys()
    fullorder = [x for x in new_key_order if x in odkeys]
    remaining = [x for x in odkeys if not x in fullorder]
    fullorder.extend(remaining)
    newod = OrderedDict([(k,None) for k in fullorder])
    newod.update(od)
    return newod

Any better ideas how to do this?


texts:
I'm solving K&R exercise 1-13:

  Write a program to print a histogram of the lengths of words
  in its input. It is easy to draw the histogram with the bars horizontal; a
  vertical orientation is more challenging.

Although the exercise itself is pretty simple, I've decided to apply a more "professional" approach and encapsulate (is that a correct word?) histogram into a structure:

typedef struct {
    /* Legend and character to 'draw' histogram with */
    char **legend, chr;
    /* Histogram data */
    int *data;
    /* Max. data value, bin width, space between bins, max. bin length */
    int datamax, binwidth, binmargin, binlength;
    /* Data and legend array lengths */
    size_t datasize, legendsize;
} chart_t;

Because it's still a toy program, I decided to not overcomplicate algorithm so my histogram is limited to only integer data (it's hard to represent floating point values graphically in console anyway).

Overall algorithm works more or less correctly, so I ask to review only my chart creation procedure. The whole point of this was to learn how to use dynamic memory (allocate, free, etc.).

#define BINWIDTH_DEFAULT 3
#define BINMARGIN_DEFAULT 1
#define BINLENGTH_DEFAULT 14

/* ... */

chart_t *create_chart(int *data, size_t ds, char **lgnd, size_t ls, char chr) {
    chart_t *out = (chart_t *) malloc(sizeof(chart_t));

    if(out == NULL)
        return NULL;

    out->chr = chr;
    out->datasize = ds;
    out->legendsize = ls;

    out->binwidth = BINWIDTH_DEFAULT;
    out->binmargin = BINMARGIN_DEFAULT;
    out->binlength = BINLENGTH_DEFAULT;

    out->data = (int *) calloc(ds, sizeof(int));

    if(out->data == NULL) {
        free(out);
        return NULL;
    }

    memcpy(out->data, data, ds);

    int dmax = 0;
    for(int i = 0; i < ds; i++)
        if(data[i] > dmax)
            dmax = data[i];

    out->datamax = dmax;

    char **legend = (char **) calloc(ls, sizeof(char *));

    for(int i = 0; i < ls; i++) {
        size_t len = strlen(lgnd[i]);

        if(len == 0)
            continue;

        char *curstr = (char *) calloc(len+1, sizeof(char));

        if(curstr == NULL) {
            if(i > 1)
                for(int j = 0; j < i; j++)
                    free(legend[j]);

            free(legend);
            free(out);

            return NULL;
        }

        strncpy(curstr, lgnd[i], len+1);

        legend[i] = curstr;
    }

    return out;
}

Haven't I missed anything? Do I have any potential memory problems in my procedure?


texts:
def merge_sort(mslist):

    if len(mslist) < 2:
        return mslist

    left = mslist[:int(len(mslist)/2)]
    right = mslist[int(len(mslist)/2):]

    left = merge_sort(left)
    right = merge_sort(right)

    return merge(left, right)

def merge(left,right):

    result = []

    while len(left) > 0 or len(right) > 0:
        if len(left) > 0 and len(right) > 0:
            if left[0] <= right[0]:
                result.append(left[0])
                left.pop(0)
            else:
                result.append(right[0])
                right.pop(0)
        elif len(left) > 0:
            result.append(left[0])
            left.pop(0)
        elif len(right) > 0:
            result.append(right[0])
            right.pop(0)

    return result

def main():

    mslist = [-9,1,1,2,3,2,7,3,6,4,5,4,3,5,6,7,8,9,0,0]
    print(merge_sort(mslist))

if __name__ == "__main__":
    main()

Please give me some comments about the actuall algorithm, i used the pseudo code from the wikipedia page as a reference.
Please give me some Pythonic advice or any other general coding paradigm you  feel should be followed.

I already made changes to my code regarding the amount of times len(direction) is done.


texts: LINQ queries to fetch first and last name

texts:
I have these two queries and they work just fine.  I use the values they retrieve to populate a title for a view in my application.  It seems though that I should be able to accomplish this with one query and I do not know how.

Dim firstName = (From row In db.ItemDetails
    Where row.Unique_Location_ID = locationID And row.Item_Type_Identifier = 1 And _
    row.Category_Attribute_Identifier = 2
    Select CStr(row.Value)).FirstOrDefault()

Dim lastName = (From row In db.ItemDetails
    Where row.Unique_Location_ID = locationID And row.Item_Type_Identifier = 1 _
    And row.Category_Attribute_Identifier = 3
    Select CStr(row.Value)).FirstOrDefault()

ViewBag.assignedTo = ("Employee this item is currently assigned to: " + firstName + " " + lastName + ".")

Is there a better way to do this?


texts:
I have implemented the following in order to handle JS XHR requests coming from HTML pages. Is there a better way to do this with OWIN?

public class Startup
{
    public void Configuration(IAppBuilder app)
    {
        app.UseFileServer(new FileServerOptions
        {
            FileSystem = new PhysicalFileSystem(string.Format("{0}{1}Web{1}Dashboard", Path.GetDirectoryName(Assembly.GetEntryAssembly().Location), Path.DirectorySeparatorChar))
        });
        app.Use<Middleware>();
    }
}

public class Middleware : OwinMiddleware
{
    private readonly List<string> _knownRequests = new List<string>
    {
        "Request"
    };

    public Middleware(OwinMiddleware next)
        : base(next)
    {
    }

    public override async Task Invoke(IOwinContext context)
    {
        #region Invoke Next Context

        await Next.Invoke(context);

        #endregion

        #region Handle Request

        var request = context.Request;
        var response = context.Response;
        var path = request.Path.Value.TrimStart('/');
        if (!_knownRequests.Contains(path))
            return;

        response.StatusCode = 200;

        switch (path)
        {
            case "Request":
            {
                await response.WriteAsync("RESPONSE!");
                break;
            }
        }

        #endregion
    }
}


texts: R Container for Multiple data.frame with a Brief Description of the Content of the data.frame

texts:
For a project I have a large dataset with a multitude of variables from different questionnaires. Not all variables are required for all analyses.
So I created a preprocessing script, in which subsets of variables (with and without abbreviations) are created. However it gets confusing pretty fast.
For convenience I decided to create a index_list which holds all data.frames as well as a data.frame called index_df which holds the name of the respective data.frame as well as a brief description of each subversion of the dataset.
######################## Preparation / Loading #####################
# Clean Out Global Environment
rm(list=ls())

# Detach all unnecessary pacakges
pacman::p_unload()

# Load Required Libraries
pacman::p_load(dplyr, tidyr, gridExtra, conflicted)

# Load Data
#source("00_Preprocess.R")
#create simulation data instead
sub_data <- data.frame(x=c(2,3,5,1,6),y=c(20,30,10,302,5))
uv_newScale <- data.frame(item1=c(2,3,5,1,6),item2=c(3,5,1,3,2))

# Resolving conflicted Namepsaces
conflict_prefer("filter", "dplyr")

# Creating an Index
index_list <- list("sub_data"=sub_data,
                   "uv_newScale"=uv_newScale
                   )

index_df <- data.frame("Data.Frame"=c("sub_data",
                                        "uv_newScale"),
                       "Description"=c("Contains all sumscales + sociodemographics, names abbreviated",
                                       "Only sum scores for the UV Scale"))

I am wondering if there is a more efficient way to do so. Like saving the data.frames together with the description in one container?


texts:
T_PROJECT is the class that will be retrieve data from linq to sql and ProjectOwnerDataFields is the class that will be used to show data in view. in edit mode i have to get value from model and send it back like this. is there anyway to refactor this and remove the reverse duplication on ProjectOwnerDataFields and UpdateToModel ?

    public class ProjectOwnerDataFields
    {
        public int Id { get; set; }
        public string CompanyName { get; set; }
        public string ContactPerson { get; set; }
        public string CountryIsoLetter { get; set; }
        public string Phone { get; set; }
        public string Email { get; set; }
        public string Fax { get; set; }
        public string Location { get; set; }
        public string Province { get; set; }
        public string Remark { get; set; }

        public string CountryFullName
        {
            get
            {
                if (String.IsNullOrEmpty(this.CountryIsoLetter) == false)
                {
                    return new RegionInfo(this.CountryIsoLetter).EnglishName;
                }

                return "";
            }
        }

        public ProjectOwnerDataFields()
        {

        }

        public ProjectOwnerDataFields(T_PROJECT project)
        {
            this.Id                =     project.proj_owner_id            ;
            this.CompanyName       =     project.proj_owner               ;
            this.ContactPerson     =     project.proj_owner_contact       ;
            this.CountryIsoLetter  =     project.proj_owner_country       ;
            this.Phone             =     project.proj_owner_phone         ;
            this.Email             =     project.proj_owner_email         ;
            this.Fax               =     project.proj_owner_fax           ;
            this.Location          =     project.proj_owner_location      ;
            this.Province          =     project.proj_owner_province      ;
            this.Remark            =     project.proj_remark              ;
        }

        public void UpdateToModel(T_PROJECT project)
        {
            project.proj_owner              =   this.CompanyName          ;
            project.proj_owner_contact      =   this.ContactPerson        ;
            project.proj_owner_country      =   this.CountryIsoLetter     ;
            project.proj_owner_phone        =   this.Phone                ;
            project.proj_owner_email        =   this.Email                ;
            project.proj_owner_fax          =   this.Fax                  ;
            project.proj_owner_location     =   this.Location             ;
            project.proj_owner_province     =   this.Province             ;
            project.proj_remark             =   this.Remark               ;
        }
    }


texts:
Wrote a basic pig latin script in python where the input is a string and it outputs the pig latin equivalent. I was just wondering what the runtime of this code would be and if there was a way to make it quicker. Off the time of my head, I would assume that the runtime would be \$O(26)\$ or just constant because all you do is look at the last letter and compare it to the list.

def pig_latin(string):
    consonants = ['b','c','d','f','g','h','j','k','l','m','n','p','q','r','s','t','v','w','x','y','z']
    if string[-1] in consonants:
        string = string[1:] + string[0] + "ay"
    else:
        string = string + "way"
    return string


texts:
The generic version of extension method is aimed to work like String.LastIndexOf which can search t from the last position of s. The BuildTable method is exactly same with the method used by normal KMP algorithm, which is to determine the differences between each element.

I am not sure if this is the best solution as there is a question about reusing BuildTable method can provide best performance in this case.

Complete source code can be viewed here. Creating issues at GitHub is also welcome.

    public static int LastIndexOf<T>(this IReadOnlyList<T> s, IReadOnlyList<T> t,
        int startIndex, IEqualityComparer<T> comparer) where T : IEquatable<T>
    {
        /*
         * Parameters check is omitted in this snippet.
         */

        var table = BuildTable(t, comparer);
        var i = 0;

        while (startIndex - i >= 0)
        {
            if (comparer.Equals(t[t.Count - i - 1], s[startIndex - i]))
            {
                if (i == t.Count - 1)
                    return startIndex - t.Count + 1;
                i++;
            }
            else
            {
                if (table[i] > -1)
                {
                    startIndex -= i;
                    i = table[i];
                }
                else
                {
                    startIndex--;
                    i = 0;
                }
            }
        }
        return -1;
    }


texts:
I'd like to improve this operator code if I can. I don't know enough Raku
to write idiomatically (or any other way for that matter), but suggestions
along those lines would be good also.

use v6d;

sub circumfix:<α ω>( ( $a, $b, $c ) ) {
    if ( $a.WHAT ~~ (Int) ) {
        so ( $a >= $b & $a <= $c );
    }
    else {
        my @b;
        for $a { @b.push( ( $_ >= $b & $_ <= $c ).so ) };
        so (False) ∈ @b;
    }
};

if (α 5, 0, 10 ω) {
    "Pass".say;
}
else {
    "Fail".say;
}
if (α ( 5, 7, 11 ), 0, 10 ω) {
    "Pass".say;
}
else {
    "Fail".say;
}

This does a range check on a variable or variables, between/bookended by $b (lower) and $c (upper). I wonder about using
some sort of signature check paired with multi as a cleaner
approach?


texts:
I am trying out a small piece of code that would generate HMAC-SHA1. I have been asked to code the HMAC implementation myself using the OpenSSL libs for SHA1 calculation.

After 'wiki'ing for the algorithm, here is what I have below.  I have used input with RFC 2104 specified test values:

  key =         0x0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b
  key_len =     16
      bytes
  data =        "Hi There"
  data_len =    8  bytes    digest =
      0x9294727a3638bb1c13f48ef8158bfc9d

But the output I get is:

675b0b3a1b4ddf4e124872da6c2f632bfed957e9*

Is this really not the way to implement HMAC? How else can this be done?

#include <openssl/evp.h>
#include <openssl/bn.h>
#include <openssl/sha.h>
#include <openssl/err.h>
#include <openssl/conf.h>
#include <openssl/engine.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>     /* for memset() */
#include <unistd.h>

#define IPAD 0x36
#define OPAD 0x5C

#define SHA1_DIGESTLENGTH 20
#define SHA1_BLOCK_LENGTH 64
#define COUNTER_LENGTH 8

typedef unsigned          char uint8_t;
typedef unsigned short     int uint16_t;
typedef unsigned           int uint32_t;

/**
 * Key
 */
#define SECRET { 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b , 0x0b , 0x0b , 0x0b , 0x0b , 0x0b , 0x0b , 0x0b , 0x0b}
#define COUNTER {  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }
/*
 * hmac sha1.
 */
int main(int argc, char *argv[]){
    unsigned char ipad[SHA1_BLOCK_LENGTH];
    unsigned char opad[SHA1_BLOCK_LENGTH];
    unsigned char algKey[SHA1_BLOCK_LENGTH];
    unsigned char msgBuffer[SHA1_BLOCK_LENGTH + COUNTER_LENGTH];
    unsigned char valBuffer[SHA1_BLOCK_LENGTH + 20];
    unsigned int i;
    uint8_t ctr[] = "Hi There";
    uint8_t hash[20];
    uint8_t key[]= SECRET;
    int len = 16;
    memset(hash, 0, sizeof(hash));
    memset(algKey, 0, sizeof(algKey));
    strncpy((char *)algKey, (char *)key, len);

    memset(ipad, IPAD, sizeof(ipad));
    memset(opad, OPAD, sizeof(opad));

    for (i = 0; i < SHA1_BLOCK_LENGTH; i++){
        ipad[i] ^= algKey[i];
    }

    for (i = 0; i < SHA1_BLOCK_LENGTH; i++){
        opad[i] ^= algKey[i];
    }

    memset(msgBuffer, 0, sizeof(msgBuffer));

    strncpy((char *)msgBuffer, (char *)ipad, SHA1_BLOCK_LENGTH);
    strncpy((char *)msgBuffer + SHA1_BLOCK_LENGTH, (char *)ctr, COUNTER_LENGTH);

    EVP_MD_CTX mdctx, md_ctx;
    const EVP_MD *md;

    unsigned char md_value[EVP_MAX_MD_SIZE];
    unsigned int md_len;

    OpenSSL_add_all_digests();

    md = EVP_get_digestbyname("sha1");

    if(!md) {
        printf("Unknown message digest\n");
        exit(1);
    }

    EVP_MD_CTX_init(&mdctx);
    EVP_DigestInit_ex(&mdctx, md, NULL);
    EVP_DigestUpdate(&mdctx, msgBuffer,(SHA1_BLOCK_LENGTH + COUNTER_LENGTH) );
    EVP_DigestFinal_ex(&mdctx, md_value, &md_len);
    EVP_MD_CTX_cleanup(&mdctx);

    printf("Digest is: ");
    for(i = 0; i < md_len; i++) printf("%02x", md_value[i]);
    printf("\n");

    unsigned char *copy;
    copy = malloc(md_len);
    strncpy((char*)copy, (char *)md_value, md_len);

    memset(valBuffer, 0, sizeof(valBuffer));
    strncpy((char *)valBuffer, (char *)opad, SHA1_BLOCK_LENGTH);
    strncpy((char *)valBuffer + SHA1_BLOCK_LENGTH, (char *)copy, md_len);

    EVP_MD_CTX_init(&md_ctx);
    EVP_DigestInit_ex(&md_ctx, md, NULL);
    EVP_DigestUpdate(&md_ctx, valBuffer, SHA1_BLOCK_LENGTH + 20);
    printf( "updated Digest..\n");
    EVP_DigestFinal_ex(&md_ctx, md_value, &md_len);
    EVP_MD_CTX_cleanup(&md_ctx);

    printf("Digest is: ");
    for(i = 0; i < md_len; i++) printf("%02x", md_value[i]);
    printf("\n");

    return 0;
}


texts:
I was working on a problem from Coderbyte. The challenge was to write a function that takes in a string and returns the longest word in the string. If two words are the same size then it asks to return the first one. The input will never be empty.

function longestword(str){
    var replaced = str.replace(/[^A-Za-z\s]/g,"");
    var final = replaced.split(" ").sort(function(a,b){return b.length - a.length})
    return final[0];
    }
longestword("This is a string theres two words that are the same size oh no!")
=>'string'

What do you think about my code?


texts: Deallocate all memory in a container of pointers

texts:
I want to erase all memory in a container. Currently I'm using this :

template<typename Cont>
void clear_mem(Cont &container)
{
    while (!container.empty())
    {
        delete container.back();
        container.pop_back();
    }
}

Should the operation of deleting the memory held by the contents be separated by clearing the container ?
Is it pointless to make this function a template, since it can only  operate on vector and list ?


texts: Unlocking spreadsheet files quickly - follow-up

texts:
I recently posted a program I made to unlock spreadsheet files( see also ), I've taken all of your advice and made it more Ruby like, it has no shell commands in it, and uses FileUtils

I personally think it looks a whole lot cleaner and a whole lot more Ruby like. I would like a critique on my work so far, and would like some pointers if possible.

Source:

#!/usr/local/bin/ruby

require 'fileutils'

def spreadsheet_unlocker
    puts "Enter Folio # if unlocking multiple seperate with comma followed by space."
    folios = gets.chomp
    folios.split(', ').each do |input_folio|
        lockfile = "/my/dir.~lock.#{input_folio}.ods#"
        if input_folio =~ /^\d{7}/
            if File.exist?( lockfile )
                puts "Unlock file?"
                input = gets.chomp
                    if input =~ /y/i
                     FileUtils.rm( lockfile )
                     puts "File unlocked."
                else
                    puts "You went through that trouble for no reason..."
                end
            else
                puts <<-EDE.gsub(/^\s*>/, ' ')
                >
                >Lockfile not found for Folio # #{input_folio}"
                >
                >If the file name doesn't match the folio number, get the file name
                >and use that instead of the Folio number...
                >
                EDE
                spreadsheet_unlocker
            end
        else
            puts <<-EDF.gsub(/^\s*>/, ' ')
            >
            >What part of 'Folio #' is hard to understand? 7 DIGITS"
            >
            >If the file name doesn't match the folio number, get the file name
            >and use that instead of the Folio number...
            >
            EDF
            spreadsheet_unlocker
        end
    end
end
spreadsheet_unlocker

Example usage:

Enter Folio # if unlocking multiple seperate with comma followed by space.
1111111, 2222222, 3333333
Unlock file?
yes
File unlocked.
Unlock file?
yes
File unlocked.
Unlock file?
yes
File unlocked.

Enter Folio # if unlocking multiple seperate with comma followed by space.
2345678

 Lockfile not found for Folio # 2345678"

 If the file name doesn't match the folio number, get the file name
 and use that instead of the Folio number...


texts: Override values for overlapping objects between two scala lists

texts:
Let's say I have a bunch of Widget, where a Widget is

class Widget (sku: Int, label: String, name: String, description: String)

And I have 2 sources of Widgets:

List[Widget] wInventory = getWidgetsInInventory()
List[Widget] wCatalog = getWidgetsFromCatalog()

I want to use the name & label from the Catalog to override any matching widget in Inventory. The match criteria is when sku == sku.
If the label is missing in the catalog, override with constant value of No Catalog Label instead of leaving label as is.
The wCatalog list may be empty.  There may be no intersections at all, or both lists can contain the same set of sku's.

First draft of the code below. There must be a way to avoid running find twice, but because find returns Optional[Widget], it started looking messy with lots getOrElse.  What's the cleanest way to do this?

case class MyWidget (sku: Int, label: String, name: String, description: String)

object HelloWorld {
  def main(args: Array[String]) {

    def setOverrideValues(inv : List[MyWidget], cat: List[MyWidget]) : List[MyWidget] = {
      inv.map (k => {
        val realName = cat.find( _.sku == k.sku).map(_.name)
        val realLabel = cat.find( _.sku == k.sku).map(_.label)

        k.copy(name = realName.getOrElse("No Catalog Label"), label=realLabel.getOrElse(k.label))
      })
    }

    val invItem1 = new MyWidget(sku=1, label="invLabel1", name="invName1", description="invDesc1");
    val invItem2 = new MyWidget(sku=2, label="invLabel2", name="invName2", description="invDesc2");
    val catItem1 = new MyWidget(sku=1, label="catLabel1", name="catName1", description="catDesc1");

    val wInventory = List(invItem1 , invItem2);
    val wCatalog = List(catItem1)

    val updated = setOverrideValues(wInventory, wCatalog)

    println("done")
  }
}


texts: Determining if current thread is executing

texts:
Using C#, create a class which gets an action (parameter-less
  delegate) in its construction and has a single public method bool
  execute() which does the following:

  Executes the action only if no other thread is currently executing the action
  If another thread is already executing, wait until thread is finished before returning (but without executing action again)
  Return true if current thread executes that action, otherwise return false.

public delegate bool Action();

private static int ThreadsCount = 100; //initialize threads count

static void Main(string[] args)
{
    Action act = Execute;
    bool t = act();
    Console.WriteLine(t);
    Console.ReadLine();
}

static bool Execute()
{
    bool retVal = false;
    Thread thread = Thread.CurrentThread;
    string s = thread.Name;
    if (s == null)
    {
        test();
        retVal = true;
    }
    else
    {
        ThreadsCount = ThreadsCount - 1;

        if (ThreadsCount < 1)
        {
            //if all threads finished executing do whatever you wanna do here..
            Console.WriteLine("C# language");
            test();
            retVal = true;
        }
        else
        {
            retVal = false;
        }

    }
    return retVal;
}

private static void test()
{
    Console.WriteLine("C# language");
}

Is the above piece of code correct? Please give me your feedback.

Please don't think that this is just exercise. This question was asked by one of the interviewers.


texts:
When reviewing a Graham scan convex hull algorithm implementation, I wrote the following function in an answer:

giftWrap :: [Vector2] -> [Vector2]
giftWrap vs = result
  where
    -- Decides whether to keep or reject vertex b.
    -- Vertex b is provisionally kept if a left turn occurs there; the result
    -- is finalized only when a closed left-turn-only tour is completed.
    giftWrap' (a:b:c:vs)
      | vs == [] && dir == TurnLeft  = (True, [b, c])
      | vs == []                     = (False, [c])
      | dir == TurnLeft && final     = (True, (b:gw))
      | dir == TurnLeft              = giftWrap' (a:gw)
      | otherwise                    = (False, (a : c : vs))
      where
        dir = turn a b c
        (final, gw) = giftWrap' (b:c:vs)
    (_, result) = giftWrap' (vs ++ [head vs])

The purpose of this function is to keep only the vertices in the input sequence at which a left turn occurs.  However, if a right turn is encountered, we must drop the right-turn vertex from consideration, backtrack, and try again.

To achieve backtracking, I've designed the inner function to return a status flag in addition to the result.  I'm not satisfied with it though, as it looks ugly and is hard to follow.

Is there a better way to implement recursion with possible backtracking?

Is recursion the appropriate technique to use in the first place?


texts: Extending Sieve of Eratosthenes beyond a billion

texts:
For MAX value of 1000000000 (\$10^9\$), it takes about 45 seconds to reach the line where it prints "done". How can I speed this up?

Is printing to screen always going to take so much time? I know it's hardware.

On increasing the size of MAX beyond \$10^9\$ gives me an exception on the line memset(a, true, MAX);. Is there any limit to this function? I should be able to use all of the RAM. Running this program uses around 954 MB of memory.

void sieve_of_eratosthenes(){
    bool* a;
    a = (bool*)malloc(MAX * sizeof(bool));
    memset(a, true, MAX);
    unsigned long int i = 1;
    while (i < MAX){

        while (((++i)<MAX)&&(!a[i]));

        if (2 * i >= MAX)
            break;

        for (unsigned long int k = 2 * i; k < MAX; k += i)
            if (a[k])
                a[k] = false;
    }
    std::cout << "done\n";
    for (unsigned long int i = 2; i < MAX; i++)
        if (a[i])
            std::cout << i << "\n";
    getchar(); getchar();
}


texts:
I know there are plenty of Caesar Cipher reviews on here, but I especially wanted to see how other programmers felt about my use of the cmd module and the efficiency of my functions.

Though this program in its current state is fully functional, I feel the design may be gridlocked and lacking flexibility, due to my lack of knowledge regarding the process of creating commands for the user to utilize.

The current design makes it difficult to implement the varying command attributes I hoped to add later on. How should I go about doing this? A format I see in other cmd programs goes something like command --numbers --property=number --filename

import cmd

def sym_extract(text,syms):
    text = text[text.find(syms[0])+1:text.find(syms[1])]
    return text

def del_punc(string):
    string = ''.join(ch if ch.isalnum() else '' if ch!=' ' else ' ' for ch in string)
    return(string.lower())

def cipher(text, shift):
    text = del_punc(text)
    secret = ''
    for c in text:
        if c in 'abcdefghijklmnopqrstuvwxyz':
            num = ord(c)
            num += shift
            if num > ord('z'):
                num -= 26
            elif num < ord('a'):
                num += 26
            secret = secret + chr(num)
        else:
            secret = secret + c
    return secret

class CryptoPromptCmd(cmd.Cmd):
    prompt = '\n> '

    def default(self, arg):
        print('invalid command, try typing "help"')

    def do_quit(self, arg):
        '''exits the program'''
        return True

    def do_encrypt(self, arg):
        '''usage: encrypt (provided string or /filename)[shift number]'''
        if arg != '':
            text  = del_punc(sym_extract(arg,'()'))
            shift = int(sym_extract(arg,'[]'))
            encrypted = cipher(text,shift)
            print('\n ',encrypted.upper())
        else:
            print('invalid command\nusage: encrypt(provided string or /filename)[shift number]')
            return

    def do_decrypt(self, arg):
        '''usage:\noutput to file: decrypt(provided string or /filename)[file]\nattempt manually: decrypt(provided string or /filename)[shift number]'''
        if arg != '':
            text  = del_punc(sym_extract(arg,'()'))
            shift = -1*int(sym_extract(arg,'[]'))
            decrypted = cipher(text,shift)
            print('\n ',decrypted.upper())
        else:
            print('invalid command\nusage:')
            print('output to file: decrypt(provided string or /filename)[output /filename]')
            print('attempt manually: decrypt(provided string or /filename)[shift number]')
            return

if __name__ == '__main__':
    print('\n'* 3)
    print("Caesar Cipher Tool")
    print('==================')
    print()
    print('type "help" for commands')
    print()
    CryptoPromptCmd().cmdloop()
    print('\nexiting...\n')


texts: Code Refactoring for Dynamic List in Angular 8

texts:
With a specific requirement of showing/hiding the pages, the following implementation has been carried out.

The pages which needs to be hidden will be provided through an array

this.unshowPages = ['menuPage', 'aboutusPage','linkedInPage'];

The corresponding HTML file,

 <ng-container *ngIf="showaboutPages">

            About us Page

      </ng-container>
       <ng-container *ngIf="showlkdPages">

            LinkedIN Page

      </ng-container>

The ts file will be

unshowPages= [];

showMenuPages: boolean = true;
showaboutPages: boolean = true;
showlkdPages: boolean = true;

ngOnInit() {
//this.unshowPages = ['menuPage', 'aboutusPage','linkedInPage'];
this.unshowPages = ['menuPage'];

this.unshowPages.forEach((x:string)=> {

  console.log(x)

  switch(x){
    case 'menuPage': this.showMenuPages = false; break;
    case 'aboutusPage': this.showaboutPages = false; break;
    case 'linkedInPage': this.showlkdPages = false; break;

  }

  });

The problem comes here is when pages gets updated, the switch case should be modified to adapt new pages. Is there any optimized way to achieve this.

The minimal reproducible working code : https://stackblitz.com/edit/angular-ivy-1antde


texts: Rob Pike's Golang presentation excercise of day 1

texts:
I'm following this presentation. At the very end there's an exercise about solving Fibonacci and says that instead of addition, make the operation setteable by a function.

Is the following is a good solution? How close might it be to what Rob Pike would have written?

package main

import "fmt"

func add(a, b int) int {
    return a + b
}

func subtract(a, b int) int {
    return a - b
}

func power(a, b int) int {
    return a ^ b
}

// fib returns a function that returns
// successive Fibonacci numbers.
func fib(op func(int, int) int) func() int {
    n0, n1 := 0, 1
    return func() int {
        n0, n1 = n1, op(n0, n1)
        return n0
    }
}

func main() {
    f := fib(add)
    // Function calls are evaluated left-to-right.
    fmt.Println(f(), f(), f(), f(), f(), f(), f())

    f = fib(subtract)
    // Function calls are evaluated left-to-right.
    fmt.Println(f(), f(), f(), f(), f(), f(), f())

    f = fib(power)
    // Function calls are evaluated left-to-right.
    fmt.Println(f(), f(), f(), f(), f(), f(), f())
}


texts:
I'd like someone to double-check my use of Atomic primitives, because multi-threading is hard.

What I don't want to do is locking the whole get method, or having too many pre-checks per get() call.

private final static AtomicReference<T> REFERENCE = new AtomicReference<>();

private final static AtomicBoolean IS_CREATED = new AtomicBoolean(false);

public static MyObject get() {
    if (IS_CREATED.compareAndSet(false, true)) {
        REFERENCE.set(new MyObject());
    }
    return REFERENCE.get();
}


texts: Issue a citation based on speed, with lenience for your birthday

texts:
You are driving a little too fast, and a police officer stops you. Write
 code to compute the result, encoded as an int value: 0=no ticket, 1=small
 ticket, 2=big ticket. If speed is 60 or less, the result is 0. If speed is
 between 61 and 80 inclusive, the result is 1. If speed is 81 or more, the
 result is 2. Unless it is your birthday -- on that day, your speed can be
 5 higher in all cases.

public int caughtSpeeding(int speed, boolean isBirthday) {
if(isBirthday) {
    if(speed <= 65) {
        return 0;
    } else if(66 <= speed && speed <= 85) {
        return 1;
    } else if(86 <=  speed) {
        return 2;
    }
}

if(speed <= 60) {
    return 0;
} else if(61 <= speed && speed <= 80) {
    return 1;
} else {
    return 2;
}}


texts:
I've recently started studying C++ (from internet) Made my very first program, calculator. It works, but i'd like to know how could i make this more "advanced"?

#include <iostream>
using namespace std;

int pluss(int num1, int num2)
{
    int answer = num1 + num2;
    cout << num1 << " + " << num2 << " = " << answer << endl;
    system("pause");
    system("CLS");
    return 0;
}

int Minus(int num1, int num2)
{
    int answer = num1 - num2;
    cout << num1 << " - " << num2 << " = " << answer << endl;
    system("pause");
    system("CLS");
    return 0;
}

int devide(double num1, double num2)
{
    double answer = num1 / num2;
    cout << num1 << " / " << num2 << " = " << answer << endl;
    system("pause");
    system("CLS");
    return 0;
}

int multiply(double num1, double num2)
{
    double answer = num1 * num2;
    cout << num1 << " * " << num2 << " = " << answer << endl;
    system("pause");
    system("CLS");
    return 0;
}

int main()
{
    int begin;
    cout << "----------------------------------------" << endl;
    cout << "-----Welcome to C++ Based Calculator!---" << endl;
    cout << "-1=Plus--2=Minus--3=devide--4=multiply--" << endl;
    cout << "----------------------------------------" << endl;
    cin >> begin;

    if (begin == 1) {
        system("CLS");
        int x;
        int y;
        cout << "Give me a first number" << endl;
        cin >> x;
        system("CLS");
        cout << "Give me a second number" << endl;
        cin >> y;
        pluss(x, y);
        return main();
    }
    else if (begin == 2) {
        system("CLS");
        int x;
        int y;
        cout << "Give me a first number" << endl;
        cin >> x;
        system("CLS");
        cout << "Give me a second number" << endl;
        cin >> y;
        Minus(x, y);
        return main();
    }
    else if (begin == 3) {
        system("CLS");
        double x;
        double y;
        cout << "Give me a first number" << endl;
        cin >> x;
        system("CLS");
        cout << "Give me a second number" << endl;
        cin >> y;
        devide(x, y);
        return main();
    }
    else if (begin == 4) {
        system("CLS");
        double x;
        double y;
        cout << "Give me a first number" << endl;
        cin >> x;
        system("CLS");
        cout << "Give me a second number" << endl;
        cin >> y;
        multiply(x, y);
        return main();
    }
    else {
        system("CLS");
    }

    system("pause");
    return 0;
}


texts: Code smell when recursively returning a List

texts:
So this is part of my AVL tree implementation, namely the infix representation of the tree. Since I wanted to use a recursive method to stay close to the original algorithm and want to return a list, I have to store the values in a parameter.

The smelly part is in getInfix when I reference that parameter to return the list. I am not even sure what's the name of this code smell but it feels wrong. I am literally only calling getInfixInternal for its side effect! But I can't simply return a list either...

How can I make this better?

private List<T> getInfix() {
    List<T> result = new ArrayList<>();
    getInfixInternal(root, result);
    return result;
}

private void getInfixInternal(Node node, List<T> infixValues) {
    if (node != null) {
        getInfixInternal(node.getLeft(), infixValues);
        infixValues.add((T) node.getValue());
        getInfixInternal(node.getRight(), infixValues);
    }
}

My Node class (excluding the getters and setters for reasons of space):

public class Node <T extends Comparable>  {
    private T value;
    private Node leftChild;
    private Node rightChild;
    private Node parent;
}


texts:
I have code that uses the brute force technique to find the message to a Caesar cipher. The program decrypts the message using different keys and then checks whether the resulting words are contained in a file called 'wordlist.txt'. if they are, it returns only that result.

from collections import namedtuple
Keycode = namedtuple('Keycode', 'key code')

def picks(filename):
    with open(filename) as f:
        lines = [line.strip() for line in f]
    return lines

message = 'vlr alkq exsb ql qefkh xylrq qexq exex.'
LETTERS = 'abcdefghijklmnopqrstuvwxyz'
result = []
for key in range(len(LETTERS)):
    translated = ''
    for symbol in message.lower():
        if symbol in LETTERS:
            num = LETTERS.find(symbol)
            num = num - key
            if num < 0:
                num = num + len(LETTERS)
            translated += LETTERS[num]
        else:
            translated += symbol
    result.append(Keycode(key, translated))

for item in result:
    d = item.code.split()
    for word in d:
        if word in picks('wordlist.txt'):
            print('Code : {0:s}\nKey  : {1:}'.format(item.code, item.key))
            break

The code that I have does the job but it takes time and the code is not clean. Is there a way to make the code a bit cleaner? I am new to Python and haven't started on classes, so I cant use those (although it would have made my job easier).


texts: How to write a method that takes a general iterator as input argument?

texts:
Now I have a bunch of these methods ( you can tell how ugly it looks like):

void ConvertUtility::ConvertEdgeIndexList(const list<EdgeIndex> &edgeIndex)
{

     list<EdgeIndex>::const_iterator sit;
     for(sit=edgeIndex.begin(); sit!=edgeIndex.end(); sit++)
     {

     }
}

void ConvertUtility::ConvertEdgeIndexList(const vector<EdgeIndex> &edgeIndex)
{

     vector<EdgeIndex>::const_iterator sit;
     for(sit=edgeIndex.begin(); sit!=edgeIndex.end(); sit++)
     {

     }
}

Is there anyway I can aggregate these two functions into one single function?


texts: The Morra game implementation in Haskell

texts:
Me and my friends play a variant of Morra when drinking. The rules are as follows:

The players sit in a circle and hold one of their hands in front of
them.
One player guesses a number. All the players (including this one)
then hold out between 0 and 5 fingers on their hand.
If there are as many fingers held out as the player guessed, he is
"saved", leaves the circle and doesn't have to play anymore. Next turn another player tries to guess
(otherwise the game just goes on with the player staying in the circle).
The last player to remain in the circle has to drink.

I'm just learning about monad transformers, so I thought it would be nice to implement this simple game.

module Morra where

import Control.Monad.Trans.State
import Control.Monad.Trans
import Control.Monad
import Data.List
import Data.Char

main :: IO ()
main = do
  putStrLn "Welcome to Morra. The last to remain has to drink."
  putStr "Please input the names of players: "
  psraw <- getLine
  putStrLn ""
  ([p], n) <- execStateT (play 0) (words psraw, 0)
  putStrLn $ p ++ " has lost, after " ++ show n ++ " rounds. (S)he has to take a shot."

play :: Int -> StateT ([String], Int) IO ()
play p = do
  (ps, n) <- get
  let currp = ps !! p
  if length ps == 1
    then put (ps, n)
    else do
      liftIO $ putStr $ "It's now " ++ currp ++ "'s turn. How many fingers will be help up? "
      a <- liftIO safeGetLine
      putNewLine
      liftIO $ putStrLn "[INPUT PHASE] Each player now chooses, how many fingers does (s)he hold up."
      fs <- liftIO $ getFingers (length ps)
      liftIO $ putStr "[END OF INPUT PHASE]"
      putNewLine
      if sum fs == a
        then do
          liftIO $ putStrLn $ currp ++ " has guessed right, he's out."
          putNewLine
          let newps = delete currp ps
          put (newps, n + 1)
          play ((p + 1) `mod` length newps)
        else do
          liftIO $ putStrLn $ currp ++ " hasn't guessed right, the game goes on!"
          putNewLine
          put (ps, n + 1)
          play ((p + 1) `mod` length ps)
  where
    putNewLine = liftIO $ putStrLn ""

getFingers :: Int -> IO [Int]
getFingers n = replicateM n helper
 where
  helper = do
    putStr "Input the number of fingers you hold up: "
    fs <- safeGetLine
    putStrLn "Pass the computer to the next player now. [ENTER]"
    getLine
    return fs

safeGetLine :: IO Int
safeGetLine = do
  x <- getLine
  if all isNumber x
    then return $ read x
    else do
      putStrLn "Please input a number"
      safeGetLine

Firstly, you can see the strings I print are pretty long, longer than the 80 chars limit. What is the common approach to tackle these and keep all the lines below 80 chars?

And secondly, please point out anything that could be made more elegant, whatever that might be (even changing the underlaying StateT). I'm also open to new ideas and challenges.


texts:
Given a tree structure (in this example it a list of some nested group nodes), what is the best way to get all branches (branch = list of nodes from root to the leaf element)?

My solution (here root element = element with parent link to itself):

case class Group(id: Int, parent: Int)

def getBranches(groups: Seq[Group]) = {
  @tailrec
  def getPaths(paths: Seq[Seq[Group]], nodes: Seq[Group]): Seq[Seq[Group]] = nodes match {
    case group :: tail =>
      paths.find(_.head.id == group.parent) match {
        case Some(parentPath) => getPaths(paths :+ (group +: parentPath), tail)
        case None => getPaths(paths, tail :+ group)
      }
    case Nil => paths
  }

  def getBranchesOnly(paths: Seq[Seq[Group]]) = {
    for(path <- paths if !paths.exists { otherPath =>
      otherPath != path && otherPath.contains(path.head)
    }) yield path
  }

  val (roots, nodes) = groups.partition(gr => gr.parent == gr.id)
  val paths = getPaths(roots.map(Seq(_)), nodes)
  getBranchesOnly(paths)
}

A node has arbitrary number of children. All id are globally unique. Order of children in a node is irrelevant.

So given a tree:

    1
  2   3
4  5

its list of nodes is:

val groups = Seq(Group(4, 2), Group(1, 1), Group(2, 1), Group(5, 2), Group(3, 1))

I wonder if there is some existing algorithm or just a better approach for this task.


texts: Project Euler #12 - first triangle number with more than 500 divisors

texts:
I tried to solve Project Euler 12 with a first very naive solution by myself. It took nearly 30 minutes to run until it found the solution. Then I made a change in the function getDivisorCount which should have made the run time to about the square root of the original code, about 5 minutes. At least this was my opinion because the complexity should have changed from \$O(n^2)\$ to \$O(n\sqrt n)\$. But it went down to less than a second which surprised me and I could not find a reason.

Here is my code for review, a second time:

#include <iostream>
#include <math.h>

using namespace std;

int getDivisorCount(unsigned int number)
{
    unsigned int count = 0;
    unsigned int sqrt_ = sqrt(number);
    for(unsigned int i = 1; i <= sqrt_; i++)
    {
        if((number % i) == 0)
            count+=2;
    }
    if (sqrt_ * sqrt_ == number)
    {
        count--;
    }
    return count;
}

int main()
{
    unsigned int number = 0;
    for (unsigned int i = 1; ; i++)
    {
        number+=i;
        if(getDivisorCount(number)>500)
            break;
    }
    cout << number;
    return 0;
}

Note that my first version used the method:

int getDivisorCount(unsigned int number)
{
    unsigned int count = 0;
    for(unsigned int i = 1; i <= number; i++)
    {
        if((number % i) == 0)
            count++;
    }
    return count;
}

Both compiled with g++ -O2.

I'm looking for a fresh code review, but an explanation of why the current version is so much faster would also be appreciated.


texts: Search for User by first and/or last name, efficiently

texts:
I am refactoring a user search that just feels dirty. (Users#search)

I need to allow a blank param to search on partial or only a first or last, but don't want to return all the records in the database (which is what seems to be happening when I search with one value nil).

That said, what's the best way to handle one blank param / nil value?
What's the most succinct, efficient way to do this?

Here is where I started:

    def user_search ## this is my before_action
      if params[:fname] || params[:lname]
        @users = User.where("first_name LIKE ? OR last_name LIKE ?", "%#{params[:fname]}%", "%#{params[:lname]}%")
      elsif params[:email_search]
        @users = User.where("email LIKE ?", "%#{params[:email_search]}%")
      end
      head 404 if @users.blank?
    end

Here is where I am:

    def user_search
      if params[:fname].presence && params[:lname].presence
        @users = User.where("first_name LIKE ? AND last_name LIKE ?", "%#{params[:fname]}%", "%#{params[:lname]}%")
      elsif query = (params[:fname] || params[:lname])
        @users = User.where("first_name LIKE ? OR last_name LIKE ?", "%#{query}%", "%#{query}%")
      elsif params[:email_search]
        @users = User.where("email LIKE ?", "%#{params[:email_search]}%")
      end
      head 404 if @users.blank?
    end

The significance behind the SQL of OR versus AND seems to be a convenient way to query and return matches on one of the names, but is it really efficient? Looking for a first_name in the last_name column sounds kind of silly hackery. Unless I'm looking at this the wrong way.

Is there a more performant way to do this?


texts:
This collects user's guesses for the word. The user has 8 guesses, a correct guess and a repeated guess does not affect the guess count.

def getAvailableLetters(lettersGuessed):
    '''
    lettersGuessed: list, what letters have been guessed so far
    returns: string, comprised of letters that represents what letters have not
      yet been guessed.
    '''
    import string
    fullstring = string.ascii_lowercase
    lettersLeft = ''
    for letter in fullstring:
        if letter not in lettersGuessed:
            lettersLeft = lettersLeft + letter
    return lettersLeft

def getGuessedWord(secretWord, lettersGuessed):
    '''
    secretWord: string, the word the user is guessing
    lettersGuessed: list, what letters have been guessed so far
    returns: string, comprised of letters and underscores that represents
      what letters in secretWord have been guessed so far.
    '''
    wordGuessed = ''
    for letter in secretWord:
        if letter in lettersGuessed:
            wordGuessed = wordGuessed + letter
        else:
            wordGuessed = wordGuessed + '_ '
    return wordGuessed

def isWordGuessed(secretWord, lettersGuessed):
    '''
    secretWord: string, the word the user is guessing
    lettersGuessed: list, what letters have been guessed so far
    returns: boolean, True if all the letters of secretWord are in lettersGuessed;
      False otherwise
    '''
    numCorrect = 0
    for letter in secretWord:
        if letter in lettersGuessed:
            numCorrect += 1
        else:
            return False
    return True

def hangman(secretWord):
    guessesLeft = 8
    lettersGuessed =[]

    print('Welcome to the game Hangman!')
    print('I am thinking of a word that is ' + str(len(secretWord)) + ' letters long.' )
    print('-----------')

    while guessesLeft > 0:
        if isWordGuessed(secretWord, lettersGuessed):
            return print('Congratulations, you won!')
        print('You have ' + str(guessesLeft) + ' guesses left.')
        print('Available Letters: ' + getAvailableLetters(lettersGuessed))
        user_input = input('Please guess a letter: ')
        user_input = str(user_input)
        user_input = user_input.lower()

        if user_input not in lettersGuessed:
            lettersGuessed.append(user_input)

            if user_input in secretWord:
                print("Good guess: " + getGuessedWord(secretWord, lettersGuessed))
                print('-----------')
            else:
                print("Oops! That letter is not in my word: " + getGuessedWord(secretWord, lettersGuessed))
                print('-----------')
                guessesLeft -= 1
        else:
            print("Oops! You've already guessed that letter: " + getGuessedWord(secretWord, lettersGuessed))
            print('-----------')

    return print("Sorry, you ran out of guesses. The word was " + str(secretWord))

hangman('stackoverflow')


texts: How to handle returned value if an exception happens in a library code

texts:
There is a lib code, trying to parse an Element Tree object. If exception happens, it either returns an empty dict of dict or a partially constructed object of such type. In this case, caller needs to parse the results to see if parsing is correctly handled or not. Or in other words, the returned dict is not deterministic. How to solve this issue? Or if this is an issue?

def parse_ET(self, ETObj):
    if ETObj == None: return None
    dict_of_dict = collections.defaultdict(dict)
    try:
        for doc in ETObj.iter("result"):
            id = doc.attrib.get("id")
            for elem in doc.iter("attrib"):
                dict_of_dict[id].setdefault(elem.attrib.get("name"), elem.text)
    except Exception, ex:
        logging.exception("%s:%s" % (self.__class__, str(ex)))
    finally:
        return dict_of_docs


texts:
I have some doubt when I should create an object in an Unit Test when the object needs to be stopped cleanly.

Usecase:
I have a class ComplexClass which has 3 functions:

Start(): starts a Thread
Stop(): stops the thread
GetX(): which gets a value

When I test this class I want to check if GetX() returns 42, but first I have to start the thread, and after it I want to stop the Thread. (During testing I don't want many dangling threads running).

Are fixtures the way to do this?:

class TestComplexClass(object):
    @pytest.fixture()
    def complexclass(self, request):
        print ("[setup] ComplexClass")

        cc = ComplexClass()
        def fin():
            print ("[teardown] ComplexClass")
            cc.stop()
        request.addfinalizer(fin)
        return cc

    def test_GetX(self, complexclass):
        // do some stuff

        complexclass.start()
        assert complexclass.GetX() == 42, "GetX() should return 42"

Or should I create the object in the Unit Test?:

class TestComplexClass(object):
    def test_GetX(self, complexclass):
        // do some stuff

        cc = ComplexClass()
        try:
            cc.start()
            assert cc.GetX() == 42, "GetX() should return 42"
        except AssertionError:
            cc.stop
            raise

(Note I'm using Py.Test)


texts: UserInfo information class with a database

texts:
I am no expert in C#, the opposite really, I just wanted an overall review on my UserInfo class that gets user information from a database using MySQL. I was also wondering if it is a good idea to really process the data in the way I did, getting everything from the database, even the things that aren't needed. But I think this way is a lot more tidy and neat. I was just wondering what you would say about it.

using MySql.Data.MySqlClient;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Scratch.Application.Habbo.Users
{
    class UserInfo
    {
        private Dictionary<string, string> _userInfo;

        public UserInfo(int Id)
        {
            this._userInfo = new Dictionary<string, string>();

            using (var DbCon = Scratch.GetEnvironment().GetDatabase().GenerateNewConnection())
            {
                DbCon.AssignQuery("SELECT * FROM `users` WHERE `id` = @id");
                DbCon.RegisterParameter("id", Id);
                DbCon.OpenConnection();

                using (MySqlDataReader Reader = DbCon.ExecuteReader())
                {
                    if (Reader.HasRows)
                    {
                        while (Reader.Read())
                        {
                            for (int index = 0; index < Reader.FieldCount; index++)
                            {
                                //bypass duplicate error, just replaces if duplicate
                                this._userInfo[Reader.GetName(index)] = Reader.GetString(index);
                            }
                        }
                    }
                }
            }
        }

        private void UpdateData(string Key, string NewValue)
        {
            if (this._userInfo.ContainsKey(Key))
                this._userInfo.Add(Key, "");

            this._userInfo[Key] = NewValue;
        }

        public string GetString(string Key)
        {
            return this._userInfo[Key];
        }

        public int GetInt(string Key)
        {
            return int.Parse(this._userInfo[Key]);
        }
    }
}


texts:
In view of the recent LinkedIn breach, would anyone care to review my data access routines relating to user access?

This is a standard node.js module, accessing a Postgres database.

(function () {

    'use strict';

    var crypto = require('crypto'),
        hash = function (pass, salt) {
            var h = crypto.createHash('sha512');

            h.update(pass);
            h.update(salt);

            return h.digest('base64');
        };

    module.exports.getUser = function (conn, email, password, callback) {
        conn.query({
            name: 'getUser',
            text: 'SELECT "id", "passwordHash" FROM "user" WHERE "email" = $1 LIMIT 1',
            values: [email]
        }, function (err, result) {
            if (err) {
                throw err;
            }
            if (result.rows.length === 0) {
                callback(null);
            } else {
                var newHash = hash(password, email),
                    row = result.rows[0];

                if (row.passwordHash === newHash) {
                    callback({id: row.id, email: email});
                } else {
                    callback(null);
                }
            }
        });
    };

    module.exports.addUser = function (conn, email, password, callback) {
        var newHash = hash(password, email);

        conn.query({
            name: 'addUser',
            text: 'INSERT INTO "user" ("email", "passwordHash") VALUES ($1, $2) RETURNING "id"',
            values: [email, newHash]
        }, function (err, result) {
            var id;

            if (err) {
                console.error(err);
                callback(null);
            } else {
                id = result.rows[0].id;

                callback({id: id, email: email});
            }
        });
    };

}());


texts: Check whether all checkboxes are checked and then execute a function

texts:
How could I make this code dry?

$("#btnSubmitToCheckOut").click(function(event) {
        var isSelected = [];

        $(".age_agree :checkbox").each(function() {
            if ($(this).is(":checked")) {
                isSelected.push("true");
            } else {
                isSelected.push("false");
            }
        });

        if ($.inArray("false", isSelected) < 0) {
            $(this).parents('form').submit();
        } else {
            alert('Please accept all the Terms and Conditions');
        }

    });


texts: Sending a file in servlet response, using a class inside a method

texts:
I am processing file inside my method - basically preparing it for the download.

But I decided to split actions for setting headers and reading bytes.
As Java does not support method declaration inside methods, I decided to go with class inside method.

public static String downloadFile(final String fileBody, HttpServletResponse response) {
    class FileDownloader {

        private static final String HEADER_KEY = "Content-Disposition";
        private static final String HEADER_VALUE = "attachment; filename=\"%s\"";
        private static final String TEMPLATE_FILE_NAME = "filename.html";

        private void setHeader(HttpServletResponse response) {
            response.setHeader(HEADER_KEY, String.format(HEADER_VALUE, TEMPLATE_FILE_NAME));
        }

        public void processResponse(HttpServletResponse response) throws IOException {
            byte[] bytes = fileBody.getBytes();
            IOUtils.copy(new ByteArrayInputStream(bytes), response.getOutputStream());
            setHeader(response);
        }
    }

    try {
        new FileDownloader().processResponse(response);
        return StringUtils.EMPTY;
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    }
}

But I am not sure whether the idea I've come up with is good or bad. Basically there is no reason for method separation because they are not doing a lot of work.


texts:
This is from a flex app that is for quizzing. It calls the database for the question and then checks to see if it has been tagged (bookmarked) by a user already. "Question" is a value object and "Tag" is also a value object.

I just wanted to post it to see how it could be better. It works fine, but I feel that since I am new to this, it probably isn't best.

public function getQuestionByNumber($itemNum, $userID) {
    $stmt = mysqli_prepare($this->connection,
          "SELECT
                        questions.id, questions.question_number, questions.chapter_id, questions.section_id,
                        questions.question_txt, questions.answers, questions.feedbacks, questions.correct_answer,
                        questions.question_type, questions.module, questions.shuffle_answer,
                        questions.tags
           FROM questions where questions.question_number=?");
      $this->throwExceptionOnError();

      mysqli_stmt_bind_param($stmt, 'i', $itemNum); $this->throwExceptionOnError();

      mysqli_stmt_execute($stmt); $this->throwExceptionOnError();

      $row = new Question();

      mysqli_stmt_bind_result($stmt, $row->id, $row->question_number, $row->chapter_id, $row->section_id,
                                        $row->question_txt, $row->answers, $row->feedbacks, $row->correct_answer,
                                        $row->question_type, $row->module, $row->shuffle_answer, $row->tags);

          if (mysqli_stmt_fetch($stmt)) {

              } else {
                          return null;
                  }
            mysqli_stmt_free_result($stmt);
            mysqli_stmt_close($stmt);

    $stmt2 = mysqli_prepare($this->connection,
          "SELECT
                        id
           FROM tagged where user_id =? && question_number=?");
      $this->throwExceptionOnError();

      mysqli_stmt_bind_param($stmt2, 'ii', $userID, $itemNum);
      $this->throwExceptionOnError();

      mysqli_stmt_execute($stmt2);
      $this->throwExceptionOnError();

      $tag = new Tag();

      mysqli_stmt_bind_result($stmt2, $tag->id);

      if (mysqli_stmt_fetch($stmt2)) {
                  $row->tagged = $tag->id;
                  return $row;
      } else {
                  $row->tagged = 0;
                  return $row;
          }

      mysqli_stmt_free_result($stmt2);
      mysqli_close($this->connection);

}


texts: AWS Lambda Function to Register in Cognito

texts:
This is the entire code for a Lambda function that registers a new user in Amazon Cognito.

The email, username, and password are passed to the Lambda function.  The client ID is stored in an environment variable to be removed from the code.

const AWS = require("aws-sdk");
const cognitoidentityserviceprovider = new AWS.CognitoIdentityServiceProvider();

const clientID1 = process.env.client_id;

function registerUser(client, password, username, email){
  var params = {
   ClientId: client, /* required */
   Password: password, /* required */
   Username: username, /* required */
   UserAttributes: [
     {
       Name: 'email',
       Value: email
     }
   ]
  };
  cognitoidentityserviceprovider.signUp(params, function(err, data) {
   if (err) console.log(err, err.stack); // an error occurred
   else{
    console.log(data);           // successful response
    return data;
   }
  });
}

function verifyInput(e){
 let data = {};
 try{
  data.password = e.password;
  data.username = e.username;
  data.email = e.email;
 } catch (e) {
   console.error(e);
   return false;
 }
 if (data.password === undefined) return false;
 if (data.username === undefined) return false;
 if (data.email === undefined) return false;
 return data;
}

exports.handler = (event, context, callback) => {
   let check = verifyInput(event);
   if (check === false) return callback(null, "Registration Failed");
   let data = registerUser(clientID1, event.password, event.username, event.email);
   callback(null, "Registration Successful");
};

Note: I am aware that returning the data object from the verifyInput function is currently useless.  I left it in for now as I thought there may need to still be some checks on the parameters at this stage.

Why I am using Lambda for the login?
I have created a login system a couple of times (not sure how well) but would like to start using Cognito.  For implementing on websites the JavaScript SDK seems to be best supported/documented.  For simple/small/static sites I'd prefer not to implement a JavaScript backend but AWS PHP SDK doesn't seem to be well supported or documented and without working examples for a Cognito login.  So I figured I could use NodeJS Lambda Functions to use the well supported JavaScript SDK then have PHP access them through an Amazon API Gateway.


texts: WordPress MU generate navigation from all sites with current site highlighted

texts:
I'm wondering if this is the most efficient way to generate a navigation in WordPress MU that contains links to all sites, with the current site highlighted.

Also looking for any advice on PHP style and structure, particularly when outputting HTML.

$dmc_current_site = get_current_blog_id();
$dmc_sites = get_sites();
if ( $dmc_sites ) {
    ob_start();
    ?>

            <?php
            foreach ( $dmc_sites as $dmc_site ) {

                $dmc_site_id = get_object_vars( $dmc_site )['blog_id'];
                $dmc_site_path = get_blog_details( $dmc_site_id )->path;
                $dmc_site_name = str_replace( '/','', $dmc_site_path );

                $dmc_active = 'class="active"';
                ?>
                <li
                    <?php
                    if ( $dmc_current_site == $dmc_site_id ) {
                        echo $dmc_active;
                    }
                    ?>
                >
                    <a href="<?php echo $dmc_site_path; ?>"><?php echo $dmc_site_name; ?>

            <?php
            } // end foreach
            ?>

    <?php
    $output = ob_get_clean();
    echo $output;
}


texts:
I have this piece of Ruby code:

HTTPCLIENT = HTTPClient.new

def read_page(url)
  HTTPCLIENT.get(url).body
end

The HTTPClient object is being created and declared as a constant, and thus it can be accessible by methods.

I would do this by declaring it as a global variable ($) or as a class variable (@), but I'm not sure if it's actually wrong the way it is.

I don't declare objects as variables because, well, their memory contents can vary. I only use constants to declare simple types (strings, numbers) or classes and modules. But objects? I'm not sure about it.

My question is: is this a bad code or it's just me? If so, then why do you think is a bad code?


texts:
I am using the following code to retrieve the URL of a random image in a remote folder that I own.

As a newbie and although this is working I would like to know if this is done properly, if it could be improved and if there is any security issue with this approach.

I am using json_encode and json_decode because I need to have an array as response. Also I am passing $params to remote through cURL because I need the returned image already with it's URL.

Thank you.

if (function_exists('curl_init')){
    $url    = 'http://example.com/images';
    $params = 'path=' . $url;

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url . '/my_remote_script.php');
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
    curl_setopt($ch, CURLOPT_HEADER, false);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

    $images = json_decode(curl_exec($ch));

    curl_close($ch);
}

my_remote_script.php

if (!$_POST['path']){
    die;
}

function getImages($path){
    if ($img_dir = opendir(dirname(__FILE__))){
        $images = array();

        while (($img_file = readdir($img_dir)) !== false){
            if (preg_match('/(\.gif|\.jpg|\.jpeg|\.png|\.GIF|\.JPG|\.JPEG|\.PNG)$/', $img_file)){
                $images[] = $path . '/' . $img_file;
            }
        }

        closedir($img_dir);
        return $images;
    }
}

function randomImage($list){
    $num   = array_rand($list);
    $image = $list[$num];

    return $image;
}

$images = getImages($_POST['path']);
$image  = randomImage($images);

print_r(json_encode($image));


texts: Nesting BsonDocuments in MongoDB queries

texts:
I have a MongoDB collection setup where each document's JSON looks like this:

{
    "_id" : "Stuff",
    "project_id" : "1234",
    "VehicleEntry" : [
        {
            // Irrelevant fields removed.
            "VehicleStatus" : "PASSED"
        },
        {
            // Irrelevant fields removed.
            "VehicleStatus" : "FAILED"
        }
    ]
}

I want to write a query that gives me the number of vehicles passed and failed for each project identifier. I have done so in this very long aggregation query:

var aggregate = collection.Aggregate()
    .Match(new BsonDocument
    {
        {
            "project_id", "1234"
        }
    })
    .Unwind(i => i["VehicleEntry"])
    .Group(new BsonDocument
    {
        {
            "_id", "$project_id"
        },
        {
            "passed", new BsonDocument
            {
                {
                    "$sum", new BsonDocument
                    {
                        {
                            "$cond", new BsonArray
                            {
                                new BsonDocument
                                {
                                    {
                                        "$eq", new BsonArray
                                        {
                                            "$VehicleEntry.VehicleStatus",
                                            "PASSED"
                                        }
                                    }
                                },
                                1,
                                0
                            }
                        }
                    }
                }
            }
        },
        {
            "failed", new BsonDocument
            {
                {
                    "$sum", new BsonDocument
                    {
                        {
                            "$cond", new BsonArray
                            {
                                new BsonDocument
                                {
                                    {
                                        "$eq", new BsonArray
                                        {
                                            "$VehicleEntry.VehicleStatus",
                                            "FAILED"
                                        }
                                    }
                                },
                                1,
                                0
                            }
                        }
                    }
                }
            }
        }
    });

While it works as expected, this seems very difficult to maintain and has even become unreadable. How can I improve the way this is written to be more maintainable?

If it's relevant to a better solution, I already have the Newtonsoft library in my project as I use it to convert Json to Bson.

EDIT I have been told I could serialize Bson to do this, but I am not familiar with the concept. What are some best practices for that and how can I convert this query to use serialized bson?


texts: Pick sequences of numbers to maximize the points

texts:
It is a single-player game. In the beginning, there is a row of integers. In one move the player can take a certain amount of adjacent numbers (let's denote it T). Then the player's points increase with the sum of the chosen numbers. The player can take S moves at most. The goal is to determine the maximum points that can be reached and we have to give the specific moves to reach it.

Example

The numbers: 1 6 8 7 6 2 1 8
S = 2 (max moves)
T = 3 (adjacent numbers to take in one move)

The max points is 32, it can be done like this:
1 6 8 7 6 2 1 8 (we take the bold numbers)
So the two moves are 2 and 6 (they indicate start indexes in the row)
I wrote a recursive code in c# that works if we have few numbers, but takes too long if e.g. has 3000 numbers, 100 max moves and T = 20.

My idea is to first count the points we will get for each number. Then try every possible combination, and store the one that gives me the most points.
So my question is how it can be made it faster?

class Value
{
    public int idx = -1;
    public int num = -1;
    public Value(int idx, int num)
    {
        this.idx = idx;
        this.num = num;
    }
}

class Program
{
    const int N = 8;
    static int S = 2;
    static int T = 3;
    static int[] numbers = new int[N] { 1, 6, 8, 7, 6, 2, 1, 8 };
    static List<Value> values = new List<Value>();
    static int maxPoint = -1;
    static List<Value> result;

    static void Main(string[] args)
    {
        CountInitValues();
        Solve(values, new List<Value>(), 0, T);
    }

    static void Solve(List<Value> remaining, List<Value> numSoFar, int pointSoFar, int StepsRemain)
    {
        if (remaining.Count == 0 || StepsRemain == 0)
        {
            if (pointSoFar > maxPoint)
            {
                maxPoint = pointSoFar;
                result = new List<Value>(numSoFar);
            }
        }
        else
        {
            List<Value> newNum = new List<Value>(numSoFar);
            for (int i = 0; i < remaining.Count; i++)
            {
                List<Value> newRemaining = new List<Value>();
                newNum.Add(remaining[i]);
                newRemaining.AddRange(remaining.Take(i - T));
                newRemaining.AddRange(remaining.Skip(i + T));
                int ujPont = pointSoFar + remaining[i].num;
                int ujLepes = StepsRemain - 1;
                Solve(newRemaining, newNum, ujPont, ujLepes);
                newNum.RemoveAt(newNum.Count - 1);
            }
        }
    }

    static void CountInitValues()
    {
        for (int i = 0; i < N - T + 1; i++)
        {
            int newValue = 0;
            for (int j = 0; j < T; j++)
            {
                newValue += numbers[i + j];
            }
            Value ee = new Value(i, newValue);
            values.Add(ee);
        }
    }
}


texts: Find the noun phrase before and after a number in a text

texts:
Given a text I have to find the preceding words to all numbers up to a stop word belonging to a check_words list (kind of stopwords).
My code:
check_words = ['the', 'a', 'with','to']
mystring = 'the code to find the beautiful words 78 that i have to nicely check 45 with the snippet'
list_of_words = mystring.split()

In that particular text I would check before '78' and '45' and will go backwards up to the point where I find any of the words in check_words (but not more than 8 words).
The code for doing that might be:
preceding_chunks = []
for i,word in enumerate(list_of_words):
    if any(char.isdigit() for char in word):

        # 8 precedent words (taking into account that I can not slice with 8 back at the beginning)
        preceding_words = list_of_words[max(0,i-8):i]
        preceding_words[::-1]

        # I check from the end of the list towards the start
        for j,sub_word in enumerate(preceding_words[::-1]):
            if  sub_word in check_words:
                # printing out j for checking
                myposition = j
                print(j)
                real_preceding_chunk = preceding_words[len(preceding_words)-j:]
                print(real_preceding_chunk)
                preceding_chunks.append(real_preceding_chunk)
                break

This code works.
basically I check every word tha
But I have the impression (perhaps I am wrong) that it can be achieved with a couple of one liners and hence without loops.
Any idea?

NOTE:
This question is about improvement the readability of the code, trying to get rid of the loops to make the code faster, and trying to make the code nicer, which is part of the Zen of Python.

NOTE 2: Some previous checks that I did:

Finding the position of an item in another list from a number in a different list
Finding the index of an item in a list
Find in list


texts:
Here is a working Python implementation of primality test. Is there something that I could change in code to achieve a better running time? For more information about algorithm see this post.

from sympy import *
from sympy.abc import x

n=int(input("Enter a number : "))

def xmat(r,n):
    return Matrix([[2*x, -1], [1, 0]])*rem(1,x**r-1)*(1%n)

def smallestr(n):
    if n==1 or n%2==0:
        return 0
    else:
        r=3
        while r<1000000:
            u=n%r
            if u==0 and r<n:
                return 0
            elif not(u==0) and not(u==1) and not(u==r-1):
                return r
            else:
                r=nextprime(r)

def myisprime(n):
    r=smallestr(n)
    if r==0:
        return n==2
    else:
        xp=(xmat(r,n)**n)*Matrix([[x],[1]])
        return trunc(xp[1],n)==(rem(x*(1%n),x**r-1))**n

if myisprime(n):
    print("prime")
else:
    print("composite")

You can run this code here.

EDIT

To clarify things, this Python code represents my attempt to translate the following PARI/GP code which is very fast.


texts: Split large file into smaller files, keeping headers and footers

texts:
I have a folder of SQL files which I need to loop through and:

Determine if any of the files are over 20MB
If so, split them into multiple files, max 20MB filesize

However, there's a complication in that the original large file will have a header and a footer which needs to be included (and slightly tweaked) in each one of the broken down files.

Here is a graphical representation, if it helps. It's based on one file in particular, which is 130MB, with around 1.8m rows

Of course I’m very happy to receive any and all feedback about my code. However, my main issue is that my current code takes around 20 minutes to break this main file into seven smaller counterparts. Therefore, any speed improvements would be fantastic!

Option Explicit

Private Type TFile
    Path As String
    Name As String
    Extension As String
    FullPath As String
    Size As String
    Data() As String
    CurrentBodyPosition As Long
    HeaderStart As Long
    HeaderEnd As Long
    FooterStart As Long
    FooterEnd As Long
End Type
Private File As TFile

Public Sub SplitLargeFiles()
    Dim newFile As String
    Dim i As Long, j As Long, numberOfNewFiles As Long, rowsPerNewFile As Long

    With File
        .HeaderStart = 0 'header always in the same position
        .HeaderEnd = 11
        .CurrentBodyPosition = .HeaderEnd + 1
        .Path = "\\...\"
        .Extension = ".sql"
        .Name = Replace(Dir(.Path & "*" & .Extension), .Extension, "") 'name only, no extension
    End With

    Do While Len(File.Name) > 0
        File.FullPath = File.Path & File.Name & File.Extension
        File.Size = FileLen(File.FullPath) / 1000000 'filesize in MB
        Debug.Print File.Size

        If File.Size >= 20 Then

            With File
                'open file, transfer data to an array and close it
                Open .FullPath For Input As #1
                .Data = Split(input(LOF(1), #1), vbNewLine)
                .Data(0) = Replace(.Data(0), .Name, .Name & "_0") 'specific tweak to data
                Close #1

                'now assign footer positions
                .FooterStart = UBound(.Data) - 5
                .FooterEnd = UBound(.Data)
            End With

            'determine how many files to split the data across, and hence how many rows each new file needs
            numberOfNewFiles = WorksheetFunction.RoundUp(File.Size / 22, 0) '22 gives a buffer over 20
            rowsPerNewFile = (CLng(UBound(File.Data)) - CLng(18)) / numberOfNewFiles

            For i = 1 To numberOfNewFiles
                newFile = File.Path & File.Name & "_" & i & File.Extension
                Open newFile For Output As #2

                'make iterative tweak to first row of header data
                File.Data(0) = Replace(File.Data(0), "_" & (i - 1), "_" & i)

                'transfer header data
                For j = File.HeaderStart To File.HeaderEnd
                    Print #2, File.Data(j)
                Next j

                'transfer body of data
                For j = 1 To rowsPerNewFile
                    If File.CurrentBodyPosition < File.FooterStart Then
                        Print #2, File.Data(File.CurrentBodyPosition)
                        File.CurrentBodyPosition = File.CurrentBodyPosition + 1
                    Else
                        Exit For
                    End If
                Next j

                'transfer footer data
                For j = File.FooterStart To File.FooterEnd
                    Print #2, File.Data(j)
                Next j

                Close #2
            Next i
        End If
        File.Name = Replace(Dir(), File.Extension, "")
    Loop
End Sub


texts:
I'm primarily looking for ways to increase the performance of my code.

It is used to transform mesh data from blender into a format I can use and then save it to a file.

First it collects the colors of each vertex with an index to reference them, then for each of the vertices it writes its coordinates followed by its average color. The last part decides if each polygon is a triangle or a rectangle and writes the indices of each of its vertices, while converting rectangles to 2 triangles.

import bpy
mesh = "mesh"
filepath = "filepath"
out = open(filepath, 'w')
m = bpy.data.meshes[mesh]
colData = m.vertex_colors["Col"].data
colors = []
index = []
for pol in m.polygons:
    count = 0
    for li in pol.loop_indices:
        for rgb in colData[li].color:
            colors += [rgb]
        index += [pol.vertices[count]]
        count += 1
for ver in m.vertices:
    indices = [i for i, x in enumerate(index) if x == ver.index]
    for f in ver.co:
        out.write(str(f)+' ')
    for f in range(3):
        c = 0
        for i in indices:
            c += colors[i*3+f]
        c = c/len(indices)
        out.write(str(c)+' ')
    out.write('\n')
out.write('\n')
for pol in m.polygons:
    if len(pol.vertices)==3:
        for i in pol.vertices:
            out.write(str(i)+' ')
    else:
        for i in pol.vertices[:3]:
            out.write(str(i)+' ')
        for i in pol.vertices[2:]:
            out.write(str(i)+' ')
        out.write(str(pol.vertices[0])+' ')
    out.write('\n')
out.write('\n')
out.close()


texts:
How can I make my code for Project Euler #4 more efficient and cleaner?

Project Euler #4: Largest palindrome product:

  A palindromic number reads the same both ways. The largest palindrome
  made from the product of two 2-digit numbers is 9009 = 91 × 99.

  Find the largest palindrome made from the product of two 3-digit
  numbers.

public class LargestPalindromeProduct {
    public static void main(String[] args) {

        int product = 0;
        int largest = 0;
        for (int first = 1; first < 1000; first++) {
            for(int second = 1; second < 1000; second++) {
                product = first * second;
                if ((product / 100000) % 10 == product % 10 && product / 10000 % 10 == product / 10 % 10 && product / 1000 % 10 == product / 100 % 10) {
                    //System.out.println(product);
                    if (product > largest) {
                        largest = product;

                    }
                }

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


texts: Compare two map objects and show relative information Java 8

texts:
I have 2 maps. First map consists of order in which a specific set of services is executed. Second map contains execution time  each service took. I need to display this information.
Following is my piece of code. How can this be improved by performance and syntax?

public static String getAllExecTimes(MasterVO masterVO, boolean displayAll) {
    StringBuilder builder = new StringBuilder();

    Map<Integer, DurationVo> durationMap = null;
    Map<Integer, Integer> orderMap = null;
    List<Integer> keys = null;

    if (displayAll) {
        builder.append("\nSection A\n");
        durationMap = masterVO.getMapA();
        orderMap = masterVO.getOrderMap();

        keys = new ArrayList<>(orderMap.keySet());
        keys.sort(new CustomComparator());

        for (Integer execOrder : keys) {
            Integer target = orderMap.get(execOrder);
            if (null != target) {
                builder.append(durationMap.get(target));
            }
        }

        if (null != masterVO.getMapB()) {
            builder.append("\nSection B\n");
            durationMap = masterVO.getMapB();
            keys = new ArrayList<>(durationMap.keySet());
            for (Integer target : keys) {
                builder.append(durationMap.get(target));
            }
        }
    }

    durationMap = masterVO.getMapC();
    keys = new ArrayList<>(durationMap.keySet());
    keys.sort(new CustomComparator());

    builder.append("\nFinal Section\n");

    for (Integer target : keys) {
        builder.append(durationMap.get(target));
    }

    return builder.toString();
}

private static final class CustomComparator implements Comparator<Integer> {

    public int compare(Integer first, Integer second) {
        return first.compareTo(second);
    }
}


texts: Find number of horizontal brush strokes to paint a skyline

texts:
Asked in interview today:

You want to paint a skyline on your wall using only horizontal brush strokes. You are given an array of numbers, each representing the size of the column/building in that position. E.g. [1,2,1] - you can use two (horizontal) brush strokes. The first will paint the entire first row, and the second will paint the middle of the 2nd column.

Write an efficient algorithm to do so.

Here's my solution - idea being you count each end of strokes, and wipe out a row (or go up a row) for every iteration:

def solution(A):
    strokes = 0
    copy = [a for a in A]
    while sum(copy) > 0:
        for i in range(len(copy)):
            if (copy[i] > 0) and ((i+1 == len(copy)) or (copy[i+1] == 0)):
                strokes += 1
            if copy[i] > 0:
                copy[i] -= 1
    return strokes

solution([1,0,5,8,0]) will output 9


texts:
I was thinking about using very basic bounded (preallocated) stack to keep track of my threads IDs in correct LIFO order. I was wondering if my implementation is thread safe:

// we use maximum 8 workers
size_t idle_ids_stack[8];
// position current write happening at
std::atomic_uint_fast8_t idle_pos(0);

// this function is called by each thread when it is about to sleep
void register_idle(size_t thread_id)
{
    std::atomic_thread_fence(std::memory_order_release);
    idle_ids_stack[idle_pos.fetch_add(1, std::memory_order_relaxed)] = thread_id;
}

// this function can be called from anywhere at anytime
void wakeup_one()
{
    uint_fast8_t old_pos(idle_pos.load(std::memory_order_relaxed));
    std::atomic_thread_fence(std::memory_order_acquire);
    size_t id;
    do
    {
        if(old_pos == 0) return; // no idle threads in stack; exit;
        id = idle_ids_stack[old_pos-1];
    }
    while (!idle_pos.compare_exchange_weak(old_pos, old_pos-1, std::memory_order_acquire, std::memory_order_relaxed));
    // wakeup single thread
    signal_thread(id);
}

Please see latest changes: Gist


texts:
I wrote a script which changes names of last downloaded songs and copy them to music directory. Can it be written better?

    #!/bin/bash
IFS=$'\n'
for file in $(find "/home/stanek/Downloads/" -iname "*.mp3" -mtime -7 | sort)
do
    nowy=$(echo $file \
    | sed "s/_/ /g" \
    | sed "s/\s*(*[A-z0-9.]*.pl)*//g" \
#leave brackets and text if it is remix
    | sed "s/\(\s*(\s\?[A-z0-9 ]*remix)\)\|\s*(\s\?[a-z0-9. ]*)/\1/gi")

    if [ "$nowy" != "$file" ]
    then
        echo "ZMIANA NAZWY DLA:"
        echo $nowy
        mv $file $nowy
    fi
done

for file in $(find "/home/stanek/Downloads/" -iname "*.mp3" -mtime -7 | sort)
do
    echo "I will copy: $file" | sed "s/\/home\/stanek\/Downloads\///g"
done
read -p "Is it ok? (y)" -n 1 -r
echo
if [[ ! $REPLY =~ ^[Yy]$ ]]
then
    exit 1
fi

i=0

for file in $(find "/home/stanek/Downloads/" -iname "*.mp3" -mtime -7 | sort)
do
    paste=$(echo $file | sed "s/\/home\/stanek\/Downloads\///g")
    cp $file "/home/stanek/Music/$paste"
    i=$((i+1))
done
echo "Copied $i files"


texts: Program to display array elements in the ascending order of number of factors each element has

texts:
Input:

1000 23 100 26 32

Output:

23  26  32  100 1000

Since 23 has '2' factors and 26 has '4' factors and 32 has '6' factors, and so on.

Should I use a linked list for these types of problems?
Is my code efficient? Or how can it be optimized?

Code:

#include <stdio.h>
#include <stdlib.h>

int facts(int);

int main(void) {
    int n,a[2][25],i,j;
    printf("Enter the no. of items\n");
    scanf("%d",&n);
    printf("Enter the items\n");
    for(j=0; j<n; j++)
    {
        scanf("%d",&a[0][j]);
    }
    for(j=0; j<n; j++)
    {
        a[1][j] = facts(a[i][j]);
    }

    for(int x=0; x<n; x++)
    {
        for(int y=0; y<n-1; y++)
        {
            if(a[1][y]>a[1][y+1])
            {
                int temp = a[1][y+1];
                int temp1 = a[0][y+1];
                a[1][y+1] = a[1][y];
                a[0][y+1] = a[0][y];
                a[1][y] = temp;
                a[0][y] = temp1;
            }
        }
    }

    for(j=0; j<n; j++)
        {
            printf("%d\t", a[0][j]);
        }

    return 0;
}

int facts(int h)
{
    int factors=0;
    for(int k=1; k<=h; k++)
    {
        if((h%k)==0)
        {
            factors++;
        }
    }
    return factors;
}


texts: Maximum absolute difference of array elements

texts:
I am trying to solve a question from array section:

  You are given an array of N integers, A1, A2 ,…, AN. Return maximum
  value of f(i, j) for all 1 ≤ i, j ≤ N.
        f(i, j) is defined as |A[i] - A[j]| + |i - j|, where |x| denotes absolute value of x.

  For example

A=[1, 3, -1]

f(1, 1) = f(2, 2) = f(3, 3) = 0
f(1, 2) = f(2, 1) = |1 - 3| + |1 - 2| = 3
f(1, 3) = f(3, 1) = |1 - (-1)| + |1 - 3| = 4
f(2, 3) = f(3, 2) = |3 - (-1)| + |2 - 3| = 5

  So, we return 5.

I solved the problem correctly, however my solution is not the optimized one. Here is my solution:

public int maxArr(List<int> A) {
    if (A==null || A.Count<=0) return 0;

    int sum = 0;
    int maxSum = 0;
    for (int i = 0; i<A.Count; i++)
    {
        for (int j= A.Count-1; j>i;j--)
        {
            sum = Math.Abs(A[i]-A[j]) + Math.Abs(i-j);
            if (sum > maxSum) maxSum = sum;
        }
    }

    return maxSum;
}

So I understand with bigger lists or arrays nested loops might not be a good idea, but what can I do to optimize this solution?

Update: I also tried removing nested loops

public int maxArr(List<int> A) {
    if (A==null || A.Count<=0) return 0;

    int sum = 0;
    int maxSum = 0;
    for (int k = 0; k<(A.Count)*(A.Count); k++)
    {
        int i = k/A.Count;
        int j = k%A.Count;

            sum = Math.Abs(A[i]-A[j]) + Math.Abs(i-j);
            if (sum > maxSum) maxSum = sum;

    }

    return maxSum;
}

Still this exceeds time limit.


texts:
This function derives a 'stars' rating from a product score that is retrieved from local storage.  What would be the best way to refactor these else if statements?

    $scope.ratingStars = function(productID) {

        var bottomLine = $filter('filter')($localStorage.bottomlinesObject.bottomlines, {domain_key:''+productID})//jshint ignore:line

        if(bottomLine.length > 0) {

            if (bottomLine[0].product_score === 'undefined') {return 0;}//jshint ignore:line
            else if(bottomLine[0].product_score > 0 && bottomLine[0].product_score <=1.5)  {return 1;}// jshint ignore:line
            else if(bottomLine[0].product_score > 1.5 && bottomLine[0].product_score <=2) {return 2;}//jshint ignore:line
            else if(bottomLine[0].product_score > 2 && bottomLine[0].product_score <=2.5) {return 2.5;}//jshint ignore:line
            else if(bottomLine[0].product_score > 2.5 && bottomLine[0].product_score <=3.2) {return 3;}//jshint ignore:line
            else if(bottomLine[0].product_score > 3.2 && bottomLine[0].product_score <=3.7) {return 3.5;}//jshint ignore:line
            else if(bottomLine[0].product_score > 3.7 && bottomLine[0].product_score < 4.3) {return 4;}//jshint ignore:line
            else if(bottomLine[0].product_score >= 4.3 && bottomLine[0].product_score < 4.75) {return 4.5;}//jshint ignore:line
            else if(bottomLine[0].product_score >= 4.75 && bottomLine[0].product_score < 5) {return 5;}//jshint ignore:line
            else if(bottomLine[0].product_score >= 5) {return 5;}// jshint ignore:line

        }

        else {return 0;}

    };


texts:
When you own an Android device and want your iTunes playlist to be copied over onto it, what do you do?

What if your playlist hits something in the region of 20GB+ ? Well, I am sure I could've paid for a tool, to do this for me and keep things in sync, but I wanted to challenge myself into writing something in Python to resolve it.

I tried dragging and dropping the files on the playlist onto the phone via Android Device Manager and often found it would just hang. This is what I ended up with:

from xml.etree.ElementTree import ElementTree
import os
from shutil import copyfile
import urllib

srcfile = "/path/to/playlist.xml"
dst = '/path/to/destination';
overwrite = 0

tree = ElementTree()
tree.parse(srcfile)
songs = tree.findall('/dict/dict/dict/string')

# Run through all the found elements
for song in songs:
    # Is this element a file?
    if song.text[0:7] == "file://":

        # Grab everything after file://
        myfile = urllib.unquote(song.text[7:])

        # Grab the filename without the path
        basefile = os.path.basename(myfile)

        # Grab the last dirname
        dirname = myfile.split('/')[-2]

        # If the dir does not exist on the destination, create it
        if not os.path.exists(dst+dirname):
            os.mkdir(dst+dirname)

        # Create the final filename
        dstFile = dst + dirname + '/' + basefile

        # If the file exists and we have chosen to not overwrite it, dont copy the file
        if os.path.exists(dstFile) and not overwrite:
            print "Skipping " + myfile
        else:
            copyfile(myfile, dst + dirname + '/' + basefile)
            print "Copying " + myfile

print "Finished...."

I have found a bug in it when copying over bands or songs with UTF-8 names in it e.g. Fantômas. Because the UTF-8 elements are encoded in the Playlist XML the names do not match the directory so I need to fix that. Have kept a copy on Gist, so if you want a copy go grab/comment/whatever. I'm new to Python so any feedback is welcome on better ways to do things.


texts: Projecteuler.net Problem 2 using collection pipeline Pattern

texts:
I solve projecteuler.net Problem 2  deferent way

Generate number from 1 to range ex 100  and get the even number
Get Fibonacci numbers from list
Reduce array

I have one problem with a large set of numbers like 1000000 or 4000000.
can I ask how can I optimize the code? I am trying to solve the problem as a collection pipeline
swift code
var evenArray = ((0..<100).filter({$0 % 2 == 0}))

print(evenArray)

var evenFibArray = evenArray.filter {(isPerfectSquare(5 * $0 * $0  + 4) || isPerfectSquare(5 * $0 * $0  - 4))}

print(evenFibArray)

var result  = evenFibArray.reduce(into: 0){$0 += $1}

print(result)

func isPerfectSquare(_ x:Int ) -> Bool {
    let i = Int(sqrt(Double(x)))
    return  (i * i == x)
}


texts:
I've made a few things in Java, and now I'm learning C#.
The code passes the tests with 100% final score. I want to know what things can be improved in my code.

  Task description

  A non-empty array A consisting of N integers is
  given.

  A permutation is a sequence containing each element from 1 to N once,
  and only once.

  For example, array A such that:

A[0] = 4
A[1] = 1
A[2] = 3
A[3] = 2 is a permutation, but array A such that:

A[0] = 4
A[1] = 1
A[2] = 3 is not a permutation, because value 2 is missing.

  The goal is to check whether array A is a permutation.

  Write a function:

  class Solution { public int solution(int[] A); }

  that, given an array A, returns 1 if array A is a permutation and 0 if
  it is not.

  For example, given array A such that:

A[0] = 4
A[1] = 1
A[2] = 3
A[3] = 2 the function should return 1.

  Given array A such that:

A[0] = 4
A[1] = 1
A[2] = 3 the function should return 0.

  Write an efficient algorithm for the following assumptions:

  N is an integer within the range [1..100,000]; each element of array A
  is an integer within the range [1..1,000,000,000].

public static int solution(int[] A)
{
    int[] orderedPermut = new int[A.Length];
    int[] unrepeated = new int[A.Length];
    int orderedPermutSum = 0, unrepeatedSum = 0;
    for ( int i = 0; i < A.Length; i++ )
    {
        orderedPermutSum += i + 1;
        orderedPermut[i] = i + 1;
        if ( A[i] >= A.Length + 1 || unrepeated[ A[i] - 1 ] != 0 )
            /*number is greater than A's length, or it's repeated,
            /*therefore,A's not a permutation.*/
            return 0;
        else
        {
            unrepeated[A[i] - 1] = A[i];
            unrepeatedSum += A[i];
        }
    }
    if ( orderedPermutSum == unrepeatedSum )
    {
        return 1;
    }
    return 0;
}


texts: An alternative algorithm for sorting a stack using only one additional stack

texts:
From "Cracking the Coding Interview":

  Write a program to sort a stack in ascending order (with biggest items on top). You may use at most one additional stack to hold items, but you may not copy the elements into any other data structure (such as an array). The stack supports push, pop, is_empty, and peek

The classic solution I found online to this (and the one in the book) is something like this:

Algo #1 (Classic)

 def sort_stack(primary):
   secondary = []
   while primary:
     tmp = primary.pop()
     while (secondary and secondary[-1] > tmp):
       primary.append(secondary.pop())
     secondary.append(tmp)
   return secondary

The gist of this being that we will return our secondary/auxiliary stack after sorting via \$O(n^2)\$ time.

This is not what my initial approach was, however, and I do think my approach has some interesting qualities:

Algo #2 (Mine)

def sort_stack(primary):
  did_sort = False
  secondary = []
  while not did_sort:
    # move from primary to secondary, pushing larger elements first when possible
    desc_swap(primary, secondary)
    # move from secondary back to primary, pushing smaller elements first when possible. Set did_sort = True if we're done and can exit.
    did_sort = asc_swap(secondary, primary)
  return primary

def asc_swap(full, empty):
  temp = None
  did_sort = True
  yet_max = None

  while full:
    if not temp:
      temp = full.pop()
    if full:
      if full[-1] < temp:
        insert = full.pop()
        if insert < yet_max:
          did_sort = False
        yet_max = insert
        empty.append(insert)
      else:
        empty.append(temp)
        temp = None
  if temp:
    empty.append(temp)
  return did_sort

def desc_swap(full, empty):
  temp = None
  while full:
    if not temp:
      temp = full.pop()
    if full:
      if full[-1] > temp:
        empty.append(full.pop())
      else:
        empty.append(temp)
        temp = None
  if temp:
    empty.append(temp)

Now obviously it is not nearly as clean or elegant, but it could be with some helper functions that dynamically choose our comparator and choose which element to push, etc.

Basically what it is doing is this:

# Start with stack in wrong order (worst case)
primary:   4 3 2 1
secondary:

# Swap to secondary, pushing larger elements first (1 is held in temp until the end because it is smaller than the following elements)
primary:
secondary: 2 3 4 1

# Swap back to primary, pushing smaller elements first
primary:   1 3 2 4
secondary:

# back to secondary
primary:
secondary: 4 3 2 1

# Back to primary, finished
primary:   1 2 3 4
secondary:

This strategy has a best-case/worst-case tradeoff.
Algo #1 actually performs worst when the stack is already sorted and best when the stack is sorted in the wrong order, and algo #2 does the opposite.

Questions

What are your thoughts? I think it is just an interesting way to sort that I haven't seen before.
Is there a name for this kind of sorting? I couldn't find similar algos but I'm sure theyre out there and would love to be able to describe it/recognize it better.