texts: Converting a natural number to a permutation matrix in Python. How to speed it up perhaps avoiding messing around with lists, sets and dicts?

texts:
It is something a bit complex to explain here, but the  code bellow takes a 128-bit number and converts it into a permutation matrix, a beast which I have already faced before. The matrix is represented as a list of numbers. Each number is a row.
The way I've found to do the mapping number->matrix was to convert the number through a multi-radix (or something that could be considered one)  numeric system, so each digit corresponds to a row in the matrix. Since there can't be duplicate rows, some offset magic was needed (that is one of the uses of map taboo used below).
How could this code be improved regarding data structures and use of loops?
More conceptually, what about my choice of conversion through a multi-radix system?
Could it be simpler and still be a perfect mapping from naturals to permutation matrices?

ps. There are 2^128 numbers and 35! matrices.  2^128 < 35! , So all numbers can have a unique corresponding matrix.

from sortedcontainers import SortedSet, SortedDict
def permutmatrix2int(m):
    """Convert permutation matrix 35x35 to number."""
    taboo = SortedSet()
    digits = []
    rowid = 34
    for bit in m[:-1]:
        bitold = bit
        for f in taboo:
            if bitold >= f:
                bit -= 1
        taboo.add(bitold)
        digits.append(bit)
        rowid -= 1

    big_number = digits[0]
    pos = 0
    base = b = 35
    for digit in digits[1:]:
        big_number += b * digit
        pos += 1
        base -= 1
        b *= base

    return big_number

def int2permutmatrix(big_number):
    """Convert number to permutation matrix 35x35."""
    taboo = SortedDict()
    res = big_number
    base = 35
    bit = 0
    while base > 1:
        res, bit = divmod(res, base)
        if res + bit == 0:
            bit = 0
        for ta in taboo:
            if bit >= ta:
                bit += 1
        base -= 1
        taboo[bit] = base

    for bit in range(35):
        if bit not in taboo:
            break
    taboo[bit] = base - 1

    return list(map(
        itemgetter(0), sorted(taboo.items(), reverse=True, key=itemgetter(1))
    ))


texts:
I wrote the function below, but I feel it could be improved and so I am open to your wise suggestions.
The use case for this is to manipulate Excel data. As a freelance dev, I cannot always choose the architecture nor the source of data I have to manipulate :-/

Sub getAdoRsFromExcel_test()
'with error retrieval'
    Dim rs As ADODB.Recordset, fName As String, sSql As String
    fName = ThisWorkbook.FullName
    sSql = "select * from [countries$a:b] where country like '%a%'"
    Set rs = getAdoRsFromExcel(fName, sSql)
    If Not rs Is Nothing Then
        Debug.Print Now, rs.EOF, rs.BOF, rs.RecordCount
    Else
        Debug.Print Now, "Shit happens"
    End If
End Sub

Function getAdoRsFromExcel(fileName As String, sSql As String) As ADODB.Recordset
'given Excel full file name and SQL query (in appropriate syntax), returns an ADODB recordset
'in case of error, returns Nothing

    Dim con As ADODB.Connection, rs As ADODB.Recordset, sConn As String, sConn2 As String

    sConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & fileName
    sConn2 = ";Extended Properties=""Excel 12.0 Xml;HDR=YES"";"
    On Error GoTo hell
    Set con = New ADODB.Connection
    con.Open sConn & sConn2
    Set rs = New ADODB.Recordset
    rs.CursorLocation = adUseClient
    rs.Open sSql, con, adOpenKeyset 'rather use this so RecordCount works
    Set getAdoRsFromExcel = rs
    'Debug.Print Format$(Now, "hh:mm:ss"), rs.RecordCount, sSql
    Set rs = Nothing
adios:
    Exit Function
hell:
    Debug.Print Format$(Now, "hh:mm:ss"), Err.Number, Err.Description
    Select Case Err.Number
        Case -2147217904: Debug.Print Format$(Now, "hh:mm:ss"), "Wrong field name ?"
        Case -2147467259: Debug.Print Format$(Now, "hh:mm:ss"), "Wrong file name ?"
        Case Else: Debug.Print Format$(Now, "hh:mm:ss"), "Shit happens - learn from mistakes"
    End Select
    'On Error Resume Next
    'rs.Close
    'con.Close
    Set getAdoRsFromExcel = Nothing
    Resume adios
    Resume
End Function


texts: Extracting specific words from PANDAS dataframe

texts:
I'm new to data analysis and doing some online training. I have a task to extract specific words from specific column in data frame, then count those words and then just to do some min/max/mean ant etc... I didn't find specific any method for that in Pandas so I have tried to create function for that. I have done this so far:
import re
import string

def countWords(data_frame, selected_words):
    words_dict = {}

    for sentence in data_frame:
        remove = string.punctuation
        remove = remove.replace("'", "") # don't remove hyphens
        pattern = r"[{}]".format(remove) # create the pattern

        test = re.sub(pattern, "", str(sentence)) #compile

        splited_words = str(test).split(' ')

        for word in splited_words:
            word = word.strip()
            word = word.lower()
            if word in selected_words:
                if word not in words_dict:
                    words_dict[word] = 1
                else:
                    words_dict[word] += 1
    return words_dict

It works as expected, but the performance is not as I expected. What could be done better in this code to improve performance?
It takes roughly ~5s to perform for 15257065 words in 183531 sentences.
Sample input
selected_words = ['awesome', 'great', 'fantastic', 'amazing', 'love', 'horrible', 'bad', 'terrible', 'awful', 'wow', 'hate']
data_frame = 'These flannel wipes are OK, but in my opinion not worth keeping. I also ordered someImse Vimse Cloth Wipes-Ocean Blue-12 countwhich are larger, had a nicer, softer texture and just seemed higher quality. I use cloth wipes for hands and faces and have been usingThirsties 6 Pack Fab Wipes, Boyfor about 8 months now and need to replace them because they are starting to get rough and have had stink issues for a while that stripping no longer handles.'


texts:
I am new to javaScript, I just coded a method where I can convert a minute to a time in hh:mm AP/PM. I was then displaying the time in a table.  I was wondering if there is a better approach to this? Because my code seems quite messy, with many if and else statement.

function convertMinsToHrsMin(minutes) {
                var str = '';
                var h = Math.floor(minutes / 60);
                var m = minutes - (h * 60);
                h = h < 10 ? '0' + h : h;
                m = m < 10 ? '0' + m : m;
                if (h >= 12) {
                    if (h == 12) {
                        str = "PM";
                    }
                    else if (h >= 22) {
                        h = (h - 12);
                        str = "PM";
                    }
                    else {
                        h = '0' + (h - 12);
                        str = "PM";
                    }
                }
                else {
                    if (h == 0) {
                        h = 12;
                        str = "AM";
                    }
                    else {
                        str = "AM";
                    }
                }
                return h + ":" + m + " " + str;
            }

            startTime = convertMinsToHrsMin(720);
            endTime = convertMinsToHrsMin(1080);

            alert(startTime);
            alert(endTime);

Here is a jsFiddle to work on: https://jsfiddle.net/Issaki1/txns3mhc/


texts:
For exercise, I wrote this code:

def BigPrime(numP, plist = [], x = 1, counter =0):
    while len(plist) <= numP:
        if x == 1 or x == 2 or x == 5:
                plist.append(x)
        elif x % 2 is not 0 and int(str(x)[-1]) is not 5:
                for div in plist[1:]:
                        if x % div == 0:
                                break
                else:
                        plist.append(x)
                counter += 1
        x += 1
    return plist, counter

It is a simple algorithm that should return a list of the first n primes.  When I tried to optimize it, I wanted to cut down all the possible already know not primes from the range.  That brought me to:

int(str(x)[-1]) is not 5

But then when I timed it, I saw that the code ran slower. Why?  It worked, and the for iterations were less indeed, but yet it was slower.

Also, when it comes to optimization, I'm a black hole of ignorance.  Any further way I could improve it?


texts: Relationship design for auto parts store database

texts:
I'm creating a design database for an autoparts store (this is a project school). For the moment, I'm not sure if the relationship model especially in MODEL, MAKE, BRAND is correct (I really have no experience about this area).

I'm not an expert in this area, so I need some help.

create database AutoParts2

use AutoParts2
go

create table Make
(
MakeID int not null identity(1,1),
Name varchar(50) not null,
constraint PK_Make primary key (MakeID)
)

create table Model
(
ModelID int not null identity(1,1),
MakeID int not null,
Name varchar(50) not null,
constraint PK_Model primary key (ModelID),
constraint FK_Model_Make foreign key (MakeID)
references Make(MakeID)
)

create table [Year]
(
YearID tinyint not null identity(1,1),
Name char(4) not null,
constraint PK_Year primary key (YearID)
)

create table Model2Year
(
Model2YearID int not null identity(1,1),
ModelID int not null,
YearID tinyint not null,
constraint PK_Model2Year primary key (Model2YearID),
constraint FK_Model2Year_Model foreign key (ModelID)
references Model(ModelID),
constraint FK_Model2Year_Year foreign key (YearID)
references [Year](YearID)
)

create table Category
(
CategoryID tinyint not null identity(1,1),
Name varchar(30) not null,
constraint PK_Category primary key (CategoryID)
)

create table Subcategory
(
SubcategoryID tinyint not null identity(1,1),
CategoryID tinyint not null,
Name varchar(30) not null,
constraint PK_Subcategory primary key (SubcategoryID),
constraint FK_Subcategory_Category foreign key (SubcategoryID)
references Category(CategoryID)
)

create table Model2Year2Category
(
Model2Year2CategoryID int not null identity(1,1),
Model2YearID int not null,
CategoryID tinyint not null,
constraint PK_Model2Year2Category primary key (Model2Year2CategoryID),
constraint FK_Model2Year2Category_Model2Year foreign key (Model2YearID)
references Model2Year(Model2YearID),
constraint FK_Model2Year2Category_Category foreign key (CategoryID)
references Category(CategoryID)
)

create table Brand
(
BrandID int not null identity(1,1),
Name varchar(50) not null,
constraint PK_Brand primary key (BrandID)
)

create table Brand2Subcategory
(
Brand2SubcategoryID int not null identity(1,1),
BrandID int not null,
SubcategoryID int not null,
constraint PK_Brand2Subcategory primary key (Brand2SubcategoryID),
constraint FK_Brand2Subcategory_Brand foreign key (BrandID)
references Brand(BrandID),
constraint FK_Brand2Subcategory_Subcategory foreign key (SubcategoryID)
references Subcategory(SubcategoryID)
)

create table Part
(
PartID int not null identity(1,1),
Name varchar(50) not null,
BrandID int not null,
PartNumber varchar(50) not null,
Description varchar(200),
constraint PK_Part primary key (PartID),
constraint FK_Part_Brand foreign key (BrandID)
references Brand(BrandID)
)

create table Model2Year2Part
(
Model2Year2PartID int not null identity(1,1),
Model2YearID int not null,
PartID int not null,
constraint PK_Model2Year2Part primary key (Model2Year2PartID),
constraint FK_Model2Year2Part_Model2Year foreign key (Model2YearID)
references Model2Year(Model2YearID),
constraint FK_Model2Year2Part_Part foreign key (PartID)
references Part(PartID)
)

create table Brand2Subcategory2Part
(
Brand2Subcategory2PartID int not null identity(1,1),
Brand2SubcategoryID int not null,
PartID int not null,
constraint PK_Brand2Subcategory2Part primary key (Brand2Subcategory2PartID),
constraint FK_Brand2Subcategory2Part_Brand2Subcategory foreign key (Brand2SubcategoryID)
references Brand2Subcategory(Brand2SubcategoryID),
constraint FK_Brand2Subcategory2Part_Part foreign key (PartID)
references Part(PartID)
)


