c++ – I wrote a header file to write German umlauts in a textfile properly

This function is about the fact that a std::wstring was used in another cpp file in order to be able to read strings with German umlauts from the console. Since it is difficult to get wstrings into a text file when a std::ofstream is already accessing the text file, this wstring was converted into a normal std::string using utf8.h. The 16-bit characters that represented umlauts are now 2 cryptic characters (which is logical, I know). A ß becomes ß, an ü becomes ü, as you often see it in everyday life. This is corrected with this .h and .cpp files.

By utf8.h, I mean this:
utf8 package which I downloaded in NuGet Packet Manager

My question is: Could you please review this function and say what you think of the code?
I’m asking because the code is copying one vector to a second one a lot, and, as you see in the last lines, I need to get rid of ‘left-over’ null characters. I want to include the header and cpp file more often, so I want the two to be good.

handle_German_umlauts.cpp

#include "handle_German_umlauts.h"

Umlaute_korrigieren::Umlaute_korrigieren()
{
}

Umlaute_korrigieren::~Umlaute_korrigieren()
{
}

std::vector<char> Umlaute_korrigieren::_std__String_to_std__vectorChar_for_ANSI(std::string stdstring)
{
     

    std::vector<char> CString(stdstring.c_str(), stdstring.c_str() + stdstring.size() + 1);
    std::vector<char> copy(stdstring.c_str(), stdstring.c_str() + stdstring.size() + 1);

    for (size_t i = (size_t)0; i < CString.size() - (size_t)1; i++)
    {
        if (CString(i) == -61 && CString(i + 1) == -97) // Pseudo-ß gefunden
        {
            copy(i) = 'xDF'; //ß ist DF(hex) in ANSI
            for (size_t j = copy.size() - (size_t)1; j > (i+(size_t)1); j--) // umkopieren
            {
                copy(j - 1) = CString(j);
            }
            CString = copy;
        }

        if (CString(i) == -61 && CString(i + 1) == -68) // Pseudo-ü gefunden
        {
            copy(i) = 'xFC'; //ü ist FC(hex) in ANSI
            for (size_t j = copy.size() - (size_t)1; j > (i + (size_t)1); j--) // umkopieren
            {
                copy(j - 1) = CString(j);
            }
            CString = copy;
        }

        if (CString(i) == -61 && CString(i + 1) == -92) // Pseudo-ä gefunden
        {
            copy(i) = 'xE4'; //ä ist E4(hex) in ANSI
            for (size_t j = copy.size() - (size_t)1; j > (i + (size_t)1); j--) // umkopieren
            {
                copy(j - 1) = CString(j);
            }
            CString = copy;
        }

        if (CString(i) == -61 && CString(i + 1) == -74) // Pseudo-ö gefunden
        {
            copy(i) = 'xF6'; //ö ist F6(hex) in ANSI
            for (size_t j = copy.size() - (size_t)1; j > (i + (size_t)1); j--) // umkopieren
            {
                copy(j - 1) = CString(j);
            }
            CString = copy;
        }

        if (CString(i) == -61 && CString(i + 1) == -124) // Pseudo-Ä gefunden
        {
            copy(i) = 'xC4'; //Ä ist C4(hex) in ANSI
            for (size_t j = copy.size() - (size_t)1; j > (i + (size_t)1); j--) // umkopieren
            {
                copy(j - 1) = CString(j);
            }
            CString = copy;
        }

        if (CString(i) == -61 && CString(i + 1) == -106) // Pseudo-Ö gefunden
        {
            copy(i) = 'xD6'; //Ö ist D6(hex) in ANSI
            for (size_t j = copy.size() - (size_t)1; j > (i + (size_t)1); j--) // umkopieren
            {
                copy(j - 1) = CString(j);
            }
            CString = copy;
        }

        if (CString(i) == -61 && CString(i + 1) == -100) // Pseudo-Ü gefunden
        {
            copy(i) = 'xDC'; //Ü ist DC(hex) in ANSI
            for (size_t j = copy.size() - (size_t)1; j > (i + (size_t)1); j--) // umkopieren
            {
                copy(j - 1) = CString(j);
            }
            CString = copy;
        }
    }

    // crop unnecessary ‘’s
    size_t _0Counter = 0;
    for (size_t i = (size_t)0; i < CString.size(); i++)
    {
        if (CString(i) == '')
        {
            _0Counter += (size_t)1;
        }
    }
    size_t original = CString.size() - (size_t)1; // because the vector gets smaller due to the deletion and the for loop is always reevaluating
    size_t wie_weit = CString.size() - _0Counter;
    for (size_t i = original; i > wie_weit; i--)
    {
        CString.erase(CString.begin() + i - 1);
    }

    return CString;
}

