texts: Checking for viruses in uploaded files using ClamAV

texts:
I have to check an uploaded file for anti-virus and if there is an exception, I have to give a message according to the exception to the users. e.g. if its a timeout, I would ask the user to try againg in a while.

My first class, fileUpload is:

public class FileUpload {

    //Message when no virus found.
    private static final String NO_VIRUS_FOUND =  "No virus found";

    //More attributes and functions

    public void checkFile(FacesContext ctx, UIComponent comp, Object value) throws IOException {
          file = (Part) value;
          if (file != null) {
                  String antiVirusResult;
                  antiVirusResult = FileCheckClass.checkVirus(getConfig(), file.getInputStream(), NO_VIRUS_FOUND);
                 if (!antiVirusResult.contains(NO_VIRUS_FOUND)) {

                     generateAntiVirusMessages(antiVirusResult);
                     throw new ValidatorException(msgs);
                 }
          }
     }

}

My seond class, FileCheck class has a checkVirus() function:

public static String checkVirus(FileConfig fileconfig, InputStream inputStream, String noVirusFound) {
        try {

            ClamAVClient cl = new ClamAVClient(fileConfig.getClamavHost(), fileConfig.getClamavPort(), DEFAULT_TIMEOUT);

            if(ClamAVClient.isCleanReply(cl.scan(inputStream))){
                return noVirusFound;
            }
        } catch (Exception e) {
            logger.error("Error while scanning file: ", e);
            return e.toString();
        }
        return noVirusFound;
    }

From the check virus function, i have to return a string so I pass NO_VIRUS_FOUND into it from the first class.

Is it an acceptable practice to pass a string from one class to another just for the purpose of string comparison at the end. My fear is that if I define the strings separately in two class, change in one class would severely affect the output of the function in the other.
Can there could be some improvements that some one can suggest to the above situation?


texts: DailyProgrammer 280 Easy: Counting on Fingers

texts:
We are trying to count to 100 on two hands!

Input is given like so: LP  LR  LM  LI  LT  RT  RI  RM  RR  RP (i.e. 0111011100)

Where:

L = Left, R = Right, P = Pinky, R = Ring Finger, M = Middle Finger, I = Index Finger, T = Thumb

Our job is to make sure the code is valid according to this counting scheme, and then show what the number represented is.

Original post can be found here.

My solution validates the input by checking to see if there is a "1" followed by a "0" for the "left" hand, and vice-versa for the right. I have it set up so that positions 3,4, and 5 aren't checked (isn't necessary as they can't invalidate the input).

Looking for feedback on best practice, convention, better ways to solve problem, and really just anything :)

EDIT: I am not interested in checking for incorrect input such as "0123456789"

#include <iostream>
#include <string>

int main () {
    bool isValid = true;
    int total = 0;
    std::string input = "0111011100"; // This one is 37

    // Divide by 2 because there is two hands; subtract 1 to zero index
    int oneHandLength = (input.length() / 2) - 1;

    // Verify
    for(int a = 0; a <= oneHandLength; ++a){

        // Left
        if(((input[a] - '0') > (input[a + 1] - '0')) && ((a + 1) < oneHandLength)){
            isValid = false;
            break;
        }

        // Right
        if(((input[a + oneHandLength] - '0') < (input[(a + oneHandLength) + 1] - '0')) && (a + oneHandLength > oneHandLength + 1)){
            isValid = false;
            break;
        }
    }

    // Count up the total
    if(isValid){

        for(int b = 0; b < input.length(); b++){
            if ((input[b] - '0')){
                if(b < oneHandLength) total += 10;
                else if(b == oneHandLength) total += 50;
                else if(b == oneHandLength + 1) total += 5;
                else total += 1;
            }
        }

        std::cout << input << " is valid: " << total;
    }
    else std::cout << input << " isn't valid!";

    return 0;
}


texts:
I'm learning Erlang. It's my first time with a non-imperative programming language.

I've written a code and I want some thoughts about it:

Is my logic easy to understand?
Is my code idiomatic?
Is my code well organized?
Is my code using Erlang features correctly?

My goal here is improve readability and functional-thinking. I'm not concerned about performance.

-module(sb).
-export([start/0, barberShop/3, clientGenerator/2, barber/2]).
-define(MAX_BARBERS, 1).
-define(MAX_SITS, 5).

start() ->
  BarberShopPID = spawn(sb, barberShop, [[], 0, yes]),
  spawn(sb, clientGenerator, [BarberShopPID, 10]).

clientGenerator(BarberShopPID, ClientsToGenerate) ->
  case ClientsToGenerate of
    0 ->
      BarberShopPID ! clientGeneratorIsDone;
    _ ->
      timer:sleep(random(1000, 6000)),
      Hair = random(100, 600),
      BarberShopPID ! {client, Hair},
      clientGenerator(BarberShopPID, ClientsToGenerate-1)
  end.

barberShop(Clients, Barbers, IsCGRunning) ->
  receive
    {client, Hair} ->
      case length(Clients) of
        ?MAX_SITS ->
          write("A client entered, but there are no available sits."),
          barberShop(Clients, Barbers, IsCGRunning);
        _ ->
          write("A client entered and found a available sit."),
          {NewC, NewB} = tryAttend([Hair | Clients], Barbers, self()),
          barberShop(NewC, NewB, IsCGRunning)
      end;
    barberIsDone ->
      {NewC, NewB} = tryAttend(Clients, Barbers-1, self()),
      case shouldContinue(NewC, NewB, IsCGRunning) of
        yes ->
          barberShop(NewC, NewB, IsCGRunning);
        no ->
          write("Bye from the glorious barber shop.")
      end;
    clientGeneratorIsDone ->
      case shouldContinue(Clients, Barbers, no) of
        yes ->
          {NewC, NewB} = tryAttend(Clients, Barbers, self()),
            barberShop(NewC, NewB, no);
        no ->
          write("Bye from the glorious barber shop.")
      end
  end.

barber(Hair, BarberShopPID) ->
  write("Barber started his job."),
  timer:sleep(Hair * 10),
  write("Barber has done his job."),
  BarberShopPID ! barberIsDone.

tryAttend(Clients, ?MAX_BARBERS, _) ->
  {Clients, ?MAX_BARBERS};
tryAttend([], Barbers, _) ->
  {[], Barbers};
tryAttend(Clients, Barbers, BarberShopPID) ->
  [First | Rest] = Clients,
  spawn(sb, barber, [First, BarberShopPID]),
  {Rest, Barbers+1}.

shouldContinue([], 0, no) ->
  no;
shouldContinue(_, _, _) ->
  yes.

random(Min, Max) ->
  random:uniform(Max-Min+1)+Min.

write(Message) ->
  io:format(Message ++ "~n", []).


texts: Is this an optimal implementation of merge sort?

texts:
I am taking an algorithm course and we are to implement merge sort that handles list of elements with even or odd number of elements and handles duplication, so I wrote this function:

void mergesort (int* list, int len)
{
        if(len == 1) return;
        int i = len/2, j = len-i;
        int list1[i], list2[j];
        for(int k=0;k<i;k++)
        {
                list1[k]= list[k];
                list2[k]= list[i+k];
        }
        if(len%2!=0) list2[j-1] = list[len-1];
        mergesort(list1 , i);
        mergesort(list2 , j);
        int k=0,l=0;
        // k represent counter over elements in list1
        // l represent counter over elements in list2
        // k+l represent counte over total elements in list
         while(k+l!=len)
        {
                if(k==i)
                {
                        for(;l<j;l++) list[k+l] = list2[l];
                        return;
                }
                else if (l==j)
                {
                        for(;k<i;k++) list[k+l] = list1[k];
                }
                else if(list1[k]<list2[l])
                {
                        list[k+l]=list1[k];
                        k++;
                }
                else if(list1[k]>list2[l])
                {
                        list[k+l] = list2[l];
                        l++;
                }
                else
                {
                //handles dublication
                list[k+l] = list1[k];
                k++;
                list[k+l] = list[l];
                l++;
                }
        }
}

I have 2 questions:

How can I make this implementation more optimal (best possible performance)?
When handling arrays of large lengths (1000000), what causes a segmentation fault?

NOTE: I tried the function using array randomly generated of length 1000 and it worked.


texts: UVa 11340 Newspaper challenge (sum of letter values in an article)

texts:
I am solving the UVA 11340 problem:

Problem Description
News agency pays money for articles according to some rules. Each
character has its own value (some characters may have value equals to
zero). Author gets his payment as a sum of all character’s values in
the article. You have to determine the amount of money that news
agency must pay to an author.
Input
The first line contains integer N (0 < N ≤ 5), it is a number of
tests. Each test describes an integer K (0 < K ≤ 100), the number of
paid characters. On next K lines there are table of paid characters
and its values (character values are written in cents). If character
can not be found in the table, then its value is equal to zero. Next,
there is integer M (0 < M ≤ 150000). Next M lines contain an article
itself. Each line can be up to 10000 characters length. Be aware of a
large input size, the whole input file is about 7MB.
Output
For each test print how much money publisher must pay for an article
in format ‘x.yy$’. Where x is a number of dollars without leading
zeros, and yy number of cents with one leading zero if necessary.
Examples: ‘3.32$’, ‘13.07$’, ‘71.30$’, ‘0.09$’.

Code
My code is written using Java. I used HashMap data structure. But I am getting Time Limit Exceeded (TLE) error from the online judge. I am not seeing any other place to make improvement for better timing. Can anyone help me to find my mistake that is causing TLE? Or is there a better algorithm to solve this problem?
import java.util.HashMap;
import java.util.Scanner;

public class UVA11340 {
    public static void main(String[] args) {
        Scanner sc=new Scanner(System.in);
        int t=sc.nextInt();
        while(t-->0)
        {
            int k=sc.nextInt();
            HashMap<Character, Integer> map=new HashMap<>();
            for(int a=0;a<k;a++)
            {
            String s=sc.next();
            int v=sc.nextInt();
            map.put(s.charAt(0),v);
            }
            int l=sc.nextInt();
            double cost=0;
            sc.nextLine();
            for(int b=0;b<l;b++)
            {
                String str=sc.nextLine();
                for(int i=0;i<str.length();i++)
                {
                    char c=str.charAt(i);

                    cost=cost+(map.get(c)==null?0:map.get(c));
                }
            }
            cost=cost/100;
            System.out.printf("%.2f$\n",cost);
        }
        sc.close();
    }
}


texts: On tkinter: scrolling multiple widgets simultaneously in different frames

texts:
Below is an example on how to scroll two canvasses in two separate frames simultaneously. The trick is on how to pass on *args from the bindings to function onscroll for scrolling and onresize for changing the dimensions of the rectangle using lambda in the commands: Scrollbar(frame3, orient='vertical', command=lambda *args: onscroll('axis', *args)) and Button(frame3, text='reduce ', command=lambda *args: onresize(False, *args)).

Is this the best way to handle this?

import tkinter as tk
from tkinter import Frame, Canvas, Scrollbar, Button

global size_x, size_y, canvas1, canvas2, block1, block2
size_x = size_y = 150
block1 = block2 = ''

def onscroll(axis, *args):
    global canvas1, canvas2
    print(f'axis: {axis} and args are {[*args]}                           ',
          end='\r')
    if axis == 'x-axis':
        canvas1.xview(*args)
        canvas2.xview(*args)
    elif axis == 'y-axis':
        canvas1.yview(*args)
        canvas2.yview(*args)

    else:
        assert False, f"axis {axis} is incorrect, use 'x-axis' or 'y-axis'"

def onresize(enlarge, *args):
    global size_x, size_y
    print(f'enlarge: {enlarge} and args are {[*args]}                    ',
          end='\r')
    if enlarge:
        size_x *= 1.1
        size_y *= 1.1
    else:
        size_x /= 1.1
        size_y /= 1.1