texts: Lemonbar + perl scripting for workspaces

texts:
I have made this program to simulate polybar's bspwm module. So far, it works flawlessly, however it consumes too much ram and cpu ie 16-30%. I suspect it is the while loop causing the trouble but what can be done to reduce resource usage ?

use strict;
use warnings;
use Switch;
use List::MoreUtils qw(first_index);

$SIG{INT}=sub{ die "goodnight !\n $!"; };
my $underline='#ffffff';
my $default_background='#51002f';
my $default_workspace_background='#727272';
my $default_workspace_foreground='#ffffff';
my $default_foreground='#ffffff';
my $focussed_background='#000000';
my $focussed_foreground='#ffffff';
my $occupied_background='#3a3a3a';
my $occupied_foreground='#ffffff';
my @desktops=qx/ bspc query -D /;
my @lemonbar_array=();
my $lemonbar_string="%{B$default_background}%{F$default_foreground}%{+u}    0x00400004  %{-u}%{B-}%{F-}";
my $date_string="%{c}%{B$focussed_background}%{F$default_foreground}%{+u}   %date   %{-u}%{B-}%{F-}";

my $add_this="%{+u}%{B$default_background}%{F$default_foreground} %{A:firefox:}  web  %{A}  %{B-}%{F-} %{B$default_background}%{F$default_foreground} %{A:evince:}  pdf  %{A} %{B-}%{F-} %{B$default_background}%{F$default_foreground} %{A:libreoffice:}  doc  %{A} %{B-}%{F-} %{B$default_background}%{F$default_foreground} %{A:firefox youtube.com:}  youtube  %{A} %{B-}%{F-} %{B$default_background}%{F$default_foreground} %{A:firefox netflix.com:}  netflix  %{A} %{B-}%{F-} %{B$default_background}%{F$default_foreground} %{A:firefox gmail.com:}  gmail  %{A} %{B-}%{F-} %{B$default_background}%{F$default_foreground} %{A:firefox protonmail.com:}  protonmail  %{A} %{B-}%{F-} %{B$default_background}%{F$default_foreground} %{A:nautilus:}  files  %{A} %{B-}%{F-} %{B$default_background}%{F$default_foreground} %{A:urxvt:}  terminal  %{A} %{B-}%{F-}%{-u}";

for(my $i=0;$i<=9;$i++){
    push(@lemonbar_array,$lemonbar_string);
}

my $current_monitor='';

while() {
    my $date=gmtime();
    $date_string=~s/%date/$date/;
    $current_monitor=qx/bspc query -D -d/;
    my $index_current_monitor=first_index { $_ eq $current_monitor } @desktops;
    my $index_print=$index_current_monitor+1;
    $lemonbar_array[$index_current_monitor]=~s/(?<=B)#.{6}/$focussed_background/;
    $lemonbar_array[$index_current_monitor]=~s/(?<=F)#.{6}/$focussed_foreground/;
    $lemonbar_array[$index_current_monitor]=~s/0x00.{6}/$index_print/;
    for(my $i=0;$i<10;$i++){
        if($desktops[$i] ne $current_monitor){
            my $i1=$i+1;
            $lemonbar_array[$i]=~s/0x00.{6}/$i1/;
            if(scalar(my @n=qx/bspc query -N -d $desktops[$i]/) gt 0){
                $lemonbar_array[$i]=~s/(?<=B)#\w{6}/$occupied_background/;
                $lemonbar_array[$i]=~s/(?<=F)#\w{6}/$occupied_foreground/;
                }
            else{
                $lemonbar_array[$i]=~s/(?<=B)#\w{6}/$default_workspace_background/;
                $lemonbar_array[$i]=~s/(?<=F)#\w{6}/$default_workspace_foreground/;

            }
        }
    }

    print "%{l}@lemonbar_array $date_string %{r}$add_this\n";
}


texts: Is this a correct implementation of quicksort in C?

texts:
I'm learning C at the moment and chose implementing quicksort as an exercise.

My code is sorting correctly, but afterwards I looked at some tutorials online about quicksort. And they implement it differently.

I don't know, if I misunderstood quicksort, or if I simply implemented it differently.

How I understood quicksort:

  Choose pivot
  bin elements according to their size (bigger/smaller than pivot)
  repeat till array is sorted

I use middle element as pivot to avoid standard worst cases.

My code:

#include <stdio.h>
#include <math.h>

void quicksort(unsigned int* array, unsigned int length)
{
    if (length <= 1)
    {
        return;
    }

    unsigned int length_tmp = length/2;

    //pivot is middle element
    unsigned int pivot = array[length_tmp];

    unsigned int array_tmp[length];
    unsigned int length_small = 0;
    unsigned int length_big = 0;

    //binning array - bigger / smaller
    //left of pivot
    for (unsigned int i = 0; i < length_tmp; i++)
    {
        if (array[i] < pivot)
        {
            array_tmp[length_small] = array[i];
            length_small++;
        }
        else
        {
            array_tmp[length-1-length_big] = array[i];
            length_big++;
        }
    }

    //right of pivot
    for (unsigned int i = length_tmp+1; i < length; i++)
    {
        if (array[i] < pivot)
        {
            array_tmp[length_small] = array[i];
            length_small++;
        }
        else
        {
            array_tmp[length-1-length_big] = array[i];
            length_big++;
        }
    }

    //inserting pivot unsigned into temporary array
    array_tmp[length_small] = pivot;

    //copying values unsigned into array
    for (unsigned int i = 0; i < length; i++)
    {
        array[i] = array_tmp[i];
    }

    //recursive function calls
    quicksort(array+0, length_small);
    quicksort(array+length_small+1, length_big);

    return;
}

int main()
{
    unsigned int array[] = {1,2,3,7,8,9,6,5,4,0};
    unsigned int length = sizeof array / sizeof array[0];  //alternative: sizeof array / sizeof *array

    //printing array
    printf("unsorted array: ");
    for (unsigned int i = 0; i < length; i++)
    {
        printf("%d", array[i]);
    }
    printf("\n");

    //calling sorting function
    quicksort(array, length);

    //printing array
    printf("sorted array: ");
    for (unsigned int i = 0; i < length; i++)
    {
        printf("%d", array[i]);
    }
    printf("\n");

    return 0;
}

I had posted this before on stackoverflow, but was informed of my mistake and that I should post it here. I didn't get answer to my question in that short time, but a few pointers regarding my code which I tried to implement in my solution.


texts: Splitting a command line into key/value pairs

texts:
The code below will split environment variables from a command line (always appear at the end of the command line). Environment variables are represented by '-E key=value'. I've achieved this like so, but I'm wondering if there's a more elegant way

public class TestSplit {

  public static void main(String... args) {
    String command = "-ps 4 -pe 5 -E opInstallDir=/home/paul -E opWD=/home/paul/remake -E opFam=fam -E opAppli=appli";

    int startPosition = command.indexOf("-E") + 2;

    String envVars = command.substring(startPosition);

    for(String pair: envVars.split("-E")) {
      String[] kv = pair.split("=");
      System.out.println(kv[0] + " " +kv[1]);
    }
  }

}

EDIT Just to clarify these aren't command line arguments for launching the program from the console, they are command line arguments for launching an external program. The details of which I haven't included.


texts: Powershell script for zipping up old files

texts:
I have a script for zipping up old files. I know using Windows Compression isn't ideal, so I will make the script run using 7-Zip later on. For now though, I just want see how I can make my current script better. By better I mean, how could I make this code cleaner or neater? How could I make the script more effective?
Here is the code:

Write-Output("Beginning script....")

#File path of file to be cleaned
$File_Path = "C:\Users\Administrator\Downloads\Testing\*"

#Location of ZIP file
$Send_To = "C:\Users\Administrator\Documents\ARCHIVE2"

#Location of old files before being zipped
$Old_Files = "C:\Users\Administrator\Documents\OLD_FILES"

#Time frame for files
$Days = "-65"
$now = Get-Date
$last_Write = $now.AddDays($Days)

#Filtering files according to time parameters
$Filter = Get-ChildItem -Path $File_Path | Where-Object { $_.LastWriteTime -lt $last_Write }

#Moving old files to destination folder
if (!$Filter){
    Write-Host "Variable is null"
}
else{
    Move-Item $Filter -Destination $Old_Files
    Write-Output("Moving files....")
}

#Compressing destination folder if there is folders in $Old_Files folder
if (!(Test-Path $Old_Files)) {
    Write-Output("No old files found")
}
else{
    Compress-Archive -Path $Old_Files -DestinationPath $Send_To -Update
    Write-Output("Old files zipped!")
    Remove-Item -Path $Old_Files -Force
}

Write-Output("Script is finished")


texts:
Earlier today I answered Timetable viewer, where one of my recommendations was to make a get_input function.
However, this hasn't been the first time I've recommended making a bespoke get_input function.

This function should get user input, until it is valid. This may be any input, or any number in a specific range.
The arguments customize how it works, such as working with strings or integers.
The function should repeatedly prompt the user for specific input, until a valid input is entered.
In the case case of valid input we should return that data, so the end user can use it.

Since it's quite a common function, with a lot of uses, I decided to make a generic version of the function, that should cover most use cases.
I decided to make two functions, as strings don't need to be converted, however when changing to numbers, you'd have to duplicate a lot of arguments.

def build_input(
    prompt=None,
    *,
    errors=None,
    values=None,
    process=None,
    wanted=None,
    end=None
  ):
    prompt = prompt or ''
    process = process or (lambda v: v)
    errors = errors or tuple()
    if values is None:
        wanted = wanted or (lambda v: True)
    else:
        values = list(values)
        prompt += '[{}] '.format('/'.join(str(i) for i in values))
        wanted = wanted or (lambda v: v in values)
        values = set(values)

    if end is not None:
        prompt += end
    elif values:
        prompt += '\n> '

    def ask():
        while True:
            value = input(prompt)
            try:
                value = process(value)
            except errors:
                continue
            if wanted(value):
                return value
    return ask

def build_number_input(
    prompt=None,
    *,
    errors=ValueError,
    values=None,
    process=int,
    wanted=None,
    end=None
  ):
    return build_input(
        prompt,
        errors=errors,
        values=values,
        process=process,
        wanted=wanted,
        end=end
    )

I have a couple of concerns:

build_number_input spans 17 lines, for a function definition and a function call. Is there a better way to define this?
Are there a better way to style my function definitions? I think they may not be PEP8 compliant, but couldn't think of anything nicer to read.
Are there any common options that you think should be added?

Below are a couple of ways to use the above functions, and a sample run:

name_input = build_input('What is your name? ')
age_input = build_number_input('What is your age? ')
day_input = build_number_input('Day: ', values=[1, 2, 3, 4, 5])
again_input = build_input('Again? ', values='yn', process=lambda v:v.lower())

print('Hello, {}! You are {}.'.format(name_input(), age_input()))
print('You want day {}'.format(day_input()))
print('You {}want to go again.'.format('' if again_input() == 'y' else "don't "))

What is your name? Peilonrayz
What is your age? 20.5
What is your age? 20a
What is your age? 20
Hello, Peilonrayz! You are 20.
Day: [1/2/3/4/5]
> 6
Day: [1/2/3/4/5]
> 0
Day: [1/2/3/4/5]
> 55
Day: [1/2/3/4/5]
> five
Day: [1/2/3/4/5]
> 5
You want day 5
Again? [y/n]
> yeah
Again? [y/n]
> Nope?
Again? [y/n]
> N
You don't want to go again.