The handle_German_umlauts.h

#ifndef HANDLE_GERMAN_UMLAUTS_H_
#define HANDLE_GERMAN_UMLAUTS_H_
#include <vector>
#include <string>
class Umlaute_korrigieren
{
public:
    Umlaute_korrigieren();
    ~Umlaute_korrigieren();
    std::vector<char> _std__String_to_std__vectorChar_for_ANSI(std::string);
private:

};
#endif // !HANDLE_GERMAN_UMLAUTS_H_

The function is called as follows:

std::string Strasse_als_stdstring;
utf8::utf16to8(physical_address.street.begin(), physical_address.street.end(), back_inserter(Strasse_als_stdstring));
std::vector<char> korrigierte_Strasse = Uk._std__String_to_std__vectorChar_for_ANSI(Strasse_als_stdstring);
for (size_t h = (size_t)0; h < korrigierte_Strasse.size() - (size_t)3; h++) // write to txt. -3, so that rn aren't printed.
{
    fs8 << korrigierte_Strasse(h);
}
fs8 << " " << physical_address.house_number << std::endl;

where physical_address.street is the std::wstring (mentioned above), and the for loop serves to write the chars in the textfile (std::ofstream fs8).

tdd – How should I test “Glue Functions” without testing that “the code I wrote is the code I wrote”?

I usually write my code in a test driven style. I write tests as specifications and then my code. It’s great and useful.

I always try to ignore implementation when testing and only test behaviour. I don’t care how it gets done, just that it got done. I find this especially easy for functional programming.

Now here is the problem I have found. I have an app that is written in a functional style. All of the unit tests are nice, clean, behavioural tests. I only ever check output and don’t do things like “did you call this function?”.

At some point however, I start needing “glue” functions. I’ll consider these functions that don’t introduce a lot of functionality and largely just call my other existing functions. Perhaps chaining a bunch together or whatever feature it may be.

How do I test these glue functions?

I ask because I want to avoid two main things as much as possible:

  • I don’t want to test them by simply mocking what they do and seeing if specific functions were called.
  • They have a desired output I want, but usually this output is just a series of outputs from other functions that are already tested. I don’t want to repeat myself and just “re-test” those inner functions to see if my glue function called them.

Hopefully that makes sense. Here is an example (written in pseudo code):

func1 (x) => x + 1;
func2 (x) => x * 2;

glue (x) => (func1(x), func2(x));

Here would be a simple way of testing these functions.

testFunc1 () => expect func1(2) == 3;
testFunc2 () => expect func1(2) == 4;

testGlue () => expect glue(2) == (3, 4);

So obviously, glue has an expected and predictable behaviour I want to model. I know that in this example these tests might be ok. So consider instead that the outputs of func1 and func2 are not simple numbers but much more complicated objects.

In such a case, implementing the checks that glue output the correct objects would be tedious AND it would be totally duplicated from the individual tests of func1 and func2. This also leads into the next issue.

Instead consider:

testGlue () => expect glue(2) == (func1(2), func2(2));

This certainly seems better. But I think it is still flawed. While this means I am not repeating my test code it now instead “tests that the code you wrote is the code you wrote” (as opposed to what the behaviour is). Again, in such a small example it’s not an issue so pretend that within glue a few variables are swapped around and yada yada is done so that to test it in this way would require my test to also set up the variables like such. Then we would be basically copying the code from the function to check if func1 and func2 were called with the correct variables leading to repetition and testing that “it’s the code you wrote”.

If a larger example is needed to showcase such results just let me know and I will get one. Hopefully there is some good discussion to be had here.

I anticipate someone to answer “don’t use glue functions” and to that i preemptively ask, “what’s the alternative method?”.

sorting – I recently wrote sort of structs in golang

I am a bit concerned about style (functions, variable names, spacings, etc.). I am also not sure about whether I should return error or panic.
What do you think?