def main():
    global canvas1, canvas2, block1, block2
    root = tk.Tk()
    frame1 = Frame(root, bg='grey')
    frame1.grid(row=0, column=0)
    frame2 = Frame(root, bg='grey')
    frame2.grid(row=0, column=1)
    frame3 = Frame(root, bg='grey')
    frame3.grid(row=0, column=2)

    yscrollbar = Scrollbar(frame3, orient='vertical',
                           command=lambda *args: onscroll('y-axis', *args))
    yscrollbar.pack(side='right', fill='y', expand='yes')
    xscrollbar = Scrollbar(frame3, orient='horizontal',
                           command=lambda *args: onscroll('x-axis', *args))
    xscrollbar.pack(side='bottom', fill='x', expand='yes')

    reduce_button = Button(frame3, text='reduce ',
                           command=lambda *args: onresize(False, *args))
    reduce_button.pack(side='right', anchor='ne')
    enlarge_button = Button(frame3, text='enlarge',
                            command=lambda *args: onresize(True, *args))
    enlarge_button.pack(side='right', anchor='ne')

    canvas1 = Canvas(frame1, width=200, height=200, bg="blue",
                     scrollregion=(0, 0, 500, 500),
                     yscrollcommand=yscrollbar.set,
                     xscrollcommand=xscrollbar.set)
    canvas1.pack(side='right')
    canvas2 = Canvas(frame2, width=200, height=200, bg="yellow",
                     scrollregion=(0, 0, 500, 500),
                     yscrollcommand=yscrollbar.set,
                     xscrollcommand=xscrollbar.set)
    canvas2.pack()

    canvas3 = Canvas(frame3, width=200, height=200, bg='pink')
    canvas3.pack()

    while True:
        canvas1.delete(block1)
        canvas2.delete(block2)
        block1 = canvas1.create_rectangle(100, 100, size_x, size_y,
                                          fill='orange')
        block2 = canvas2.create_rectangle(100, 100, size_x, size_y,
                                          fill='blue')
        root.update()

    root.mainloop()

if __name__ == "__main__":
    main()


texts: Replace sequence of strings in binary file

texts:
I have searched for method to find and replace strings sequence in binary files without any luck. The main requirement was that method should not load all file in memory but rather use chunks. I am new in c# and code may look not "polished" but it works fine. Maybe someone will have ideas how this code could be improved or does it have any flaws? p.s. Thanks goes to Jon Skeet for idea.

public static void ReplaceTextInFile(string inFile, string find, string replace)
{

    if (find.Length!=replace.Length) throw new ArgumentException("The lenght of find and replace strings must match!");

    const int chunkPrefix = 1024*10;
    var findBytes = GetBytes(find);
    var replaceBytes = GetBytes(replace);
    long chunkSize = findBytes.Length * chunkPrefix;
    var f = new FileInfo(inFile);
    if (f.Length < chunkSize)
        chunkSize = f.Length;

    var readBuffer = new byte[chunkSize];

    using (Stream stream = File.Open(inFile, FileMode.Open))
    {
        int bytesRead;
        while ((bytesRead=stream.Read(readBuffer, 0, readBuffer.Length)) != 0)
        {
            var replacePositions = new List<int>();
            var matches = SearchBytePattern(findBytes, readBuffer, ref replacePositions);
            if (matches != 0)
                foreach (var replacePosition in replacePositions)
                {
                    var originalPosition = stream.Position;
                    stream.Position = originalPosition - bytesRead + replacePosition;
                    stream.Write(replaceBytes, 0, replaceBytes.Length);
                    stream.Position = originalPosition;
                }

            if (stream.Length == stream.Position) break;
            var moveBackByHalf = stream.Position - (bytesRead / 2);
            stream.Position = moveBackByHalf;
        }

    }

}

static public int SearchBytePattern(byte[] pattern, byte[] bytes, ref List<int> position)
{
    int matches = 0;
    for (int i = 0; i < bytes.Length; i++)
    {
        if (pattern[0] == bytes[i] && bytes.Length - i >= pattern.Length)
        {
            bool ismatch = true;
            for (int j = 1; j < pattern.Length && ismatch == true; j++)
            {
                if (bytes[i + j] != pattern[j])
                    ismatch = false;
            }
            if (ismatch)
            {
                position.Add(i);
                matches++;
                i += pattern.Length - 1;
            }
        }
    }
    return matches;
}

public static byte[] GetBytes(string text)
{
    return Encoding.UTF8.GetBytes(text);
}

usage

 ReplaceTextInFile(@"MyFile.bin", "Text to replace", "New Text! Test!");


texts: Alternating sort order within a sorted group

texts:
When sorting by multiple keys, I need the second key to alternate between standard and reverse sorting.  This is to minimize the change in the second key.  For example, if I have a list of dictionaries, I want the first sort (group key) to be sorted and then the second sort (sort key) to alternate.  This should produce a sort like this:

[{'group': 'a', 'sort': 1},
 {'group': 'a', 'sort': 2},
 {'group': 'a', 'sort': 2},
 {'group': 'b', 'sort': 2},
 {'group': 'b', 'sort': 1},
 {'group': 'b', 'sort': 1},
 {'group': 'c', 'sort': 1},
 {'group': 'c', 'sort': 1},
 {'group': 'c', 'sort': 2}]

That limits the change in the field called "sort" as it alternates each time as the "group" changes.

I have looked around and did not see a standard way to accomplish this without rolling my own.  I think the code is fairly straight forward but curious if I might be missing something or an easier/faster way.

Any comments would be appreciated.

#!/usr/bin/env python3
""" Misc sort routines """
from operator import itemgetter
import pprint

def alternate_sort(data, group_key, sort_key,
        group_reverse=False, sort_reverse=False):
    """ Sort data within groups while alternating asc/desc on sort key. """
    partitions = []     # Tuples of start/end indexes per group
    last_key = None     # Remember when groups change
    group_start = 0     # Remember start index of group
    final_sort = []     # The final sorted listing

    # Make sure the data is sorted by group
    data = sorted(data, key=itemgetter(group_key), reverse=group_reverse)

    # Gather the group partitions
    for i, g in enumerate(data):

        # When the group changes
        if last_key != g[group_key]:

            # End the previous group partition if there is one
            if i > 0:
                partitions.append((group_start, i))

            # Start a new group partition
            group_start = i
            last_key = g[group_key]

    # Close the last group partition
    partitions.append((group_start, len(data)))

    # Go through the partitions, alternate the sort each time using sort key.
    for i, p in enumerate(partitions):
        part = data[p[0]: p[1]]
        if i % 2 == 0:
            final_sort += sorted(
                    part, key=itemgetter(sort_key), reverse=sort_reverse)
        else:
            final_sort += sorted(
                    part, key=itemgetter(sort_key), reverse=not sort_reverse)

    return final_sort

if __name__ == "__main__":
    unsorted_data = [
            {"group": "a", "sort" : 1},
            {"group": "a", "sort" : 2},
            {"group": "b", "sort" : 2},
            {"group": "b", "sort" : 1},
            {"group": "c", "sort" : 1},
            {"group": "a", "sort" : 2},
            {"group": "c", "sort" : 2},
            {"group": "b", "sort" : 1},
            {"group": "c", "sort" : 1}
    ]

    sorted_data = alternate_sort(unsorted_data, "group", "sort",
            group_reverse=True, sort_reverse=True)
    pprint.pprint(sorted_data)

    sorted_data = alternate_sort(unsorted_data, "group", "sort")
    pprint.pprint(sorted_data)


texts:
This Python main is what greets the user to a thrice nested super duper barebones OS.  The entire rest of my code isn't bug free but this section is, and it feels dirty anyway.  I'd like to know how to make it better, by adhering to conventions, or by removal of fatty code.

NOTE: I am not looking to use classes with any of this, because part of the challenge of this program is structuring it with procedural means.

from functions import *

innerLoopFlag = False
while True:
 if innerLoopFlag:
     break
 makeNew = raw_input("Login || Create New Account... ")
 if makeNew == "c-na":
     ui = createAccount()
     createFileSyst(ui)
     break
 if makeNew == "l-a":
     ui = [raw_input("Username... ").strip(),pw("Password... ").strip()]
     if not os.path.isdir(ui[0]):
         print "It appears that this username doesn't exist, please log in legitimately or create an account"
         continue
     if ui:
         while True:
             if takeCheck(ui):
                 print "Successful login..."
                 innerLoopFlag = True
                 break
             else:
                 print "Failure logging in, retrying..."

all()
print "Goodbye", ui[0]


texts: Split every vector in a sequence into two parts: old elements that were contained in previous vectors and new elements never before seen

texts:
Am I doing it right? Is there some function in the standard library I should be using? This is my first real(ish) world Clojure program…

Input

(def data
  [[{:id 5 :name "a"} {:id 1 :name "b"}], [{:id 4 :name "c"} {:id 1 :name "d"}]])

Code

The elements are maps and they are compared based on their :id.