texts: Solution for kth row of Pascal's triangle for a job interview

texts:
Question:

  Given an index \$k\$, return the \$k^{th}\$ row of the Pascal's triangle.

  For example, given \$k = 3\$, return \$[1,3,3,1]\$.  Bonus points for using \$O(k)\$ space.

Can it be further optimized using this way or another?

class Solution {
   public:
    long long C(int n, int r) {
       if(r > n / 2) r = n - r; // because C(n, r) == C(n, n - r)
       long long ans = 1;
       int i;

       for(i = 1; i <= r; i++) {
           ans *= n - r + i;
           ans /= i;
       }

       return ans;
   }

       vector<int> getRow(int rowIndex) {
           vector<int> v;
           long long sol;
           for(int i=0;i<=rowIndex;i++)
           {sol=C(rowIndex,i);
           v.push_back(sol);}

          return v;
       }
   };


texts: Using brute force to do large scale permutations and combinations

texts:
This problem should self explanatory based on namings of variables and functions. In essence I am doing well over 720*720*90 checks/calculations. Hence, this is taking far, far too long. How do I make my code more optimized with regards to time/performance. Space is not an issue. The question is pretty complicated(at least in my opinion), so please let me know what I should clarify.

Most of the optimization should be doable by just reading my comments, I hope. I don't want to bog down the task by adding in details of the convoluted math problem.

import java.io.*;
import java.util.*;
import java.lang.*;

public class Concat{
    static String[] designs = new String[720]; //6! permutations of 6 unique characters
    static int index = 0; //index used to iterate through designs[]

    public static void main(String[] args){
        Concat concat = new Concat();
        genDesigns("", "123456"); //123456 will be the unique characters

        String[][] interleavedData = new String[720][720];
        for(int i = 0; i < 720; i++)
            interleavedData[i] = //remap using design[i]

        String[][] interleavedSubsets = new String[720][90];
        for(int interleaveIndex = 0; interleaveIndex < 720; interleaveIndex++)
        {
            for(int j = 0; j < 720; j++)
                interleavedSubsets[j] = gen8String(genDelPatterns(designs[j]), genDelPatterns(interleavedData[interleaveIndex][j]));

            System.out.println(checkSubsets(interleavedSubsets));
        }

    }

    //generate all permutations
    public static void genDesigns(String prefix, String data){
        int n = data.length();
        if (n == 0) designs[index++] = prefix;
        else {
            for (int i = 0; i < n; i++)
                genDesigns(prefix + data.charAt(i), data.substring(0, i) + data.substring(i+1, n));
        }
    }

    public static String[] genDelPatterns(String design){
        //stimulating 6choos4 operation
    }

    //generating a subset of 90 eight character strings (unique deletion patterns)
    public static String[] gen8String(String[] pattern1, String[] pattern2){
        String[] combinedSubset = new String[90]; //emty array for the subset of 90 strings
        String  combinedString = ""; //string holder for each combined string
        int index = 0; //used for combinedSubset array
        int present = 0; //used to check if all 6 characters are present

        for(int i = 0; i < 15; i++){

            for(int j = 0; j < 15; j++){
                combinedString = pattern1[i] + pattern2[j]; //combine both 4 letter strings into 8 char length string
                char[] parsedString = combinedString.toCharArray(); //parse into array

                //check if all 6 characters are present
                for(int k = 1; k <= 6; k++)
                {
                    if(new String(parsedString).contains(k+"")) {
                        present++;
                    }
                    else
                        break;
                    //if all 6 are present, then add it to combined subset
                    if(present == 6)
                        combinedSubset[index++] = combinedString;
                }
                present = 0;
            }
        }
        return combinedSubset;
    }

    //check all the subsets of the interleaved data
    public static int checkSubsets(String[][] subsets){
        List subset = new ArrayList();
        int numOfUnique = 0;
        for(int i = 0; i< 720; i++){
            for(int j = 0; j < 90; j++)
                subset.add(subsets[i][j]);
        }
        Object duplicate;
        Iterator itr = subset.iterator();
        while(itr.hasNext()){
            duplicate = itr.next();
            while(itr.hasNext()){
                subset.remove(duplicate);
                itr=subset.iterator(); //to avoid concurrent modification
                itr.next();
            }
        }
        return subset.size();
    }
}


texts:
I implemented a function that prints all the numbers from the Fibonacci sequence until max_num. The minimum value allowed is 0 (so, fib(0) prints 1). It works until 92, and I want to know how to improve the code, in general.

void fib(unsigned int max_num)
{
    unsigned long fib_num = 1;
    unsigned long fib_temp = 0;
    size_t count = 0;

    if (max_num < 0)
    {
        fprintf(stderr, "Please, enter a non-negative number\n");
        return;
    }

    for (; count <= max_num; count++)
    {
        printf("%lu\n", fib_num);
        fib_num += fib_temp;
        fib_temp = fib_num - fib_temp;
    }
}


texts:
Doing homework, implementation of the algorithm flood fills. I'm writing a program to this guide: http://en.wikipedia.org/wiki/Flood_fill. And I have some questions:

Is it normal to specify the parameters in function replaces the color of any character bucketFill.fill (0, 0, '*', 'O');, I do not know what kind of color will be initially to these coordinates?
An algorithm is correct? I wrote it for example in Wikipedia, but the result of my program is as follows:

@@@@@
@@@@@
@@@@@
@@@@@
@@@@@
@@@@@
@@@@@

I think must be this:

*@@@@
@@@@@
@@#@@
@@@@@
@@@@@
@@@##
@@@@@

My code:

class BucketFill {

    private char[][] pixels;

    public BucketFill(char[][] pixels) {
        this.pixels = pixels;
    }

    public void fill(int x, int y, char newColor, char oldColor) {
        if (x < 0) return;
        if (y < 0) return;
        if (x >= pixels.length) return;
        if (y >= pixels[x].length) return;

        oldColor = pixels[x][y];

        if (newColor == pixels[x][y]) return;
        if (oldColor != pixels[x][y]) return;

        pixels[x][y] = newColor;

        fill(x - 1, y, newColor, oldColor);
        fill(x + 1, y, newColor, oldColor);
        fill(x, y - 1, newColor, oldColor);
        fill(x, y + 1, newColor, oldColor);
    }

    public void inspect() {
        for (int y = 0; y < pixels.length; y++) {
            for (int x = 0; x < pixels[y].length; x++) {
                System.out.print(pixels[y][x]);
            }
            System.out.print("\n");
        }
    }

    public static void main(String argv[]) {
        char pixels[][] =
        {
            { 'O', 'X', 'X', 'X', 'X' },
            { 'X', 'O', 'O', 'O', 'X' },
            { 'X', 'O', '#', 'O', 'X' },
            { 'X', 'O', 'O', 'O', 'X' },
            { 'X', 'X', 'X', 'X', 'X' },
            { 'X', 'X', 'X', '#', '#' },
            { 'X', 'X', 'X', 'X', 'X' }
        };
        BucketFill bucketFill = new BucketFill(pixels);
        bucketFill.fill(0, 0, '*', 'O');
        bucketFill.fill(3, 0, 'O', 'O');
        bucketFill.fill(2, 1, '@', 'O');
        bucketFill.inspect();
    }
}


texts: Finding the largest of a series of numbers being XORed

texts:
I'm working on solving a problem involving finding the largest of a series of numbers being XORed.

This is the actual problem:

  Xorq has invented an encryption algorithm which uses bitwise XOR
  operations extensively. This encryption algorithm uses a sequence of
  non-negative integers \$x_1, x_2, ... x_n\$ as key. To implement this
  algorithm efficiently, Xorq needs to find maximum value for (\$a\$ xor \$x_j\$)
  for given integers \$a\$, \$p\$ and \$q\$ such that \$p<=j<=q\$. Help Xorq to implement
  this function.

  Input

  First line of input contains a single integer \$T\$ (\$1 <= T <= 6\$). T test
  cases follow.

  First line of each test case contains two integers \$N\$ and \$Q\$ separated
  by a single space (\$1 <= N <= 100,000\$; \$1 <= Q <= 50,000\$). Next line contains
  \$N\$ integers \$x_1, x_2, ... x_n\$ separated by a single space (\$0 <= x_i < 2^{15}\$).
  Each of next Q lines describe a query which consists of three integers
  \$a_i\$, \$p_i\$ and \$q_i\$ (\$0 <= a_i < 2^{15}\$, \$1 <= p_i <= q_i <= N\$).

  Output

  For each query, print the maximum value for (\$a_i\$ xor \$x_j\$) such that
  \$p_i <= j <= q_i\$ in a single line.

I keep failing because of a timeout.  What are some ways in which I could optimize my code to reduce time?

Is there a better way to do the bit manipulation?  Should I be using a different data structure than an array?  I've read a few articles on optimization and changed a few things, but nothing that made a real difference.  Maybe I need to attempt the problem in a different fashion?

#include <stdio.h>

int main (int argc, char * argv[]) {
    unsigned int T,N,Q,i,a,p,q,count,max,n[100000],res[100000];
    scanf ("%d\n%d %d", &T, &N, &Q);
    while (T--) {
        for (i = 0; i < N; i++) {
            scanf ("%d", &n[i]);
        }
        while (Q--) {
            count = 0;
            scanf ("%d %d %d", &a, &p, &q);
            p--;
            q--;
            for (i = p; i <= q; i++) {
                res[count++] = a ^ n[i];
            }
            max = res[0];
            for (i = count; i--;) {
                if (res[i] > max) {
                    max = res[i];
                }
            }
            printf ("%d\n", max);
        }
    }
    return 0;
}

I apologize for all the arbitrarily named variables.  All of these problems just use single character names as their variables.


texts: Java Cryptography AES/GCM/NoPadding without IV

texts:
I'm implementing a PAKE-protocol as a university project and one step of the protocol involves sending encrypted data from a key created via a hash function (I'm using SHA-256). I want to use AES/GCM but do not have an IV so I'm using HKDF to expand the key into an IV and key with the following implementation:

import org.bouncycastle.crypto.digests.SHA256Digest;
import org.bouncycastle.crypto.generators.HKDFBytesGenerator;
import org.bouncycastle.crypto.params.HKDFParameters;
import org.bouncycastle.util.Arrays;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.GCMParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

public class AesGcmSymmetricCipher {

    public static final String CIPHER_ALGORITHM = "AES/GCM/NoPadding";

    public static final int GCM_TAG_BITS = 128;
    public static final int IV_BYTES = 12;
    public static final int KEY_BYTES = 32; // AES-256

    private final Cipher cipher;

    public AesGcmSymmetricCipher() throws NoSuchPaddingException, NoSuchAlgorithmException {
        this.cipher = Cipher.getInstance(CIPHER_ALGORITHM);
    }

    public byte[] encrypt(byte[] key, byte[] clearData) throws InvalidAlgorithmParameterException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException {

        var spec = expandKeys(key);
        cipher.init(Cipher.ENCRYPT_MODE, spec.getKeySpec(), spec.getParameterSpec());

        return cipher.doFinal(clearData);
    }

    public byte[] decrypt(byte[] key, byte[] cipherData) throws InvalidAlgorithmParameterException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException {

        var spec = expandKeys(key);
        cipher.init(Cipher.DECRYPT_MODE, spec.getKeySpec(), spec.getParameterSpec());

        return cipher.doFinal(cipherData);
    }