//SortStructs sorts user-made structs, given that "a" is a pointer to slice of structs
//and key's type (which is name of a field by which struct would be sorted) is one of the basic GO types
//which will be sorted in ascending order when asc is true and the other way around, fields must be exported
func SortStructs(a interface{}, key string, asc bool) error {
    var (
        fName    string
        fPos     int
        valSlice ()reflect.Value
    )

    if a == nil {
        return errors.New("mysort: given interface is empty")
    }

    structSlicePointer := reflect.ValueOf(a)
    if structSlicePointer.Kind() != reflect.Ptr {
        return errors.New("mysort: given interface is not pointer")
    } else if structSlicePointer.Elem().Kind() != reflect.Slice {
        return errors.New("mysort: given interface is not pointer to slice")
    }

    //append single structs here
    for i := 0; i < structSlicePointer.Elem().Len(); i++ {
        valSlice = append(valSlice, structSlicePointer.Elem().Index(i))
    }

    if valSlice(0).Kind() != reflect.Struct {
        return errors.New("mysort: interface is not a struct")
    }

    //search for key here
    sl := valSlice(0)
    for ; fPos < sl.NumField(); fPos++ { //range over fields and search for match with key
        fName = sl.Type().Field(fPos).Name
        if fName == key {
            break
        }
    }

    if fPos == sl.NumField() && fName != key {
        return errors.New("mysort: key not found")
    } else if !basicGoType(sl.FieldByName(key)) {
        return errors.New("mysort: key is not a basic go type")
    }

    sortReflect(valSlice, 0, len(valSlice)-1, key, asc)
    return nil
}

func basicGoType(a reflect.Value) bool {
    return a.Kind() == reflect.Bool ||
        a.Kind() == reflect.Int || a.Kind() == reflect.Int8 || a.Kind() == reflect.Int16 || a.Kind() == reflect.Int32 || a.Kind() == reflect.Int64 ||
        a.Kind() == reflect.Uint || a.Kind() == reflect.Uint8 || a.Kind() == reflect.Uint16 || a.Kind() == reflect.Uint32 || a.Kind() == reflect.Uint64 ||
        a.Kind() == reflect.Complex64 || a.Kind() == reflect.Complex128 || a.Kind() == reflect.Float32 || a.Kind() == reflect.Float64 || a.Kind() == reflect.String
}

func aLessThanBReflect(a reflect.Value, b reflect.Value) bool {
    switch a.Kind() {
    case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
        int1 := a.Int()
        int2 := b.Int()
        return int1 < int2
    case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
        uint1 := a.Uint()
        uint2 := b.Uint()
        return uint1 < uint2
    case reflect.Bool:
        bool1 := a.Bool()
        bool2 := b.Bool()
        return !bool1 && bool2
    case reflect.Float32, reflect.Float64:
        float1 := a.Float()
        float2 := b.Float()
        return float1 < float2
    case reflect.Complex64, reflect.Complex128:
        complex1 := a.Complex()
        complex2 := b.Complex()
        if real(complex1) == real(complex2) {
            return imag(complex1) < imag(complex2)
        }
        return real(complex1) < real(complex2)
    case reflect.String:
        str1 := a.String()
        str2 := b.String()
        return str1 < str2
    }
    return false
}

//This is Hoare partition scheme adapted for this code
func partitionReflect(a ()reflect.Value, low, high int, key string, asc bool) int {
    pivot := a(int((high+low)/2))
    low -= 1
    high += 1

    for {
        if asc {
            low += 1
            for a(low).FieldByName(key) != pivot.FieldByName(key) && aLessThanBReflect(a(low).FieldByName(key), pivot.FieldByName(key)) {
                low += 1
            }
            high -= 1
            for a(high).FieldByName(key) != pivot.FieldByName(key) && !aLessThanBReflect(a(high).FieldByName(key), pivot.FieldByName(key)) {
                high -= 1
            }
        } else {
            low += 1
            for a(low).FieldByName(key) != pivot.FieldByName(key) && !aLessThanBReflect(a(low).FieldByName(key), pivot.FieldByName(key)) {
                low += 1
            }
            high -= 1
            for a(high).FieldByName(key) != pivot.FieldByName(key) && aLessThanBReflect(a(high).FieldByName(key), pivot.FieldByName(key)) {
                high -= 1
            }
        }

        if low >= high {
            return high
        }

        //allocate memory for struct and copy a(low)'s value here
        //couldn't do temp := a(low).Interface() because it shared 1 memory adress
        temp := reflect.New(a(low).Type()).Interface()
        temp = a(low).Interface()
        a(low).Set(a(high))
        a(high).Set(reflect.ValueOf(temp))
    }
}