(def precomputed
  (reductions
   (fn [global, v]
     (let [seen? (:seen? global)
           new   (remove #(-> % :id seen?) v)
           old   (filter #(-> % :id seen?) v)]
       {:seen? (clojure.set/union seen? (->> new (map :id) (set)))
        :new   new
        :old   old}))
   {:seen? #{} :new '() :old '()}
   data))

At this moment precomputed looks like

({:seen? #{}, :new (), :old ()}
{:seen? #{1 5}, :new ({:id 5, :name "a"} {:id 1, :name "b"}), :old ()}
{:seen? #{1 4 5}, :new ({:id 4, :name "c"}), :old ({:id 1, :name "d"})})

Print some sort of output

(doseq [i (rest precomputed)]
  (println "new: " (->> (i :new) (map :name) (interpose ", ") (reduce str))
           "old: " (->> (i :old) (map :name) (interpose ", ") (reduce str))))

Output

new:  a, b old:     ; first vector, every element is new
new:  c old:  d     ; we have seen element with :id 1 before


texts: Wrapper to mount partition before launching executable

texts:
Solved task is pretty straightforward: mounting partition if not mounted already, to start executable.
There is a couple of checks and notifications because it is supposed to be launched from X and there are no way to see stdout/stderr stream. I have started with much larger version and a lot of error handling, that is why it has a function despite being so simple. On the other hand, it is much more cleaner of what is going on, when you read it and it will be easier to come back to it later on.
#!/usr/bin/env bash
DEVICE="/dev/sda5"
PARTITION="/mnt/Games"
EXECUTABLE="$PARTITION/MultiMC/MultiMC"

launch() {
    if ! findmnt "$PARTITION"; then
        DETAILS=`SUDO_ASKPASS="$(which ssh-askpass)" sudo --askpass mount "$DEVICE" "$PARTITION" 2>&1`
        [ $? -ne 0 ] && return 1
    fi
    notify-send "Launching.."
    exec "$EXECUTABLE"
}

launch || notify-send "Launching failed" "$DETAILS"


texts: Creating a filtered list by comparing one list to another other list - Python

texts:
I have a list and I need to get certain elements out of it. The way I did it was to compare the second list to the first list and then append to a third list. Here is my code:
l1 = ["0 = 0","1 = 1","2 = 2", "And",
      "Something", "Wicked", "This", "Way", "Comes",
      f"zero.0 = 0", f"one.0 = 1", f"two.0 = 2",
      f"zero.1 = 0", f"one.1 = 1", f"two.1 = 2",
      f"zero.2 = 0", f"one.2 = 1", f"two.2 = 2",
      "purple", "monkey", "dishwasher"]
l3 = []
for element in l1:
   for i in range(3):
       l2 = [f"zero.{i} = 0", f"one.{i} = 1", f"two.{i} = 2"]
       for j in l2:
           if j in element:
               l3.append(element)

The results of this nested for loop is:
['zero.0 = 0', 'one.0 = 1', 'two.0 = 2', 'zero.1 = 0', 'one.1 = 1', 'two.1 = 2', 'zero.2 = 0', 'one.2 = 1', 'two.2 = 2']

The result is exactly what I want but I'm looking for a more Pythonic way of writing this. Any help would be greatly appreciated.


texts:
Please see the code below:

public sealed class DateOfBirth : IEquatable<DateOfBirth>, IComparable<DateOfBirth>
    {
        private readonly DateTime _value;

        public DateTime Value
        {
            get { return _value; }
        }
        public DateOfBirth(DateTime dateOfBirth)
        {
            if(dateOfBirth == DateTime.MinValue)
                throw new ArgumentException("Invalid value.", "DateOfBirth");
            this._value= dateOfBirth;
        }

        private static int Comparison(DateOfBirth dateOfBirth1, DateOfBirth dateOfBirth2)
        {
            if (ReferenceEquals(dateOfBirth1, dateOfBirth2))
                return 0;
            else if (ReferenceEquals(dateOfBirth1, null))
                return -1;
            else if (ReferenceEquals(dateOfBirth2, null))
                return 1;
            if (dateOfBirth1._value < dateOfBirth2._value)
                return -1;
            else if (dateOfBirth1._value == dateOfBirth2._value)
                return 0;
            else if (dateOfBirth1._value > dateOfBirth2._value)
                return 1;
            return 0;
        }

        public int CompareTo(DateOfBirth other)
        {
            if (other != null)
                return this._value.CompareTo(other._value);
            else
                throw new ArgumentNullException("DateOfBirth");
        }

        public static bool operator ==(DateOfBirth dateOfBirth1, DateOfBirth dateOfBirth2)
        {
            return Comparison(dateOfBirth1, dateOfBirth2) == 0;
        }

        public static bool operator !=(DateOfBirth dateOfBirth1, DateOfBirth dateOfBirth2)
        {
            return !(dateOfBirth1 == dateOfBirth2);
        }

        public static bool operator <(DateOfBirth dateOfBirth1, DateOfBirth dateOfBirth2)
        {
            return Comparison(dateOfBirth1, dateOfBirth2) < 0;
        }

        public static bool operator >(DateOfBirth dateOfBirth1, DateOfBirth dateOfBirth2)
        {
            return Comparison(dateOfBirth1, dateOfBirth2) > 0;
        }

        public static bool operator <=(DateOfBirth dateOfBirth1, DateOfBirth dateOfBirth2)
        {
            return Comparison(dateOfBirth1, dateOfBirth2) <= 0;
        }

        public static bool operator >=(DateOfBirth dateOfBirth1, DateOfBirth dateOfBirth2)
        {
            return Comparison(dateOfBirth1, dateOfBirth2) >= 0;
        }

        public bool Equals(DateOfBirth other)
        {
            if (ReferenceEquals(other, null))
                return false;
            return _value == other._value;
        }

        public override bool Equals(object obj)
        {
            return Equals(obj as DateOfBirth);
        }

        public override int GetHashCode()
        {
            return _value.GetHashCode();
        }
    }

I realise it could be argued as over engineering a simple date of birth field.  I am more interested whether or not the nine comparisons (https://ericlippert.com/2013/10/07/math-from-scratch-part-six-comparisons/) are implemented correctly.  This article helped me: https://blogs.msdn.microsoft.com/abhinaba/2005/10/11/c-comparison-operator-overloading-and-spaceship-operator/ - the only concern I have about the code in this article is that the Comparison method does not do this (which my code does):

if (ReferenceEquals(dateOfBirth1, dateOfBirth2))
                return 0;
            else if (ReferenceEquals(dateOfBirth1, null))

Q1) Is the code above fit for purpose (are there any bugs)?

Q2) Is a DateTime data type (DateOfBirth._value) suitable for a Date of Birth?
                    return -1;

Q3) Is the validation in the constructor fit for purpose?


texts: Util method for generating an INSERT sql dynamically

texts:
I'm currently building software that:

'talks' to Google Analytics API,
fetches data,
persists the data to a MySql db.

Insertion of data into the db needs to happen automatically - based on the received headers and rows. This is a utility method that I wrote to generate the needed sql:

public static function generateInsertQuery($tableName, array $headers, array $rows)
{
    /**
     * Normalize column names
     */
    $columns = [];
    foreach($headers as $header) {
        $columns[] = str_replace(':', '_', $header['name']);
    }

    $columnsStr = implode(',', $columns);

    /**
     * Make initial sql with placeholders ready
     */
    $sql = "INSERT INTO $tableName ($columnsStr) VALUES %s";
    $value = '(%s)';
    $values = [];

    /**
     * Quote string values to insert
     */
    foreach ($rows as $row) {
        foreach ($row as &$entry) {
            $entry = "'" . $entry . "'";
        }

        $formattedRow = sprintf($value, implode(',', $row));
        $values[] = $formattedRow;
    }

    /** Generate sql */
    $sql = sprintf($sql, implode(',', $values));

    return $sql;
}

As you can see, the sql will be generated dynamically each time the method is called.

Nevertheless, when I look at this method I have an impression that it could be improved and 'prettified' a lot.

I'd be very grateful to receive your review and perhaps some advice on how I can do it better.

P.S.

You might be asking - how is that supposed to work with a permanent db schema since we do not know what data will be inserted. This issue, however, has been sorted. I'm working with Doctrine DBAL and I am using Doctrine\DBAL\Schema\Comparator to make sure the schema is ready for data insertion:

    /**
     * Compare the current db schema with the new schema
     */
    $schemaDiff = $this->schemaComparator->compare($currentSchema, $this->schema);
    $saveQueries = $schemaDiff->toSaveSql($platform);

    /**
     * Changed the db schema to if there are any differences in a safe mode
     * - no data will ever be deleted
     */
    if (!empty($saveQueries)) {
        $this->updateSchema($saveQueries);
    }


texts: Efficient way to add a colon before and after every word in strings inside a Series

texts:
I was working with twitter data, and extracted every emoji from the data. But, when I passed that data through CountVectorizer, colons where substracted from the strings. So, the string emoji :ok_hand: :thumbs_up: turned into  ok_hand thumbs_up. I wanted to re-add those colons so then I could emojize them back. I managed to do that, but I'm quite sure my method is very inefficient. The emojis are the indexes of a coefficients DataFrame, like this:

    index              coef

ok_hand thumbs_up      0.4
    airplane           0.2

So what I did was this:

to_emojize=pd.Series(coef_mat_emoji.index)
to_emojize=to_emojize.apply(lambda x: x.split())
to_emojize=to_emojize.apply(lambda x:[':'+i+':' for i in x])
to_emojize=to_emojize.apply(lambda x: emoji.emojize(x, use_aliases=True))
coef_mat_emoji.index=to_emojize

Is there a better way to do this?


texts:
My code implementing rock, paper and scissors in Python, using dicts to hold choices.

import random

choices = ['rock', 'paper', 'scissors']

def choice():

    player_choice = raw_input('Choose rock, paper or scissors: ')
    if player_choice.lower() in choices:
        computer_choice = random.choice(choices)
        play(player_choice, computer_choice)
    else:
        choice()

def play(p_choice, c_choice):

    win_table = {'rock' : {'rock':'It was a Tie', 'paper':'You Lose', 'scissors':'You Win'},
                 'paper' : {'rock':'You Win', 'paper':'It was a Tie', 'scissors':'You Lose'},
                 'scissors' : {'rock':'You Lose', 'paper':'You Win', 'scissors':'It was a Tie'}}

    print 'Computer chose', c_choice
    print win_table[p_choice][c_choice]

    new = raw_input('Play again ? (Y/N):  ')
    if new.lower() == 'y':
        choice()
    else:
        print 'Have a nice day !'

choice()

win_table dictionary names are player choices and dictionary keys are computer choices, seems more efficient to me. I haven't run any memory usage tests, though.


texts: Checkboxes behave like radio buttons with angular

texts:
This is short Angular 5 code which works as intended: check boxes behave like radio buttons - only one can be selected at a time.

Both versions of 'toggleCheckbox' works but I am interested is if there is better, more elegant way to set 'checkbox1' and 'checkbox2'?

template-driven-form.component.ts

import {Component, OnInit} from '@angular/core';

import {User} from './domain/user';

@Component({
  selector: 'app-template',
  templateUrl: './template-driven-form.component.html',
  styleUrls: ['./style.css']
})

export class TemplateDrivenFormComponent implements OnInit {
  user = new User();

  ngOnInit() {
    this.setDefaultValues();
  }

  constructor() {
  }

  // toggleCheckbox(event) {
  //   if (event.target.id === 'checkbox1') {
  //     this.user.checkbox1 = true;
  //     this.user.checkbox2 = false;
  //   } else {
  //     this.user.checkbox1 = false;
  //     this.user.checkbox2 = true;
  //   }
  // }

  toggleCheckbox(event) {
    event.target.id === 'checkbox1' ? (this.user.checkbox1 = true, this.user.checkbox2 = false)
      : (this.user.checkbox2 = true, this.user.checkbox1 = false);
  }

  setDefaultValues() {
    this.user.checkbox1 = true;
    this.user.checkbox2 = false;
  }
}

template-driven-form.component.html

Template Driven Form

      Label 1<input type="checkbox" id="checkbox1" name="checkbox1" [ngModel]="user.checkbox1" (change)="toggleCheckbox($event)" [checked]="user.checkbox1">

      Label 2<input type="checkbox" id="checkbox2" name="checkbox2" [ngModel]="user.checkbox2" (change)="toggleCheckbox($event)" [checked]="user.checkbox2">


texts:
This seems to do the job of the EAV tables. Besides being EAV, is there room for improvement? Maybe there is something obvious, but how about indexing certain columns?

from django.db import models

class Entity(models.Model):
    entity_id = models.AutoField(primary_key=True)
    entity = models.CharField(max_length=100)

class Attribute(models.Model):
    attribute_id = models.AutoField(primary_key=True)
    entity_id = models.ForeignKey(Entity)
    value = models.CharField(max_length=100)

class EntityTableAbstract(models.Model):
    class Meta:
        abstract = True

    entity_id = models.ForeignKey(Entity)
    attribute_id = models.ForeignKey(Attribute)

class EntityVarchar(EntityTableAbstract):
    value = models.TextField()

class EntityInteger(EntityTableAbstract):
    value = models.IntegerField()


texts:
I'm learning C# and have written a function which generates an easily-pronounceable fictional name by alternating between taking one vowel and one consonant. The one parameter, halfLength, will be the amount of vowels added and the amount of consonants added, meaning that the length of the returned string is double the given halfLength.

static string GeneratePronounceableName(int halfLength)
{
    char[] vowels = "aeiou".ToCharArray();
    char[] consonants = "bcdfghjklmnpqrstvwxyz".ToCharArray();
    List<char> chosenVowels = new List<char>();
    List<char> chosenConsonants = new List<char>();

    Random r = new Random();

    for (int i = 0; i < halfLength; i++)
    {
        chosenVowels.Add(vowels[r.Next(0, 5)]);
        chosenConsonants.Add(consonants[r.Next(0, 21)]);
    }

    return string.Join("", chosenConsonants.Zip(chosenVowels, (v, c) => v.ToString() + c.ToString()));
}

Is there a way this can be made shorter, more idiomatic or more efficient?


texts: Invert a dictionary to a dictionary of lists

texts:
I have a dictionary whose keys are related to list of values, but any value may be related to many keys, hence be contained in various lists-attached-keys.

To highlight such relation; I build (in Python 3.6.1) the reverse dictionary using this:

   from collections import defaultdict
   #defaultdict is a dict that you set up to output a datatype as default, instead of throwing a KeyError exception, when a key not contained into it is called, it outputs the default datatype and the corresponding key is created on the fly and kept.
   reversed_dict =defaultdict(list)
   primary_dict ={"abc":[1,2,3], "cde":[3,5,7],"efg":[4,2,1,7]}
   #in the call of default dict, you must input a callable
   [reversed_dict[term].append(key) for key, innerset in primary_dict.items() for term in innerset]
   #append should be used instead of extend, as keys are strings, and extend would result in their breakdown

   #desired output for reversed_dict:
   #defaultdict(list,
   #     {1: ['abc', 'efg'],
   #      2: ['abc', 'efg'],
   #      3: ['abc', 'cde'],
   #      4: ['efg'],
   #      5: ['cde'],
   #      7: ['cde', 'efg']})

The code is very simple, and efficient.
My question is more about using the list comprehension to get the loading of the dict done, while it is not assigned to anything. Can't this cause any sort of problem? Shouldn't I better assign the comprehension and then delete it?

I am not very much used to "leaving in the air" something in Python. So I wonder if it is not "ugly", or problematic. I feel like it is bad because the comprehension is not actually doing what it is intended to, aka creating a list, I am only using its related feature of mimicking a for loop for it, because it is more efficient and readable than such loop.

What do you think?
I have been using such pattern for a long time now, but I was never  completely satisfied with it, I only kept it because the other way I found were too convoluted to do this, or not using only one step.
About the context, it is difficult to say because I very often have to use such practice. I am in bioinformatics, so I often get associations between a key (say a gene or protein) and a list (of biological effects, related drugs and so on). Sometimes I use dataframes, but actually I find groupby not very convenient, as to get the related info you have to handle indexes (granted, you can set you keys as index and drop the column, but it is many operations, plus you have an index as output and this comes with its own kind of hassle.


texts: How to improve my JS code? Avoid repeated element

texts:
I'm trying to learning JS good practices. With jQuery, everything was easier and organized. With JS, I really don't know if I doing this right.

I must repeat the element I am manipulating all the time? For example:

elementHere.className = "";
elementHere.classList.add(test);
elementHere.addEventListener(etc, function() {
}, true);

Is it a a good code, for example? Is it DRY? I really need to repeat the element name all the time? How to improve?

I would like tips to improve and make it DRY! I did not find any tutorial on the internet.

I think it is also not good for maintenance.


texts:
I implemented reversing a linked list in iterative way, just by knowing we need 3 pointers and I have never seen a code before, when I coded. I ran this code and tested it, it works fine. Even for null element and one element. But all the implementations on net have slightly different code. I was just wondering, how my algorithm is.

Do you guys see any major concern in my implementation?

int reverse(List *l) {

 if(!l) {
        printf("List is NULL \n");
        return -1;
 }

 if(!l->head) {
        printf("List is empty \n");
        return -1;
 }

 Node *prev_node = l->head;
 Node *curr_node = l->head->next;

 while(curr_node) {
        prev_node->next = curr_node->next;
        curr_node->next = l->head;
        l->head = curr_node;
        curr_node = prev_node->next;
 }

 return 0;
}


texts: Separating and organising modules with objects?

texts:
As I'm creating a 3D Tic-Tac-Toe game, I'm having several modules inside my JavaScript application. For example, there is a 3D module which handles perspective calculations, whereas a Multiplayer module manages everything with relation to online playing.

Is it good practice to put functions of each module in its separate object?

I currently have:

multiplayer.js:

var Multiplayer = {
    socket: new Socket("ws://192.168.0.100:123/test"), // Relevant variables concerning multiplayer stuff

    createSession:
    function() {
       //...
    }
}

renderer.js:

var Renderer = {
    f: 200, // Relevant variables concerning 3D rendering stuff
    g: 200;

    render:
    function() {
        //...
    }
}

and so on.

Is this a good practice of organising my project? Or is there a more efficient way?


texts:
I was wondering for quite some time how to clean up the below code without blowing it up any further. The extension of the classes is the main concern here, it looks a bit too much like magic. That's mainly because it has to handle all the different cases, and I haven't figured out a way to reduce the code in a meaningful fashion here.

Maybe I'm paranoid and the code is just fine, but I'd still love to get some feedback on it.

The original code and test cases are here.

function is(type, obj) {
    return Object.prototype.toString.call(obj).slice(8, -1) === type;
}
function copy(val) { /* ...make shallow copy */ }
function wrap(caller, obj) {
    obj = obj || Function.call;
    return function() {
        return obj.apply(caller, arguments);
    };
}

function Class(ctor) {
    // ...default ctor stuff here....
    function clas(args) { /* ...actual instance ctor stuff... */}

    var proto = {};
    clas.init = wrap(ctor);

    // extend needs to be reduced in width, it easily goes over 80 columns
    // without some ugly if statements
    clas.extend = function(ext) {
        if (is('Function', ext)) {
            return ext.extend(proto); // holy closure!
        }

        for (var e in ext) {
            if (!ext.hasOwnProperty(e)) {
                continue; // a bit ugly imo, but it helps to prevent the indentation
                          // from blowing up
            }

            // this needs some refactoring, it creates bound and unbound
            var val = ext[e], func = is('Function', val);
            if (/^\$/.test(e)) { // statics
                proto[e] = copy(val);
                clas[e] = clas.prototype[e] = func ? wrap(clas, val) : val;

            } else if (func) {
                clas[e] = wrap(proto[e] = clas.prototype[e] = val);
            }
        }
        return clas;
    };

    // this could also need some clean up I suppose
    for (var i = ctor.hasOwnProperty('init') ? 0 : 1,
             l = arguments.length; i < l; i++) {

        var arg = arguments[i];
        is('Object', arg) ? clas.extend(arg) : arg.extend(clas);
    }
    return clas;
}


texts: Constant time string comparision in PHP to prevent timing attacks

texts:
I've been advised that when checking the password hash for a user I should use a string comparison function that always takes the same amount of time, to avoid timing attacks.

So I wrote this:

//this is a constant time string compare,
//it does not exit early even if the strings don't match
//it is case sensitve
//the time to compare is the time needed for the shorter string
//(if they are not the same length)
function time_strcmp($str1, $str2)
{
  $res = $str1 ^ $str2;
  $ret = strlen($str1) ^ strlen($str2); //not the same length, then fail ($ret != 0)
  for($i = strlen($res) - 1; $i >= 0; $i--) $ret += ord($res[$i]);
  return !$ret;
}

(I do it this way instead of checking equality in a loop just in case of optimization. Not sure if PHP does any, but it might in the future.)

Anyway, since this is such a critical part of the code, returning true when it shouldn't would completely defeat security.

Can anyone give me a code review? Or a better way?


texts: NRPE script for monitoring filesystems usage

texts:
Next script returns NRPE friendly output. It checks percentage usage of all local filesystems.

Desired output if everything is ok:

OK | /=56;;;; /boot=20;;;; /opt=40;;;; /var=60;;;; (and exit_code0 = ok)

Desired output if something is wrong:

CHECK /var | /=56;;;; /boot=20;;;; /opt=40;;;; /var=93;;;; (and exit_code1 = warning, 2 = error)

#!/usr/bin/env bash

set -o errexit -o nounset -o pipefail

warning=80
critical=95

declare -a output_text
declare -a output_data
exit_code="0"

while read -r filesystem _ _ _ used mountpoint; do
  if [[ ${filesystem:0:4} = "/dev" ]] && [[ ${filesystem:0:8} != "/dev/sr0" ]]; then
    code="$(( ( ${used%"%"} > warning ) + ( ${used%"%"} > critical ) ))"

    # Never decrease the exit_code value!
    if [[ $code -gt $exit_code ]]; then
      exit_code="$code"
      output_text+=("$mountpoint")
    fi

    output_data+=("${mountpoint}=${used%"%"};;;;")
  fi
done < <( df -P )

if [[ exit_code -gt 0 ]]; then
  echo "CHECK" "${output_text[@]}" "|" "${output_data[@]}"
else
  echo "OK |" "${output_data[@]}"
fi

exit $exit_code

Could I do something better?


texts: Uni-directional singly linked list in JavaScript

texts:
I've been studying data structures and have taken a stab at implementing a singly LL in JavaScript. Please review and advise on any additional improvements and optimizations:

function Node(val){
  this.data = val;
  this.next = null;
};

function SinglyList(){
  this._length = 0;
  this.head = null;
};

//Add
SinglyList.prototype.add = function(val){
  var node = new Node(val),
      currentNode = this.head;

  //if list is empty
  if(!currentNode){
    this.head = node;
    this._length++;
    return;
  }

  //locate tail
  while(currentNode.next){
    currentNode = currentNode.next;
  }
  //Add to the tail
  currentNode.next = node;
  this._length++;

  return node;
}
//isEmpty
SinglyList.prototype.isEmpty = function(){
  return this._length === 0;
}

//Contains
SinglyList.prototype.contains = function(val){
  var currentNode = this.head;

  if(this.isEmpty()) return;

  while(currentNode){
    if(currentNode.data === val) return true;
    currentNode = currentNode.next;
  }

  return false;
}
//Reversed
SinglyList.prototype.reverse = function(){
  var currentNode = this.head,
      prev = null;

  while(currentNode){
    var temp = currentNode.next;
    currentNode.next = prev;
    prev = currentNode;
    currentNode = temp;
  }
  this.head = prev;
  return this;
}
//RemoveAt
SinglyList.prototype.removeAt = function(index){

  if(index<0 || index > this._length)
    return;

  var currentNode = this.head, i=0, prev;

  //if 1st in the list
  if(index === 0){
    this.head = currentNode.next;
    this._length--;
    return this;
  }
  //Subsequent items in the list
  while(i++ < index-1){
    prev = currentNode;
    currentNode = currentNode.next;
  }
  prev.next = currentNode.next;
  this.head = prev;
  this._length--;

  return this;
}
//Remove by value
SinglyList.prototype.removeByVal = function(val){
  if(this.isEmpty()) return;
  if(!this.contains(val)) return;

  var currentNode = this.head;

  if(currentNode.data===val){
    this.head = currentNode.next;
    this._length--;
    return this;
  }

  while(currentNode.next){
    if(currentNode.next.data===val){
      prev = currentNode;
    }
    currentNode = currentNode.next;
  }

  prev.next = prev.next.next;
  this._length--;

  return this;

}
//Append
SinglyList.prototype.append = function(val){
  this.add(val);
  return this;
}
//Prepend
SinglyList.prototype.prepend = function(val){
  var node = new Node(val),
      temp = this.head;

  node.next = temp;
  this.head = node;
  return this;
}

var singlyList = new SinglyList();

singlyList.add(5);
singlyList.add(10);
singlyList.add(15);
singlyList.add(20);
singlyList.add(25);
singlyList.add(30);
singlyList.add(35);
singlyList.add(40);

console.log('Singly LL:\n'+JSON.stringify(singlyList));
console.log('isEmpty method:\n'+singlyList.isEmpty());
console.log('Contains:\n'+singlyList.contains(5));

console.log('Reversed:\n'+JSON.stringify(singlyList.reverse()));
console.log('Remove:\n'+JSON.stringify(singlyList.removeAt(2)));
console.log('Reversed:\n'+JSON.stringify(singlyList.reverse()));

console.log('Append:\n'+JSON.stringify(singlyList.append(45)));
console.log('Prepend:\n'+JSON.stringify(singlyList.prepend(50)));
console.log('Remove by value:\n'+JSON.stringify(singlyList.removeByVal(50)));


texts: Modularized JavaScript event handler to increment counters

texts:
In the following code we use the function Incrementer (capitalized for clarity, despite that it's to be used without new), to instantiate a number.

Incrementer provides a method increment to augment a counter in a span. We have two such counters, and so we define Incrementer to avoid code duplication (although it would be nice to program always like this, even in the absence of the worry of duplication).

function Incrementer(name, value) {
    let that = {};

    // Constructor
    that.name = name;
    let mydiv = document.getElementById('mydiv');
    mydiv.appendChild(document.createElement('br'));
    that.span = document.createElement('span');
    that.span.id = '#num' + name;
    that.span.innerHTML = value;
    mydiv.appendChild(that.span);

    that.increment = function() {
        var i = parseInt(that.span.textContent) + 1;
        that.span.innerHTML = i;
    }
    return that;
}
var incrementer1 = Incrementer('one', 10);
var incrementer2 = Incrementer('two', 20);

function double_increment() {
    incrementer1.increment();
    incrementer2.increment();
}

    <button id="inc" onclick="double_increment()">Increment</button>

The function double_increment() is then used to increment both numbers.

I'm seeking critique of this code, in particular:

The block marked "Constructor" is directly inside the function Incrementer rather than in a function called Constructor. What is the right basis for cleaner code?
The function double_increment() seems awkward. It exists at the global scope merely to respond to events (from user input in general, whether a button or otherwise). Is this an adequate basis for a (larger) code base?


texts: Bootstrap show many move one carousel modification

texts:
I've been steadily improving a show many move one carousel sample that I found a few weeks ago. I want to post my improvements for others to use but don't want to spread bad code. I'm not an expert in JavaScript but I always like to produce clean code.

Working demo

(function(){
  $('.carousel-showmanymoveone .item').each(function(){
    var itemToClone = $(this);

    for (var i=1;i<4;i++) {
      itemToClone = itemToClone.next();

      // wrap around if at end of item collection
      if (!itemToClone.length) {
        itemToClone = $(this).siblings(':first');
      }

      // grab item, clone, add marker class, add to collection
      itemToClone.children(':first-child').clone()
        .addClass("cloneditem-"+(i))
        .appendTo($(this));
    }
  });
}());

Thoughts

I've done all the improvements I can think of but:

I'm wondering about seeing $(this) appear twice.
Are the siblings, children, :first-child, :first usages the best options?
Any other improvements or best practices I've missed?

Is there something I could do better?


texts:
Any suggestions for improvement are welcome.

public static int[] concatArrays(int[] a1, int[] a2) {
    int n1 = a1.length;
    int n2 = a2.length;
    if(n1 == 0) return a2;
    if(n2 == 0) return a1;

    int n = n1 + n2;
    int counter = 0;
    int[] result = new int[n];
    for(; counter < n1; counter++) {
        result[counter] = a1[counter];
    }
    for(; counter < n; counter++) {
        result[counter] = a2[counter - n1];
    }
    return result;
}

public static int[] concatArrays(int[] a1, int a2) {
    int[] a2New = new int[] {a2};
    return concatArrays(a1, a2New);
}

public static int[] sort(int[] data) {
    if(data.length == 0) return new int[0];
    int nBefore = 0;
    int nAfter = 0;
    int[] beforeArray = new int[data.length];
    int[] afterArray  = new int[data.length];
    for(int i = 1; i < data.length; i++) {
        if(data[i] < data[0]) {
            beforeArray[nBefore++] = data[i];
        }
        else {
            afterArray[nAfter++] = data[i];
        }
    }
    int[] beforeArrayTrimmed = new int[nBefore];
    int[] afterArrayTrimmed = new int[nAfter];
    System.arraycopy(beforeArray, 0, beforeArrayTrimmed, 0, nBefore);
    System.arraycopy(afterArray, 0, afterArrayTrimmed, 0, nAfter);
    return concatArrays(
            concatArrays(sort(beforeArrayTrimmed), data[0]),
            sort(afterArrayTrimmed)
    );
}


texts:
I use a JavaScript library called Alertify to show simple, pretty messages, like "note created", or whatever. Often I want to send the user to a new page and then show an Alertify message.

I'm trying to find a way to do this on the fly, without tons of configuration.

Currently I do this by creating an AlertifyMessages object:

public class AlertifyMessages
{
    public string LogMessage { get; set; }
    public string LogCallback { get; set; }

    public string SuccessMessage { get; set; }
    public string SuccessCallback { get; set; }

    public string ErrorMessage { get; set; }
    public string ErrorCallback { get; set; }

    public AlertifyMessages() { }

    public AlertifyMessages(string logMessage = null, string logCallback = null,
                            string successMessage = null, string successCallback = null,
                            string errorMessage = null, string errorCallback = null)
    {
        LogMessage = logMessage;
        LogCallback = logCallback;
        SuccessMessage = successMessage;
        SuccessCallback = successCallback;
        ErrorMessage = errorMessage;
        ErrorCallback = errorCallback;
    }
}

and passing it to an action method:

public ActionResult Test()
{
    // RedirectToAction([action], [controller], [routeValues])
    return RedirectToAction("Details", "Notes",
        new AlertifyMessages(logMessage: "Lorem ipsum"));
}

and in the destination action method:

public class NotesController : Controller
{
    // GET
    public ActionResult Details(AlertifyMessages alertify)
    {
        return View(new NoteDetailsViewModel(alertify));
    }
}

which, finally, displays the messages in the view:

@if (Model.Alertify.LogMessage != null)
{
    @:@Html.Alertify("log", Model.Alertify.LogMessage, Model.Alertify.LogCallback)
}
@if (Model.Alertify.SuccessMessage != null)
{
    @:@Html.Alertify("success", Model.Alertify.SuccessMessage, Model.Alertify.SuccessCallback)
}
@if (Model.Alertify.ErrorMessage != null)
{
    @:@Html.Alertify("error", Model.Alertify.ErrorMessage, Model.Alertify.ErrorCallback)
}

The helper method Alertify just adds the JavaScript to call alertify.js, but you can see it here

Besides being a nightmare in so many ways, this doesn't even work unless the AlertifyMessage is all I need to pass. I could make some kind of complicated ToString() override to resolve this, but otherwise attempting to pass, say, an ID as well as an AlertifyMessages like so

return RedirectToAction("Details", "Notes",
    new { id = 1, alertify = new AlertifyMessages(logMessage: "Lorem ipsum")});

yields a URL like

https://localhost/Notes/Details/1?alertify=Project.Namespace.AlertifyMessages

This is way too complicated. There must be a better way.

  Edit: I'd like a way to specify the message in the calling action method (the one performing the redirect), and nowhere else. Is there a way to do this other than adding code to every single method and view?


texts: Loading sub items of TreeView in background

texts:
I am working with a TreeView (default control from .Net Framework) that displays hierachical data. Data are bound to the view using MVVM pattern with the HierarchicalDataTemplate.

<HierarchicalDataTemplate DataType="{x:Type models:TreeItemViewModel}" ItemsSource="{Binding Children, Mode=OneWay}">
    <TextBlock Text="{Binding Name}" />
</HierarchicalDataTemplate>

The child items are loaded automatically when the view requests the child collection. To stay responsive, the child items are loaded in background up to a specific depth:

public class TreeItemViewModel : ViewModelBase
{
    private readonly ObservableCollection<TreeItemViewModel> myChildren = new ObservableCollection<TreeItemViewModel>();
    private const int PRELOADING_DEPTH = 1;

    public string Name { get; set; }
    public bool IsLoaded { get; set; }
    public bool IsLoading { get; set; }

    public ObservableCollection<TreeItemViewModel> Children
    {
        get
        {
            ThreadPool.QueueUserWorkItem(o => EnsureChildrenAreLoaded(myChildren, 0));
            return myChildren;
        }
    }

    public void EnsureChildrenAreLoaded(ObservableCollection<TreeItemViewModel> childrenToFill, int depth)
    {
        if (!IsLoaded && !IsLoading)
        {
            IsLoading = true;
            var children = LoadChildren().ToArray();
            App.RunOnGuiThread(() =>
            {
                foreach (var child in children)
                    childrenToFill.Add(child);
                IsLoaded = true;
                IsLoading = false;
            });
        }
        if (depth < PRELOADING_DEPTH)
            foreach (var child in myChildren)
                child.EnsureChildrenAreLoaded(child.myChildren, depth + 1);
    }

    protected virtual IEnumerable<TreeItemViewModel> LoadChildren()
    {
        // logic for loading sub items
        return Enumerable.Empty<TreeItemViewModel>();
    }
}

RunOnGuiThread:

    public static void RunOnGuiThread(Action action)
    {
        if (Current == null || Current.Dispatcher == null)
            action();
        else
            Current.Dispatcher.Invoke(action);
    }

Is that a proper solution? Has it any disadvantages / potential for improvements?


texts: Finding a Bash script's Runfiles as generated by Bazel

texts:
When building a sh_binary with dependencies using Bazel, a tree of Runfiles containing the dependencies is generated:

my_executable
my_executable.sh
my_executable.runfiles/
    __main__/
        a_dependency/
            lib_dependency.sh

When deploying such a binary to a typical Unix filesystem, one would install the above file tree to /usr/local/opt/my_executable for example. Binaries however are usually linked to the /usr/local/bin directory:

ln -s /usr/local/opt/my_executable/my_executable /usr/local/bin/my_executable

Like this, it is possible to run the executable as my_executable from anywhere on the system. However the trivial approach of finding the runfiles with

RUNFILES="${BASH_SOURCE[0]}.runfiles/__main__"

then fails since ${BASH_SOURCE[0]} refers to the symlink. Preferably it would be possible to find Runfiles for an arbitrary number of "indirections" using symlinks. The following snippet provides a cross-platform implementation, that searches for a script's Runfiles by successively following symlinks.

# Determine the script's executable name
if [[ ! -v EXEC_NAME ]]; then
  export EXEC_NAME="${BASH_SOURCE[0]##*/}"
fi

# Determine the script's runfiles location, possibly resolving symlinks
if [[ ! -v RUNFILES ]]; then
  EXEC_PATH="${BASH_SOURCE[0]}"
  while [[ ! -a "$EXEC_PATH.runfiles" ]]; do
    if [[ ! -h "$EXEC_PATH" ]]; then
      printf "$EXEC_NAME: error: could not find runfiles\n" 1>&2
      exit 1
    fi
    EXEC_PATH=$(readlink "$EXEC_PATH")
  done
  export EXEC_PATH
  export RUNFILES="$EXEC_PATH.runfiles/__main__"
fi

And later in the script, it is then possible to use the dependency like this:

source "$RUNFILES/a_dependency/lib_dependency.sh"


texts:
I am new to JavaScript and jQuery, and I would like to know what can be improved of the code in this slideshow.

(function ($) {
let pointer = 0;

let slides = document.getElementsByClassName('mySlide');
for (let i = 0; i < slides.length; i++) {
    slides[i].style.left = 100 * i + "%";
    $('#dots').append('');
}

function changeSlide() {
    $('#slider').css('left', -100 * pointer + '%');
    changeDot();
    pointer++;
    if (pointer > (slides.length - 1)) pointer = 0;
    setTimeout(changeSlide, 3000);
}

$(document).ready(function () {
    changeSlide();
});

})(jQuery);

As can be observed in the code, I'm changing the left property of the
 inside another
 with overflow: hidden where the images are set to position: absolute.


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

texts:
I have a sparse matrix (term-document) containing integers (word counts/tf) and I am trying to compute the tf-idf, for every non-zero value in the sparse-matrix.

The formula for tf-idf I am using is:

log(1 + tf) * log(N / (1 + df))   # N is the number of coloumns of the matrix
# tf is the value at a cell of the matrix
# df is the number of non-zero elements in a row

So for a matrix csr, at an index [i,j] with a non-zero value, I want to compute:

csr[i,j] = log(1 + csr[i, j]) * log(csr.shape[1] / (1 + sum(csr[i] != 0))

Since I have a large matrix, I am using sparse matrices from scipy.sparse. Is it possible to do the tf-idf computation more efficiently?

import numpy as np
import scipy.sparse
import scipy.io

csr = scipy.sparse.csr_matrix(scipy.io.mmread('thedata'))

for iter1 in xrange(csr.shape[0]) :

    # Finding indices of non-zero data in the matrix
    tmp,non_zero_indices = csr[iter1].nonzero()
    # dont need tmp

    df = len(non_zero_indices)
    if df > 0 :
        # This line takes a long time...
        csr[iter1,non_zero_indices] = np.log(1.0+csr[iter1,non_zero_indices].todense())*np.log((csr.shape[1])/(1.0+df))


texts:
From problem #119 of the Project Euler :

The number 512 is interesting because it is equal to the sum of its digits raised to some power: 5 + 1 + 2 = 8, and 83 = 512. Another example of a number with this property is 614656 = 284.
We shall define an to be the nth term of this sequence and insist that a number must contain at least two digits to have a sum.
You are given that a2 = 512 and a10 = 614656.
Find a30.

The number 512 fits because :

5+1+2 = 8
and 83 = 512.

The number 17576 fits because :

1+7+5+7+6 = 26
and 263 = 17576.

There's my solution but it's extremely inefficient. I need the variable c to reach 25 but I haven't seen past 16.
    public static int c = 0;
    public static void TryAll(long x, long y)
    {
        for (int i = 2; i < 10; i++)
        {
            double powered = Math.Pow(y, i);
            if (x % y == 0 && powered == x && x % 10 != 0)
            {
                c++;
                Console.WriteLine("----- {0}", c);
                Console.WriteLine(powered);
                Console.WriteLine(y);
                Console.WriteLine(i);
            }
        }
    }
    public static void Main(string[] args)
    {
        int baseNum = 0;
        for (c = c; c < 26; baseNum++)
        {

            if (baseNum > 9)
            {
                int sum = 0;
                int baseNumD = baseNum;
                while (baseNumD != 0)
                {
                    sum += baseNumD % 10;
                    baseNumD /= 10;
                }
                TryAll(baseNum, sum);
            }
        }
    }


texts: "The Trip" challenge from Programming Challenges

texts:
Here is a problem from the book Programming Challenges by Skiena and Revilla:

  The Trip

  A number of students are members of a club that travels annually to
  exotic locations. Their destinations in the past have included
  Indianapolis, Phoenix, Nashville, Philadelphia, San Jose, and Atlanta.
  This spring they are planning a trip to Eindhoven. The group agrees in
  advance to share expenses equally, but it is not practical to have
  them share every expense as it occurs. So individuals in the group pay
  for particular things, like meals, hotels, taxi rides, plane tickets,
  etc. After the trip, each student's expenses are tallied and money is
  exchanged so that the net cost to each is the same, to within one
  cent. In the past, this money exchange has been tedious and time
  consuming. Your job is to compute, from a list of expenses, the
  minimum amount of money that must change hands in order to equalize
  (within a cent) all the students' costs.

  The Input

  Standard input will contain the information for several trips. The
  information for each trip consists of a line containing a positive
  integer, n, the number of students on the trip, followed by n lines of
  input, each containing the amount, in dollars and cents, spent by a
  student. There are no more than 1000 students and no student spent
  more than $10,000.00. A single line containing 0 follows the
  information for the last trip.

  The Output

  For each trip, output a line stating the total amount of money, in
  dollars and cents, that must be exchanged to equalize the students'
  costs.

  Sample Input

3
10.00
20.00
30.00
4
15.00
15.01
3.00
3.01
0

  Sample Output

$10.00
$11.99

Here is my solution which gives correct answer for all inputs I have tried so far, but there must be some case when it does not work because the judge says so. Can anybody help me to understand why?

int main (int argc, char * argv[]) {
    int64_t a;
    float paid[1000];
    std::vector<float> results;
    while (std::cin >> a && a != 0) {

        int sum = 0;
        for (int i = 0; i < a; i++) {
            std::cin >> paid[i];
            paid[i] *= 100;
            sum += paid[i];
        }
        int result = 0;
        int avg = (std::ceil)((float)sum/a);

        int mod = sum % a;
        int c = 0;
        if (mod > 0) {
            for (int i = 0; i < a; i++) {
                if (c >= a - mod)
                    break;
                if (paid[i] < avg) {
                    paid[i]++;
                    c++;
                }
            }
            for (int i = 0; i < a; i++) {
                if (c >= a - mod)
                    break;
                if (paid[i] > avg) {
                    paid[i] += a - mod - c;
                    break;
                }
            }
        }

        for (int i = 0; i < a; i++) {
            if (paid[i] > avg) {
                result += (paid[i] - avg);
            }
        }

        results.push_back((float)result/100);
    }
    std::cout << std::fixed;
    std::cout << std::setprecision(2);
    for (std::vector<float>::iterator it = results.begin(); it != results.end(); ++it) {
        std::cout << "$" << *it << std::endl;
    }
    return 0;
}


texts: Fetching user details, posts, and comments using promises in ExpressJS

texts:
I'm creating an API service in NodeJS using Express (version 4) Framework. Created an MVC architecture for the same (no views, only model, and controller as this is an API).

Also, there are routes. When a request is made, the router redirects the request to the controller function and from there functions written in models are called and the response is returned to users in JSON format.

I gotta make multiple asynchronous requests from the controller for some functions. I earlier nested the asynchronous calls (callback hell) before I switched to Promises.

My NodeJS version is 6.12 and it does not support async/await.

I wanna make sure the way I implemented promises is correct.

Here is a sample function from my controller using which I fetch user details.
The user passes a userID and using that I fetch user details. And using details from the 1st async request, I fetch user's posts and after that, I fetch user comments. I wanna make sure my implementation is correct.

Note: I removed error handling from some asynchronous requests to make the code look more understandable.

exports.fetchUserInformation = function (req, res) {
  var response = {};

  if (req.query.userId) {
    var userId = req.query.userId;
    response['userId'] = userId;
    new Promise(function (resolve, reject) {
      var param = {
        userId: userId
      };
      //1 - Call to Model function to fetch user info
      User.getUserDetails(param, function (err, rows) {
        if (err) {
          reject(err);
        } else {
          resolve(rows);
        }
      });
    }).then(function (result1) {
      var result2;
      response['userDetails'] = result1;

      //Pass result from previous promise to fetch next result
      var params1 = {
        userId: userId,
        result: result1
      };
      //2 - Call to Model function to fetch user timeline posts
      User.fetchUserPosts(params1, function (err, rows) {
        result2 = rows;
      });
    }).then(function (result2) {
      response['userPosts'] = result2;

      var params2 = {
        userId: userId,
        userType: 'user'
      };
      User.fetchUserComments(params2, function (err, rows) {

        response['userComments'] = rows;

        //return the response to user
        res.json({
          success: true,
          response: response
        });

      });
    }).catch(function (error) {
      //error logging starts
      var logData = {
        stackTrace: error
      };
      logHlpr.logThisError(logData); //calling another function to log data
      //error logging ends

      res.json({
        success: false
      });
    });
  }
};

I've few doubts:

I'm making 3 async requests to the Model - User.getUserDetails, User.fetchUserPosts, User.fetchUserComments using one promise. Should I implement 3 promises?

I'm pretty new to NodeJS and promises.


texts: Polymorphism with overrides and base calls simulating an employee

texts:
I've studied and worked a lot on the subject for a month or two to get closer to the concept in a cleaner way, i.e. no virtual tables and no bunch of functions with prefixes etc. and most importantly functions are to be defined within structs as pointers to simulate OOP classes as much as possible.

Only constructors with prefixes are to be available publically. I also wanted to have the ability to call the override super method.

I'm not sure if following example is a compile time or run time polymorphism but it's satisfying the runtime aspects of it but then isn't it what we need without the need to have a look at the type of object? Please enlighten.

I'm putting it out there for critical analysis and review or problem with the approach.

The idea is to introduce a pointer of the parent type that retains a reference to original methods, the sub structures can override the parent implementation of the methods but the call to original methods are available via base pointer.

main.c

int main() {
    Person* person = Person_new("John", "Doe");
    Employee* employee = Employee_new("Jane", "Doe", "Acme", 40000);
    person->display(person); // displaying Person object
    puts("------");
    employee->super.display(&employee->super); // displaying employee info
    // ((Person *)employee)->display(employee); // or this
    person->release(person);
    employee->super.release(&employee->super);
    return 0;
}

person.h

typedef struct Person Person;
struct Person {
    Person *base; // to keep access to original funcs in case of overrides
    char* first;
    char* last;
    void (*display)(const Person *self);
    void (*release)(Person *self);
};
Person* Person_new(char* first, char* last);

person.c

static void display(const Person *self) {
    printf("First: %s\n", self->first);
    printf("Last: %s\n", self->last);
}

static void release(Person *self) {
    free(self);
}

Person* Person_new(char* first, char* last) {
    Person* self = malloc(sizeof *self);
    if(self == NULL) return NULL;

    self->first = strdup(first);
    self->last = strdup(last);
    self->display = display;
    self->release = release;

    self->base = self; // assigning reference to self to retain original functions in case they get overridden

    return self;
}

employee.h

typedef struct Employee Employee;
struct Employee {
    Person super;
    char* company;
    int salary;
};
Employee* Employee_new(char* first, char* last, char* company, int salary);

employee.c

static void display(const Person* self) {
    self->base->display(self->base); // calling super class func

    printf("Company: %s\n", ((Employee *)self)->company);
    printf("Salary: %d\n", ((Employee*)self)->salary);
}

static void release(Person *self) {
    self->base->release(self->base); // calling super class func
    free(self);
}

Employee* Employee_new(char* first, char* last, char* company, int salary) {
    Employee* employee = malloc(sizeof(Employee));
    if(employee == NULL) return NULL;

    employee->super = *Person_new(first, last);
    employee->super.display = display; // override
    employee->super.release = release; // override

    employee->company = strdup(company);
    employee->salary = salary;

    return employee;
}

First: John
Last: Doe
---
First: Jane
Last: Doe
Company: Acme
Salary: 40000

Edit

Discussion with Pablo confirmed that the approach is correct. I'm still seeking some discussion on whether this approach falls under compile time or run time polymorphism.


texts:
First I'm not sure what this is called formally but whatever.

Basically I need to form "wildcard buckets". I think the best way to explain what I need to do is to take an example. For instance, say I have the three words "aaa", "aab", and "baa".

Let me use * as the wildcard. Then from aaa I can form -aa, a-a, aa-, --a, a--, a-a, and ---. I then add these to a dictionary where the keys are the buckets and values are sets of (complete) words that fit these buckets. I repeat for all my words. So in the end I get that, for instance, -a- fits all three of the example words that I have above.

I have working code, but it is very slow in forming these buckets when I have a word list that has hundreds of thousands of words.

for numberSpaces in range(0, len(word) + 1):  # loop through all spaces of word
    buckets = itertools.combinations(range(0, len(word)), numberSpaces)
    for indicesToReplace in buckets:  # for each index in this combination
        newWord = word
        for index in indicesToReplace:  # replace character with "*"
            newWord = newWord[0:index] + "*" + newWord[index + 1:]
        if newWord not in bucketDictionary.keys(): # Add to dictionary
            bucketDictionary[newWord] = set()
        bucketDictionary[newWord].add(word)

I would like to know how to best optimize this code. I've tried recursion but I'm not sure if that is any better than this iterative method.

Thank you!


texts:
Let's assume we have the following situation:

Multiple project topics exist, each corresponding to a natural number n,
students can sign in and choose two projects and give them either priority_1 or priority_2,
The name and the time when they sign in is tracked as well.

With all of the information above assume you receive data in the from of a txt-file looking like this

Martin  16:46:32    8   19
Alice   15:22:56    8   12
Alex    17:23:11    19  1
John    19:02:11    11  13
Phillip 19:03:11    11  13
Diego   15:23:57    14  5
Jack    16:46:45    8   3

where the columns represent the name, time, priority 1 and priority 2 in this order. You can assume that all of them signed in on the same day and students which signed in first have a higher priority in comparison to the others.

I wanted to write a program that takes this txt-file as input and returns a txt-file with output

Name    Assigned Project
Alice   8
Diego   14
Martin  19
Jack    3
Alex    1
John    11
Phillip 13

The solution I came up with looks like this:

import numpy as np

dat = np.genfromtxt("data.txt", dtype="str")

class person:
    def __init__(self, name, time, prio1, prio2):
        self.name = name
        sp = time.split(":")
        t = sp[0]*3600 + sp[1]*60 + sp[2]
        self.time = t
        self.prio1 = prio1
        self.prio2 = prio2

names = dat[:, 0]
time = dat[:, 1]
prio1 = dat[:, 2]
prio2 = dat[:, 3]

people = []
for i,j,k,l in zip(names, time, prio1, prio2):
    people.append(person(i,j,k,l))

people_sorted_time = sorted(people, key=lambda x: x.time)

for k in range(len(people_sorted_time)):
    for j in range(k + 1, len(people_sorted_time)):
        if people_sorted_time[k].prio1 == people_sorted_time[j].prio1:
            people_sorted_time[j].prio1 = people_sorted_time[j].prio2

res = open("results","w")
res.write("Name"+"\t"+"Assigned Project"+"\n")
for k in range(len(people_sorted_time)):
    res.write(people_sorted_time[k].name + "\t"
        + people_sorted_time[k].prio1 + "\n")

The code seems to work fine, but I'm not sure if I actually was able to take care of all edge-cases. I'm also not sure if this is really a efficient way to solve the problem, I rarely code stuff like that (mostly computational physics stuff), and would appreciate any kind of suggestions on how one could improve the code in general.

EDIT: What I realized after some thinking is that it would probably be  quite hard do implement further priority variables (like prio 3, prio 4, etc.). If someone could suggest a better way of deciding how to assign the projects in terms of priority, I'd be glad to see it.


texts:
this.Items is a list of products. Each product has a category (product.Attributes["category"]).

I want to render a drop down list, where all the products are grouped by category.
This works well, but how could I improve it? Could there be a way to not use a dictionary?

protected override void RenderContents(System.Web.UI.HtmlTextWriter writer)
{
    var groups = new Dictionary<string, List<ListItem>>();

    // sort by category
    foreach (ListItem product in this.Items)
    {
        if (!groups.ContainsKey(category))
        {
            groups.Add(category, new List<ListItem>());
        }
        groups[category].Add(product);
    }

    // render each category
    foreach (var group in groups)
    {
        // <optgroup>
        RenderOptionGroupBeginTag(group.Key, writer);

        // each option
        group.Value.ForEach(p => this.RenderListItem(p, writer));

        // </optgroup>
        RenderOptionGroupEndTag(writer);
    }
}


texts:
Please help me decide whether this should be good or bad idea to declare a Singleton variable in Global.asax file. (It is not actually singleton pattern, I just want to make sure that only one instance is created for this class.)

public class Global : System.Web.HttpApplication
{
    private HTML5Video dailyHtml5Video;

    public HTML5Video DailyHtml5Video
    {
        get
        {
            if (dailyHtml5Video==null)
            {
                dailyHtml5Video = new HTML5Video();
            }

            return dailyHtml5Video;
        }
    }

}

Will this cause any thread-related issues or other possible issues?


texts:
I have created a naive string parser for unsolicited wpa_supplicant messages.  I could potentially extend this in the future.  I am not sure if this is the best way to parse these kinds of messages.  I would prefer something resembling a switch statement but I am not sure I could do that without increasing code complexity.  I would like a more scalable solution though, in case I need to look for many different message types in the future.

Code:

#include <stdio.h>
#include <string>
#include <map>

#define DEBUG_PRINT printf

class wpa_monitor
{
    public:
        void handle_wpa_message( const std::string& message );

    private:
        std::map< std::string, std::string > mac_ssid_association_map;
};

void wpa_monitor::handle_wpa_message( const std::string& message )
{
    DEBUG_PRINT( "WPA event: '%s'\n", message.c_str() );
    size_t pos;

    pos = message.find( "Trying to associate with " );

    if( pos != std::string::npos )
    {
        std::string mac_substring = message.substr( pos + sizeof( "Trying to associate with " ) - 1 );
        std::string mac_addr = mac_substring.substr( 0, mac_substring.find( " " ) );

        if( mac_addr.empty() )
        {
            return;
        }

        pos = message.find( "SSID='" );

        if( pos == std::string::npos )
        {
            return;
        }

        std::string ssid_substring = message.substr( pos + sizeof( "SSID='" ) - 1 );
        std::string ssid = ssid_substring.substr( 0, ssid_substring.find( "'" ) );

        DEBUG_PRINT( "Associating mac_address '%s' with ssid '%s'\n", mac_addr.c_str(), ssid.c_str() );
        mac_ssid_association_map.insert( std::make_pair< std::string, std::string >( mac_addr, ssid ) );

        return;
    }

    pos = message.find( "CTRL-EVENT-CONNECTED - Connection to " );

    if( pos != std::string::npos )
    {
        std::string mac_substring = message.substr( pos + sizeof( "CTRL-EVENT-CONNECTED - Connection to " ) - 1 );
        std::string mac_addr = mac_substring.substr( 0, mac_substring.find( " " ) );

        if( mac_addr.empty() )
        {
            return;
        }

        std::map< std::string, std::string >::iterator it = mac_ssid_association_map.find( mac_addr );

        if( it != mac_ssid_association_map.end() )
        {
            DEBUG_PRINT( "We are now connected to ssid '%s'\n", it->second.c_str() );
        }

        return;
    }

    pos = message.find( "CTRL-EVENT-SCAN-RESULTS" );

    if( pos != std::string::npos )
    {
        //scan results ready
        DEBUG_PRINT( "Scan results are ready\n" );
        return;
    }
}

Example Output (personal data obfuscated):

WPA event: '<3>CTRL-EVENT-SCAN-STARTED '
WPA event: '<3>CTRL-EVENT-BSS-ADDED 0 00:00:00:00:00:00'
WPA event: '<3>CTRL-EVENT-BSS-ADDED 1 00:00:00:00:00:01'
WPA event: '<3>CTRL-EVENT-BSS-ADDED 2 00:00:00:00:00:02'
WPA event: '<3>CTRL-EVENT-SCAN-RESULTS '
Scan results are ready
WPA event: '<3>WPS-AP-AVAILABLE '
WPA event: '<3>Trying to associate with 00:00:00:00:00:00 (SSID='my_ssid' freq=5745 MHz)'
Associating mac_address '00:00:00:00:00:00' with ssid 'my_ssid'
WPA event: '<3>Associated with 00:00:00:00:00:00'
WPA event: '<3>CTRL-EVENT-SUBNET-STATUS-UPDATE status=0'
WPA event: '<3>WPA: Key negotiation completed with 00:00:00:00:00:00 [PTK=CCMP GTK=TKIP]'
WPA event: '<3>CTRL-EVENT-CONNECTED - Connection to 00:00:00:00:00:00 completed [id=1 id_str=]'
We are now connected to ssid 'my_ssid'


texts: Using Python tricks to find Minimum Coin Change (Amazon Interview)

texts:
What is the coin change problem?
The change-making problem addresses the question of finding the minimum number of coins (of certain denominations) that add up to a given amount of money. It is a special case of the integer knapsack problem and has applications wider than just currency. Read more: Wiki
My code:
def coin_change(n,coins,known_results):
     min_coins = n

     if n in coins:
        known_results[n] = 1
        return 1

     elif known_results[n] > 0:
            return known_results[n]

     else:
        for i in [c for c in coins if c<=n]:
            count = 1 + coin_change(n-i,coins,known_results)
            if count < min_coins:
                min_coins = count

                known_results[n] = min_coins

     return min_coins

coins = [1,2,3]
n = 4
known_results = [0]*(n+1)
print(coin_change(n,coins,known_results))

Question:
This code works fine and perfectly but can it be done better and more efficiently using python tricks giving it an edge more the other languages? Can it be more efficient and better?


texts: Create directories for outputs based on setting

texts:
I have a dict with a series of bools to specify if a particular aspect of my program will be run (e.g. settings['A'] and settings['B']).

If they are run the results need to go into an aptly named directory.  The directory names (not the entire path) are also stored in the dict (e.g. settings['outputDirNameOut1'] and settings['outputDirNameA'])

In order to create the directories I'm using the following code.

for each in filePathList:
    path = os.path.dirname(each)

    if not os.path.exists(os.path.join(path, settings['outputDirNameOut1'])):
        os.makedirs(os.path.join(path, settings['outputDirNameOut1']))

    if settings['A'] is True and not os.path.exists(os.path.join(path, settings['outputDirNameA'])):
        os.makedirs(os.path.join(path, settings['outputDirNameA']))

    if settings['B'] is True and not os.path.exists(os.path.join(path, settings['outputDirNameB'])):
        os.makedirs(os.path.join(path, settings['outputDirNameThreshold']))

    if settings['C'] is True and not os.path.exists(os.path.join(path, settings['outputDirNameC'])):
        os.makedirs(os.path.join(path, settings['outputDirNameC']))
        os.makedirs(os.path.join(path, settings['outputDirNameOut2']))

    if settings['D'] is True and not os.path.exists(os.path.join(path, settings['outputDirNameOut2'])):
        os.makedirs(os.path.join(path, settings['outputDirNameOut2']))

I'm wondering if there's a simpler, easier to read way to accomplish this.


texts: Changing attributes in different objects

texts:
First some background - I am developing a Python program which has thousands of lines spread across many files. I have intermediate programming skills - and no commercial OOP experience, and have taught myself Python recently. I have come across a problem which I can solve, in a number of different ways, but I'm not really happy with any of my solutions - they don't feel quite right from an OOP point of view. I have tried to make things generic so they can be used for lots of different options, but by doing so it seems massively convoluted.

I have distilled the problem down into a comparatively small piece of code for review. I have a main object, and I have an object which holds some options (which are just true/false for now, but could be other things in the future). I then have a third object (a tkinter button) that each show the status of the option (via being sunken or raised), and when clicked, change the value.

I felt the right way to do this would be for the functionality (in italics above) to be contained entirely in the toggleButton class. At first I just passed it self.options.Option1 (or whatever), but that didn't work. I then read up on does Python pass by value or reference, which (I know I am simplifying here) seemed to say that when you pass an object it passes the object, but when you pass something like an integer or boolean it passes the value. So I changed it to what you see now - where you pass the variable, an integer representing the variable, and changing the options class to have a function to change the option. It all seems so needlessly verbose. Is there a better way?

from Tkinter import *

class optionsClass():
    _OPTION1 = 1
    _OPTION2 = 2

    def __init__(self):
        self.Option1 = True
        self.Option2 = False

    def change(self, optionid):
        if optionid == optionsClass._OPTION1:
            if self.Option1 == True:
                self.Option1 = False
            else:
                self.Option1 = True
        if optionid == optionsClass._OPTION2:
            if self.Option2 == True:
                self.Option2 = False
            else:
                self.Option2 = True

class toggleButton(Button):
    def __init__(self, master, targetObject, targetoptionid, initialval
                    , **kwargs):
        Button.__init__(self, master, command = self.callback, **kwargs)
        self.targetoptionid = targetoptionid
        self.targetObject = targetObject
        if initialval==True:
            self.config(relief=SUNKEN)
        else:
            self.config(relief=RAISED)

    def callback(self):
        self.targetObject.change(self.targetoptionid)
        if self.cget("relief") == SUNKEN:
            self.config(relief=RAISED)
        else:
            self.config(relief=SUNKEN)

class mainframe(Frame):
    def __init__(self, master):
        Frame.__init__(self, master)
        self.options = optionsClass()
        option1box = toggleButton(self, self.options, optionsClass._OPTION1,
                self.options.Option1, text="Option 1")
        option1box.grid(column=0, row=0)
        option2box = toggleButton(self, self.options, optionsClass._OPTION2,
                self.options.Option2, text="Option 2")
        option2box.grid(column=0, row=1)
        testbutton= Button(self, command = self.outputoptions,
                             text="Return option values")
        testbutton.grid(column=0, row=2)

    def outputoptions(self):
        print "Option 1 is " + str(self.options.Option1)
        print "Option 2 is " + str(self.options.Option2)

top = Tk()
m = mainframe(top)
m.pack()
top.mainloop()

Things to bear in mind...

I would like the options class to work for things other than boolean without much difficulty.
I like the convenience and readability of the main class to simply say self.options.Option1.
Ideally there will still be three classes, as mainframe and option do a lot more in the actual program, and toggleButton is used multiple times and is therefore a good candidate to be a class.


texts:
I made the code underneath to sort my array and group people with the same score to show who all got 1st, 2nd and 3rd.
the "points" variable looks like this
points: {
  '204255221017214977': 3,
  '208993609255485441': 5,
  '382197942762602496': 4,
  '664606841409634324': 5,
  '779857709155090432': 4,
  '381084508276916225': 5,
  '794200859612545075': 4,
  '155149108183695360': 4,
  '438978127973318656': 3,
  '304028235082104843': 2,
  '174548757151481856': 1
}

I was wondering if there is a much easier way to sort and put together the string like I did underneath with much easier code. Cuz I'll be honest this code looks and feels aweful.
example endresult:
:first_place: @Excanator had 5 points
:first_place: @zerow had 5 points
:first_place: @AnimeHotOwO had 5 points

:second_place: @christmas beans had 4 points
:second_place: @ExcavatorGames had 4 points
:second_place: @Dyno had 4 points
:second_place: @LogiBot Premium had 4 points

:third_place: @Restarter v3 had 3 points
:third_place: @YAGPDB.xyz had 3 points

@aNt had 2 points
@Kaori had 1 point

const sorted = Object.keys(points).sort((a, b) => {
    return points[b] - points[a]
})

var results = `\n`

var firstPlace = points[sorted[0]]
var secondPlace = null
var thirdPlace = null
var leftover = null

for(const key of sorted) {
    var amount = points[key]
    if(leftover){
        results += `<@${key}> had ${amount} point${amount === 1 ? '' : 's'}\n`
    } else if(thirdPlace) {
        if(thirdPlace === amount) {
            results += `:third_place: <@${key}> had ${amount} point${amount === 1 ? '' : 's'}\n`
        } else {
            results += `\n`
            results += `<@${key}> had ${amount} point${amount === 1 ? '' : 's'}\n`
            leftover = amount
        }
    } else if(secondPlace) {
        if(secondPlace === amount) {
            results += `:second_place: <@${key}> had ${amount} point${amount === 1 ? '' : 's'}\n`
        } else {
            results += `\n`
            results += `:third_place: <@${key}> had ${amount} point${amount === 1 ? '' : 's'}\n`
            thirdPlace = amount
        }
    } else if(firstPlace) {
        if(firstPlace === amount) {
            results += `:first_place: <@${key}> had ${amount} point${amount === 1 ? '' : 's'}\n`
        } else {
            results += `\n`
            results += `:second_place: <@${key}> had ${amount} point${amount === 1 ? '' : 's'}\n`
            secondPlace = amount
        }
    }
}
```


texts:
I have created a python system that runs Linux core files through the crash debugger with some python extensions. This all works fine but one bit of is problematic.

These files are send to the system in gzip format and consist of a single huge data file. The compressed file can often be as big as 20G. The unzipping works fine but is very slow and often uses huge amounts of memory. As an example, last night this processed a 14G gzip file and it took 9.2 hours to uncompress it (60G uncompressed) and the memory utilisation hovered between 30G, peaking at 60G.

Starting to think perhaps my code is the cause.

def chk_gzip_file(FILE):
    logger.info ("Will write uncompressed file to: "+ COREDIR)
    if os.path.isdir(FILE) == False:
        inF = gzip.open(FILE, 'rb')
        s = inF.read()
        inF.close()
        gzip_fname = os.path.basename(FILE)
        fname = gzip_fname[:-3]
        uncompressed_path = os.path.join(COREDIR, fname)
        open(uncompressed_path, 'w').write(s)
        uncompressedfile=COREDIR+"/"+fname
        return uncompressedfile
    else:
        logger.critical ("No gz file found  : " + FILE)
        sys.exit()

I am not a programmer so I imagine this is fairly poor code. Can this be improved for huge files? I know that speed will be an issue as gzip uncompress is single threaded.


texts: Calculate amount of necessary ingredients

texts:
I have started to learn C and decided to recreate my bakery task in C.
As I am new to the language, I am unsure if I have approached the task in the right way using structs. Feedback on the style of the code would also be appreciated.

#include <stdio.h>

double cup_ingredients[4] = {4.0,0.1,12.0,14.0}; // Amount of each ingredient for 1 cupcake = {Butter, eggs, flour, sugar}
double lemon_ingredients[4] = {80.0,4.5,240.0,300.0}; // Amount of each ingredient for 1 lemon cake = {Butter, eggs, flour, sugar}
double total[4];
double cup_req;
double lemon_req;

struct Bags {
    int big_bag;
    int med_bag;
    int small_bag;
};

void calc_bag(double total_ingredient, struct Bags* bag_sizes, struct Bags* type);

int main() {
    printf("How many cupcakes would you like? ");
    scanf("%lf", &cup_req);

    for (int x = 0; x<cup_req; x++){ // For the number of cupcakes required:
        for (int y = 0; y<4; y++){ // For each ingredient
            total[y] += cup_ingredients[y]; // Add the amount of each ingredient to the total amount of that ingredient
        }
    }

    printf("How many lemon cakes would you like? ");
    scanf("%lf", &lemon_req);

    for (int x = 0; x<lemon_req; x++){ // For the number of lemon cakes:
        for (int y = 0; y<4; y++){ // For each ingredient
            total[y] += lemon_ingredients[y]; // Add the amount of each ingredient to the total amount of that ingredient
        }
    }

    //Structs for the amount of each ingredient a bag can hold
    struct Bags Butter_size = {.big_bag = 500, .med_bag = 250, .small_bag = 125};
    struct Bags Egg_size = {.big_bag = 12, .med_bag = 10, .small_bag = 6};
    struct Bags Flour_size = {.big_bag = 750, .med_bag = 500, .small_bag = 250};
    struct Bags Sugar_size = {.big_bag = 600, .med_bag = 400, .small_bag = 200};

    //Set the bags required to 0
    struct Bags Butter_req = {0,0,0};
    struct Bags Egg_req = {0,0,0};
    struct Bags Flour_req = {0,0,0};
    struct Bags Sugar_req = {0,0,0};

    //Calculate the amount of each ingredient bag required
    calc_bag(total[0], &Butter_size, &Butter_req);
    calc_bag(total[1], &Egg_size, &Egg_req);
    calc_bag(total[2], &Flour_size, &Flour_req);
    calc_bag(total[3], &Sugar_size, &Sugar_req);

    printf("\nButter: %d large bags, %d medium bags, %d small bags.", Butter_req.big_bag, Butter_req.med_bag, Butter_req.small_bag);
    printf("\nEgg: %d large bags, %d medium bags, %d small bags.", Egg_req.big_bag, Egg_req.med_bag, Egg_req.small_bag);
    printf("\nFlour: %d large bags, %d medium bags, %d small bags.", Flour_req.big_bag, Flour_req.med_bag, Flour_req.small_bag);
    printf("\nSugar: %d large bags, %d medium bags, %d small bags.", Sugar_req.big_bag, Sugar_req.med_bag, Sugar_req.small_bag);
}

void calc_bag(double total_ingredient, struct Bags* bag_sizes, struct Bags* type){
    while (total_ingredient > 0){
        if (total_ingredient > bag_sizes->big_bag) {
            type->big_bag++;
            total_ingredient -= bag_sizes->big_bag;
        }
        else if (total_ingredient > bag_sizes->med_bag) {
            type->med_bag++;
            total_ingredient -= bag_sizes->med_bag;
        }
        else if (total_ingredient > bag_sizes->small_bag) {
            type->small_bag++;
            total_ingredient -= bag_sizes->small_bag;
        }
        else {
            type->small_bag++;
            total_ingredient = 0;
        }
    }
}


texts:
I've written a query to compare the clients in our database with the people in a list that I've received. It needs to check if anyone from the list is one of our clients. I've created a temporary table which has been filled with the names and the query below makes a cross-join with the two tables. That query works very slowly (two very large tables), so I was wondering if there's any way to speed this up.
Would it be faster to just join everything in the database and compare strings in code (java or something similar)?

(The second list was just names, so I can't use any indexed columns in our database.)

select C.NUMCLI, C.NAAM, T.FULLNAME, (UTL_MATCH.EDIT_DISTANCE_SIMILARITY(NAAM, FULLNAME))
as DIFF from (select LASTNAME ||' '|| FIRSTNAME ||' '|| MIDDLENAME  as FULLNAME from
TMP_CONTROL) T, (select NUMCLI, NOMCLI ||' '|| PRNCLI as NAAM from CLIENT
where CODLAN = 3 and STAANN <> 'D') C
where (UTL_MATCH.EDIT_DISTANCE_SIMILARITY(NAAM, FULLNAME)) >= 60

NOTE: A large portion of people on the list may have their name written in a slightly different manner, which is why I'm using the EDIT_DISTANCE SIMILARITY >= 60. The goal is just to filter out the large differences, so I can easily compare the smaller ones.

Update

This is the explain-plan for the query:

SQL> SET LINESIZE 130
SQL> SET PAGESIZE 0
SQL> SELECT *
  2  FROM   TABLE(DBMS_XPLAN.DISPLAY);
Plan hash value: 1462516232

---------------------------------------------------------------------------------
| Id  | Operation          | Name       | Rows  | Bytes | Cost (%CPU)| Time     |
---------------------------------------------------------------------------------
|   0 | SELECT STATEMENT   |            |    74M|  3041M|  2197K  (3)| 07:19:29 |
|   1 |  NESTED LOOPS      |            |    74M|  3041M|  2197K  (3)| 07:19:29 |
|*  2 |   TABLE ACCESS FULL| CLIENT     | 71843 |  2174K|  2386   (2)| 00:00:29 |
|*  3 |   TABLE ACCESS FULL| TMP_CONTROL|  1033 | 12396 |    31   (4)| 00:00:01 |
---------------------------------------------------------------------------------

Predicate Information (identified by operation id):

2 - filter("STAANN"<>'D' AND TO_NUMBER("CODLAN")=3)
3 - filter("UTL_MATCH"."EDIT_DISTANCE_SIMILARITY"("NOMCLI"||'
          '||"PRNCLI","LASTNAME"||' '||"FIRSTNAME"||' '||"MIDDLENAME")>=60)

17 rows selected.