    public String getAlgorithm() {
        return "AES-256/GCM/NoPadding using HKDF";
    }

    private KeyedMaterial expandKeys(byte[] initialKey) {
        var iv = new byte[IV_BYTES];
        var key = new byte[KEY_BYTES];

        var digest = new SHA256Digest();
        var kdf = new HKDFBytesGenerator(digest);
        var parameters = new HKDFParameters(initialKey, null, null);

        kdf.init(parameters);
        kdf.generateBytes(iv, 0, IV_BYTES);
        kdf.generateBytes(key, 0, KEY_BYTES);

        var gcmParameters = new GCMParameterSpec(GCM_TAG_BITS, iv);
        var keySpec = new SecretKeySpec(key, CIPHER_ALGORITHM);

        Arrays.clear(iv);
        Arrays.clear(key);

        return new KeyedMaterial(gcmParameters, keySpec);
    }

    private static class KeyedMaterial {

        private final GCMParameterSpec parameterSpec;
        private final SecretKeySpec keySpec;

        public KeyedMaterial(GCMParameterSpec parameterSpec, SecretKeySpec keySpec) {
            this.parameterSpec = parameterSpec;
            this.keySpec = keySpec;
        }

        public GCMParameterSpec getParameterSpec() {
            return parameterSpec;
        }

        public SecretKeySpec getKeySpec() {
            return keySpec;
        }
    }
}

I'm interested in feedback especially from a security perspective, if relevant the initial key passed to encrypt/decrypt is ephemeral and will only be used once for encryption and once for decryption.


texts: Small Python class for Lindenmayer Systems

texts:
L-systems are basically rules for recursively rewriting a string, which can be used to characterize e.g. some fractal and plant growth.

I wrote a small class to represent deterministic L-systems and used it for two examples. Any comments would be greatly appreciated, especially about the class design, the structure of the second example, and how to make things more pythonic. I'm new to Python and don't have any training in "grammars", this is just a hobby.

The class LSystem.py:

class LSystem:
    """ Lindenmayer System
    LSystem( alphabet, axiom )
      axiom: starting "string", a list of Symbols
      rules: dictionary with rules governing how each Symbol evolves,
             keys are Symbols and values are lists of Symbols
    """
    def __init__(self, axiom, rules):
        self.axiom = axiom
        self.rules = rules

    """ Evaluate system by recursively applying the rules on the axiom """
    def evaluate(self,depth):
        for symbol in self.axiom:
            self.evaluate_symbol( symbol, depth )

    """ Recursively apply the production rules to a symbol """
    def evaluate_symbol( self, symbol, depth ):
        if depth <= 0 or symbol not in self.rules:
            symbol.leaf_function()
        else:
            for produced_symbol in self.rules[symbol]:
                self.evaluate_symbol( produced_symbol, depth - 1 )

class Symbol:
    """ Symbol in an L-system alphabet
    Symbol( leaf_function )
      leaf_function: Function run when the symbol is evaluated at the final
                     recursion depth. Could e.g. output a symbol or draw smth.
    """
    def __init__(self, leaf_function ):
        self.leaf_function = leaf_function

Example: Algae growth (example 1 from the wikipedia article)

import LSystem

# define symbols. their "leaf function" is to print themselves.
A = LSystem.Symbol( lambda:print('A',end='') )
B = LSystem.Symbol( lambda:print('B',end='') )
# define system
algae_system = LSystem.LSystem(
    axiom = [A],
    rules = { A: [A,B], B: [A] }
)
# run system
algae_system.evaluate(4) # prints "ABAABABA"

Example: Draw a Koch snowflake (as in my previous question)

import LSystem
import pygame
from math import pi, sin, cos

# some constants
WINDOW_SIZE = [300,300]
LINE_WIDTH = 1
LINE_LENGTH = 1

# global variables for "turtle drawing"
# maybe I should pass around a turtle/cursor object instead?
turtle_angle = 0
turtle_x = 0
turtle_y = WINDOW_SIZE[1]*3/4

# define drawing functions used to draw the Koch snowflake
def draw_forward():
    global turtle_angle, turtle_x, turtle_y
    start = [turtle_x, turtle_y]
    turtle_x += LINE_LENGTH * cos(turtle_angle)
    turtle_y += LINE_LENGTH * sin(turtle_angle)
    end = [turtle_x, turtle_y ]
    pygame.draw.line(window, pygame.Color('black'), start, end, LINE_WIDTH )
def turn_left():
    global turtle_angle
    turtle_angle += pi/3
def turn_right():
    global turtle_angle
    turtle_angle -= pi/3

# symbols in the L-system
Line = LSystem.Symbol( draw_forward )
Left = LSystem.Symbol( turn_left )
Right = LSystem.Symbol( turn_right )

# L-system axiom and rules
koch_curve_system = LSystem.LSystem(
    axiom = [ Line, Right, Right, Line, Right, Right, Line ],
    rules = { Line: [ Line, Left, Line, Right, Right, Line, Left, Line ] }
)

# init pygame
pygame.init()
window = pygame.display.set_mode(WINDOW_SIZE)
window.fill(pygame.Color('white'))

# evaluate the L-system, which draws the Koch snowflake
# (recursion depth was chosen manually to fit window size and line length)
koch_curve_system.evaluate(5)

# display
pygame.display.flip()

# wait for the user to exit
while pygame.event.wait().type != pygame.QUIT:
    1


texts:
The challenge is simple:

  Return the length of the longest word in the provided sentence.

The solution is just as simple:

function findLongestWord(str) {
  arr = str.split(' ');
  size = 0;
  for (var s in arr) {
    if (arr[s].length > size) {
      size = arr[s].length;
    }
  }
  return size;
}

However, I vaguely remember you're not supposed to use for..in in JavaScript unless absolutely necessary. What would be the more idiomatic approach for this loop?


texts: Tortoise and hare cycle detection algorithm using iterators in Python

texts:
Reading the article in Wikipedia about cycle detection I came across a relatively small code snipped of Floyd's cycle-finding algorithm. I'll put it here to keep everything in one place:

def floyd(f, x0):
    # The main phase of the algorithm, finding a repetition x_mu = x_2mu
    # The hare moves twice as quickly as the tortoise
    tortoise = f(x0) # f(x0) is the element/node next to x0.
    hare = f(f(x0))
    while tortoise != hare:
        tortoise = f(tortoise)
        hare = f(f(hare))

    # at this point the start of the loop is equi-distant from current tortoise
    # position and x0, so hare moving in circle and tortoise (set to x0 )
    # moving towards circle, will intersect at the beginning of the circle.

    # Find the position of the first repetition of length mu
    # The hare and tortoise move at the same speeds
    mu = 0
    tortoise = x0
    while tortoise != hare:
        tortoise = f(tortoise)
        hare = f(hare)
        mu += 1

    # Find the length of the shortest cycle starting from x_mu
    # The hare moves while the tortoise stays still
    lam = 1
    hare = f(tortoise)
    while tortoise != hare:
        hare = f(hare)
        lam += 1

    return lam, mu

But then I decided, why not rewrite this algorithm using iterators.

The result wasn't as good as I had hoped it to be.

In some parts of the code I needed the values that the iterators have already returned. So I had keep the values apart from iterators themselves. And I introduced the class animal to keep them in one place.

To my mind, the code got very hefty and ugly. Here it is:

# -*- coding: utf-8 -*-

from __future__ import print_function
from itertools import islice,cycle,chain

def detect_cycle(iterable):

    class animal(object):
        '''Holds the iterator and keeps the last value returned by the iterator'''
        def __init__(self,iterable):
            self.it = iter(iterable)
            self.value = next(self.it) #get the first value

        def next(self):
            self.value = next(self.it)
            return self.value

        def __iter__(self):
            return self

    tortoise = animal(iterable)
    hare = animal(islice(iter(iterable),None,None,2))  #two steps at a time

    while True:
        if next(tortoise) == next(hare):
            break

    hare = tortoise #put hare in the place of tortoise
    tortoise = animal(iterable) #start tortoise from the very beginning
    mu = 0
    while True:
        if hare.value == tortoise.value:
            break
        next(hare)
        next(tortoise)
        mu += 1

    lamb = 0
    tortoise_val = tortoise.value #save the value of tortoise as the object is reassigned to hare
    hare = tortoise
    while True:
        next(hare)
        lamb += 1
        if hare.value == tortoise_val: #check AFTER the first step by hare
            break

    print('mu: {}'.format(mu))
    print('lamb: {}'.format(lamb))

if __name__ == '__main__':

    class iterable(object):
        '''Emulate the object returning iterators having cycles'''
        def __init__(self,beginning,cycling):
            '''
beginning: the beginning part with no cycles (its length corresponds to mu)
cycling: the part which will be cycling (its length corresponds to lamb)
'''
            self.beginning = beginning
            self.cycling = cycling

        def __iter__(self):
            return chain(iter(self.beginning),cycle(iter(self.cycling)))

    detect_cycle(iterable('1234','678'))

Is there anything that can be done to improve the code?
Is it the best that can be done using iterators?


texts: Escape the Trolls, or just walking through a maze

texts:
Clojure beginner, looking to improve this code I submitted for Escape the Trolls, a Weekly Programming challenge over in reddit. No trolls yet, just walking through a maze for now.

(ns ctrollmaze.core
  (:gen-class)
  (:require [clojure.string :as str]))