func sortReflect(a ()reflect.Value, low, high int, key string, asc bool) {
    if low < high {
        p := partitionReflect(a, low, high, key, asc)
        sortReflect(a, low, p, key, asc)
        sortReflect(a, p+1, high, key, asc)
    }
}
```

Why do I have a picture on my contact list of a iPhone number I wrote down?

I wrote down someone’s phone number on my iPhone. He also had an iPhone. However, we are not connected in any way. Example: no social media, he hasn’t sent me a message, no email, etc. I know that the iPhone pulls pictures from many places but in this case, we don’t have anything in common. How would his picture appear on my phone under his contact name? Thank you in advance for the help.

python – I wrote this code, and I’m struggling to remove readlines, open, and the print statement in my code

I wrote this code, and I’m struggling to remove readlines, open, and the print statement in my code since it says in the homework that we are not allowed to use these statements in the functions file code.

Any help is highly appreciated, I struggling to fix it coz

functions.py file:

def median(file_handle):
    """
    -------------------------------------------------------
    Extracts numbers from a file and calculates their median value.
    Use: median = locate_median(file_handle)
    -------------------------------------------------------
    Parameters:
        file_handle - a file already open for reading (file handle)
    Returns:
        m - median of the values in file_handle (float)
    -------------------------------------------------------
    """
    infile = open(file_handle, "r")
    numbers = ()
    for line in infile.readlines():
        line = line.rstrip()
        words = line.split(",")
        for word in words:
            numbers.append(int(word))

    numbers.sort()
    print(numbers)
    mid = len(numbers) // 2
    if len(numbers) % 2 == 0:
        m = (numbers(mid - 1) + numbers(mid)) / 2
    else:
        m = numbers(mid)
    return m

t02.py file:

from functions import median


file_name = input("Enter file name: ")

median = median(file_name)
print("Median is:", median)

outfile = open("out_t02.txt", "w")
outfile.write("Median is: ")
outfile.write(str(median))

print("Data written into out_t02.txt")
outfile.close()

The numbers.txt file that we have to work with:

10,20,30
40,50,60
90,80,70
11,22,13 
14,14,20

The code’s goal is:

Write a function median that takes a file handle as an parameter and find the median of a
group of scores.

Requirements:

  • Read the group of scores from a file (that contains numbers only, each line has 3
    numbers), and put the scores into a list of numbers.
  • Your function must sort the elements in order. You can use the build-in sort method
  • Find and return the median from the sorted list of scores. Here a median is the middle
  • element of a sorted list if the number of elements is odd, and the average of the two
    middle elements if the number of elements is even.
  • for a list (40,20,50,10,30), the median is 30 as it is the middle element (odd number of
    elements in the sorted list)
  • for a list (40,60,30,10,50,20), the median is 35 as it the average of 30 and 40 (two
    middle items in an even number of elements in the sorted list)

Save the function in a PyDev library module named functions.py .

A sample run for the function:

median(file_handle) returns 35.

Write a testing program named t02.py that tests the median function and write/print the
results to the output file out_t02.txt

• Your function should ask the user for the input file name they would like to open.

• Test your program with the sample file provided numbers.txt.

c – I wrote this code for the function lock pairs in tideman, but i doesnt work! am i on the right paths?

void lock_pairs(void)
{
    // TODO
    int k = 0;
    for(int n = 0; n < pair_count; n++)
    {
        if(!cycle(n, k))
        {
            locked(pairs(n).winner)(pairs(n).loser) = true;
            break;
        }
    }
    return;
}

bool cycle(int i, int j )
{
    //checking if a loser in other locked pairs is a winner in pair w're looking to lock or not
    if (pairs(j).loser ==  pairs(i).winner )
    {
        return true;
    }
    else
    {
        for (j = 0; j < pair_count; j++)
        {
            if ((locked(pairs(i).winner)(pairs(i).loser) == true) && (pairs(i).loser == pairs(j).winner))
            {
                int h = j;
                {
                    cycle(h, j);
                }
            }
        }
    }
    return false;
}

dnd 5e – Is there a spell, ability or magic item that will let a PC identify who wrote a letter?

In my campaign my players are working for a secretive organisation, and gets their orders through a magical scroll that lets them send messages back and forth. There are two copies of the scroll, and a copy will display whatever is written in the other.

They now suspect that someone is impersonating their contact, and want to try to locate either the other copy of the scroll, or somehow identify the person writing in the scroll.

Is there a spell, ability, or magic item that will let a PC do this?

So far I’ve identified Legend Lore, which could probably get them some information on the organisation they’re working for, and Scrying, which (depending on how you rule) could let them target the sender. There is also the Retriever, even if it feels a little extreme.

(I could just homebrew something, but it is interesting for me to know if such a thing already exists)

python – Multiplication algorithm I wrote – slower than I expected

Recently I thought of an algorithm for multiplication and decided to stop dreaming and start writing on paper my ideas, and even implement this to code (in this case – Python 3.9.1).
I do not know if it resembles Karatsuba’s algorithm, but I glanced at it and it seems to work very differently.


The idea behind this multiplication (calculating $x cdot y$) algorithm is to represent them as a power of two, plus some remainder, then use the distributive rule of multiplication to get:

$$x = 2^a + K \ y = 2^b + T$$

$$ x cdot y = (2^a + K) cdot (2^b + T) = 2^{a+b} + T cdot2^a + K cdot 2^b + K cdot T$$

I chose the power to be $2$ as it would help us with bit-manipulation later on.
Calculating $2^{a+b}$ is easy using bitwise operations as so: $$ 2^{a+b} = 1 << (a+b)$$

But how would we find $a$ and $b$?

We want $2^a$ or $2^b$ to be the largest power of $2$ below our $x$ (or $y$ correspondingly), to take as much ‘volume’ from the original number, and thus making the calculations easier with bit manipulations. So, I just used the $lg$ function, which from what I’ve read it can run in $O(1)$ running-time complexity (Or at worst, $lg lg n$). We have:

$$ a = lfloor lg(x) rfloor, ~~~ b = lfloor lg(y) rfloor$$

We then need to find $K$ which is just the remainder when we subtract $2^a$ from $x$: $$K= x – 2^a = x – (1 << a)$$

However, maybe subtraction isn’t the best idea, maybe it takes too much time, and though about another bit manipulation. All I had to do is to flip the most significant bit (left most bit) which represents the greatest power of $2$ this number consists of, and so I had to pad exactly $a$ $1$‘s and use the $&$ bitwise operation to clear the MSB. We now have a code to find $K$ and $T$ respectively:

$$ K = x~~ &~~ text{int(‘1’ * a, 2)} \ T = y~~ &~~ text{int(‘1’ * b, 2)}$$

Finally, we can add all the factors together, calling the function recursively to compute $K cdot T$ to get:

$$ (1 << (a + b)) + (T << a) + (K << b) + overbrace{text{mult(K,T)}}^{text{recursive call}}$$


def mult(x, y):
    if x == 1:
        return y
    elif y == 1:
        return x
    elif x == 0 or y == 0:
        return 0

    base_x = int(log2(x))
    base_y = int(log2(y))

    K = x & int('1' * base_x, 2)
    T = y & int('1' * base_y, 2)

    return (1 << (base_x + base_y)) + (T << base_x) + (K << base_y) + mult(K, T)

But oh! from what I’ve tested, this algorithm does not seem to get near the time it takes to multiply two numbers by just using the plain-old $text{*}$ operation, Sob!

times = ()
for _ in range(10000):
    x = random.randint(10 ** 900, 10 ** 1000)
    y = random.randint(10 ** 900, 10 ** 1000)
    start = time.time()
    mult(x, y)
    end = time.time()
    times.append(end - start)
print(sum(times)/len(times))

This tests $1,000$ multiplications of $900$ to $1000$ digits long random integers, then printing the average time. On my machine the average is: 0.01391555905342102 seconds. Python’s regular multiplication won’t even show a number, just 0.0 because it is so fast.

From what I know, Python’s algorithm uses Karatsuba’s algorithm, and it is roughly $O(n^{approx 1.58})$ – I did not analyze mine strictly, but in one sense it runs at approximately: $$O(max (text{#Number_of_on_bits_x, #Number_of_on_bits_y}))$$
Because every recursive call, we turn off the $text{MSB}$ – thus the number of recursive calls we make is the maximum number of bits that are on ($=1$) in $x$ and $y$, which is strictly smaller than the numbers themselves.. thus we can surely say it is $O(max (x,y)) sim O(n)$ as all the other operations in the functions are $O(1)$. So it boils down to the question of ‘why?’ – why is it slower? What have I done wrong in my algorithm so it is slower even that from first glance it seems faster?

Thank you!