texts:
I am new to C++, learning from the book primer C++

The exercise:

Write a program to read strings from standard input looking for duplicated
words. The program should find places in the input where one word is followed
immediately by itself. Keep track of the largest number of times a single repetition
occurs and which word is repeated. Print the maximum number of duplicates, or
else print a message saying that no word was repeated.

vector<string> words;
string w, highest_occ_word;
int occ = 1, highest_occ = 0;

while (cin >> w)
    words.push_back(w);

for (auto i = words.begin(); i != words.end(); ++i)
{
    if ((i + 1) != words.end() && *i == *(i + 1))
    {
        ++occ;
        if (highest_occ < occ)
        {
            highest_occ = occ;
            highest_occ_word = *i;
        }
    }
    else
        occ = 1;
}

cout << highest_occ_word << " occured for " << highest_occ << " times \n";

Is this good code? If not, what can I do to improve it?


texts: Optimize Implementation - Wait for all threads using LINQ

texts:
In my program I read several information's about the system. I read each categories like CPU, memory, services, software and so on with a own thread. The main program have to wait for the longest thread.

To implement this, I use LINQ and the Join function from Thread.

Here is a small part from my code:

var culture = CultureInfo.CreateSpecificCulture("en-US");
var thread_list = new List<Thread>();
var c = new Computer();

var thrma = new Thread(() =>
{
    c.Mainboard = new Mainboard().GetInformation();
});
thrma.CurrentUICulture = culture;
thrma.Start();
thread_list.Add(thrma);

var thrce = new Thread(() =>
{
    c.ProcessorList = new CentralProcessingUnit().GetInformation();
});
thrce.CurrentUICulture = culture;
thrce.Start();
thread_list.Add(thrce);

...

var thrsvr = new Thread(() =>
{
    DeviceService.ScanServices();
});
thrsvr.CurrentUICulture = culture;
thrsvr.Start();
thread_list.Add(thrsvr);

foreach (Thread t in thread_list)
{
    t.Join();
}

// Everyone is done!

Each hardware device is derived from the Hardware class.

What do you think about the solution? Is there a "nicer" or better implementation? I would like to use a function, because the code is very similar, but I'm not sure how to do it. Any idea?

Thanks for your advices.


texts: Comparing long lists of strings for the closest match

texts:
What's the fastest (quality is important too, but a little less important) way to compare two strings?

I'm looking for the most efficient way to compare two strings. Some of the strings I'm comparing can be over 5000 characters long. I'm comparing a list of about 80 strings with another list of about 200 strings. It takes forever, even when I'm threading it.

I'm using the StringUtils.getLevenshteinDistance(String s, String t) method from Apache Commons. My method follows. Is there a better way to do this?

private void compareMe() {
  List<String> compareStrings = MainController.getInstance().getCompareStrings();
  for (String compare : compareStrings) {
    int levenshteinDistance = StringUtils.getLevenshteinDistance(me, compare, bestScore); //bestScore begins at 999999999 :)
    if (bestScore > levenshteinDistance
          && levenshteinDistance > -1) {
      bestScore = levenshteinDistance; //global variable
      bestString = compare; //global variable
    }
  }
}

Here's a sample of two strings which should have a good score:

String 1:

SELECT
CORP_VENDOR_NAME as "Corporate Vendor Name",
CORP_VENDOR_REF_ID as "Reference ID",
MERCHANT_ID as "Merchant ID",
VENDOR_CITY as "City",
VENDOR_STATE as "State",
VENDOR_ZIP as "Zip",
VENDOR_COUNTRY as "Country",
REMIT_VENDOR_NAME as "Remit Name",
REMIT_VENDOR_REF_ID as " Remit Reference ID",
VENDOR_PRI_UNSPSC_CODE as "Primary UNSPSC"
FROM DSS_FIN_USER.ACQ_VENDOR_DIM
WHERE VENDOR_REFERENCE_ID in
(SELECT distinct CORP_VENDOR_REF_ID
FROM DSS_FIN_USER.ACQ_VENDOR_DIM
WHERE CORP_VENDOR_REF_ID = '${request.corp_vendor_id};')

String 2:

SELECT
CORP_VENDOR_NAME as "Corporate Vendor Name",
CORP_VENDOR_REF_ID as "Reference ID",
MERCHANT_ID as "Merchant ID",
VENDOR_CITY as "City",
VENDOR_STATE as "State",
VENDOR_ZIP as "Zip",
VENDOR_COUNTRY as "Country",
REMIT_VENDOR_NAME as "Remit Name",
REMIT_VENDOR_REF_ID as " Remit Reference ID",
VENDOR_PRI_UNSPSC_CODE as "Primary UNSPSC"
FROM DSS_FIN_USER.ACQ_VENDOR_DIM
WHERE VENDOR_REFERENCE_ID in
(SELECT distinct CORP_VENDOR_REF_ID
FROM DSS_FIN_USER.ACQ_VENDOR_DIM
WHERE CORP_VENDOR_REF_ID = 'ACQ-169013')

You'll notice the only difference is the '${request.corp_vendor_id};' at the end of the string. This would cause it to have a score of 26.


texts: Iterating thousands of times over large collections: advices

texts:
This is a pet project :)

I have hundreds of playlist files .m3u whose many entries have a wrong path. I'd like to fix them programmatically. Suppose one of my .m3U contains the following entry:

z:\wrong-folder\Michael Jackson - Thriller.mp3

The file is stored in:

G:\my-collection-of-mp3\any-folder\Michael Jackson - Thriller.mp3

The goal is to update the wrong path with the right one :)

I have to create a collection of all my mp3 (around 6000 files) and their path. As I said, I have hundreds of .mu3 ; each .m3u has 15-20 entries. I have to check each entry against my 6000-entries-collection until the name matches. Well it is a plethora of loops :)

To ease the process I would create an ordered dictionary of dictionary whose the key would be the first letter of the name i.e. "M" (for Michael Jackson - Thriller.mp3) and the sub dictionary would be:

- key: Michael Jackson - Thriller.mp3
- value: G:\my-collection-of-mp3\any-folder\Michael Jackson - Thriller.mp3

Doing so I would only to iterate over a subset of the collection (looking up for the first letter of the name) instead of iterating over the whole non ordered collection.

A / Albert Jones - Song 1.mp3 -> G:\my-collection-of-mp3\any-folder\Albert Jones - Song 1.mp3

M / Madonna - Song 1.mp3 -> D:\somewhere-else\Madonna - Song 1.mp3
M / Michael Jackson - Thriller -> G:\my-collection-of-mp3\any-folder\Michael Jackson - Thriller.mp3

Do you think it is ok? What else would you recommend?


texts: Factory for arbitrarily high-order operations

texts:
Grade 0: ++

This is so low that it is boring; the operation of grade 0 is incrementing or counting up, for example:

5++ -> 6
8++ -> 9

Grade 1: +

Addition is repeated incrementing:

4 + 3 -> 4++ ++ ++ -> 7
2 + 2 -> 2++ ++ -> 4

Grade 2: *

Multiplication is repeated addition:

3 * 4 -> 3 + 3 + 3 + 3 -> 12
5 * 2 -> 5 + 5 -> 10

...

I may go on but you understand that each operation of grade n + 1 is just a repetition of the operation of grade n, and that something like:

operation_of_order_100(4, 3)

is going to be unimaginably big, so big that it would be impossible to write it as a tower of exponents (exponentiation is a mere grade 3).

Even if computing an operation of order bigger than 5 is pratically impossible, I have gone through the mental exercise of writing a programme that raises the level of a given function and generates functions of a given grade, and I ask you for suggestions:

def increase_order(op):
    def increased(a, b):
        start_a = a
        for _ in range(b-1):
            a = op(a,start_a)
            #print(a)
        return a
    return increased

def add(a, b):
    return a + b

mul = increase_order(add)

assert mul(3,5) == 15
assert mul(7,3) == 21

exp = increase_order(mul)

assert exp(3,2) == 9
assert exp(7,2) == 49

tetract = increase_order(exp)

assert tetract(7,2) == 823543 # 7**7
assert tetract(4,3) == 4294967296 # 4**4**4

pentation = increase_order(tetract)

# print(pentation(4, 2)) :: Very big already

def op_of_order(order, start=add):
    for _ in range(order-1):
        start = increase_order(start)
    return start

BEAST_OPERATION = op_of_order(10**5)
# BEAST_OPERATION(2, 3) :: unimaginably big


texts:
This method is taken from Syntactic Aspartame. This is my attempt at a generic version.

The goal is to create an operator X <NAME> Y where name is anything, and X, Y, and the return is of any type.

Here is the 'library':

#ifndef COMPUTERSCIENCE_ANGULAR_OPERATOR_H
#define COMPUTERSCIENCE_ANGULAR_OPERATOR_H

template <typename LHS, typename RHS, typename RET> struct AngularOperator;

template <typename LHS, typename RHS, typename RET>
struct InnerAngularOperator {
    const AngularOperator<LHS, RHS, RET>* outer;
    LHS* lhs;
    bool outer_l;

    RET operator>(RHS& rhs) {
        return (outer_l) ? outer->angular_lr(*lhs, rhs) : outer->angular_rr(*lhs, rhs);
    }

    RET operator<(RHS& rhs) {
        return (outer_l) ? outer->angular_ll(*lhs, rhs) : outer->angular_rl(*lhs, rhs);
    }
};

template <typename LHS, typename RHS, typename RET>
struct AngularOperator {
    explicit AngularOperator() { }

    virtual RET operator()(LHS& lhs, RHS& rhs) const = 0;
    virtual RET angular_lr(LHS& lhs, RHS& rhs) const { return operator()(lhs, rhs); }
    virtual RET angular_rr(LHS& lhs, RHS& rhs) const { return operator()(lhs, rhs); }
    virtual RET angular_ll(LHS& lhs, RHS& rhs) const { return operator()(lhs, rhs); }
    virtual RET angular_rl(LHS& lhs, RHS& rhs) const { return operator()(lhs, rhs); }
};

template <typename LHS, typename RHS, typename RET>
InnerAngularOperator<LHS, RHS, RET> operator<(LHS& lhs, const AngularOperator<LHS, RHS, RET>& outer) {
    return {&outer, &lhs, true};
};

template <typename LHS, typename RHS, typename RET>
InnerAngularOperator<LHS, RHS, RET> operator>(LHS& lhs, const AngularOperator<LHS, RHS, RET>& outer) {
    return {&outer, &lhs, false};
};

#endif //COMPUTERSCIENCE_ANGULAR_OPERATOR_H

And here is a simple implementation for string concatenation:

static const struct OP__ANG__STRING_CONCAT : AngularOperator<std::string, std::string, std::string> {
    std::string operator()(std::string& lhs, std::string& rhs) const override { return lhs + rhs; }
} C{};

And finally the usage of all of this would be:

std::string a = "123", b = "456";
std::string c = a <C> b;
// c == "123456


texts:
I'm posting my code for a LeetCode problem. If you'd like to review, please do so. Thank you for your time!
Problem

For an integer n, we call k>=2 a good base of n, if all digits of n
base k are 1.
Now given a string representing n, you should return the smallest good
base of n in string format.
Example 1:

Input: "13"
Output: "3"
Explanation: 13 base 3 is 111.

Example 2:

Input: "4681"
Output: "8"
Explanation: 4681 base 8 is 11111.

Example 3:

Input: "1000000000000000000"
Output: "999999999999999999"
Explanation: 1000000000000000000 base 999999999999999999 is 11.

Note:

The range of n is [3, 10^18].
The string representing n is always valid and will not have leading zeros.

Inputs
"1000000000000000000"
"999999999999999999"
"141038407950127511"
"836507047502348570"
"123489798271512411"
"995437985793784539"
"4681"
"4800"
"48000"
"480000"
"5120000"
"51200000"

Outputs

"999999999999999999"
"999999999999999998"
"141038407950127510"
"836507047502348569"
"123489798271512410"
"995437985793784538"
"8"
"4799"
"47999"
"479999"
"5119999"
"51199999"

Code
#include <cstdint>
#include <string>
#include <algorithm>

struct Solution {
    std::string smallestGoodBase(const std::string n) {
        std::uint_fast64_t num = (std::uint_fast64_t) std::stoull(n);
        std::uint_fast64_t x = 1;

        for (int bit = 62; bit > 0; --bit) {
            if ((x << bit) < num) {
                std::uint_fast64_t curr = binarySearch(num, bit);

                if (curr) {
                    return std::to_string(curr);
                }
            }
        }

        return std::to_string(num - 1);
    }

private:

    static std::uint_fast64_t binarySearch(
        const std::uint_fast64_t num,
        const
        std::uint_fast8_t bit
    ) {
        const long double dnum = (long double) num;
        std::uint_fast64_t lo = 1;
        std::uint_fast64_t hi = (std::uint_fast64_t) (std::pow(dnum, 1.0 / bit) + 1);

        while (lo < hi) {
            std::uint_fast64_t mid = lo + ((hi - lo) >> 1);
            std::uint_fast64_t sum = 1;
            std::uint_fast64_t curr = 1;

            for (std::uint_fast8_t iter = 1; iter <= bit; ++iter) {
                curr *= mid;
                sum += curr;
            }

            if (sum == num) {
                return mid;

            } else if (sum > num) {
                hi = mid;

            } else {
                lo = mid + 1;
            }
        }

        return 0;
    }
};

References

Problem

Discuss

Solution


texts: Generator for the collatz conjecture sequence

texts:
I tried to write this code as concisely as possible. Is this the best way to do it?

def collatz(n):
    """
    Generator for collatz sequence beginning with n

    >>> list(collatz(10))
    [5, 16, 8, 4, 2, 1]
    """
    while n != 1:
        n = n / 2 if n % 2 == 0 else 3*n + 1
        yield int(n)


texts: Computing the cost for creating a perfect square (with N = 3)

texts:
You are given a square matrix \$A \in \mathbb{ N}^{n,n}\$, this number contains integers from \$1\$ to \$n^2\$.  The task is to compute the minimal cost, to change this square into a perfect square. A perfect square is a Matrix, such that every row, column and (full) diagonal add up to a magic number. The Matrix is limited by containing each number from \$1\$ to \$n^2\$
exactly once.

E.g.:

$$M = \begin{bmatrix}4\,\, 9\,\, 2 \\ 3 \,\,5\,\,7 \\ 8 \,\,1\,\,6\end{bmatrix}$$

\$M\$ is a perfect square.

To change \$A\$ into a perfect square, you are allowed to change every number freely. However this increases the cost by \$c_{n+1} = c_{n} + |m_{i,j} - a|\$, where \$a\$ is the new number.

It turns out, by the way, that the magic number is always:

$$m = \frac{n\cdot (n^2+1)}{2}$$

Example of computing the cost:

$$f(\begin{bmatrix}3\,\, 7\,\, 6 \\
9\,\, 5\,\, 1 \\
4\,\, 3\,\, 8\end{bmatrix}) = 1$$ If we change s[1][1] to 2 and s[1][3] to 6, we get a perfect square. The cost is 2-1 = 1;

Compute the minimal cost for n = 3:

This implementation solves the problem, but I have needed to realize that there are only 8 perfect squares for n = 3.

int formingMagicSquare(size_t s_rows, const int** s) {
    long long cost = -1;
    if(s_rows == 3){
        cost = LLONG_MAX;
        const int perfect_squares[8][3][3] = {
                                    {{2,7,6},{9,5,1},{4,3,8}},
                                    {{4,3,8},{9,5,1},{2,7,6}},
                                    {{6,1,8},{7,5,3},{2,9,4}},
                                    {{2,9,4},{7,5,3},{6,1,8}},
                                    {{8,3,4},{1,5,9},{6,7,2}},
                                    {{6,7,2},{1,5,9},{8,3,4}},
                                    {{4,9,2},{3,5,7},{8,1,6}},
                                    {{8,1,6},{3,5,7},{4,9,2}}
                                    };
        for(int k = 0; k < 8; k++){
            long long cost4_this_operation = 0;
            for(int i = 0; i < 3;i++){
                for(int j = 0; j < 3; j++){
                    long long diff = perfect_squares[k][i][j] - s[i][j];
                    cost4_this_operation += ((diff < 0) ? -diff : diff);
                }
            }
            if(cost4_this_operation < cost)cost = cost4_this_operation;
        }
    }
    return cost;
}

I have more questions about this code and I am not sure if I am allowed to ask them here because they ask for better ways to do this.
However, I have specific questions:

How do you return properly if the program cannot solve a certain case?
Can you calculate the absolute amount better than:

long long diff = perfect_squares[k][i][j] - s[i][j];
cost4_this_operation += ((diff < 0) ? -diff : diff);

The for-Looping seems not to be proper. How would you do that?

Thank you.


texts:
I have this view class for constant time rotations of a std::vector:

#include <iostream>
#include <string>
#include <vector>

template<typename T>
class vector_view {

public:
    vector_view(std::vector<T>& vec) : vec{&vec}, offset{0} {}
    const T& operator[](int index) const {
        return (*vec)[(index + offset) % vec->size()];
    }

    T& operator[](int index) {
        return (*vec)[(index + offset) % vec->size()];
    }

    void rotate(int rotation_length) {
        offset = (offset + vec->size() - rotation_length) % vec->size();
    }

    friend std::ostream& operator<<(std::ostream& os, vector_view<T>& view) {
        os << "[";
        std::string separator = "";

        for (int index = 0; index < view.vec->size(); ++index)
        {
            os << separator << view[index];
            separator = ", ";
        }

        return os << "]";
    }

private:
    std::vector<T>* vec;
    int offset;
};

int main() {
    std::vector<char> v{'a', 'b', 'c', 'd', 'e'};
    vector_view<char> view{v};

    for (int i = 0; i < v.size(); ++i) {
        std::cout << view << std::endl;
        view.rotate(1);
    }

    std::cout << std::endl;

    for (int i = 0; i < v.size(); ++i) {
        std::cout << view << std::endl;
        view.rotate(-1);
    }
}

The demo output is:

[a, b, c, d, e]
[e, a, b, c, d]
[d, e, a, b, c]
[c, d, e, a, b]
[b, c, d, e, a]

[a, b, c, d, e]
[b, c, d, e, a]
[c, d, e, a, b]
[d, e, a, b, c]
[e, a, b, c, d]

Since I am still in the process of learning modern C++, please tell me anything I could improve here; such as:

Naming,
coding conventions,
API,
...


texts:
I wrote a function returning the n-th Fibonacci number in Python 3:

# Functions returns the nth Fibonacci number F_n
# Parameters: n >= 0, (Optional: F_0, F_1)
def fibonacci(n, f0=0, f1=1):
    if n == 0:
        return f0

    while n > 1:
        f0, f1 = f1, f0 + f1
        n -= 1

    return f1

Here are a few things I noticed and want to get a review on:

Is the notation clear? The functions returns the n-th Fibonacci number, but n=0 returns the first Fibonacci number (this is a special case)
I'm new to Python and any general style guide is welcome.
Performance: The function isn't intended to be used under incredible performance pressure, but I always try to look what's at the horizon. This implementation should run way faster than an recursive (or even memoized recursive) implementation, but what can be done to improve performance? I tried using the explicit formula including the golden ratio, but accuracy lost in using floating point numbers resulted in wrong return values after some n.


texts: Short script to hash files in a directory

texts:
What improvements could be made to this script and can you explain why you would make those changes?

import hashlib
import os
import time
time = time.strftime("%Y%m%d-%H%M%S")
Masterhash = open("Filehash" + time, "a")
#get a list of files from your directory
for filename in os.listdir('.'):
    #ignore directory names
    if not os.path.isdir(filename):
        #open the file for readying
        primingfiletohash = open(filename, "r")
        #read contents of file
        filetohash = primingfiletohash.read()
        #close the file
        primingfiletohash.close()
        #use hashlib to generate an md5 hash of the file contents
        Filehash = hashlib.md5(filetohash)
        Filehash = Filehash.hexdigest()
        #write file names and hashes to a file
        Masterhash.write(filename + "\t")
        Masterhash.write(Filehash + "\n")
        #close the file
Masterhash.close()


texts:
Could you please advise on the code and its design? Is there any way I can apply object oriented principles to make the design robust yet flexible?

public class RouteFinder{

    /** Used to compute shortest distance from source station to all other station in a given network.
     * @param source source station from which shortest distance will be calculated to the stations
     */
    public void computePaths(Vertex source)
    {
        source.minDistance = 0.;
        PriorityQueue<Vertex> vertexQueue = new PriorityQueue<Vertex>();
        vertexQueue.add(source);
        while (!vertexQueue.isEmpty()) {
            Vertex u = vertexQueue.poll();
            // Visit each edge exiting u
            for (Edge e : u.adjacencies)
            {
                Vertex v = e.target;
                double weight = e.weight;
                double distanceThroughU = u.minDistance + weight;
                if (distanceThroughU < v.minDistance) {
                    vertexQueue.remove(v);
                    v.minDistance = distanceThroughU ;
                    v.previous = u;
                    vertexQueue.add(v);
                }
            }
        }
    }
    /** Used to return the shortest path from a source to destination station.
     * @param target destination station
     * @return shortest path from source station to destination station.
     */
    public static List<Vertex> getShortestPathTo(Vertex target)
    {
        List<Vertex> path = new ArrayList<Vertex>();
        for (Vertex vertex = target; vertex != null; vertex = vertex.previous)
            path.add(vertex);
        Collections.reverse(path);
        return path;
    }
}


texts: Inter Thread communication between n thread

texts:
The following program takes 3 integer inputs(noOfThreadToBeCreate,fromNo,toNo) and print the Consecutive numbers based on the range using different threads e.g (Thread 1 - Print 1, Thread 2 - print 2, and so on ).

I am new to the multi threading and implement this program as per my basic understanding without taking any online help.

One of my senior colleague reviewed this and told its incorrect.