(def sample-maze
"#####################################
# #       #       #     #         # #
# # ##### # ### ##### ### ### ### # #
#       #   # #     #     # # #   # #
##### # ##### ##### ### # # # ##### #
#   # #       #     # # # # #     # #
# # ####### # # ##### ### # ##### # #
# #       # # #   #     #     #   # #
# ####### ### ### # ### ##### # ### #
#     #   # #   # #   #     # #     #
# ### ### # ### # ##### # # # #######
#   #   # # #   #   #   # # #   #   #
####### # # # ##### # ### # ### ### #
#     # #     #   # #   # #   #     #
# ### # ##### ### # ### ### ####### #
# #   #     #     #   # # #       # #
# # ##### # ### ##### # # ####### # #
# #     # # # # #     #       # #   #
# ##### # # # ### ##### ##### # #####
# #   # # #     #     # #   #       #
# # ### ### ### ##### ### # ##### # #
# #         #     #       #       # #
#X###################################")

(defrecord Maze [width
                 height
                 grid])

(defn flatten-coords
  [maze x y]
  (let [width (:width maze)]
    (+ x (* y width) y)))

(defn token-at
  [maze x y]
  (let [grid (:grid maze)]
    (nth grid (flatten-coords maze x y))))

(defn is-token?
  [maze x y given-token]
  (let [token (token-at maze x y)]
    (= given-token token)))

(defn is-wall?
  [maze x y]
  (is-token? maze x y \#))

(defn is-walkable?
  [maze x y]
  (some (partial is-token? maze x y) '(\space \X)))

(defmulti gen-maze (fn [strategy] (:strategy strategy)))

(defmethod gen-maze :static
  [strategy]
  (->Maze (:width strategy) (:height strategy) (into [] (seq sample-maze))))

(defn move-player
  [direction player]
  (case direction
    "a" (assoc player :dir \< :x (dec (:x player)))
    "d" (assoc player :dir \> :x (inc (:x player)))
    "w" (assoc player :dir \^ :y (dec (:y player)))
    "s" (assoc player :dir \v :y (inc (:y player)))
    player))

(defn gen-static-maze
  []
  (gen-maze { :strategy :static :width 37 :height 23 }))

(defn place-player
  ([maze player] (place-player maze player player))
  ([maze player' player]
   (println player' player)
   (let [{:keys [grid width height]} maze
         x' (:x player')
         y' (:y player')
         dir' (:dir player')
         x (:x player)
         y (:y player)]
     (->Maze width height (assoc grid
                                 (flatten-coords maze x y) \space
                                 (flatten-coords maze x' y') dir')))))

(defn pretty-print
  [maze]
  (let [grid (:grid maze)]
    (println (str/join grid))))

(defn is-game-finished?
  [maze]
  (->> (:grid maze)
       (some #{\X})
       (boolean)
       (not)))

(defn play-maze
  []
  (loop [player { :dir \> :x 1 :y 1 }
         maze (place-player (gen-static-maze) player)
         input-dir nil]
    (let [player' (move-player input-dir player)]
      (if (is-walkable? maze (:x player') (:y player'))
        (let [maze' (place-player maze player' player)]
          (pretty-print maze')
          (if (is-game-finished? maze')
            true
            (recur player' maze' (read-line))))
        (recur player maze (read-line))))))

(defn -main
  "I don't do a whole lot ... yet."
  [& args]
  (when (play-maze)
    (println "Congratulations, you won!")))

Version 1.1: No longer does the output lag behind one move.


texts: PHP function for encrypt / decrypt using openssl

texts:
This is a function that is the building block of one wordpress plugin. I came up with this code after some search but i need to optimize it and get any info from more experienced guys.

public static function afz_encrypt_decrypt( $action, $string ) {
    $output = false;

    $encrypt_method = "AES-256-CBC";
    $secret_key     = '12345678901234567890123456789012';
    $iv_size        = 16;

    if ( $action == 'encrypt' ) {
        $encrypt_iv = mcrypt_create_iv( $iv_size, MCRYPT_DEV_URANDOM );
        $output     = openssl_encrypt( $string, $encrypt_method, $secret_key, 0, $encrypt_iv );
        $output     = base64_encode( $encrypt_iv . $output );
    } else if ( $action == 'decrypt' ) {
        $decrypt_iv = substr( base64_decode( $string ), 0, $iv_size );
        $output     = stripslashes( openssl_decrypt( substr( base64_decode( $string ), $iv_size ), $encrypt_method,
            $secret_key,
            0,
            $decrypt_iv ) );
        if ( false === $output ) {
            $output = $string;
        }
    }

    return $output;
}

Update: The stripslashes is indeed unneeded and i will take it out of context of this function. I need it because wordpress automatically escapes strings regardless if the relevant PHP Setting. See the NOTES section here: CODEX Link

What i still need though is more insight (if possible) to Tim's answer in regards to the security aspect of the source.


texts:
I have cleanly separated functionality of a message bus - namely the diagnostics (optional), sending, decoding and the bus driver, I need to now bind this together and have done so with a MessageBus class.
It feels anemic though, with a lot of pass through methods.
On the flip side it is necessary for coordinating StartAsync() which links dependencies on the driver and receiver (binding them so they can call back) - I saw no other way of achieving this if I registered all individual interfaces via an inversion of control container as it would get out of sync (how to bind the driver to the decoder for instance).
If this is the wrong place for comments on code please let me know and I will remove straight away. Any pointers much appreciated.
public class MessageBus : IDisposable
{
    private readonly MessageBusReceiver receiver;
    private readonly MessageBusPublisher publisher;
    private readonly IMessageBusDriver driver;
    private int isRunning;
    private readonly MessageBusDiagnostics diagnostics = null;

    public MessageBus(IMessageBusDriver driver, SerializerRegistry serializerRegistry, ITypeIdentifier typeIdentifier, ILoggerFactory loggerFactory, bool isDebug = false)
    {
        this.driver = driver;
        this.publisher = new MessageBusPublisher(serializerRegistry, driver, typeIdentifier);
        this.receiver = new MessageBusReceiver(serializerRegistry, typeIdentifier, loggerFactory.CreateLogger<MessageBusReceiver>());
        if (isDebug)
            diagnostics = new MessageBusDiagnostics(driver, loggerFactory.CreateLogger<MessageBusDiagnostics>());
    }

    void AssertIsRunning()
    {
        if (this.isRunning == 0)
            throw new InvalidOperationException($"{nameof(StartAsync)} must be called before calling other methods.");
    }

    public async Task SubscribeAsync(string topic, QualityOfService qos, CancellationToken cancellationToken = default)
    {
        AssertIsRunning();
        await this.driver.SubscribeAsync(topic, qos, null, null, null, cancellationToken);
    }

    public async Task UnsubscribeAsync(string topic, CancellationToken cancellationToken = default)
    {
        AssertIsRunning();
        await this.driver.UnsubscribeAsync(topic, cancellationToken);
    }

    public async Task StartAsync(Func<object, Task> receiveApplicationMessage)
    {
        if (Interlocked.CompareExchange(ref this.isRunning, 1, 0) == 1)
            throw new InvalidOperationException("Already running.");

        this.receiver.OnMessageDecoded = receiveApplicationMessage;
        await this.driver.StartAsync(this.receiver.ReceiveMessageFromMessageBusDriver);
    }

    public async Task StopAsync()
    {
        if (Interlocked.CompareExchange(ref this.isRunning, 0, 1) == 0)
            throw new InvalidOperationException("Not running.");

        await this.driver.StopAsync();
    }

    public async Task PublishAsync(object notification, string busPath, QualityOfService qos = QualityOfService.AtMostOnce, CancellationToken cancellationToken = default)
    {
        AssertIsRunning();
        await this.publisher.PublishAsync(notification, busPath, qos, cancellationToken);
    }

    public async Task PublishAsync(object notification, Dictionary<string, string[]> pathTokens = null, QualityOfService qos = QualityOfService.AtMostOnce, CancellationToken cancellationToken = default)
    {
        AssertIsRunning();
        await this.publisher.PublishAsync(notification, pathTokens, qos, cancellationToken);
    }

    public void Dispose()
    {
        this.driver.Dispose();
        this.diagnostics?.Dispose();
    }
}


texts:
I decided to implement a random walk.

The rules

The rules are easy, an object is moved in the direction dictated by random or pseudo-random numbers.
If you want to read more about it, see the Wikipedia Page.

A simple example

Let's say we decide:

1 = "Go right"
2 = "Go down"
3 = "Go left"
4 = "Go up"

We then generate the random or pseudo-random sequence: 3,1,4,1.
And we convert it to directions:

Left
Right
Up
Right

we obtain the following:

A more complex example

Runnning my code with:

step_size = 15
step_number = 1000

Generated the following walk:

Running the code with the exact same parameters may yield completely different results because pseudo-random numbers are used.

I think my code is well written and fully Pep8 compliant, two things bother me

I define many go_<direction> methods to go to absolute directions, I could have done something like:

turn_of_random_deegres()
turtle.forward(step)

But it looked cleaner to me, albeit a little longer, to define absolute moving.

The go_<direction> methods change between logo and standard edition. (Control-Find setheading in this doc-page)

The code

import turtle
import random

def go_right(step):
     turtle.setheading(0)
     turtle.forward(step)

def go_up(step):
     turtle.setheading(90)
     turtle.forward(step)

def go_left(step):
     turtle.setheading(180)
     turtle.forward(step)

def go_down(step):
     turtle.setheading(270)
     turtle.forward(step)

def make_random_walk(step_size, step_number):
    move_dict = {1: go_up,
                 2: go_right,
                 3: go_left,
                 4: go_down
                 }
    for _ in range(step_number):
        move_in_a_direction = move_dict[random.randint(1, 4)]
        move_in_a_direction(step_size)

if __name__ == "__main__":
    turtle.hideturtle()
    turtle.speed("fastest")
    make_random_walk(15, 1000)


texts: A Note class which plays a note and stops it after specific period of time

texts:
This code plays a note for a specific period of time using NAudio.dll 1.3.8.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using NAudio.Midi;
using System.Threading;

namespace SoundVision
{
    class Note
    {
        public Note(MidiOutWrapper midi_output,int number, int duration, int volume=127, int channel=0)
        {
            if (midi_output == null)
                return;
            //midi_output is not null because it's referenced in this constructor and therefore cannot be collected
            //Check for disposed is not to rely on disposed resources in Send function
            lock (midi_output)
            {
                if (!midi_output.disposed)
                    midi_output.Send(MidiMessage.StartNote(number, volume, channel).RawData);

                Timer t = new Timer(_ =>
                {
                    lock (midi_output)
                    {
                        if(!midi_output.disposed)
                            midi_output.Send(MidiMessage.StopNote(number, 0, channel).RawData);
                    }
                },
                null, duration, Timeout.Infinite);
            }

        }
    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using NAudio.Midi;

namespace SoundVision
{
    class MidiOutWrapper:MidiOut
    {
        public MidiOutWrapper(int device) : base(device)
        {
            disposed = false;
        }

        public bool disposed { get; private set; }
        //kill() is called only during locking of object, so in Note midi_output can't become disposed inside lock
        public void kill()
        {
            disposed = true;
            Reset();
            Close();
        }
    }
}


texts: PHP - using static variables to store "client" for later use

texts:
I had this S3Helper class before such that, every time I called a function to any of its methods (which I haven't shown here, but which do things like upload files to s3 or get temporary s3 links), it called the getClient() method and it would make a new client every time.

Now I don't know about the performance hit on that, if calling new S3Client([]) makes http requests every time it's called, but I supposed it did so decided I'd rather just make the client once and then use the same client for future calls.

So I cached the result in a static variable, and now my getClient function checks if the cache exists first, and if it does it returns it, otherwise it makes a new client and sets the cache.

Is this a recommended PHP way of doing things? Can it be improved?

<?php // Code within app\Helpers\Helper.php

namespace App\Helpers;
use Aws\S3\S3Client;

class S3Helper {
    protected static $client = null;

    private static function getAuth() {
        return [
                'endpoint' => env('S3_ENDPOINT'),
                'key' => env('S3_KEY'),
                'secret' => env('S3_SECRET'),
                'bucket' => env('S3_BUCKET')
            ];
    }

    private static function getClient() {
        if (self::$client) return self::$client;

        $auth = self::getAuth();
        self::$client = new S3Client([
            'region' => 'eu-west-2',
            'version' => '2006-03-01',
            'endpoint' => $auth['endpoint'],
            'credentials' => [
                'key' => $auth['key'],
                'secret' => $auth['secret']
            ],
            'use_path_style_endpoint' => true
        ]);
        return self::$client;
    }
}


texts:
When programming debug functions I am left with 2 options, either put them all within preprocessor blocks so that they don't exist at release runtime, or put them within an if block with a debug flag constant variable (determined at launch) to control their execution. I wanted to write an improved method where in release mode the end user doesn't have access to the functions, but with a special DLL they can use them.

I want to know two things:

Is this more efficient than using a debug flag constant (determined at program launch) variable to control there execution. (e.g. will control flow prediction simply ignore all the calls to these debug functions)
Is this is a good practice. To be precise, would this be frowned upon by developers or horrible for some other reason (like security).

The DLL contains an essentially empty DllMain, here are the important definitions:

#include <iostream>

extern "C" void __cdecl println(const char* str)
{
#ifdef GEN_DEBUG_FUNCS
    std::cout << str << std::endl;
#endif
}

extern "C" int __cdecl test()
{
#ifdef GEN_DEBUG_FUNCS
    return 1;
#else
    return 0;
#endif
}

And on the primary program side of things we have:

The header to hold the function ptrs:

typedef void(__cdecl *f_println)(const char*);
typedef int(__cdecl *f_test)();

#ifdef FPTR_INIT
  #define EXTERN
#else
  #define EXTERN extern
#endif

EXTERN f_println println;
EXTERN f_test test;

/* Used for testing the functions in a CPP file other than main */
void testFuncs();

The CPP file to test the function pointers:

#include "FunctionPtrs.h"
#include <iostream>

void testFuncs()
{
    println("Hello World");
    std::cout << "funci() returned " << test() << std::endl;
}

And finally the Main CPP file which contains the entry-point and function pointer loading:

#include <windows.h>
#include <iostream>
#define FPTR_INIT
#include "FunctionPtrs.h"

int importDeclarations(const bool debug);

int main(int argc, char* argv[])
{
    bool debug = false;
    for(int i = 0; i < argc; ++i)
    {
        if(strcmp(argv[i], "--debug") == 0)
        { debug = true; }
    }

    const int status = importDeclarations(debug);
    if(status) { return status; }

    testFuncs();

    system("pause");

    return EXIT_SUCCESS;
}

int importDeclarations(const bool debug)
{
    const char* path = debug ? "%PATH_TO_DLL%\\debug\\DebugDLL.dll" :
                               "%PATH_TO_DLL%\\release\\DebugDLL.dll";

    const HINSTANCE hGetProcIDDLL = LoadLibrary(path);

    if(!hGetProcIDDLL)
    {
        std::cout << "Could not load the dynamic library." << std::endl;
        return EXIT_FAILURE;
    }

    println = (f_println)GetProcAddress(hGetProcIDDLL, "println");
    test = (f_test)GetProcAddress(hGetProcIDDLL, "test");

    if(!println || !test)
    {
        std::cout << "Could not locate function." << std::endl;
        return EXIT_FAILURE;
    }

    return 0;
}


texts:
I'm trying to read doubles from a relatively small binary file. This currently reads a 100 KB file in about 6 milliseconds in my system. I would like to reduce that if possible.

void readNParseData(const char* filePath, vector<double> *&data){

    ifstream ifs(filePath, ios::in | ios::binary);

    // If this is a valid file
    if (ifs) {
        // Temporary Variables
        std::streampos fileSize;
        double *fileBuffer;
        size_t sizeOfBuffer;

        // Check whether the parameter is already full
        if (data != 0){
            // Reset the output
            data->clear();
            data = 0;
        }

        // Get the size of the file
        ifs.seekg(0, std::ios::end);
        fileSize = ifs.tellg();
        ifs.seekg(0, std::ios::beg);

        sizeOfBuffer = fileSize / sizeof(double);
        fileBuffer = new double[sizeOfBuffer];

        ifs.read(reinterpret_cast<char*>(fileBuffer), fileSize);

        // Now convert the double array into vector
        data = new vector<double>(fileBuffer, fileBuffer + sizeOfBuffer);

        free(fileBuffer);
    }
}

As you can see there is a redundant copy of a double * array to a vector. Perhaps reading to the vector directly might speed it up, but I don't know how.


texts:
I use CodeIgniter at work, and one of our model files had a lot of subqueries in it.  I originally had to manually write each subquery, and wondered if I could use active records instead.
So, to make my life easier, I made a subquery library for CodeIgniter.
I put it on the CodeIgniter Wiki, but I never really had any one look over it.  So, can you tell me if there is anything I should improve in this, or anything I really shouldn't be doing?
P.S. Feel free to use this if you wish.
P.P.S. join_range is a helper method for use with the answer to this question.
P.P.P.S. The latest version can be found here.
class Subquery{
    var $CI;
    var $db;
    var $statement;
    var $join_type;
    var $join_on;

    function __construct(){
        $this->CI =& get_instance();
        $this->db = array();
        $this->statement = array();
        $this->join_type = array();
        $this->join_on = array();
    }

    /**
     * start_subquery - Creates a new database object to be used for the subquery
     *
     * @param $statement - SQL statement to put subquery into (select, from, join, etc.)
     * @param $join_type - JOIN type (only for join statements)
     * @param $join_on - JOIN ON clause (only for join statements)
     *
     * @return A new database object to use for subqueries
     */
    function start_subquery($statement, $join_type='', $join_on=1){
        $db = $this->CI->load->database('', true);
        $this->db[] = $db;
        $this->statement[] = $statement;
        if(strtolower($statement) == 'join'){
            $this->join_type[] = $join_type;
            $this->join_on[] = $join_on;
        }
        return $db;
    }

    /**
     * end_subquery - Closes the database object and writes the subquery
     *
     * @param $alias - Alias to use in query
     *
     * @return none
     */
    function end_subquery($alias=''){
        $db = array_pop($this->db);
        $sql = "({$db->_compile_select()})";
        $alias = $alias!='' ? "AS $alias" : $alias;
        $statement = array_pop($this->statement);
        $database = (count($this->db) == 0)
            ? $this->CI->db: $this->db[count($this->db)-1];
        if(strtolower($statement) == 'join'){
            $join_type = array_pop($this->join_type);
            $join_on = array_pop($this->join_on);
            $database->$statement("$sql $alias", $join_on, $join_type);
        }
        else{
            $database->$statement("$sql $alias");
        }
    }

    /**
     * join_range - Helper function to CROSS JOIN a list of numbers
     *
     * @param $start - Range start
     * @param $end - Range end
     * @param $alias - Alias for number list
     * @param $table_name - JOINed tables need an alias(Optional)
     */
    function join_range($start, $end, $alias, $table_name='q'){
        $range = array();
        foreach(range($start, $end) AS $r){
            $range[] = "SELECT $r AS $alias";
        }
        $range[0] = substr($range[0], 7);
        $range = implode(' UNION ALL ', $range);

        $sub = $this->start_subquery('join', 'inner');
        $sub->select($range, false);
        $this->end_subquery($table_name);
    }
}

Example Usage
This query:
SELECT `word`, (SELECT `number` FROM (`numbers`) WHERE `numberID` = 2) AS number
FROM (`words`) WHERE `wordID` = 3

would become:
$this->db->select('word')->from('words')->where('wordID', 3);
$sub = $this->subquery->start_subquery('select');
$sub->select('number')->from('numbers')->where('numberID', 2);
$this->subquery->end_subquery('number');


texts:
I came across this question in a coding contest (Java-restricted) and I got TLE. I am unable to provide the link of the question as the contest is closed now. Can I know how can I optimise this?

Four Functions
Given four functions

A(x) = Number of i where 1 <= i <= x and gcd(i,x) = 1
B(x) = Sum of A(d) where d divides the number x
C(x) = Sum of exponents of each prime in the prime factorization of B(x)
D(x) = Sum of C(i) where 1 <= i <= x

If $$B(x) = {p_1} ^ {a1} {p_2} ^ {a2} {p_3} ^ {a3}$$
where p1,p2,p3 are prime factors of B(x), then C(x) is a1 + a2
Find the value of D(N) Constraints:
$$1 \le testcases \le 1000000$$
$$1 \le N \le 1000000$$
Example :
Input :
1
4
Output :
4
For n = 4
$$C(1) = 0$$
$$C(2) = 1$$
$$C(3) = 1$$
$$C(4) = 2$$
$$D(4) = C(1) + C(2) + C(3) + C(4) = 4$$

This is my approach
public class Main {
    static long commonDivisor(long num1,long num2) {
        if(num1 == 0) {
            return num2;
        }
        return commonDivisor(num2 % num1, num1);
    }

    static long funcA(long numb) {
        long answer = numb;
        for (long itr = 2; itr * itr <= numb; itr++) {
            if(numb % itr == 0) {
                while(numb % itr == 0) {
                    numb /= itr;
                }
                answer -= answer / itr;
            }
        }
        if(numb > 1) {
            answer -= answer / numb;
        }
        return answer;
    }
    static long funcB(long numb) {
        long sum = 0;
        for (long itr = 1; itr <= Math.sqrt(numb); itr++){
            if (numb % itr == 0){
                if(numb/itr == itr){
                    sum = sum + funcA(itr);
                } else {
                    sum = sum + funcA(itr) + funcA(numb/itr);
                }
            }
        }
        return sum;
    }
    static boolean check_prime(long numb) {
        BigInteger bigint = new BigInteger(String.valueOf(numb));
        return bigint.isProbablePrime(1);
    }
    static long funcC(long numb) {
        if (numb <= 1) {
            return 0;
        }
        long remNum = numb;
        long expo = 0;
        for (long itr = 2; itr <= Math.sqrt(numb); itr++) {
             if(check_prime(itr)) {
                while (remNum % itr == 0) {
                    expo++;
                    remNum /= itr;
                }
             }
        }
        if(check_prime(remNum)) {
            if (remNum > 1) {
                expo++;
            }
        }
        return expo;
    }
    static long funcD(long numb) {
         long result = 0;
         for(long itr = 1; itr <= numb; itr++){
             result += funcC(funcB(itr));
         }
         return result;
    }

    public static void main(String[] args) {
        try {
        BufferedReader buffer = new BufferedReader(new InputStreamReader(System.in));
        long testCases = Long.parseLong(buffer.readLine());
        for(long itr = 1; itr <= testCases; itr++) {
            long number = Long.parseLong(buffer.readLine());
            System.out.println(funcD(number));
        }
    } catch(Exception e) {
        System.out.println("Error");
    }
}


texts: Using different instances of an object to lock threads

texts:
I'd like to use lock objects that are specific to the person I'm updating. In other words, if thread A is updating Person 1, thread B is blocked from also updating Person 1, but thread C is not blocked from updating Person 2.

99% of the time, I don't really need the locks since I'm working with different Person.Id values. In the occasional situations when I am working with the same Person.Id value, I want to lock around some read/write code.

The following code is working as I expect. I'm looking for any "gotcha's" I may have missed, or better ways of accomplishing the same thing. I decided to use the .NET Cache to store the lock objects so I don't need to worry about cleaning them up later (the lock objects are removed from cache when they haven't been used for a certain TimeSpan).

This code provides the object to lock on

public static class PersonLocks
{
    private static readonly object CacheLock = new object();
    private const string KeyPrefix = "LockForPersonID:";

    public static object GetPersonLock(long personId)
    {
        lock (CacheLock)
        {
            string key = BuildCacheKey(personId);
            object cachedItem = HttpRuntime.Cache[key];
            if (cachedItem == null)
            {
                cachedItem = new object();
                HttpRuntime.Cache.Insert(key, cachedItem, null, Cache.NoAbsoluteExpiration, new TimeSpan(0, 5, 0));
            }

            return cachedItem;
        }
    }

    private static string BuildCacheKey(long personId)
    {
        return KeyPrefix + personId.ToString();
    }

}

This is how I'm using the code

object padlock = PersonLocks.GetPersonLock(person.Id);
lock (padlock)
{
    //do read

    //do some data mapping

    //do write
}


texts:
I Have orders table, every order has different payment method and made by different user, has different total of money.

and i want to make a detailed report, i export date as a hash to the views, as follow :

orders = Order.where(state: 'paid').settled(false).order(showtime: 'ASC')

my_hash = {
  users: Hash.new { |h, k| h[k] = {
    showtimes: Hash.new { |h, k| h[k] = {
      movies:  Hash.new { |h, k| h[k] = {
        payment_methods: Hash.new { |h, k| h[k] = Hash.new(0) },
        total_cash: Hash.new(0), total_credit: Hash.new(0) } },
      total_cash: Hash.new(0), total_credit: Hash.new(0) } },
    total_cash: Hash.new(0), total_credit: Hash.new(0) } },
  total_cash: Hash.new(0), total_credit: Hash.new(0) };

orders.each do |o|
  user = o.user.name
  showtime = o.showtime.strftime('%m-%d %H:%M')
  movie = o.movie.name
  payment_method = o.payment_method

  my_hash[:users][user][:showtimes][showtime][:movies][movie][:payment_methods][payment_method][:tickets] += o.t_count
  my_hash[:users][user][:showtimes][showtime][:movies][movie][:payment_methods][payment_method][:money] += o.m_total
  my_hash[:users][user][:showtimes][showtime][:movies][movie][:total_cash][:tickets] += o.t_count
  my_hash[:users][user][:showtimes][showtime][:movies][movie][:total_cash][:money] += o.m_total
  my_hash[:users][user][:showtimes][showtime][:total_cash][:tickets] += o.t_count
  my_hash[:users][user][:showtimes][showtime][:total_cash][:money] += o.m_total
  my_hash[:users][user][:total_cash][:tickets] += o.t_count
  my_hash[:users][user][:total_cash][:money] += o.m_total
  my_hash[:total_cash][:tickets] += o.t_count
  my_hash[:total_cash][:money] += o.m_total
end

is there a better way, with less number of lines, can i fill the hash in one line every loop ?


texts: Creating and calling objects sequentially in Tkinter with Python 3

texts:
I am trying to build a very simple user interface in Python 3 using Tkinter to be used in windows. and have written a code which is not efficient - it is excessively long for no good reason. I am looking for advice, perhaps even conceptual, about how to make this short and elegant.

Here is a simple excerpt from the code, for only 2 periods. I have many periods, and have created each of them as a class, which is the problem that I am trying to replace. I presume that we should just have one Period class, objects of which will be called sequentially. I do not understand how to do this with Tkinter.

import tkinter as tk
from tkinter import ttk

class Game(tk.Tk):

    def __init__(self, *args, **kwargs):

        tk.Tk.__init__(self, *args, **kwargs)

        container = tk.Frame(self)
        container.pack(side='top', fill='both', expand=True)
        container.grid_rowconfigure(0, weight=1)
        container.grid_columnconfigure(0, weight=1)

        self.frames = {}
        for F in (Period1, Period2):
            frame = F(container, self)
            self.frames[F] = frame
            frame.grid(row=0, column=0, sticky='nsew')

    def show_frame(self, cont):
        frame = self.frames[cont]
        frame.tkraise()

class Period1(tk.Frame):

    def __init__(self, parent, controller):

        tk.Frame.__init__(self, parent)

        buttonNext = ttk.Button(self, text='next', command=lambda: controller.show_frame(Period2))
        buttonNext.pack()

class Period2(tk.Frame):

    def __init__(self, parent, controller):

        tk.Frame.__init__(self, parent)

        buttonNext = ttk.Button(self, text='next', command=lambda: controller.show_frame(Period1))
        buttonNext.pack()

app = Game()
app.mainloop()


texts: I have a Java Class that I suspect can use a ReflectionUtil here because there are too many switch/cases, any advice?

texts:
I have a chunk of code here:
public class ParserFactory
{
    public static ParserClass getParserClass(InputStream is, CustomMap customMap,
                                           DataHandler recordHandler, DataHandler columnHandler) throws JsonProcessingException
    {
        ParserClassType ParserClassType = ParserClassType.getParserClassType(customMap.getParser());
        switch (ParserClassType)
        {
            case SPECIFIC_XML:
                return new SpecificXMLParser(is, customMap.getProperties(), recordHandler, columnHandler);
            case XML:
                return new GenericXMLParser(is, customMap.getProperties(), recordHandler, columnHandler);
            case JSON:
                return new GenericJSONParser(is, customMap.getProperties(), recordHandler, columnHandler);
            case SPECIAL:
                return new SpecialParser(is, customMap.getProperties(), recordHandler, columnHandler);
            case FW:
                return new GenericFixedWidthParser(is, customMap.getProperties(), recordHandler, columnHandler);
            case CSV:
                return new GenericCSVParser(is, customMap.getProperties(), recordHandler, columnHandler);
            default:
                throw new IllegalArgumentException("ParserClassType not found.");
        }
    }

    public static String getFileExtension(CustomMap customMap)
    {
        ParserClassType ParserClassType = ParserClassType.getParserClassType(customMap.getParser());
        switch (ParserClassType)
        {
            case SPECIFIC_XML:
                return SpecificXMLParser.FILE_TYPE_OUTPUT;
            case XML:
                return GenericXMLParser.FILE_TYPE_OUTPUT;
            case JSON:
                return GenericJSONParser.FILE_TYPE_OUTPUT;
            case SPECIAL:
                return SpecialParser.FILE_TYPE_OUTPUT;
            case FW:
                return GenericFixedWidthParser.FILE_TYPE_OUTPUT;
            case CSV:
                return GenericCSVParser.FILE_TYPE_OUTPUT;
            default:
                throw new IllegalArgumentException("ParserClassType not found.");
        }
    }
}

Now, it's not exactly too important what all these arguments are. In getParserClass, I retrieve an enum from ParserClassType. The switch handles all the possible values. A certain value will return a ParserClass.
The other function, getFileExtension, retrieves a static string from a parser class.
As my project grows, I will have many new parsers that I add. I want to make this as flexible and less-hectic as possible. I don't want to keep adding cases to this function. So.
I was looking into EnumMap. I was thinking of mapping an ENUM to a ParserClass name, so for example "XML" would make to "GenericXMLParser.class", and then I could use a ReflectionUtil to create the class with the arguments necessary or retrieve that string. Therefore, if I have to make any additions, all I need to do is add the ENUM to the enum class and make an addition to the map. But, ReflectionUtils seems to require me to provide the path of the parser. Something like "com.package.service.more.bs.SpecificXMLParser". I would rather not do that...
Any ideas?


texts: Adding and removing classes at different heights on page using jQuery

texts:
I want to remove/add classes when the user is at different distances from the top by using jQuery.

I have successfully done it, and it works fine, but I think I'm doing it wrong, and I would like your help to optimize the code.

The html is simple, basically the sections(including the header), have 100% width. and different colors. I want to make the header change color when its over the first section(for aesthetical purposes).
And I also want it to have a shadow when the page has been scrolled more than 1 pixel.

I'm doing it by adding/removing classes.

When I use one big else if statement it doesn't work well because whenever any any condition is matched js stops checking for other matches, so it doesn't apply all the classes needed.

The next code works, however as I said, I think that it's not optimal/badly written.
Here is the HTML markup:

  Header

  Please Scroll Down to see the header changes...

  The header color Should change when you pass through me.

And here is the jQuery code:

var header = $('header'),
        blueSection = $('section.blue'),
    // Calculate when to change the color.
        offset = blueSection.offset().top + blueSection.height() - header.height();

$(window).scroll(function(){
  var scroll = $(window).scrollTop();

    // Remove Class "dark" after scrolling over the dark section
  if (scroll >= offset) {
    header.removeClass('dark');
  } else {
    header.addClass('dark');
  }

    // Remove Class "no-shadows" whenever not on the top of the page.
  if (scroll >= 1) {
    header.removeClass('no-shadow');
  } else {
    header.addClass('no-shadow');
  }

});

And for those of you who like to use JSFiddle(like me!):
https://jsfiddle.net/shock/wztdt077/6/


texts: Computing the circumference of two circles

texts:
This is a program which computes the circumference of two circles and gives some information such as the difference between circumferences.  I want to know whether the method declarations and method calling in my code is correct.  I didn't face any errors.

import java.text.*;
import javax.swing.*;
class Q5Main{
    public static void main(String args[]){
        double smallCircum;
        double largeCircum;
        InputHandler input = new InputHandler();
        Question5 myq = new Question5();

        double a = input.getDouble("Radius for the smaller circle:");

        smallCircum = (myq.start(a));//calculate the small circle circumference

        a = input.getDouble("Radius for the larger circle: ");
        largeCircum = (myq.start(a));//calculate the large circle circumference

        myq.showDetails(smallCircum, largeCircum);

    }

}

class Question5{
    DecimalFormat df = new DecimalFormat("0.000");

    private double circumference;//to store circumference

    //carry out the full process
    public double start(double value){
        return circum(value);
    }

    //compute the circumference
    private double circum(double radius){
        circumference = 2 * Math.PI * radius;
        return circumference;
    }

    public void showDetails(double smallCircum, double largeCircum){
        System.out.println("Circumference of smaller circle: "+df.format(smallCircum));
        System.out.println("\n");
        System.out.println("Circumference of larger circle: "+df.format(largeCircum));
        System.out.println("\n");
        System.out.println("Difference: "+df.format((largeCircum-smallCircum)));

    }

}

class InputHandler{
    private static final String DOUBLE_DEFAULT_PROMPT = "Enter integer: ";

    public double getDouble(){
        return getDouble(DOUBLE_DEFAULT_PROMPT);
    }

    public static double getDouble(String prompt){
        String inStr;
        inStr = JOptionPane.showInputDialog(null,prompt);
        return Double.parseDouble(inStr);
    }
}


texts:
This is my first F# program.

It's a command line utility that takes a parameter containing a path to an height map bitmap and prints out this height map converted to JSON format.

open System.Drawing

let convertLine (y:int) (bitmap:System.Drawing.Bitmap) =
    [ for x in 0 .. bitmap.Width - 1 -> "\"" + bitmap.GetPixel(x, y).R.ToString() + "\"" ] |> String.concat ", "

let convert (path:string) : string =
    let bitmap = new System.Drawing.Bitmap(path)
    let results = [ for y in 0 .. bitmap.Height - 1 -> convertLine y bitmap ] |> String.concat ", "

    "{\"X\": \"" + bitmap.Width.ToString() +
    "\", \"Y\": \"" + bitmap.Width.ToString() +
    "\", \"values\":[" + results + "]}"

[<EntryPoint>]
let main argv =
    let arglist = argv |> List.ofSeq

    let returnValue =
        match arglist with
            | path :: _ -> convert path
            | _ -> "Wrong number of arguments supplied"

    printfn "%s" returnValue

    match returnValue with
        | "Wrong number of arguments supplied" -> 1
        | _ -> 0

I want to make sure to write idiomatic F# and to write in a functional style.


texts:
I've decided to learn C++, coming from Python, and this is my first program. I would love some feedback on it.

It's split up into two header files and one .cpp file:

Board.h

class Board {

public:

    std::string board[7][4] = {
        { "\n\n-------------\n" },
        { "| 1 ", "| 2 ",  "| 3 ", "|\n" },
        { "----+---+----\n" },
        { "| 4 ", "| 5 ",  "| 6 ", "|\n" },
        { "----+---+----\n" },
        { "| 7 ", "| 8 ",  "| 9 ", "|\n" },
        { "-------------\n" }
    };

    void displayBoard(); // Displays the board[2D Array]

} board;

void Board::displayBoard()
{
    for (int x = 0; x < 7; x++) // Row of the 2D array
        for (int i = 0; i < 4; i++) // Column of the 2D array
            std::cout << board[x][i];
}

Player.h

class Player {

private:

    int in, row, col;
    std::string peice, player;

public:

    Player(std::string x); // Sets up peice, depending on parameter
    int move();           // Gets input and makes move
    bool winner();       // Checks for winner

} p1("X"), p2("O");

// CLASS FUNCTIONS

Player::Player(std::string x)
{
    player = x;
    peice = player == "X" ? "| X " : "| O ";
}

int Player::move()
{
beginning:

    while (!(in > 0 && in < 10)) // Only accpets values between 1-9
    {
        std::cout << "\nPlayer " << player << " enter position: ";
        std::cin >> in;
    }

    row = in > 3 && in < 7 ? 3 : 1;                    // Sets row
    row = in > 6 && in < 10 ? 5 : row;

    col = in == 2 || in == 5 || in == 8 ? 1 : 0;       // Sets Column
    col = in == 3 || in == 6 || in == 9 ? 2 : col;

    in = 0; // Sets back to 0 so the while expression will work again

    if (board.board[row][col] == "| X " || board.board[row][col] == "| O ")
    { // If space has already been taken, ask for input again
        goto beginning;
    }

    board.board[row][col] = peice;  // Convert position from board into the peice
    system("cls");                 // Clears everything in the window
    board.displayBoard();         // Display Board

    if (winner() == true) { return 1; } // Checks if this player has won
}

bool Player::winner()
{
    for (int x = 1; x < 6; x += 2)
    {
        if (board.board[x][0] == peice && board.board[x][1] == peice && board.board[x][2] == peice || // Horizontal
            board.board[1][x - 1] == peice && board.board[3][x - 1] == peice && board.board[5][x - 1] == peice || // Verical
            board.board[1][x - 1] == peice && board.board[3][1] == peice && board.board[5][x == 1 ? 2 : 0] == peice) // Diagonal
        {
            std::cout << "\nPlayer " << player << " has won\n";
            return true;
        }
    }
}

TicTacToe.cpp

// Tic Tac Toe - TCG

#include <iostream>
#include <string>

#include "Board.h"
#include "Player.h"

int main()
{
    std::cout << "Welcome to Tic Tac Toe";
    board.displayBoard();

    for (int x = 0; x < 6; x++)
    {
        if (p1.move() == 1) { break; } // Player X

        if (x == 4) // If there is no winner up until the end of the game; end game
        {
            std::cout << "\n\n\nThe match was a draw\n";
            break;
        }

        if (p2.move() == 1) { break; } // Player O
    }
}

Here is the program compiled and running:

Welcome to Tic Tac Toe

-------------
| 1 | 2 | 3 |
----+---+----
| 4 | 5 | 6 |
----+---+----
| 7 | 8 | 9 |
-------------

Player X enter position:

Here is the updated version.


texts:
Doing practise questions for a Java exam which have no answers (useful) I have been asked to do the following:

Write a class called Person with the following features:

a private int called age;
a private String called name;
a constructor with a String argument, which initialises name to the received value and age to 0;
a public method toString(boolean full). If full is true, then the
method returns a string consisting of the person’s name followed by their
age in brackets; if full is false, the method returns a string consisting of
just the name. For example, a returned string could be Sue (21) or Sue;
a public method incrementAge(), which increments age and returns the
new age;
a public method canVote() which returns true if age is 18 or more and
false otherwise.

My code is as follows can someone point out any errors?

public class Person
{
    private int age;
    private String name;

    public Person(String st)
    {
      name = st;
      age = 0;
    }

   public String toString(boolean full)
   {
     if(full == true)
     {
        return name + "(" + age + ")";
     }
     else
     {
        return name;
     }
   }

   public int incrementAge()
   {
      age++;
      return age;
   }

   public boolean canVote()
   {
     if(age >= 18)
     {
        return true;
     }
     else
     {
        return false;
     }
   }
}


texts: Search and sort customers from JSON file

texts:
I have just completed my first JavaScript/jquery project. It searches customers from .JSON file and sorts them by name or ID. Everything just works fine. The thing is, I am not sure that I have understood all the functions and methods that I have written. Could anyone tell me if this is the best way to read .JSON file and going through the queries that I have written below?

<!DOCTYPE html>

    <title>Toolbox Search</title>

    <link href="autocomplete/easy-autocomplete.min.css" rel="stylesheet" />
    <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
    <link href="custom.css" rel="stylesheet" />

                <input type="text" id="KUNDE" size="50" placeholder="Search by name." />

                <button class="btn btn-default" type="button" id="buton" value="search" onclick="find();">Search</button>

        <button id="button"class="btn btn-default">
            Clean Results
        </button>

 © Copyright 2016
 .


texts: Array-like data structure for fixed sized types with non-machine-word sizes

texts:
I am writing an array-like data structure for types other than 8 16 32 64 – the usual type sizes.
Ideally, my interface is the following for addressing the array.
void setindex(uint8_t *array, size_t width, size_t index, uint64_t value);
uint64_t getindex(uint8_t *array, size_t width, size_t index);

This is basically an array of unsigned integers of size width. A uint8_t value would contain 4 elements for width=2, at max.
This should hold no more metadata than that. So in theory, it should work with any blob of allocated memory. Bound-checks should be done by the caller.
I have the following code, packed as a very small header library:
#include <cstdio>
#include <iostream>
#include <bitset>
#include <cassert>

using namespace std;

uint64_t getindex(uint64_t *A, size_t width, size_t index)
{
    uint64_t mask, mask1, mask2, ret, shift;
    uint64_t size, d, m;

    size = sizeof A[0] * 8;
    mask = (1 << width) - 1;
    shift = index * width;

    // Any decent compiler does this in one instruction
    d = (index + 1) * width / size;
    m = (index + 1) * width % size;

    if (!d) {
        ret = (*A & (mask << (shift))) >> shift;
    } else {
        mask1 = (1 << m) - 1;
        mask2 = (1 << (width - m)) - 1;

        ret = (A[d] & mask1) << (width - m) | (A[d - 1] & (mask2 << (size - (width - m)))) >> (size - (width - m));
    }

    return ret;
}

uint64_t setindex(uint64_t *A, size_t width, size_t index, uint64_t value)
{
    uint64_t mask, mask1, mask2, shift;
    uint64_t size, d, m;

    assert(value < (1 << width));

    size = sizeof A[0] * 8;

    mask = (1 << width) - 1;

    shift = index * width;

    // Any decent compiler does this in one instruction
    d = (index + 1) * width / size;
    m = (index + 1) * width % size;

    if (!d) {
        A[0] = (A[0] & ~(mask << (shift))) | (value << shift);

    } else {
        mask1 = (1 << m) - 1;
        mask2 = (1 << (width - m)) - 1;

        A[d] = (A[d] & ~mask1) | (((mask1 << (width - m)) & value) >> (width - m));
        A[d - 1] = A[d - 1] & ~(mask2 << size - m) | ((mask2 & value) << (size - (width - m)));
    }

    return value;
}

I come from C, so the code may be very C-like, as I don't fully know most of the C++ features well.
Can this be simplified and made more robust? The above code may have problems with bit shifting and undefined behavior. I have the feeling that this problem is very well suited for fors and divmods algorithms, like those used to construct gcd. But in my implementation, I did not manage to do that. Are there existing libraries I can better use?


texts: Locating the Bash history file for a user

texts:
This looks quite verbose to me, using the command substitution and echo:

# Source file
source=$( [[ ! -z "$1" ]] && echo "/home/$1" || echo '/root' )
source="$source"/.bash_history
[[ ! -f "$source" ]] && echo "History file '$source' not found." 1>&2 && exit 1;

# Am I dealing with root
isRoot=$([[ "$source" =~ ^/root ]] && echo 1 || echo 0 )

Is there a cleaner (maybe faster?) manner to assign a value to variable depending on some condition?


texts:
Currently, the code below looks awful because of all the callbacks involved. How can I reduce the amount of nesting?  Also, would you recommend the use of q or Async.js?

var mongoose = require('mongoose');
var User = require('../models/user.js');
var Genre = require('../models/genre.js');
var Album = require('../models/album.js');
var Band = require('../models/band.js');

exports.populate = function (req, res) {
  var bandNames = [
    'The Cool Group',
    'The Peeps',
    'Music Creation',
    'Number and Wumbers',
    'Testing For You',
    'What What',
    'Alrightly Then',
    'Is this the way it is?',
    'It hurts to know who you are',
    'There has been one or two of you',
    'Please and eyond'
  ];

  var userNames = [
    'syte',
    'koumarianos',
    'ericStas',
    'bloodCobia'
  ];

  albumId = Album.create({
      name: 'Test Album',
      biography: 'example'
    },
    function (err, album) {
      if (!err) {

        var albumId = album._id;

        Genre.create({ name: 'Rock' }, function (err, genre) {
            if (!err) {
              var genreId = genre._id;

              var users = [];

              for (var i = 0; i < userNames.length; i++) {
                users.push({
                  username: userNames[i]
                });
              }

              User.create(users, function (err) {
                var bands = [];
                var users = Array.prototype.slice.call(arguments, 1);
                var userIds = []

                for (var i = 0; i < users.length; i++) {
                  userIds.push(users[i]._id);
                }

                res.send(userIds);

                if (!err) {
                  for (var i = 0; i < bandNames.length; i++) {
                    bands.push({
                      name: bandNames[i],
                      biography: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean ac iaculis dui. Duis dignissim est ut ante cursus sodales. Duis et turpis ac nisl dictum mollis. Ut vel tempus metus. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Duis eu risus aliquet, mattis est vitae, tempus sem. In eget ante semper, adipiscing arcu eu, fringilla lectus. Sed non tortor vulputate magna sodales varius eu quis nulla. Sed dignissim sed magna sit amet sodales. Ut nisi tortor, dapibus quis nulla eu, consectetur ornare dolor. Morbi mollis diam ut vulputate consectetur. In tincidunt, elit quis ultricies auctor, dolor odio condimentum ligula, quis sodales magna dui at est. Integer a orci rutrum, fermentum sapien quis, facilisis purus.',
                      albums: [albumId],
                      genres: [genreId],
                      members: userIds
                    });
                  }

                  // save all bands
                  Band.create(bands, function (err) {
                      if (!err) {
                        res.send("Successfully made all test data");
                      } else {
                        res.send(err);
                      }
                  });
                }
              });
            } else {
              res.send(err);
            }
          });
      } else {
        res.send(err);
      }
    });
};


texts: Create dictionary with default immutable keys

texts:
I've created a dictionary subclass with a set of default immutable keys.

from collections import MutableMapping

class Bones(MutableMapping):
    """Basic dict subclass for bones, that forbids bones from being deleted
    and new bones from being added."""

    def __init__(self, init_val=0):
        self.bones = {"between_hips": init_val,
                      "bicep_right": init_val,
                      "bicep_left": init_val,
                      "arm_right": init_val,
                      "arm_left": init_val,
                      "thigh_right": init_val,
                      "thigh_left": init_val,
                      "leg_right": init_val,
                      "leg_left": init_val,
                      "spine_lower": init_val,
                      "spine_upper": init_val}

    def __getitem__(self, item):
        return self.bones[item]

    def __setitem__(self, key, value):
        if key in self.bones:
            self.bones[key] = value
        else:
            raise KeyError("Can't add a new bone!")

    def __delitem__(self, key):
        raise TypeError("Can't delete bones")

    def __iter__(self):
        return iter(self.bones)

    def __len__(self):
        return len(self.bones)

Here are a few tests to check that it's working correctly:

from bones import Bones

bn = Bones()
bn["between_hips"] = 1

# these should all raise errors
bn["foo"] = 1
del bn["between_hips"]

Is this the proper way to create the subclass?

Background

My search to do this correctly started at the StackOverflow question "How to 'perfectly' override a dict" where I discovered there were two approaches to doing this. One was sub-classing an Abstract Base Class from the collections module and the other was actually sub-classing dict.

The justification for actually sub-classing dict confused me. Specifically the discussion of the object properties of __dict__ and __slots__. As best as I can tell from this question, I should be using __slots__, but I'm super unclear how.