It would be great help if somebody review the code and provide comments, what wrong in this.

    package multithreading.programs;

    public class PrintConsecutiveNumberByThreads {
        int whoseThreadTurnToRun = 1;
        int fromNumber;
        int toNumber;
        int threadSize;

        public PrintConsecutiveNumberByThreads(int threadSize, int fromNumber, int toNumber){
            this.fromNumber = fromNumber;
            this.toNumber = toNumber;
            this.threadSize = threadSize;
        }
        public static void main(String[] args) {
            PrintConsecutiveNumberByThreads obj = new PrintConsecutiveNumberByThreads(4,1,100);
            Runnable task = obj.createRunnableTask();
            obj.createAndExecuteThread(task);

        }

        private void createAndExecuteThread(Runnable task){
            for(int i = 0; i < threadSize; i++){
                new Thread(task,String.valueOf(i+1)).start();
            }
        }

        private Runnable createRunnableTask() {

            Runnable task = () -> {
                synchronized (this) {
                    while (fromNumber <= toNumber) {
                        if (whoseThreadTurnToRun != Integer.parseInt(Thread.currentThread().getName())) {
                            this.notifyAll();
                        } else {
                            System.out.println("Thread "+Thread.currentThread().getName() + " :: " + fromNumber++);
                            whoseThreadTurnToRun = whoseThreadTurnToRun % threadSize + 1;
                            this.notifyAll();
                        }
                        try {
                            this.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
            };
            return task;
        }
    }

   Output :
            Thread 1 :: 1
            Thread 2 :: 2
            Thread 3 :: 3
            Thread 4 :: 4
            Thread 1 :: 5
            Thread 2 :: 6
            Thread 3 :: 7
            Thread 4 :: 8
            Thread 1 :: 9
            Thread 2 :: 10
            Thread 3 :: 11
            Thread 4 :: 12

            So on....


texts: Parsing and formatting var_export() string

texts:
I have this script to format var_export's result string. The information in the output is good, but I need know if the code performance is good or if it can be improved.

https://wtools.io/php-sandbox/biDk

<?php
#Variable:

$Test                            = [];
$Test['Check1']                  = null;
$Test['Check2']                  = [];
$Test['Check2']['int']           = 20;
$Test['Check2']['float']         = 20.35;
$Test['Check2']['string']        = 'Hello World';
$Test['Check2']['bolean']        = true;
$Test['Check2']['array']         = [];
$Test['Check2']['array']['data'] = 'Array Text';
class Example {
    function foo_function() {
        return "Hello World! Object";
    }
}
$var_object                         = new Example;
$Test['Check2']['array']['object']  = $var_object;
$Test['Check2']['array']['object2'] = $var_object->foo_function();

#Script Type:
function myGetType($var) {
    if (is_null($var) OR $var == 'null' OR $var == 'NULL') {
        return "(NULL)";
    }

    if (is_array($var)) {
        return "array";
    }

    if (in_array($var, array("true", "false"), true)) {
        return "boolean";
    }

    if ((int) $var == $var && is_numeric($var)) {
        return "integer" . '(' . strlen($var) . ')';
    }

    if ((float) $var == $var && is_numeric($var)) {
        return "float" . '(' . strlen($var) . ')';
    }

    if (is_object($var)) {
        return "object";
    }

    if (is_resource($var)) {
        return "resource";
    }

    if (is_string($var)) {
        return "string" . '(' . strlen($var) . ')';
    }

    return "unknown";
}

#Script Analisis:
function VarExportFormat($Var) {
    $textvar    = '';
    $textvar    = var_export($Var, true);
    $textvar    = preg_replace("/^([ ]*)(.*)/m", '$1$1$2', $textvar);
    $textvarArr = preg_split("/\r\n|\n|\r/", $textvar);
    # Analisis del tipo.
    foreach ($textvarArr as $key => $value) {
        preg_match('~=>\\s(.*?),~', $value, $newvalue);
        if (!empty($newvalue)) {
            $newvalue[1]      = str_replace("'", "", $newvalue[1]);
            $typeval          = myGetType($newvalue[1]);
            $value            = str_replace("=> ", "=> " . $typeval . ': ', $value);
            $textvarArr[$key] = $value;
        }
    }
    $textvarArr = preg_replace(["/\s*array\s\($/", "/\)(,)?$/", "/\s=>\s$/"], [NULL, ']$1', ' => array ['], $textvarArr);
    $textvar    = join(PHP_EOL, array_filter(["array ["] + $textvarArr));
    if (substr($textvar, -1) == '[') {
        $textvar = str_replace("[", "[]", $textvar);
    }
    $textvar = str_replace("__set_state", "__set_state(object)", $textvar);

    $textvar = highlight_string("<?php \n#output of Variable:\n" . $textvar . ";\n?>", true);
    return $textvar;
}

echo VarExportFormat($Test);


texts:
This is related to a question I posted on Stack Overflow.  The consensus was to use JAXB, which is what I did.

One of the requirements was that it needed to work with legacy XML configuration files. The code needed to be able to start reading new configuration settings from XML files already used to configure pre-existing applications.

In trying to make the code reusable, I added the generic type parameter. However, this causes some yuckiness for the user, as it requires user to pass in the class type.   (It shouldn't be necessary - but due to Java implementation of generics, there's no easy way around that).

I had to throw this together very quickly, so I would welcome any suggestions on improvement (or finding errors). I wasn't very skilled with JAXB, so perhaps there is a better solution I overlooked.

package com.eztech.config;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;

import org.w3c.dom.Document;
import org.w3c.dom.Node;

import com.eztech.xml.XmlUtils;

public class JAXBConfigurator<T> {

    private String filePath;
    private Class<T> clazz;
    public JAXBConfigurator(Class<T> toConfigure, String xmlFilePath) {
        this.clazz = toConfigure;
        this.filePath = xmlFilePath;
    }

    /**
     * Parses Xml and reads configuration from Document element. Using this method
     * assumes that the configuration xml starts at the top of the xml document.
     * @return
     * @throws Exception
     */
    public T createAndConfigure() throws Exception {
        return createAndConfigure(null);
    }

    /**
     * Selects specified element from the parsed Xml document to use as the base
     * for reading the configuration.
     *
     * @param tagName
     * @return
     */
    public T createAndConfigure(String tagName) throws Exception {
        Document doc = XmlUtils.parse(filePath);
        Node startNode;
        if (tagName == null) {
            startNode = doc;
        } else {
            startNode = XmlUtils.findFirstElement(doc, tagName);
        }

        return readConfigFromNode(startNode);
    }

    private T readConfigFromNode(Node startNode) throws JAXBException {
        JAXBContext context = JAXBContext.newInstance(clazz);
        Unmarshaller unmarshaller = context.createUnmarshaller();
        JAXBElement<T> configElement = unmarshaller.unmarshal(startNode, clazz);
        return configElement.getValue();
    }

}

How to use it:

JAXBConfigurator<MyConfig> configurator =
    new JAXBConfigurator<Config>(MyConfig.class, xmlfilePath);
instance = configurator.createAndConfigure("MyXmlStartTag");


texts:
I want to run rolling regressions over each group and store the coefficient. The following works, but it's slow, since I have too many series and I want to run too many regressions for each group.

Using foreach(), speeds things up (and also getting the coefficient with (X'X)^{-1}X'Y but is there a way to vectorize this operation? Also open for any and all improvements.

library(data.table)

run.rolling.regressions <- function(x) {
DT <- data.table(   Y = rnorm(10000),
                    X = rnorm(10000),
                    key.group = rep(LETTERS[1:10], each = 1000))

window.length <- 12
names.of.groups <- unique(DT$key.group)
number.of.groups <- length(names.of.groups)

X.coefficients <- list()

for(j in 1:length(names.of.groups)) {
regressed.DT <- DT[key.group == names.of.groups[j]]
nrows.of.group <- nrow(regressed.DT)
            print(paste0(j, ', key.group: ', names.of.groups[j]))
for (i in window.length:nrows.of.group) {
            if(i == window.length) {
            X.coefficients[[names.of.groups[j]]] <- c(rep(NA, nrows.of.group)) }
            X.coefficients[[names.of.groups[j]]][i] <-  lm(Y ~ 1 + X,
                    data = regressed.DT[(i - 11):i])$coefficients['X']

}
}
return(X.coefficients)
}
system.time(X.coef <- run.rolling.regressions())


texts: Project Euler 22: Names scores using dictionary

texts:
I solved Project Euler 22 using Python 3. The problem reads as follows:

  Using names.txt (right click and 'Save Link/Target As...'), a 46K text
  file containing over five-thousand first names, begin by sorting it
  into alphabetical order. Then working out the alphabetical value for
  each name, multiply this value by its alphabetical position in the
  list to obtain a name score.

  For example, when the list is sorted into alphabetical order, COLIN,
  which is worth 3 + 15 + 12 + 9 + 14 = 53, is the 938th name in the
  list. So, COLIN would obtain a score of 938 × 53 = 49714.

  What is the total of all the name scores in the file?

As you can see, the problem has much to do with handling lists of items and not so much with mathematics, unlike most other Euler problems. I chose to break the list of names, with the index/rank of each name as the key.

Are there ways to improve its performance that you can see? I'm also interested in any other possible improvements in style, naming, PEP8, etc.

'''
Project Euler 22: Names scores
https://projecteuler.net/problem=22
'''
import string
from typing import List, Dict

def get_names_from_file(file_path: str) -> List:
    '''
    Parses a text file containing names in this format:
    "FOO","BAR","BAZ"
    and returns a list of strings, e.g.,
    ["FOO","BAR","BAZ"]
    '''
    with open(file_path, "r") as file_:
        return file_.read().replace("\"", "").split(",")

def get_sorted_indexed_dict(items: List, is_0_indexed: bool = False) -> Dict:
    '''
    Takes a list of strings and returns an alphabetically sorted dict
    with the item's 1-indexed (by default) position as key, e.g.,
    `list` arg: [ "FOO", "BAR", "BAZ" ]
    returns: { 1 : "BAR", 2 : "BAZ", 3 : "FOO" }
    The return dict can be 0-indexed by adding a 2nd argument as True.
    '''
    ix_start = 1
    if is_0_indexed:
        ix_start = 0
    items = sorted(items)
    numbered_dict = {}
    for item in items:
        numbered_dict[items.index(item) + ix_start] = item
    return numbered_dict

def get_alpha_values() -> Dict:
    '''
    Assigns ASCII chars A-Z, inclusive, to a
    number value 1-26, respectively.
    '''
    alpha_values = {}
    index = 1
    letters = list(string.ascii_uppercase)
    for letter in letters:
        alpha_values[letter] = index
        index += 1
    return alpha_values

def get_word_alpha_value(word: str, alpha_values: Dict) -> int:
    '''
    Calculates the value of each letter in the word
    and returns the sum of the letter values.
    '''
    word_value = 0
    for letter in list(word):
        word_value += alpha_values[letter]
    return word_value

def get_word_ranked_value(rank: int, word: str, alpha_values: Dict) -> int:
    '''
    Calculates the ranked value according to problem 22, i.e.,
    the value of each word's letters multiplied by its
    alphabetical rank.
    '''
    return rank * get_word_alpha_value(word, alpha_values)

def get_pe22_solution(file_path: str) -> int:
    '''
    Returns the solution to Project Euler 22 based on the file path provided.
    '''
    alpha_values = get_alpha_values()
    # sanity check some alpha values
    assert alpha_values['A'] == 1
    assert alpha_values['Z'] == 26
    assert alpha_values['S'] == 19

    names = get_names_from_file(file_path)
    names = get_sorted_indexed_dict(names)
    # sanity checks name order based on PE 22 problem description
    assert names[1] == "AARON"
    assert names[938] == "COLIN"
    assert names[5163] == "ZULMA"

    name_values = [
        get_word_ranked_value(k, v, alpha_values)
        for (k, v) in names.items()
    ]
    return sum(name_values)

if __name__ == "__main__":
    FILE = "names.txt"
    print("The answer to PE 22 is: {}".format(get_pe22_solution(FILE)))


texts: Function to class migration: constructor best practice

texts:
I am working on moving some complex script logging from functions to classes. In the functional version I would use a string like this

"{header-[cf][0][:12]}_Started: 11:30:21"

{????}_ is the identifying info, here I have a header item header- (which has formatting implications), it will log to both console and file [cf], have no initial indentation [0], and will pad the following string to provide 12 characters before the : that follows Started [:12], so 5 spaces of padding. I had functions to increment the tab value, change the destination (console, file or both), etc. All driven with complicated RegularExpressions to extract the identifying info from the start of the string.
Now, as I move to classes, I have

Enum PxLogType {
    blankLine
    header
    milieuCondition
}

class Px_LogItem {
    [PxLogType]$type
    [bool]$logToConsole
    [bool]$logToFile
    [int]$indent
    [char]$alignToSymbol
    [int]$alignSymbolLocation
    [string]$string

    # Constructor
    Px_LogItem ([PxLogType]$type, [bool]$logToConsole, [bool]$logToFile, [int]$indent, [string]$string) {
        $this.type = $type
        $this.logToConsole = $logToConsole
        $this.logToFile = $logToFile
        $this.indent = $indent
        $this.string = $string
    }
    Px_LogItem ([PxLogType]$type, [bool]$logToConsole, [bool]$logToFile, [int]$indent, [char]$alignToSymbol, [int]$alignSymbolLocation, [string]$string) {
        $this.type = $type
        $this.logToConsole = $logToConsole
        $this.logToFile = $logToFile
        $this.indent = $indent
        $this.alignToSymbol = $alignToSymbol
        $this.alignSymbolLocation = $alignSymbolLocation
        $this.string = $string
    }
}

Ultimately I will have more enumerations, a method to increase the tab indent, etc. This is working, but

$logItem = [Px_LogItem]::New([PxLogType]::header, $true, $true, 0, ':', 12, "Started: 11:30:21")

is not as readable to my eye. Especially the two instances of $true that replace [cf] to define the target for the log. And depending on where I go, I can see having a few more constructor variations, which starts to get messy. At least, messy in my eyes that are as yet not so familiar with the way constructors are so... specific.

So, I wonder if I am on the right track, and just not familiar enough yet with how class based code looks, or am I off track? I imagine I could do another enum for the log target, with valid values of c, f & cf. Or even have a version that doesn't take those arguments, and defaults both to true to simplify things. That would require method chaining for the constructors, which might actually be a good idea, but how many constructors is considered the threshold for that change? I realize this is all pretty non specific and basically just opinion, but I hope specific enough for some folks to weigh in with their opinions, since I'm too ignorant to have a valid opinion yet.


texts:
As practice, I have written a prime number sieve in Standard ML.

It works in a pretty straightforward way:

The list of known primes starts with just 2.
Starting with 3, check whether each odd integer is relatively prime to all numbers in the list of known primes (i.e. is not divisible by them)

If it's relatively prime, add it to the list of known primes.
If it's not, check the next odd integer.

Repeat step 2 until the list has however many primes we're looking for.
Reverse the list so that the primes are in ascending order.

Here's my code:

fun primes 0 = []
  | primes n =
    let
      fun relativelyPrime x = List.all (fn p => (x mod p <> 0))
      fun buildPrimes ps x =
          if length ps >= n then ps
          else if relativelyPrime x ps then buildPrimes (x::ps) (x + 2)
          else buildPrimes ps (x + 2)
    in
      rev (buildPrimes [2] 3)
    end

I'm still fairly new to Standard ML, so I doubt the above code is optimal or entirely idiomatic. Are there any improvements I could have made if I knew more about the language?

(Note: I realize that negative numbers will return [2]. I could raise an exception, but that's not the point of this question.)


texts:
I have this small function for reading the TSC (time-stamp counter) in *nix. Using it seems to report my CPU frequency more or less correctly.

#include <stdint.h>
#include <stdio.h>
#include <unistd.h>

uint64_t read_time_stamp_counter()
{
    uint32_t my_edx;
    uint32_t my_eax;

    asm ("cpuid\n\t" /* Discourage out-of-order execution. */
         "rdtsc\n\t"
         "movl %%edx, %0\n\t"
         "movl %%eax, %1"
         :"=r"(my_edx), "=r"(my_eax)
         :
         : /* List of registers clobbered by both RDTSC and CPUID. */
           "%eax", "%ebx", "%ecx", "%edx"
         );

    return (((uint64_t) my_edx) << 32) | my_eax;
}

int main(int argc, char** argv) {
    uint64_t tmp;
    uint64_t cycles;
    uint64_t sleep_overhead;

    tmp = read_time_stamp_counter();
    sleep(1);
    cycles = read_time_stamp_counter() - tmp;

    tmp = read_time_stamp_counter();
    sleep(0);
    sleep_overhead = read_time_stamp_counter() - tmp;

    printf("Sleep overhead: %llu cycles.\n", sleep_overhead);

    cycles -= sleep_overhead;

    printf("Cycles: %llu\n", cycles);
    printf("Estimated frequency: %.3f GHz\n", cycles / 1e9);

    return 0;
}

The current implementation does not look good: there should be a better way. Also, is it possible to make it more precise?


texts:
This is a practice problem on Kattis

I have exceeded the time limit for the 5th out of 11 test case. Can anyone inspire me what could be done to optimize the code?

Problem Description

  Quido plans to send a New Year greeting to his friend Hugo. He has
  recently acquired access to an advanced high-precision plotter and he
  is planning to print the greeting card on the plotter.

  Here’s how the plotter operates. In step one, the plotter plots an
  intricate pattern of n dots on the paper. In step two, the picture
  in the greeting emerges when the plotter connects by a straight
  segment each pair of dots that are exactly 2018 length units
  apart.

  The plotter uses a special holographic ink, which has a limited
  supply. Quido wants to know the number of all plotted segments in the
  picture to be sure that there is enough ink to complete the job.

  Input

  The first line of input contains a positive integer n specifying the
  number of plotted points. The following n lines each contain a pair of
  space-separated integer coordinates indicating one plotted point. Each
  coordinate is non-negative and less than 2^31. There are at most
  10^5 points, all of them are distinct.

  In this problem, all coordinates and distances are expressed in
  plotter length units, the length of the unit in the x-direction and in
  the y-direction is the same.

  Output

  The output contains a single integer equal to the number of pairs of
  points which are exactly 2018 length units apart.

Sample input

4
20180000 20180000
20180000 20182018
20182018 20180000
20182018 20182018

Output

4

Here is my code

import java.util.*;

class Coordinates {
    int x;
    int y;

    public Coordinates(int x,int y) {
        this.x=x;
        this.y=y;
    }

    public double distanceWith(Coordinates z) {
        return Math.hypot((x-z.x),(y-z.y));
    }
}

class GreetingCard {
    public static void main(String [] args) {
        Scanner sc = new Scanner(System.in);
        HashSet<Coordinates> set = new HashSet<>();
        int count = sc.nextInt();
        int total = 0;
        for (int i=0;i<count;i++) {
            int x = sc.nextInt();
            int y = sc.nextInt();
            Coordinates curr = new Coordinates(x,y);
            if (i!=0) {
                total+=findDistances(curr, set);
            }
            set.add(curr);
        }
        System.out.println(total);
    }

    public static int findDistances(Coordinates curr, HashSet<Coordinates> set) {
        int total = 0;
        for (Coordinates inside : set) {
            if (inside.distanceWith(curr)==2018) {
                total+=1;
            }
        }
        return total;
    }
}


texts: Tree list recursion from Stanford tutorial

texts:
I have found this appearing-to-be famous problem in Stanford tutorial about trees and decided to solve it.

My solution appears to work great:

 #include <iostream>
    using namespace std;

    struct num {

        int n;
        num* left;
        num* right;
        num* next;
        num* pre;
    };

    num* cr (int data) {

        num* node = new num;
        node->n = data;
        node->left = 0;
        node->right = 0;
        return node;
    }

/* function for tree creation*/
    void treecre (num* & node) {

        node = cr (10);
        node->left = cr (8);
        node->left->left = cr (6);
        node->left->left->left = cr (4);
        node->right = cr (12);
        node->right->right = cr (14);
        node->right->right->right = cr (16);
        node->right->left = cr(11);
        node ->left->right = cr (9);
    }
   // function for transforming the tree into linked list with next and previous // links
// but without linking the first and last element yet
    num* btc (num* node, num*& list) {
        num* temp1 = 0;
        num* max = node;
        if (node == 0) return 0;
        else {
        btc (node->right, list);
        num* temp = new num;
        temp->n = node->n;
        temp ->next = list;
        if (list != 0) list->pre = temp;
        list = temp;
        btc (node->left, list);
        }
        return list;
    }

    void printtree (num* node) {
        if (node != 0) {
            printtree (node->left);
            cout << node->n;
            printtree (node->right);
        }
    }
    // printing the linked list backwards
    void printback (num*& list, int& k) {
        if (k < 15) {
            cout << list->n;
            list = list->pre;
            printback (list, ++k);}
        else {cout << list->n;}
    }
    // and in right direction
    void printlistto (num*& list, int& k) {
        if (k < 12) {
            cout << list->n;
            list = list->next;
            printlistto (list, ++k);
        }
        else {
            cout << list->n; }
    }

    int main () {
        num* node = 0;
        num* list = 0;
        int k = 0;
        treecre (node);
        printtree (node);
        cout << endl;
        list = btc (node, list);
// next lines link the first and last elemets
        num* temp1 = list;
        if (temp1->next!= 0) {
        while (temp1->next != 0) {
            temp1 = temp1->next;
        }}
        temp1->next = list;
        list->pre = temp1;

        printback (list, k);
        cout << endl;
        cin.get ();
        cin.ignore();
    }

But then I take a look at this Stanford solution, which is way longer and uses other tactics.

Could you please tell me if I overlooked something? Does my version have some sufficient drawbacks or if it is fine?


texts: Ruby function to capitalize all words in a string

texts:
The task is to write a function, which capitalize the first letter of all words in a string. For this we'll class a word as any characters separated by a blank. Because the standard String.capitalize method only capitalizes the first character of the string I have written the following.

Could the task be accomplished with writing less code? Any other improvements-suggestions concerning the function?

Here's the code I have written:

def capitalizeAllWords(str)
    caps = str.split(" ").map do |word|
        word.capitalize
    end
    caps.join " "
end

puts capitalizeAllWords "Red orange green blue indigo violet"
# Prints: "Red Orange Green Blue Indigo Violet"


texts: Handling keyboard shortcuts in C# software

texts:
Edit: I have added the revised code in an answer to this question.

Currently, I handle the keyboard shortcuts of my applications in a single huge method that looks like this:

    protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
    {
        // Next issue (validate the fix)
        if (keyData == (Keys.Control | Keys.Enter) ||
            keyData == (Keys.Shift | Keys.Enter))
        {
            mark_as_fixed();
            return true;
        }
        // Skip to next issue without validating or changing anything
        if (keyData == (Keys.Alt | Keys.Down))
        {
            next_issue();
        }
        // Previous issue
        if (keyData == (Keys.Alt | Keys.Up))
        {
            previous_issue();
            return true;
        }
        ... [130 lines of this]

It works perfectly, it isn't particularly hard to read or maintain, but having a method 130 lines long and constantly growing just feels wrong.

Also I may want to implement shortcut customization in the future, and there is no easy way to find out what keys are mapped to which method so it will have to be rewritten.

Since all non trivial applications have a gazillion shortcuts, I assume it's a solved problem, but I couldn't find a good explanation on how applications handle their shortcuts.


texts:
string Format(string format_string, T1 p1, T2 p2, ..., TN pn)

The Format() function takes a copy of format_string and replace occurrences of "___" with the remaining parameters to the function (p1, p2,...).  The first occurrence of "___" will be replaced by p1, the next by p2, and so on.  If there are no occurrences of "___" the remaining parameters will be appended to the string delimited by spaces.  If the parameters are not strings they will be converted to strings with operator<<(ostream,x).  Format will return the modified string.

For example:

Format("The ___ is ___ years", "fox", 8, "old")

evaluates to:

  "The fox is 8 years old"

The implementation follows:

struct FormatEmptyStruct {};

const string FormatPlaceholder("___");

template<class T>
inline FormatEmptyStruct OStreamWriteT(ostringstream& os, const std::string& sFormat, string::size_type& iCurrentPos, const T& t)
{
    auto iNextPos = sFormat.find(FormatPlaceholder, iCurrentPos);

    if (iNextPos == std::string::npos)
    {
        os.write(sFormat.data() + iCurrentPos, sFormat.size() - iCurrentPos);
        iCurrentPos = sFormat.size();

        os << " ";

        os << t;
    }
    else
    {
        os.write(sFormat.data() + iCurrentPos, iNextPos - iCurrentPos);

        os << t;

        iCurrentPos = iNextPos + FormatPlaceholder.size();
    }
    return {};
}

struct EmptyStruct {};

inline string Format() { return ""; }

template <class... Args>
inline string Format(const string& sFormat, const Args&... args)
{
    ostringstream os;
    string::size_type iCurrentPos = 0;

    initializer_list<FormatEmptyStruct>{ OStreamWriteT(os, sFormat, iCurrentPos, args)... };

    if (!sFormat.empty())
        os.write(&sFormat.front() + iCurrentPos, sFormat.size() - iCurrentPos);

    return os.str();
}


texts:
I'm brand new to JavaScript and jQuery and I feel like there's probably a better way to do this. It seems that the way I designed it may not be very optimal once you get a thousand entries in the list but I do like the fact that it's a live search.

Note: I tried changing the style of the <option>'s to display:none but that doesn't work in all browsers.

http://jsfiddle.net/x6cfF/3/

<input type="search" id="SearchBox" />

    <select size=2 class="scrollableinside" id="CustomerSelect">
        <option value=100>test</option>
        <option value=101>test1</option>
        <option value=102>test2</option>
        <option value=103>test3</option>
    </select>

    <select id="CustomerSelectHidden"></select>


texts:
I'm using Mulit-Context CoreData for Asynchronous Saving, which follows this architecture:

Here is code stack:

class DatabaseInterface: NSObject {

static let shared = DatabaseInterface()
private var _mainThreadMOC: NSManagedObjectContext?
private var _masterMOC: NSManagedObjectContext?

func privateManagedObjectContext() -> NSManagedObjectContext {
    let privateMOC = NSManagedObjectContext(concurrencyType: .privateQueueConcurrencyType)
    privateMOC.parent = mainThreadManagedObjectContext()
    privateMOC.undoManager = nil
    return privateMOC
}
func mainThreadManagedObjectContext() -> NSManagedObjectContext {
    if _mainThreadMOC != nil {
        return _mainThreadMOC!
    }
    _mainThreadMOC = NSManagedObjectContext(concurrencyType: .mainQueueConcurrencyType)
    _mainThreadMOC!.parent = masterManagedObjectContext()
    _mainThreadMOC!.undoManager = nil
    return _mainThreadMOC!
}
private func masterManagedObjectContext() -> NSManagedObjectContext {
    if _masterMOC != nil {
        return _masterMOC!
    }
    _masterMOC = NSManagedObjectContext(concurrencyType: .privateQueueConcurrencyType)
    _masterMOC!.persistentStoreCoordinator = //persistant store coordinator
    _masterMOC!.undoManager = nil
    return _masterMOC!
}
}

Whenever I need to perform DB operations, e.g. non-UI related, I use privateMOC as:

let privateMOC = DatabaseInterface.shared.privateManagedObjectContext()
//do some DB operation
privateMOC.saveMOC()

And here is my MOC extension for saving:

extension NSManagedObjectContext {
func saveMOC() {
    //synchronous saving
    if self.saveMOCIfNeeded() {
        guard let parentMOC = self.parent else {
            return;
        }
        parentMOC.perform {
            //asynchronous saving
            if parentMOC.saveMOCIfNeeded() {
                guard let grandParentMOC = parentMOC.parent else {
                    return;
                }
                grandParentMOC.perform {
                    //asynchronous saving
                    grandParentMOC.saveMOCIfNeeded()
                }
            }
        }
    }
}
private func saveMOCIfNeeded() -> Bool {
    if !hasChanges {
        return false;
    }
    do {
        try self.save()
        return true
    }catch {
        print("\(error)")
        return false
    }
}
}

saveMOC() functions takes care of saving all the MOC hierarchy!
It works with mainThreadMOC also as:

let mainThreadMOC = DatabaseInterface.shared.mainThreadManagedObjectContext()
//do some DB operation
mainThreadMOC.saveMOC()

I don't have to worry about which type of MOC I'm working on to save it.
Everything works fine!

My worries are:
1 Is there any scope to improve my code quality?
2 Will it affect performance as each-n-every saveMOC() call is saving changes to mainThreadMOC and 'masterMOC` also?


texts: Evaluating an arithmetic expression from a binary tree

texts:
Let's say I have a Binary Tree that looks like

        +
    2       *
          5   8

I've written a function to traverse inorder to solve it as 2+5*8

Is there a better way? Using eval seems a bit hacky and perhaps I can just have a function calculate the total sum on either side and then do a left + right instead.

class Node {
  constructor(value) {
    this.value = value;
    this.left = null;
    this.right = null;
  }
}

class BinarySearchTree {
  constructor() {
    this.root = null;
  }

  solveEquation() {
    let equation = "";
    let traverse = (currentNode = this.root) => {
      if (currentNode !== null) {
        if (currentNode.left !== null) traverse(currentNode.left);
        equation += currentNode.value;
        if (currentNode.right !== null) traverse(currentNode.right);
      }
    }

    traverse();
    return eval(equation);
  }

  init() {
    this.root = new Node('+');
    let currentNode = this.root;
    currentNode.left = new Node(2);
    currentNode.right = new Node('*');
    currentNode = currentNode.right;
    currentNode.left = new Node(5);
    currentNode.right = new Node(8);
  }
}

let bst = new BinarySearchTree();
bst.init();
console.log(bst.solveEquation());


texts: Swift: extract string with regex and range

texts:
In Swift, I have a string like this

  http://mnc-hdqp.oss-cn-shanghai.aliyuncs.com/user%2Fheat%2Fdefault.jpg?Signature=2BI%2BauSvy&Expires=1568682491&OSSAccessKeyId=LTAIQ8Lif1HHVkXd

Need to extract 2BI%2BauSvy, the value of key Signature

here is code: regex match, then use range to subtract the key ahead.

let key = "Signature"
let signatures = icon.matches(for: "\(key)[^&]+")
guard !signatures.isEmpty else{
     return
}
if let range = signatures[0].range(of: "\(key)="){
      let signature = String(signatures[0][range.upperBound...])
      print(signature)
}

Any way to implement it conveniently?

PS: func matches(for:)

extension String{

    func matches(for regex: String) -> [String] {

        do {
            let regex = try NSRegularExpression(pattern: regex)
            let results = regex.matches(in: self,
                                        range: NSRange(self.startIndex..., in: self))
            return results.map {
                String(self[Range($0.range, in: self)!])
            }
        } catch let error {
            print("invalid regex: \(error.localizedDescription)")
            return []
        }
    }


texts: small web scraper to read product highlight from given urls

texts:
I have written a Python scraping program, using the Scrapy framework. The following code reads a list of urls that need to crawled and gets product highlights from the list. It also follows the next page button.
The resulting products are automatically written to an output file, as I have set FEED_URI in setting.py (which is scrap's setting file), as below:
FEED_URI = 'product_export__%(time)s.xml'
This is the code of my crawler/spider:
import scrapy

# list of wanted organisation is written in: organisation.txt
def get_wanted_organisations():
    org_file = open('config/organisation.txt', 'r')
    return org_file.read().splitlines()

# list of urls to crawl is writtem in url.txt
def get_start_urls():
    org_file = open('config/url.txt', 'r')
    return org_file.read().splitlines()

class ProductSpider(scrapy.Spider):
    name = 'product_spider'

    def __init__(self):
        self.product_highlight_dict = {}
        self.wanted_organisations = get_wanted_organisations() # ignore products listed by any other organisation

    def start_requests(self):
        org_file = open('config/url.txt', 'r')
        start_urls = get_start_urls()
        for url in start_urls:
            yield scrapy.Request(url=url, callback=self.parse)

    def parse(self, response):
        # get a list of product highlights in the page
        product_highlight = response.css('div > article[data-product-id]')

        for product_highlight in product_highlights:
            organisation = product_highlight.css('a[data-company="ListingCompany"]::text').get()

            if organisation and organisation.lower() in self.wanted_organisations:

                # we are interested in the following 4 fields, they will be written to output file, by setting FEED_URI setting of Scrapy framework
                yield {
                    'product_id': product_highlight.css('[data-id="ProductId"] span::text').get(),
                    'title': product_highlight.css('[data-title="ProductTitle"] h1::text').get(),
                    'price': response.css('[data-price="ProductPrice"] span span::text').get(),
                    'organisation': organisation,
                }

        # follow pagination link
        next_page = response.css('a[data-pager="NextPage"]::attr(href)').get()
        if next_page is not None:
            yield response.follow(next_page, self.parse)

I come from .NET background and this is my first Python program. Appreciate any feedback. Not sure if I am following the correct coding convention for naming variables, functions, etc.
Also, the entire program is in one file. Would it be better to move the first two functions into a different file and name the file something like settings_reader?


texts: Print a string of characters with their occurrences

texts:
I have worked out a solution for this problem, however I am trying to reach an O(1) solution without the use of two for loops. The output should read as a3b2c4d1 for the solution below.

i.e. I want to be able to describe which is a "greedy" approach and the tradeoffs of each.

Here is my current solution:

let countLetters = (str) => {
    let arr = str.split(''),
      map = {},
      ret = '';

    for (var i = 0; i < arr.length; i++) {
      map[arr[i]] = str.match(new RegExp(arr[i], 'g')).length
    }

 for (let i in map) {
     ret += `${i + map[i]}`
    }

    return ret;
}

console.log(countLetters('aaabbccccd'));

Can someone explain to me what is the time complexity of the current solution, and possible how to think in better terms of reaching a better time complexity?


texts:
I am reading a text, that from a higher level explained adjacency list implementation of a graph.

I have now tried to implement this as simply as I could. I did not see any reason to have an actual vertex or node class.

Based on my implementation, does it look like I understood properly how an adjacency list graph works?

import java.util.*;

public class Graph {
    private HashMap<String, HashSet<String>> nodes;

    public Graph ()
    {
        nodes = new HashMap<String, HashSet<String>>();
    }

    public void addNode(String name)
    {
        if (!nodes.containsKey(name))
            nodes.put(name ,  new HashSet<String>());
    }

    public void addEdge(String src , String dest)
    {
        HashSet<String> adjList = nodes.get(src);

        if (adjList == null)
            throw new RuntimeException("addEdge - src node does not exist");

        adjList.add(dest);
    }
}


texts: Unpacking tuple from Django's get_or_create function

texts:
Django's get_or_create function returns 2 values: the object and a boolean whether it was freshly created or not. I'm only really interested in the object it returns and this is how I'm doing it.

keywords = [element for (element, _) in [Keyword.objects.get_or_create(keyword=key) for key in keywords]]

But this doesn't look particularly elegant. Is there a better way to do this, possibly avoiding the double loop?


texts: Remove value from linked list if it is equal to a parameter

texts:
Problem: Given a singly linked list of integers l and an integer k, remove all elements from list l that have a value equal to k.

My solution works, but I suspect it's not smart and optimized because I have many extra variables to solve this question.

Node.h:

#ifndef NODE_H_INCLUDED
#define NODE_H_INCLUDED

 template<typename T>
 struct ListNode {
   ListNode(const T &v) : value(v), next(nullptr) {}
   T value;
   ListNode *next;
};

#endif // NODE_H_INCLUDED

main.cpp:

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

void print(ListNode<int> * l){
    while(l != nullptr){
        std::cout << l->value << "\n";
        l = l->next;
    }
}

ListNode<int> * removeKFromList(ListNode<int> * l, int k) {
    if(l == nullptr){
        return nullptr;
    }else{
        if(l->value != k){
            ListNode<int> * L2 = new ListNode<int>(l->value);
            ListNode<int> * current = L2;
            l = l->next;
            while(l != nullptr){
                if(l->value != k){
                    ListNode<int> * L3 = new ListNode<int>(l->value);
                    while(current->next != nullptr){
                        current = current->next;
                    }
                    current->next = L3;
                }
                l = l->next;
            }
            return L2;
        }else{
            return removeKFromList(l->next, k);
        }
    }
}

int main(){
    ListNode<int> * L = new ListNode<int>(5);
    ListNode<int> * L1 = new ListNode<int>(6);
    ListNode<int> * L2 = new ListNode<int>(8);
    L1->next = L2;
    L->next = L1;
    print(removeKFromList(L, 7));
    return 0;
}


texts:
Given an integer, k, we define its odd divisor sum to be the sum of all k's odd divisors. For example, if k = 20, then the odd divisor sum would be 1 + 5 = 6. Similarly, if given an array of values, we can find the odd divisor sum of the array by summing the odd divisor sums for each element in the array.
For example, if array K = [3, 4, 20], the odd divisor sum of the array would be oddDivisorSum(3) + oddDivisorSum(4) + oddDivisorSum(20) = (1 + 3) + (1) + (1 + 5) = 11.

This code works, but it does not pass all the cases due to time. I wanted to see if there was a more efficient way to write this. I heard that memoization could work, but I am not sure show how to implement it.
numbers = [3,21,11,7]

def  count(numbers):
    total = 0
    for k in numbers:
        for i in range(1,k+1,2):
            if k % i == 0:
                total+=i
    return total


texts:
I am learning Python. I have a scenario in my current project to benchmark the following code snippet; by using refactoring to increase the performance. Upon deployment my code will be used on a larger scale.
I'm trying from my side and am also looking for suggestions/guidance from you all. Is there a way to make this code much faster and cleaner with less line of code?
def test(x1, x2):
    if x2 is None:
        return
    elif len(x2) == 1:
        x1.append(x2)
        return
    else:
        for i in range(len(x2)):
            x1.append(x2[i])
    return

l = ['tt', 'yy', 'pp']
test(l, None)
print (l)

test(l, ['hello'])
print(l)

test(l, ['hello', 'world'])
print(l)


texts:
I'm trying to implement LSD radix sort in python, but my code used 4 loop, is there any way I can do it in three or less?

Here is the 4 loops:

First loop iterate through the input list, convert it to desired radix, and change each number to a reversed list, like so:

123 --> 173 --> [3, 7, 1] #radix == 8

Second loop iterate through the newly created list, make them have the same length by adding 0, add a pointer to the corresponding element in input list, then reverse the list.Like this:

input: [1234, 56, 7]
After first loop: [[4, 3, 2, 1], [6, 5], [7]]
After the second loop: [[0, 1, 2, 3, 4], [1, 0, 0, 5, 6], [2, 0, 0, 0, 7]]

Third loop sort element in LSD order using counting sort, code is below.

Fourth loop put every thing in a new list with sorted order using the pointers.

Here's the code for radix sort:

def radix_sort(collection, radix):

    new_collect = []
    max_len = 0

    #loop through collection, convert them to desired form and put in new_collect
    for i in collection:
        num = []
        while i >= radix:
            remain = i % radix
            num.append(remain)
            i = i // radix
        num.append(i)
        new_collect.append(num)

        if len(num) > max_len:
            max_len = len(num)

    #loop through new_collect, extend the each item to same length
    for i in range(0, len(new_collect)):
        space = max_len - len(new_collect[i])
        patch = [0 for j in range(space)]
        new_collect[i].extend(patch)

        #add a pointer to the corresponding element in collection
        new_collect[i].append(i)
        new_collect[i].reverse()

    #sort by digit with counting_sort
    for i in range(-1, -1 - max_len, -1):
        new_collect = counting_sort(new_collect, radix - 1, i)

    #create a new list with same length as collection
    return_list = list(range(len(collection)))

    #put elements in collection to return_list, using the pointer in new_collect
    for i in range(0, len(collection)):
        return_list[i] = collection[new_collect[i][0]]

    return return_list

And here is the code for counting sort:

def counting_sort(collection, d_range, digit = -1):

    d_range += 1

    B = list(range(len(collection) + 1))
    C = list(range(d_range))

    for i in range(d_range):
        C[i] = 0

    for j in collection:
        #C[j] = |{key = j}|
        C[j[digit]] += 1

    for i in range(1, d_range):
        #C[i] = |{key <= i}|
        C[i] = C[i] + C[i - 1]

    for i in range(len(collection) - 1, -1, -1):
        B[C[collection[i][digit]]] = collection[i]
        C[collection[i][digit]] -= 1

    return B[1:]

Reply to Gareth Rees 's answer.

Wow, thank you for the detailed answer!

1.I guess I'm pretty bad at naming and documenting.

2.Never even tought of using |{key < k}| that's pretty neat!

3.The second argument is not the number of keys, at least I don't have the intention to make it so, it should be the range for the input, and I add 1 so that it includes 0. So I guess it's all possible value of keys.
In your improved version of the code, the value of the seq could be greater than the length of the bound, which I think will cause a out of range error.

4.About what you said in 4.1, since my radix_sort function require a radix for sorting, and I use the range of value instead of number of keys, wouldn't it be quicker to just input radix-1 or radix instead of using max()?

5.About what you said in 4.2, in my radix sort function, i need to change the raidx of input to a given value, so I need to use a loop to change it, and since I don't want the letters get involved for radixs greater than 10, I need to separate each digit, that's why I used lists. So unless I'm missing something, I don't think I can use you method in this particular scenario.

6.Do you use timeit to calculate the runtime? Or some other modules?

Thanks again for the answer!

PS: Is there anything you can say about my radix sort function's general logic? Is there anyway I can improve it?


texts:
I want a better way to do the if statements, and if there is a better way to do it. How is it more efficient? Is there something like a switch statement in Java that would help?

import java.util.Scanner;

public class main {

    private static boolean playing = false;
    private static int enemyHealth = 100;
    private static int playerHealth = 100;
    private static double enemyChoice = Math.ceil(Math.random() * 3);
    private static String pName;

    public static void checkHealth(){
        if(enemyHealth <= 0){
            System.out.println("Mother! "+pName+" wins!");
            playing = false;
        }else if(playerHealth <= 0){
            System.out.println(pName+" has fallen! Rocky wins!");
            playing = false;
        }
    }

    public static void main(String[] args) {
        Scanner user_input = new Scanner(System.in);

        String wantPlay;
        // asking the player if they want to play
        System.out.println("Want to play a fighting game?: ");
        wantPlay = user_input.next();

        // if the player chooses to play, it wil lstart the game loop
        if(wantPlay.equals("Yes") || wantPlay.equals("yes")){

            System.out.println("What do you want your name to be?: ");
            pName = user_input.next();

            System.out.println("Hey folks!, were going to have an exiting game today!");
            System.out.println("In the left corner, we have Rocky Balboa!!!!!");
            System.out.println("and in the right corner, we have "+pName+"!!!!!");
            System.out.println("");

            playing = true;
        }

        while(playing == true){

            System.out.println("Rocky has "+enemyHealth+" health remaining.");
            System.out.println("You have "+playerHealth+" health remaining.");

            String action;
            System.out.println("What would you like to do? (a)upper cut (b)side punch (c)down cut: ");
            action = user_input.next();
            // a = 1     b = 2      c = 3
            enemyChoice = Math.ceil(Math.random() * 3);
            checkHealth();

            if(action.equals("a") && enemyChoice == 2){
                checkHealth();
                System.out.println("oohh! and "+pName+" throws a devistating blow into Rocky!");
                enemyHealth-=10;
                checkHealth();

            }else if (action.equals("a") && enemyChoice == 3){
                checkHealth();
                System.out.println("OH! "+pName+" JUST GOT SMASHED!");
                playerHealth -=10;
                checkHealth();
            }else if (action.equals("b") && enemyChoice == 3){
                checkHealth();
                System.out.println("Rocky just got smashed!!!!");
                enemyHealth-=10;
                checkHealth();
            }else if (action.equals("b") && enemyChoice == 1){
                checkHealth();
                System.out.println(pName+" better step up his game!");
                playerHealth-=10;
                checkHealth();
            }else if (action.equals("c") && enemyChoice == 1){
                checkHealth();
                System.out.println("Rockey just got pucnhed so hard that he might not even know he exists!");
                enemyHealth-=10;
                checkHealth();
            }else if (action.equals("c") && enemyChoice == 2){
                checkHealth();
                System.out.println(pName+" Just got smashed!");
                playerHealth -=10;
                checkHealth();
            }else if(action.equals("a") && enemyChoice == 1){
                System.out.println("Their fists collided! this is intense!");
            }else if(action.equals("b") && enemyChoice == 2){
                System.out.println("Their fists collided! this is intense!");
            }else if (action.equals("c") && enemyChoice == 3){
                System.out.println("Their fists collided! this is intense!");

            }

        }

    }

}


texts:
I wrote a recursive sorting algorithm and was wondering what would be the run time complexity of this. The bulk of the work is done in the push_up function, which I think is linear in time. There are a linear amount of recursive calls though. If \$n\$ is the length of the list, would the runtime then be \$O(n^2)\$?

def sort(lst):
    """Recursive sorting algorithm. Sorts the remainder of the list
    and then pushes the first element up to its appropriate position"""

   if lst == []:
       return []
   if len(lst) == 1:
       return [lst[0]]
   elt = lst[0]
   sorted_lst = sort(lst[1:])
   return push_up(elt, sorted_lst)

def insert(val, lst, i):
    """Inserts [val] into [lst] at index [i] """

    return lst[:i] + [val] + lst[i:]

def push_up(val, lst):
    """Pushes [val] up the list until it reaches its sorted position.
    Precondition: lst is sorted"""
    start = 0
    while start < len(lst) and lst[start] < val:
        start += 1

    return insert(val, lst, start)


texts: Convert Extension methods to generic methods

texts:
I was looking at some Linq queries with multiple join statements. I was thinking that they could be cleaned up using extension methods that hide away the join / where statements.

For example:

(from myObject in _context.MyObject
join myObjectGroupName in _context.MyObjectGroupNames on myObject.TaskGroupNameKey equals myObjectGroupName.ReportGroupNameKey
join myObjectResourceType in _context.MyObjectResourceTypes on myObject.ResourceKey equals myObjectResourceType.ResourceKey
where myObjectGroupName.ReportGroupName.Trim().ToUpper().Equals(groupName.Trim().ToUpper()) && fileTypes.Contains(myObjectResourceType.ResourceType)
select myObject.PermissionKey);

Now becomes:

_context.MyObject.JoinWhere(_context.MyObjectGroupNames, groupName)
                 .JoinWhere(_context.MyObjectResourceTypes, fileTypes)
                 .Select(x => x.PermissionKey);

Using:

public static IQueryable<MyObject> JoinWhere(this IQueryable<MyObject> initialObject, IQueryable<MyObjectGroupName> customerReportGroupNames, string groupName)
{
    return (from myObject in initialObject
        join myObjectGroupName in customerReportGroupNames on myObject.TaskGroupNameKey equals myObjectGroupName.ReportGroupNameKey
        where myObjectGroupName.ReportGroupName.Trim().ToUpper().Equals(groupName.Trim().ToUpper())
        select myObject);
}

public static IQueryable<MyObject> JoinWhere(this IQueryable<MyObject> initialObject, IQueryable<MyObjectResourceType> myObjectResourceTypes, IEnumerable<string> types)
{
    return (from myObject in initialObject
        join myObjectResourceType in myObjectResourceTypes on myObject.ResourceKey equals myObjectResourceType.ResourceKey
        where types.Contains(myObjectResourceType.ResourceType)
        select myObject);
}

After more consideration I was wondering if it would be possible to make these methods generic:

public static IQueryable<T> JoinWhere(this IQueryable<T> initialObject, IQueryable<TJoinOn> joinOn, IEnumerable<string> types)
{
    return (from myObject in initialObject
                                               //Here                      //Here
        join myObjectResourceType in joinOn on myObject.ResourceKey equals myObjectResourceType.ResourceKey
                             //Here
        where types.Contains(myObjectResourceType.ResourceType)
        select myObject);
}

Where I have put my comments are specific to specific objects. Could those be used generically or would I have to create an extension method for each dataObject making this WAY more work than it's really worth?


texts: Checking if a bag has enough coins in program

texts:
The objective of the program is to check that the weight of the bag that the user inputs and then calculate how many coins are needed to the added/removed to ensure the bag has the right amount of coins in. It needs to display the difference in weight and the number of coins to be added/removed and a total value of coins added/removed. The weights can be found within the file.

The bags for 1p and 2p add up to £1. The bags for 5p and 10p add up to £5. The bags for 20p and 50p add up to £10. The bags for 100p and 200p add up to £20.

print("Calculation")
print("===========================\n")

one_coin_weight = 3.56
one_bag_amount = 1 / 0.01
one_bag_weight = one_coin_weight * one_bag_amount

two_coin_weight = 7.12
two_bag_amount = 1 / 0.01
two_bag_weight = two_coin_weight * two_bag_amount

five_coin_weight = 3.25
five_bag_amount = 5 / 0.05
five_bag_weight = five_coin_weight * five_bag_amount

ten_coin_weight = 6.50
ten_bag_amount = 5 / 0.10
ten_bag_weight = ten_coin_weight * ten_bag_amount

twenty_coin_weight = 5.00
twenty_bag_amount = 10 / 0.20
twenty_bag_weight = twenty_coin_weight * twenty_bag_amount

fifty_coin_weight = 8.00
fifty_bag_amount = 10 / 0.50
fifty_bag_weight = fifty_coin_weight * fifty_bag_amount

onehundred_coin_weight = 9.50
onehundred_bag_amount = 20 / 1.00
onehundred_bag_weight = onehundred_coin_weight * onehundred_bag_amount

twohundred_coin_weight = 12.00
twohundred_bag_amount = 20 / 2.00
twohundred_bag_weight = twohundred_coin_weight * twohundred_bag_amount

coins_value_added = 0
coins_value_removed = 0

bag_count = int(input("How many bags do you have? "))
print("\n===========================\n")

for x in range(bag_count):
    print("Bag", x + 1, "\n")

    bag_weight = float(input("How much does the bag weigh in grams? "))
    coin_type = int(input("Which type of coin is in the bag in pence? "))

    if coin_type == 1:
        weight_difference = one_bag_weight - bag_weight
        coins_changed = weight_difference / one_coin_weight
    elif coin_type == 2:
        weight_difference = two_bag_weight - bag_weight
        coins_changed = weight_difference / two_coin_weight
    elif coin_type == 5:
        weight_difference = five_bag_weight - bag_weight
        coins_changed = weight_difference / five_coin_weight
    elif coin_type == 10:
        weight_difference = ten_bag_weight - bag_weight
        coins_changed = weight_difference / ten_coin_weight
    elif coin_type == 20:
        weight_difference = twenty_bag_weight - bag_weight
        coins_changed = weight_difference / twenty_coin_weight
    elif coin_type == 50:
        weight_difference = fifty_bag_weight - bag_weight
        coins_changed = weight_difference / fifty_coin_weight
    elif coin_type == 100:
        weight_difference = onehundred_bag_weight - bag_weight
        coins_changed = weight_difference / onehundred_coin_weight
    elif coin_type == 200:
        weight_difference = twohundred_bag_weight - bag_weight
        coins_changed = weight_difference / twohundred_coin_weight

    print("\nThe weight difference is", str(round(weight_difference)) + "g.")

    if coins_changed > 0:
        print("Add", round(coins_changed), "coins to the bag.\n")
        coins_value_added += coin_type
    else:
        print("Remove", round(coins_changed), "coins from the bag.\n")
        coins_value_removed += coin_type

    print("\n===========================\n")

print("There were", bag_count, "bags checked.")
print("There is", coins_value_added, "pence that needs to be added.")
print("There is", coins_value_removed, "pence that needs to be removed.")


texts: Angular service for fetching and passing data with observables

texts:
I have an Angular service consisting of three methods:

This method makes a call to my server to get a URL

private itemUrl = "http://fooserver/api/get/item/details";
getItemDetailsUrl(productId): Observable<any> {
    return this.http
        .get(this.itemUrl, {
            params: { productId: productId }
         })
        .flatMap(res => this.getItemDetails(res.json().itemUrl))
        .map(item => item);
}

This takes that URL from #1 and grabs the XML data returned from the request and passes it to #3

getItemDetails(url): Observable<any> {
    return this.http
        .get(url)
        .flatMap(item => this.parseItemFromUrl(item));
}

The XML passed is then converted to a JSON object using a third party library and then returned:

parseItemFromUrl(xml): any {
    let item;
    xml2js.parseString(xml.text(), function (err, result) {
        item = result.ItemLookupResponse.Items[0].Item[0];
    });
    return Observable.of(item);
}

This code does return the expected JSON object back. But since this is my first time really using Observables, I'd like to know of any improvements or changes I could make and if I used the appropriate array methods in the appropriate places.


texts:
For a big dictionary, the following code gives a time limit error. I was trying to use ES6 constructs in the code. The inputs that gave TLE are here.

I have tried to use BFS for the problem, adding words in the Q only if it has not been visited and it exists in the dictionary.

function getShortestPathBetweenWords(st, end, dict) {
  if (st === end) {
    return 1;
  }
  if (st.length < end.length) {
    return 0;
  }
  let q = [];
  let isVisited = new Map();
  q.push(st);
  let level = 0;
  while (q.length!== 0) {

    level++;
    let size = q.length;
    for (let i = 0; i < size; i++) {
      let newWord = q.shift();
      if (newWord === end) {
        return level;
      }
      let listOfWords = _generateNewWords(newWord, dict);

      for (let i = 0; i < listOfWords.length; i++) {
        if (isVisited.get(listOfWords[i]) !== true) {
          q.push(listOfWords[i]);
          isVisited.set(listOfWords[i], true);
        }
      }

    }

  }
  return 0;
}
/**
 * to generate new words from given Words
 */
function _generateNewWords(word, dict) {
  let len = word.length;
  let listOfWords = [];
  let alphabhets = 'abcdefghijklmnopqrstuvwxyz'.split('');
  for (let i = 0; i < len; i++) {
    for (let j = 0; j < 26; j++) {
      let charArray = word.split('');
      charArray[i] = alphabhets[j];
      if (checkinDictionary(charArray.join(""), dict) === true) {
        listOfWords.push(charArray.join(""));
      }
    }
  }
  return listOfWords;
}
/**
 * checkinDictionary
 */
function checkinDictionary(str, dict) {
  for (let i = 0; i < dict.length; i++) {
    if (dict[i] == str) {

      return true;
    }
  }
  return false;
}


texts:
Is there a better way of writing this? I feel like there's a lot of lines for such a small thing.  Can it be optimized?

$j('#hideShowBtn').toggle(function() {
     $j('.playlist-bar-tray').slideUp();
     $j(this).attr("title","Show Playlist");
     $j(this).children("div").html('Show Playlist');
     $j(this).children("span").html('&#9660;');
 }, function() {
     $j('.playlist-bar-tray').slideDown();
     $j(this).attr("title","Hide Playlist");
     $j(this).children("div").html('Hide Playlist');
     $j(this).children("span").html('&#9650;');
});


texts: Initializing values of a singly linked list with a constructor

texts:
I have to create a constructor that allows a new linked list to be populated with ten consecutive values, starting at 0. Then I need to print the list! So i want to check if the functions I wrote for those are ok.

#include <iostream>
#include <string>
#include <stdexcept>

using namespace std;

template <typename E> class SLinkedList;    // forward declaration to be used when declaring SNode

template <typename E>
class SNode {
private:
    E elem;
    SNode<E> *next;
    friend class SLinkedList<E>;
};

template <typename E>
class SLinkedList {
public:
    SLinkedList();
    SLinkedList(SNode<E>* v);   //What I need help with
    ~SLinkedList();
    bool empty() const;
    E& front();
    void printList(SLinkedList<E> &list); //what i need help with
    void addFront(const E& e);
    void removeFront();
    int size() const;
private:
    SNode<E>* head;
    int     n;                          // number of items
};

template <typename E>
SLinkedList<E>::SLinkedList()           // constructor
    : head(NULL), n(0) { }

template <typename E>
SLinkedList<E>::SLinkedList(SNode<E>* v){ //WHat I  Need Help With
    SNode<E>* v = new SNode<E>;
    for (int i = 0; i < 10; i++)
        v->elem = i;
}

template <typename E>
bool SLinkedList<E>::empty() const
{
    return head == NULL; // can also use return (n == 0);
}

template <typename E>
E& SLinkedList<E>::front()
{
    if (empty()) throw length_error("empty list");
    return head->elem;
}

template <typename E>
SLinkedList<E>::~SLinkedList()
{
    while (!empty()) removeFront();
}

template<typename E>
void SLinkedList<E>::printList(SLinkedList<E> &list) //What I need help with
{
    for (int i = 0; i < list.size(); i++)
    {
        cout << list << " ";
    }
    cout << endl;
}

template <typename E>
void SLinkedList<E>::addFront(const E& e) {
    SNode<E>* v = new SNode<E>;     // create new node
    v->elem = e;                // store data
    v->next = head;             // head now follows v
    head = v;               // v is now the head
    n++;
}

template <typename E>
void SLinkedList<E>::removeFront() {
    if (empty()) throw length_error("empty list");
    SNode<E>* old = head;
    head = old->next;
    delete old;
    n--;
}

template <typename E>
int SLinkedList<E>::size() const {
    return n;
}


texts:
The app: Creates CountDownTimers and displays them in a simple layout. The user can choose how long the timer should be through SharedPreferences and a settings activity. Each timer has a preparation period before it actually starts.

The problem: I'm not sure how, but I feel like the code is messy and needs to be cleaned up. In particular, the CountDownTimer is nested five layers deep:

public void startSession(View v) {
    if (!isTicking) {
        // Runs on play press
        countDownTimer = new CountDownTimer(session.getPrepRemaining() + session.getMindRemaining(), 10) {

            @Override
            public void onTick(long millisUntilFinished) {
                if (millisUntilFinished > session.getMindRemaining()) {
                    // Preparation timer
                    session.setPrepRemaining(millisUntilFinished - session.getMindRemaining());
                    setPrepDigits(millisUntilFinished - session.getMindRemaining());
                } else {
                    // Mindfulness timer
                    prepDigits.setVisibility(View.INVISIBLE);
                    session.setMindRemaining(millisUntilFinished);
                    circularProgressBar.setProgress(((session.getMindLength() - millisUntilFinished) / (float) session.getMindLength()) * 100);
                    setMindDigits(millisUntilFinished);
                }
            }

            @Override
            public void onFinish() {
                session = null;
                isTicking = false;
                circularProgressBar.setProgress(100);
                initializeSession();
            }
        };
        countDownTimer.start();
        isTicking = true;
        startPauseButton.setImageDrawable(getResources().getDrawable(android.R.drawable.ic_media_pause));

        // Alarm
        AlarmReceiver.scheduleAlarm(this);
    } else {
        // Runs on pause press
        countDownTimer.cancel();
        isTicking = false;
        startPauseButton.setImageDrawable(getResources().getDrawable(android.R.drawable.ic_media_play));
    }
}

If you'd like to see the rest of the code, please check out the gist.

It seems like I should have one class managing the counting and another class managing UI, but again, I'm just not sure what steps I should take to make that happen. I also feel like there are several blocks of code that could be pulled out into their own methods, but I feel like they'd be too entwined with, for example, the timer itself.

I've been doing a lot of reading on clean code, and I'm aware of the principles, but I don't know how to put them into practice. So, how can I organize, simplify, and clarify my code?


texts: Loss function in python is a bit cumbersome

texts:
This is my first post here. I seek to improve my way of writing Python and C++ code. I hope I can also contribute to others when I have increased my skill.
Here is a python function I have for a neural network I have implemented. I feel it become a bit cumbersome. The intention is to weight positive labels in channels 1:end higher than background pixels. Hence the distinction between foreground and background.
def loss_function(
        self,
        x: torch.tensor,
        groundtruth: torch.tensor,
        weight: float
) -> torch.tensor:

    delta = 0.00001
    groundtruth_pos = groundtruth[:, 1:, :, :] == 1
    groundtruth_neg = groundtruth[:, 1:, :, :] == 0
    foreground_gt = groundtruth[:, 1:, :, :]
    background_gt = groundtruth[:, 0, :, :]

    foreground_x = x[:, 1:, :, :]
    background_x = x[:, 0, :, :]
    loss_foreground_pos = -(torch.sum(foreground_gt[groundtruth_pos] * torch.log(foreground_x[groundtruth_pos] + delta))
                            + torch.sum((1 - foreground_gt[groundtruth_pos]) * torch.log(1 - foreground_x[groundtruth_pos] + delta)))
    loss_foreground_neg = -(torch.sum(foreground_gt[groundtruth_neg] * torch.log(foreground_x[groundtruth_neg] + delta))
                            + torch.sum((1 - foreground_gt[groundtruth_neg]) * torch.log(1 - foreground_x[groundtruth_neg] + delta)))

    loss_background = -(torch.sum(background_gt * torch.log(background_x + delta))
                        + torch.sum((1 - background_gt) * torch.log(1 - background_x + delta)))
    return weight * loss_foreground_pos + loss_foreground_neg + loss_background


texts:
I don't use Ruby on a regular basis, but I felt inspired to write an extensible, object-oriented version of FizzBuzz to sharpen my skills. I welcome all feedback.

The main class:

class FizzBuzzer
  def initialize(*tests)
    @tests = tests
  end

  def run(values)
    result = []
    values.each do |value|
      str = ''
      @tests.each do |test|
        str << test.word if test.satisfied_by? value
      end
      str = value.to_s if str.empty?
      result << "#{str}\n"
    end
    result.join
  end
end

Sample test operation classes:

class ModuloTester
  attr_accessor :word

  def initialize(modulo, word)
    @modulo = modulo.to_i
    @word = word
  end

  def satisfied_by?(number)
    (number % @modulo).zero?
  end
end

class SquareRootTester
  attr_accessor :word

  def initialize(word)
    @word = word
  end

  def satisfied_by?(number)
    (Math.sqrt(number) % 1).zero?
  end
end

In use:

fizz_buzzer = FizzBuzzer.new ModuloTester.new(3, 'Fizz'), ModuloTester.new(5, 'Buzz')
puts fizz_buzzer.run 1..100

puts

fizz_buzzer = FizzBuzzer.new SquareRootTester.new('(PerfectSquare)')
puts fizz_buzzer.run 1..10
puts fizz_buzzer.run 20..30
puts fizz_buzzer.run 45..55

Which produces the expected output. Is this idiomatic Ruby? Is the naming scheme acceptable? What can be improved?


texts: Python function to match filenames with extension names

texts:
I have written a Python function which matches all files in the current directory with a list of extension names. It is working correctly.

import os, sys, time, re, stat

def matchextname(extnames, filename):
    # Need to build the regular expression from the list
    myregstring = ""
    for index in range(len(extnames)):
        # r1 union r2 and  so on operator is pipe(|)
        # $ is to match from the end
        if index <  len(extnames) - 1:
            myregstring =  myregstring + extnames[index] + '$' + '|'
        else:
            myregstring = myregstring + extnames[index] + '$'
    # getting regexobject
    myregexobj = re.compile(myregstring)
    # Now search
    searchstat = myregexobj.search(filename)
    if searchstat:
        print 'Regex', filename

It is called like this:

if __name__ == '__main__':
    fileextensions = ['\.doc', '\.o', '\.out', '\.c', '\.h']
    try:
        currentdir = os.getcwd()
    except OSError:
        print 'Error occured while getting current directory'
        sys.exit(1)
    for myfiles in os.listdir(currentdir):
        matchextname(fileextensions, myfiles)

Could you please review the code and suggest if there is any better way of doing this, or share any other comments related to errors/exception handling which are missing - or anything else in terms of logic?


texts: Validate optional input parameters with if(!empty)

texts:
I have a function which accepts four parameters, which are all optional. Once they're received, it validates using if(!empty).

$subject = (empty($params['subject'])) ? '' : addslashes(trim(strip_tags($params['subject'])));
$message = (empty($params['message'])) ? '' : addslashes(htmlentities($params['message']));
$userIdArray = (!empty($params['users']) && is_array($params['users'])) ? array_map('intval', $params['users']) : array();
$messageId = (empty($params['id'])) ? null : intval($params['id']);

$validMessage = true;

$valHelper = new validation();

if(!empty($message)){
    $validMessage = ($valHelper->validateMessageTextLength($message)) ? true : false;
}

if(!empty($subject) && $validMessage){
    $validMessage = ($valHelper->validateMessageSubjectTextLength($subject)) ? true : false;
}

if($messageId && $validMessage){
    $validMessage = ($valHelper->validateMessageId($messageId)) ? true : false;
}

if ($validMessage) {

    // go to save method
    $messageDbHelper = new Message_MessageDbHelper();
    $messageDbHelper->saveMessage($subject, $message)
}  else {
    // show a common error message
}

As you can see, I'm giving a common error message and in a scenario where $message fails in validation then the rest of the if(!empty) statements become an extra overhead.

I need this code to be more optimized. Or is there a better way to do this?

EDIT-

save method is something similar to below

public function saveMessage($subject='', $message=''){
            try {
                $query = 'INSERT INTO message(subject, message) VALUES ("'.$subject.'", "'.$message.'")';
                return $this->dbAdapter->query($query)->rowCount();
            } catch (Exception $ex) {
                throw $ex;
            }
}


texts: Tic Tac Toe Program: Are there any ways to make this code more readable?

texts:
This is my second Python program, and I wonder if this code is readable to most people or if it
only applies to me. Should I make more distinct functions or use more appropriate names? Are there
other ways that lessen the lines of codes and do lesser lines mean more readability?

Any suggestions would genuinely be appreciated. Thanks!

   # -*- coding: utf-8 -*-
"""
Tic-Tac-Toe
Started on: 17/04/2020
Finished on: 20/04/2020
Use the numpad to mark your position
7 8 9
4 5 6
1 2 3
"""

board = [' ',' ',' ',' ',' ',' ',' ',' ',' ',' ']
symbols = ['X','O']
running = True

def display_board(board):
    """
    Takes the board list as an argument
    and displays it as a Tic-Tac-Toe board
    when the game is running

    """

    display_board.row3 = "{0:^5s}||{1:^5s}||{2:^5s}".format(board[7],board[8],board[9])
    display_board.row2 = "{0:^5s}||{1:^5s}||{2:^5s}".format(board[4],board[5],board[6])
    display_board.row1 = "{0:^5s}||{1:^5s}||{2:^5s}".format(board[1],board[2],board[3])
    spaces = "{0:5s}||{1:5s}||{2:5s}".format('','','')
    display_board.board = [display_board.row3,display_board.row2,display_board.row1]

    for row in display_board.board[:2]:
       print(spaces+'\n'+row+'\n'+spaces)
       print('='*20)
    print(spaces+'\n'+display_board.row1+'\n'+spaces)

def alternate_symbols(symbols):

    temp = symbols[1]
    symbols[1] = symbols[0]
    symbols[0] = temp

    return symbols[1]

def check_win(board,mark):

    running = True
    mark = [mark] * 3

    if ((board[1:4] == mark) or (board[4:7] == mark) or
            (board[7:10] == mark) or (board[1:8:3] == mark) or
            (board[2:9:3] == mark) or (board[3:10:3] == mark) or
            (board[1:10:4] == mark) or (board[3:8:2] == mark)):
        print(mark[0] + ' has won!')
        running = False
    elif board.count(' ') == 1:
        print("It's a draw!")
        running = False

    return running

def start_game():
    """
    Starts the game
    """
    #Resets the board
    for marks in board:
        for index in range(len(board)):
            board[index] = board[index].replace(marks, ' ')

    print('='*24 + "\n Welcome to Tic TAC TOE\n" + '='*24)

    #Resets the symbols
    symbols = ['X','O']

    while True:
        player_input = input("Player 1: Choose X or O: ")
        if player_input.upper() == 'X':
            print("Player 1 will go first")
            break
        elif player_input.upper() == 'O':
            print("Player 2 will go first")
            break
        else:
            print("Invalid input. Try again! ")
            continue
    #Displays empty board
    display_board(board)
    game_is_running(running,symbols)

def game_is_running(running,symbols):
    """
    when the game starts this will run continuously to check
    valid inputs from the user

    """

    while running:
        while True:
            #Check if position is type int
            try:
                position = int(input("Choose your next position: (1-9)\n"))
                break
            except:
                print('Invalid input. Try again!')

        if position in range(1,10) and board[position] == ' ':
            print('\n'*100)
            board[position] = alternate_symbols(symbols)
            display_board(board)
            running = check_win(board, symbols[1])
        else:
            print('Invalid input. Try again!')
            continue

    while not running:

            player_input = input("Play again?(yes or no) ")

            if player_input.lower() == 'yes':
                start_game()
                running = True
            if player_input.lower() == 'no':
                print("Thanks for playing!")
                return
            else:
                continue

start_game()