texts:
I am building a string for a search query and I think I am doing it the wrong way.

So basically I have serveral textfields, dates, integers and so on in one form. On submit I am checking the forms if its empty or not and building the query string.

I am submitting the model and building a kind of "pyramid" by checking if it is null or not, which is ending in a very large if statement (marked emphasis).

public string CreateSearchQuery(SearchViewModel model)
    {
        StringBuilder buildQueryString = new StringBuilder(2048);

        if (model == null)
        {
            //empty model: return newest results
            return buildQueryString.Append("SELECT * FROM newTbl.files").ToString();
        }

        buildQueryString.Append("SELECT * FROM newTbl.files INNER JOIN newTbl.folders ON folders.id = f_folders_id WHERE ");

        if (model.NumberClubs > 0)
        {
            buildQueryString.Append("folders.numberClubs = ");
            buildQueryString.Append(model.NumberClubs);
        }

        if(model.MrDateFrom != null)
        {
             //those if statements will get very large, when I have more then ten fields
            *if (model.NumberClubs > 0)*
            {
                buildQueryString.Append(" AND ");
            }
            buildQueryString.Append("folders.mrDate = '");
            buildQueryString.Append(model.MrDateFrom.Value.ToString("dd/MM/yyyy"));
            buildQueryString.Append("'");
        }

        if (model.Period > 0)
        {
            //those if statements will get very large, when I have more then ten fields
            *if (model.NumberClubs > 0 || model.MrDateFrom != null)*
            {
                buildQueryString.Append(" AND ");
            }
            buildQueryString.Append("folders.period = ");
            buildQueryString.Append(model.Period);
        }

        buildQueryString.Append(" ORDER BY newTbl.period DESC");

        return buildQueryString.ToString();
    }

I don't think that this is the correct way. So I have a model with several values, but to build a query string I have to check if it is empty or not to append the AND? I mean it is working, but it is really complicated (in my opinion).


texts:
I have a program which splits a url into host and path:

int main(int argc, char** argv){
  std::vector<std::string> url = parseUrl(argv[1]);

  memset(&hints, 0, sizeof hints);
  hints.ai_family = AF_UNSPEC;
  hints.ai_socktype = SOCK_STREAM;
  int MAXDATASIZE = 1024;
  std::string request = "GET " +url.at(1) + " HTTP/1.1\r\n\r\n";
  const char* charRequest = request.c_str();
  char buf[MAXDATASIZE];
  if((status = getaddrinfo(url.at(0).c_str(), "80", &hints, &servinfo)) != 0){
    std::cout << "getaddrinfo: " << gai_strerror(status) << "\n";
    return 2;
  } else {
    std::cout << "Server struct created successfully\n";
  }
  if((sock = socket(servinfo->ai_family, servinfo->ai_socktype, servinfo->ai_protocol)) == -1){
    std::cout << "Error creating socket\n";
    return 2;
  } else {
    std::cout << "Successfully created socket\n";
  }
  if(connect(sock, servinfo->ai_addr, servinfo->ai_addrlen) == -1){
    std::cout << "Error connecting to host " << url.at(0) << " at port " << "80" << "\n";
    return 2;
  } else {
      std::cout << "Connected successfully to " << url.at(0) << "at port " << "80" << "\n";
  }
  if((send(sock, charRequest, strlen(charRequest), 0)) == -1){
     std::cout << "Error communicating with website\n";
     return 2;
  } else {
     std::cout << "Sent request successfully to " << url.at(0) << " at port " << "80" << "\n";
  }
  if(recv(sock, buf, MAXDATASIZE, 0) == -1){
     std::cout << "Error recciving data from " << url.at(0) << " at port " << "80" << "\n";
  } else {
    std::cout << "Recieved data successfully from " << url.at(0) << " at port " << "80" << "\n";
  }
  std::ofstream file;
  file.open(argv[2]);
  file << buf;
  file.close();
  close(sock);

  freeaddrinfo(servinfo);
}

 // Returns vector with host as first argument and path as second
  std::vector<std::string> parseUrl(std::string url){
    std::vector<std::string> ret;
    size_t dotPos = url.find('.');
    size_t slashPos = url.find('/', dotPos);
    std::string host = url.substr(0, slashPos);
    std::string path = url.substr(slashPos, url.length());
    ret.push_back(host);
    ret.push_back(path);
    return ret;
  }

Does anyone have suggestions for improvement. Especially about the clunky vector return?


texts:
I am working with very large datasets in a distributed environment. In particular, I am writing some code in Python for analyzing web logs in Spark. Because of the nature of Map-Reduce computing and the size of the logs I am working with, I would like to restrict the amount of data being passed around as much as possible.

For any given analysis, I am likely to only be interested in a few fields out of the several dozen available, some of which are very large. I don't want to store the whole object in memory; I only want a pared-down version containing the fields I'm interested in.

A simple data structure like a list would be possible, but it would be convenient to be able to refer to fields by name rather than keep track of what position they've been placed in the list. A dict would allow this, but with the heavy overhead of storing key names for each log line. This led me to namedtuple.

So here's a simplified example of what I have in mind. I have four main concerns (but any other tips are welcome, as I am quite new to Python):

Is using namedtuple here the best choice? (As opposed to, possibly, another object with only a few fields initialized.)
Is this going to create a new namedtuple type for each line, thus creating a new list of field names each time and defeating the purpose of avoiding dict?
The parsing method makes me long for an auto-increment syntax, so perhaps I'm missing a more pythonic way of doing it
This method does not seem to offer a clean way of including individual values from the properties dictionary

The code:

import ast
from collections import namedtuple
from IPy import IP

class LogRecord:
    def __init__(self, line):
        self.parse(line)

    def parse(self, line):
        fields = line.split('\t')
        i = 0
        self.version = fields[i]

        i += 1
        self.date = fields[i]

        i += 1
        self.time = long(fields[i])

        i += 1
        self.ipAddress = IP(fields[i])

        i += 1
        self.url = fields[i]

        i += 1
        self.userAgentString = fields[i]

        i += 1
        self.properties = ast.literal_eval(fields[i])

        i += 1
        self.customerId = fields[i]

    def select(self, *fields):
        d = { key: getattr(self, key) for key in fields }
        Tuple = namedtuple('Tuple', fields)
        return Tuple(**d)

l = LogRecord("8.53\t2014-12-13\t1420007099253\t127.0.0.1\thttp://www.google.com/abc/123\tMozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/37.0.2062.120 Safari/537.36\t{'x': 11, 'y': 22}\tx97ag89x77d")

print l.select('version', 'url', 'customerId')

When run, it produces the following output:

Tuple(version='8.53', url='http://www.google.com/abc/123', customerId='x97ag89x77d')


texts:
This is the "Pairs with Positive Negative values" problem from geeksforgeeks.org.

  Given an array of distinct integers, print all the pairs having positive value and negative value of a number that exists in the array.

  NOTE: If there is no such pair in the array , print "0".

  Input:
  The first line consists of an integer T i.e number of test cases. The first line of each test case consists of an integer n. The next line of each test case consists of n spaced integers.

  Output:
  Print all the required pairs in the increasing order of their absolute numbers.

Here is my code:

def findPairs(l):
    listLen=len(l)
    nums=set()
    for i in range(listLen):
        if (-1*l[i]) in l[i+1:]:
            nums.add(abs(l[i]))
            continue
    nums=sorted(nums)
    #print (nums)
    pairs=[]
    for num in nums:
        pairs.extend([-1*num,num])

    return pairs

T=int(input())
pair=[]
for i in range(T):
    input()
    pair=findPairs(list(map(int,input().split())))
    if len(pair):
        print(" ".join(str(x) for x in pair))
    else:
        print("0")


texts:
I have a web application where users can uploads image documents.

Now, after a new document is uploaded into the system, it should:

1) Be optimized. (OCR)

2) Perform various rules on the OCR output.

For this, I rely on Events in Laravel.

I have registered below events for my model Document.php:

protected $dispatchesEvents = [
    'created' => DocumentCreated::class, //Once document has been uploaded.
    'updated' => DocumentUpdated::class, //Once OCR has been performed.
];

Now, for each event, I have also defined listeners.

This is my EventServiceProvider.php:

DocumentCreated::class => [
    PerformOCROnDocument::class,
],
DocumentUpdated::class => [
    ParseDocument::class,
],

So when a new document is created, it will:

1) Perform OCR on the document. This class PerformOCROnDocument will do various tasks.
Most importantly, PerformOCROnDocument will ultimately call:

$document->save();

Since I have defined updated on my Document model, once the save() method is called, it will trigger the next event: DocumentUpdated.

2) Now, ParseDocument will run, and do some various tasks as well.

Important:

The ParseDocument cannot run before PerformOCROnDocument has finished.

Now my question is: is this the correct way of doing this and handling events? Ultimately, my events will implement ShouldQueue so everything will be added to a queue and handled async.

Alternative solution

Now, what I could also do was to trigger an event inside PerformOCROnDocument, like this:

$document->save();
event(new OCRFinished($document));

And then in EventSerivceProvider.php, do like this:

OCRFinished::class => [
    ParseDocument::class,
],


texts: How to make my save/load to/from file function more canonical?

texts:
I  started to learn Kotlin and am now looking for common ways to save object to file and then load an object from a file. In my case, I am saving map<String, List<Int>> and have feeling that my approach is not good enough.

fun main(args: Array<String>) {
//    CreateDs.createLabeledList()
    val map = mutableMapOf<String, List<Int>>()
    map.put("first", listOf(1, 2, 3))
    map.put("second", listOf(4, 5, 6))
    val f = File("labels.txt")
    save(f, map)
    System.out.println(map)
    map.clear()
    load(f, map)
    System.out.println(map)

}

fun save(f: File, map: Map<String, List<Int>>) {
    f.printWriter().use { out ->
        map.forEach {
            out.println("${it.key}:${it.value.toString().replace("[", "").replace("]", "").replace(" ", "")}")
        }
    }
}

fun load(f: File, map: MutableMap<String, List<Int>>) {
    f.inputStream().bufferedReader().useLines { lines ->
        lines.forEach {
            val parts = it.split(":")
            map.put(parts[0], parts[1].split(",").map { it.toInt() })
        }
    }
}


texts: Computing average without overflows and with half-decent precision

texts:
At some point I needed to compute the average of a big collection of integers. I knew the size of the collection prior computation, but a naive average computation was prone to integer overflow while repeatedly adding every elements divided by the size was prone to loss of precision. To mitigate overflow and loss of precision (speed wasn't an issue), I came up with the following algorithm:

#include <cstdint>
#include <iterator>
#include <type_traits>

template<typename RandomAccessIterator>
auto average(RandomAccessIterator first, RandomAccessIterator last)
    -> long double
{
    static_assert(std::is_integral<
        typename std::iterator_traits<RandomAccessIterator>::value_type
    >::value, "average only available for built-in integer types");

    auto size = std::distance(first, last);
    if (size == 0) return 0.0L;

    std::intmax_t accumulator = 0;
    long double res = 0.0L;

    while (first != last) {
        std::intmax_t tmp;
        if (__builtin_add_overflow(*first, accumulator, &tmp)) {
            res += static_cast<long double>(accumulator) / static_cast<long double>(size);
            accumulator = *first;
        } else {
            accumulator = tmp;
        }
        ++first;
    }

    res += static_cast<long double>(accumulator) / static_cast<long double>(size);
    return res;
}

Basically, here is what the program does:

It initializes the result and an accumulator with 0.
It accumulates the values from the collection in an std::intmax_t accumulator as long as said accumulator does not overflow.
When the accumulator is on the verge of overflowing, the accumulator is divided by the size of the collection and added to the result. It then takes the value that would have made it overflow. The loop continues.
When then is nothing more to treat in the collection, the current value of the accumulator is divided by the size of the collection and added to the result.

I think that the goal of avoiding overflows is reached: the accumulation is guarded against overflow, and the division of every element to add by the size ensures that the result itself can't overflow either.

Regarding the precision, adding integers in an std::intmax_t as long as possible ensures that no precision is lost before the division. In the best case, a single division will occur. Moreover, the algorithm should divide bit integers most of the time, which may help the precision too. I picked long double to have the best precision guaranteed by the standard too.

Now, there are a few known shortcomings, to name a few:

Returning 0.0L is probably not the best solution when the collection is empty, but I'm not sure that returning NaN would be better either. One way to circumvent that would be not to handle the case, and document it as a precondition.
__builtin_add_overflow is a GCC builtin, not a standard C++ function. Unfortunately, I don't know any standard equivalent to it, and manually checking for overflows is hard to do correctly.

The algorithm obviously uses O(1) extra memory. Now, did I properly manage to correctly avoid overflow while mitigating precision loss? Is there anything else to be said about this code?


texts:
The intention is to implement an xmlHttpRequest in plain vanilla js while considering all possible errors and problem situations without crashing in the browser. Result and faults are to be properly communicated back to the caller.

function get() {
    return new Promise(function(resolve, reject){
        var xmlHttpRequest = new XMLHttpRequest();
        xmlHttpRequest.open("GET", "http://localhost/products", true);
        xmlHttpRequest.onreadystatechange = function() {
            if (xmlHttpRequest.readyState === 4) {
                try {
                    var data = JSON.parse(xmlHttpRequest.response);
                } catch (error) { // in case parser error
                    reject(error);
                    return;
                }
                if(xmlHttpRequest.status === 200) {
                    resolve(data);
                } else {
                    reject(data);
                }
            }
        };
        xmlHttpRequest.addEventListener("error", function(error){
            reject(error);
        });
        xmlHttpRequest.send();
    });
}


texts:
I was working on making a cache in bash and I found this link - But this guy is attempting to generate new bash functions by introspecting their source and generating a new one as a cache. This seems to me, way overkill. Here is my implementation and it works just fine:

cache() {
  local file
  file="/tmp/$(printf "%s" ${@})"
  if [[ -f "${file}" && $(($(date +%s) - $(date -r "$file" +%s))) -le 1800 ]]; then
    cat "${file}"
  else
    ${1} ${@:2} | tee "${file}"
  fi
}

mkurls() {
  local url="${1:?You must supply a URL}"
  local batchSize=${2:-100}
  local repoCount
  repoCount=$(curl -fsnL "$url?pagelen=0&page=1" | jq -re .size)
  local pages=$(((repoCount / batchSize) + 1))

  printf "$url?pagelen=${batchSize}&page=%s\n" $(seq 1 "$pages")
}

bbusers() {
  _users() {
    mkurls https://api.bitbucket.org/2.0/teams/twengg/members/ |
      xargs -n 30 -P 20 curl -fsnL | jq -ser '.[].values[] | "\(.display_name), \(.links.self.href)" ' | sort
  }
  cache _users $@
}

and here are the results:

$ time bbusers &> /dev/null
#output

real    0m5.670s
user    0m0.184s
sys     0m0.099s

$ time bbusers &> /dev/null # seconds later

real    0m0.053s
user    0m0.010s
sys     0m0.017s

As you can see, it's literally 100x faster. If I delete the file behind the cache:

$ rm -fR /tmp/_users

$ time bbusers &> /dev/null

real    0m4.924s
user    0m0.170s
sys     0m0.082s

It goes right back to normal. So, how can this be improved and what am I missing that warrants such a wildly complicated approach as the other guy has?


texts: Comparison of two regression types on the same set of models

texts:
I wrote a relatively simple R script to run a bunch of regressions. To be precise, it is a hurdle negative binomial regression (fancy stuff for count data). To print it out easily to Latex readable format, I store the results in a list.

I run five regressions in a row: one baseline regression, two specifications that add one variable at a time to the baseline, and finally two specifications that add one variable at a time to the four regressions before. The first two and the last two additional variables have the same beginning ("A" and "B" resp.) while the variables of the additional specifications have the same ending ("xyz" and "abc", resp.). To accomplish this, I construct the regression formula in a loop.

I also compare these regression results to the results of an ordinary negative binomial regression using Vuong's test (more fancy stuff on count data) right thereafter.

# Load packages
require(MASS) # for NegBin regression
require(pscl) # for Hurdle NegBin regression

# Load example data
Master <- read.csv("http://www.ats.ucla.edu/stat/data/fish.csv")
Master <- within(Master, {
  nofish <- factor(nofish)
  camper <- factor(camper)
  A_xyz <- persons
  A_abc <- persons*2
  B_xyz <- livebait
  B_abc <- livebait*2
})

# Define variables that are used throughout the script
status <- "without"
var_control <- c("child", "camper")
var_A <- c("A_xyz", "A_abc")
var_B <- c("B_xyz", "B_abc")

estimation_hurdle <- estimation_negbin <- list()

# Define a file to write out the results of Vuong's test
sink(file=paste0("filepath/", status, "/filename.txt"))

# Run baseline regression
writeLines("baseline")
estimation_hurdle$baseline <- hurdle(as.formula(formula_hurdle),
                                     data=Master, dist="negbin", link="probit"
)
estimation_negbin$baseline <- glm.nb(as.formula(formula_hurdle),
                                     data=Master
)
vuong(estimation_hurdle$baseline, estimation_negbin$baseline)

# Run regression for A variables
for (var in var_A) {
  writeLines(paste0("\n\n", var))
  estimation_hurdle[[var]] <- hurdle(as.formula(paste(formula_hurdle, var, sep=" + ")),
                                     data=Master, dist="negbin", link="probit"
  )
  estimation_negbin[[var]] <- glm.nb(as.formula(paste(formula_hurdle, var, sep=" + ")),
                                     data=Master
  )
  vuong(estimation_hurdle[[var]], estimation_negbin[[var]])
}
rm(var)

# Run regression for B and corresponding A variables
for (i in 1:length(var_B)) {
  writeLines(paste0("\n\n", var_B[i]))
  estimation_hurdle[[var_B[i]]] <- hurdle(as.formula(paste(formula_hurdle, var_A[i], var_B[i], sep=" + ")),
                                            data=Master, dist="negbin", link="probit"
  )
  estimation_negbin[[var_B[i]]] <- hurdle(as.formula(paste(formula_hurdle, var_A[i], var_B[i], sep=" + ")),
                                            data=Master
  )
  vuong(estimation_hurdle[[var_B[i]]], estimation_negbin[[var_B[i]]])
}
rm(i)
sink()

# Additional stuff to write out the results which are not much interesting here

Any idea to improve this code and make it easier/understandable?


texts: Minimum number of letters removed, to make a string Peragram

texts:
Here is the link to the problem Peragrams.

  Peragrams: If a word is an anagram of at least one palindrome, we call it a Peragram.

  Problem: Given a string, find the minimum number of letters you have to remove from it, so that the string becomes a Peragram.

    Input #1: abc

    Output #1: 2

    Input #2: abb

    Output #2: 0

My Python code is as follows:

# Checks whether a string is palindrome
def IsPalindrome(str):
    m = int(len(str) / 2)

    str1 = str[:m]
    str2 = str[m:][::-1]

    if(len(str) % 2 != 0):
        str2 = str[m + 1:][::-1]

    if(str1 != str2):
        return False

    return True

##################################################

str = input()               #Read input from console
toBeRemoved = 0

if(IsPalindrome(str)):      #If the string is already a palindrome
    print(0)
    exit(0)

str = ''.join(sorted(str))  #Sort the string

i = 0
isOdd = True

while i < len(str):
    if(i + 1 < len(str) and str[i] == str[i + 1]):          #If two consecutive chars map, skip matched char
        i += 2
        continue

    toBeRemoved += 1                                        #Increment the number of chars to remove

    if(len(str) % 2 != 0 and isOdd and toBeRemoved > 0):   #If the string is odd length, skip first non-duplicate character & skip to next char
        isOdd = False
        toBeRemoved -= 1
        i += 1
        continue

    str = str[:i] + str[i + 1:] #Remove the char at i

    if(IsPalindrome(str)):
        break

print(toBeRemoved)

How can I improve the code to get a better running time?


texts: A Simple Interactive Program that Can Solve A Linear System of Equations

texts:
So I was just reading my algebra-precalculus textbook, and learned that matrices can be used to solve systems of equations. Since the whole process seemed so algorithmic, I wondered if I could implement it as a program. The result is the following:

/*
 *
 * Solve a system of equations in two variables, x and y
 *
 */

#include <iostream>

struct LinearEquation
{
    double xCoefficient;
    double yCoefficient;
    double constantTerm;
};

struct Solution
{
    double x;
    double y;
};

LinearEquation readEquation();
double findDeterminant(const LinearEquation& a, const LinearEquation& b);
Solution solveEquation(const LinearEquation& a, const LinearEquation& b, double determinant);

int main()
{
    std::cout << "Welcome to the linear equation solver! Enter the following inputs for two equations of the form ax + by = c.\n\n";

    LinearEquation one, two;

    std::cout << "Equation #1\n";
    one = readEquation();

    std::cout << "Equation #2\n";
    two = readEquation();

    double det = findDeterminant(one, two);
    if (det != 0)
    {
        Solution solution = solveEquation(one, two, det);
        std::cout << "The solution:\n";
        std::cout << "x = " << solution.x << "\n";
        std::cout << "y = " << solution.y << "\n";
    }
    else
    {
        std::cout << "This linear equation has no unique solutions!\n";
    }
}

LinearEquation readEquation()
{
    LinearEquation result;
    std::cout << "X coefficient: ";
    std::cin >> result.xCoefficient;
    std::cout << "Y coefficient: ";
    std::cin >> result.yCoefficient;
    std::cout << "Constant term: ";
    std::cin >> result.constantTerm;

    return result;
}

double findDeterminant(const LinearEquation& a, const LinearEquation& b)
{
    return a.xCoefficient * b.yCoefficient - a.yCoefficient * b.xCoefficient;
}

Solution solveEquation(const LinearEquation& a, const LinearEquation& b, double determinant)
{
    // Calculating the inverse
    double matrixTL = b.yCoefficient / determinant;
    double matrixTR = -1 * (a.yCoefficient / determinant);
    double matrixBL = -1 * (b.xCoefficient / determinant);
    double matrixBR = a.xCoefficient / determinant;

    Solution result;
    // Matrix multiplication
    result.x = matrixTL * a.constantTerm + matrixTR * b.constantTerm;
    result.y = matrixBL * a.constantTerm + matrixBR * b.constantTerm;

    return result;
}

This program simply goes through each coefficient and constant term and basically applies a "formula" to solve the equation. It works as far, but it could have minor bugs. I am looking for ways this program can be improved in terms of program size or efficiency. Another problem I want to solve is in terms to making this program handle more equations/variables, which would currently require manually adding parts of the matrix.


texts: Find the length of the longest consecutive elements

texts:
The task:

  Given an unsorted array of integers, find the length of the longest
  consecutive elements sequence.

  For example, given [100, 4, 200, 1, 3, 2], the longest consecutive
  element sequence is [1, 2, 3, 4]. Return its length: 4.

  Your algorithm should run in O(n) complexity.

My solution:

const sample = [1, 100, 2, 90, 3, 88, 4, 9, 5];
const compare = prefix => (a,b) => prefix * (a - b);
const ascending = compare(1);

const maxObj = {
  maxResult: 0,
  maxCurrent: 1,
};

const getMax = (max, current) => current > max ? current : max;
const countConsecutive = (maxObj, _, idx, src) => {
  if ((src[idx] + 1) === src[idx + 1]) {
    maxObj.maxResult = ++maxObj.maxCurrent > maxObj.maxResult ?
        maxObj.maxCurrent : maxObj.maxResult;
  }
  return maxObj;
}
const result = sample
  .sort(ascending)
  .reduce(countConsecutive, maxObj);
console.log(result.maxResult);

Can you write the code so it is faster (and still be readable/maintainable)?


texts: Am I interfacing in a secure manner with rijndael?

texts:
I have been working to create an easy-to-use set of methods to encrypt configuration objects for my client application. It will contain username and passwords to databases and similar vaults of data, so it's rather important that I've got the fundamentals correct.

I'm fairly new to this form of encryption, and I certainly haven't done this in  .NET before. So I am curious - is there any given, open caveats in the attached code? I'll greatly appreciate your comments!

Also, please don't mind the comments in the code. This is a late-night side-project for me, and I'll look into sprucing it all up once I've got it all examined.

 public byte[] CalculatePasswordHash(byte[] salt)
 {
     var hash = Encoding.UTF8.GetBytes(Password);
     var hashing = SHA256.Create();
     var iterations = 10000;

     while (iterations > 0)
     {
         // Compute the hash
         hash = hashing.ComputeHash(hash);

         // Apply the salt
         for (int position = 0, cursor = 0; position < hash.Length; position += 1)
         {
             hash[position] ^= salt[cursor];

             cursor += 1;
             if (cursor >= salt.Length)
                 cursor = 0;
         }

         iterations -= 1;
     }

     return hash;
 }

 public byte[] CreateSalt()
 {
     return CreateSalt(SaltLength);
 }

 public byte[] CreateSalt(int size)
 {
     var random = new RNGCryptoServiceProvider();
     var buf = new byte[size];
     random.GetBytes(buf);

     return buf;
 }

 public void Lock(string filePath, byte[] source)
 {
     // Ensure that the path is rooted
     filePath = RootPath(filePath);

     // Generate salt as well as the encryption key
     var salt = CreateSalt();
     var key = CalculatePasswordHash(salt);

     // Initialize the Rijndael encryption tool
     var crypto = Rijndael.Create();
     var iv = CreateSalt(crypto.BlockSize / 8);

     using (var mem = new MemoryStream())
     {

         // Encrypt the source array
         crypto.Key = key;
         crypto.IV = iv;

         var desc = crypto.CreateEncryptor();
         using (var cryptoStream = new CryptoStream(mem, desc, CryptoStreamMode.Write))
         {
             cryptoStream.Write(source, 0, source.Length);
         }

         desc.Dispose();

         // Append the salt and iv to the end of the file
         using (var fs = new FileStream(filePath, FileMode.Create))
         {
             var encrypted = mem.ToArray();
             fs.Write(encrypted, 0, encrypted.Length);
             fs.Write(salt, 0, salt.Length);
             fs.Write(iv, 0, iv.Length);
         }
     }
 }


texts:
I'm just starting in Go.

Please review the below code, and let me know what I can improve in this code.

//BubbleSort takes an []int {7,5,6,9,8} and returns {5,6,7,8,9}
func BubbleSort(arr []int) []int {
    keepRunning := true
    for keepRunning {
        keepRunning = false
        for i := 0; i < len(arr)-1; i++ {
            a := arr[i]
            b := arr[i+1]
            if a > b {
                arr[i], arr[i+1] = b, a
                keepRunning = true
            }
        }
    }
    return arr
}

//edit
In this case, I'm doing return simply cause I want to return a new copy, and not modify the original.

But I recently as well learned about GO's GC tricolor pattern.
Which will discard the variable until there are no connections left.

So I guess I will need to use the original variable and pass it around and let the code modify the original Slice itself.


texts: Check if two types are the same without template instantiations

texts:
Below is my attempt to check if two types are the same without template instantiations.
#include <cstddef>
template<class, class> struct twoTypes;
template<class T> std::size_t isSame(twoTypes<T,T>*);
bool isSame(void*);

template<class T, class U>
using checkIfSame = decltype(isSame(static_cast<twoTypes<T,U>*>(0)));

And to check if they're the same, checkIfSame's size will be compared to std::size_t's size:
static_assert(sizeof(checkIfSame<int,int>) == sizeof(std::size_t)); //They're the same
static_assert(sizeof(checkIfSame<const int,int>) == sizeof(bool)); //Not the same

Are there any cases where my code will give the wrong result? My benchmarks show my version compiling faster than std::is_same, but are there any ways to make it faster?


texts:
I have a Swing application with no real design pattern. I want to start learning to design Swing or any types of application properly. Here is the main JFrame class.

    import java.awt.Component;
    import java.awt.Dimension;
    import javax.swing.JFrame;
    import javax.swing.JTabbedPane;
    import org.text.gui.components.tabs.*;

    public class TextFrame extends JFrame {

        private static final long serialVersionUID = 1289484372051624149L;
        public static final String INBOX = "Inbox";
        public static final String CONTACT = "Contact";
        public static final String SEND = "Send";
        private JTabbedPane pane;

        public TextFrame() {
            initComponents();
            layoutComponents();
            pack();
            setLocationByPlatform(true);
            setVisible(true);
        }

        public Component getTab(String title) {
        return pane.getComponentAt(pane.indexOfTab(title));
    }

    public void setSelectedTab(String title) {
        pane.setSelectedComponent(getTab(title));
    }

    private void initComponents() {
        setTitle("Text");
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        pane = new JTabbedPane();
        pane.setPreferredSize(new Dimension(225, 300));
        pane.addTab(INBOX, new InboxTab(this));
        pane.addTab(CONTACT, new ContactTab(this));
        pane.addTab(SEND, new SendTab());
    }

    private void layoutComponents() {
        add(pane);
    }
}

The tabs are JPanels with some logic in them. Any advice on a design pattern to implement or examples or anything would be greatly appreciated. I hope I included enough information.


texts: Serialize the properties of an entity framework entity to data fields and back

texts:
I am trying to write code to convert properties of an Entity Framework entity to strings and back.

Here is the code so far that converts back from strings to the object properties.

I am stuck trying to figure out how to handle datetime.  I am also wondering if there is a better approach.

private static FormatterConverter formatConverter;
public static FormatterConverter FormatConverter
{
    get
    {
        if (formatConverter == null)
        {
            formatConverter = new FormatterConverter();
        }
        return formatConverter;
    }
}

// ChangeValue is an entity framework entity.
static void DoSetValue(ChangeValue cv , PropertyInfo pi, object obj )
{
    try
    {
        switch (pi.PropertyType.ToString())
        {
            case "System.TimeSpan":
            case "System.Nullable`1[System.TimeSpan]":
                var s = cv.Value;
                if (s == "") s = "0";
                var ticks = Convert.ToInt64(s);
                var ts = new TimeSpan(ticks);
                obj = ts;
                break;
            case "":
            case "System.Nullable`1[System.DateTime]":
                // code needed here
                break;
            case "System.Guid":
                obj = new Guid(cv.Value);
                break;
            default:
                pi.SetValue(obj,  FormatConverter.Convert(cv.Value, pi.PropertyType), null);
                break;
        }
    }
    catch (Exception ex)
    {
        ex.Data.Add("", string.Format( "Error converting type for {0} {1} ",pi.Name ,pi.PropertyType.ToString()));
        throw ex;
    }
}


texts:
I have created this code for both boolean and integer values to display a truth table for an "AND","OR","XOR", "NOT" gate. However I think that my code needs reviewing as it could be simplified.

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

        boolean p,q;

        System.out.println("P\tQ\tAND\tOR\tXOR\tNOT");

        p = false;
        q = false;
        System.out.print(p + "\t" + q + "\t" + (p&&q) + "\t");
        System.out.println((p||q)+"\t"+(p^q)+"\t"+(!p));

        p = false;
        q = true;
        System.out.print(p + "\t" + q + "\t" + (p&&q) + "\t");
        System.out.println((p||q)+"\t"+(p^q)+"\t"+(!p));

        p = true;
        q = false;
        System.out.print(p + "\t" + q + "\t" + (p&&q) + "\t");
        System.out.println((p||q)+"\t"+(p^q)+"\t"+(!p));

        p = true;
        q = true;
        System.out.print(p + "\t" + q + "\t" + (p&&q) + "\t");
        System.out.println((p||q)+"\t"+(p^q)+"\t"+(!p));

        System.out.println();

        withBinary();

    }

    public static void withBinary(){

        System.out.println("A\tB\tAND\tOR\tXOR\tNOT");
        int a = 0;
        int b = 0;
        int and = a&b;
        int or = a|b;
        int xor = a^b;
        int not  = a;

        if(a==0 && b == 0 )
            not = 1;
            System.out.println(a + "\t" + b + "\t" + and + "\t" + or + "\t" + xor + "\t" + (not));

        b=1;
        and = a&b;
        or = a|b;
        xor = a^b;
        not = a;
        if(a==0 && b == 1)
            System.out.println(a + "\t" + b + "\t" + and + "\t" + or + "\t" + xor + "\t" + (not));

        a=1;
        b=0;
        not = b;
        and = a&b;
        or = a|b;
        xor = a^b;
        not = a;
        if(a==1 && b == 0)
            System.out.println(a + "\t" + b + "\t" + and + "\t" + or + "\t" + xor + "\t" + (not));

        a=1;
        b=1;
        not = 0;
        and = a&b;
        or = a|b;
        xor = a^b;
        if(a==1 && b == 1)
            System.out.println(a + "\t" + b + "\t" + and + "\t" + or + "\t" + xor + "\t" + (not));
        }
}


texts: Parse data from Input file and print results

texts:
I have written a script which does parsing to the input file and take out some values from them with respect to the node and print the data accordingly.
Below is my script, and it works as expected:
#!/usr/bin/perl

use strict;
use warnings;

use Time::Local 'timelocal';
use List::Util qw(reduce);
use POSIX qw( strftime );

my $i = 0;

print "*"x20; print "\n";

while(<DATA>){
    chomp;

    next unless ($_);

    my @data = split / /, $_;

    $i++;
    my ($node, $time, $date, $time1, $unit);
    my %hash;
    if (scalar @data == 3){
        if( $data[0] =~ /FileName=([^_]+(?=_))_(\S+)_file.csv:(\S+),/gm ){
            ($node, $time, $unit) = ($2, $1, $3);
            if( $time =~ /[a-zA-Z](\d+).(\d+)/gm ){
                $date = $1; $time1 = $2;
            }
        }
        print "Node_$i:$node\n";
        my $datetime = $date.$time1;
        my ($second,$minute,$hour,$day,$month,$year);
        my $unix_time;

       if ($datetime =~ /(....)(..)(..)(..)(..)/){
            ($second,$minute,$hour,$day,$month,$year) = (0, $5, $4, $3, $2, $1);
            $unix_time = timelocal($second,$minute,$hour,$day,$month-1,$year);
        }
       my @vol = split /,/, $data[2];
       foreach my $element (@vol){
            $hash{$unix_time} = $element;
            $unix_time += 6;
        }

        my $key = reduce { $hash{$a} <= $hash{$b} ? $a : $b } keys %hash;
        my $val = $hash{$key};

        my $dt = strftime("%Y-%m-%d %H:%M:%S", localtime($key));

        print "Text_$i:First occured on $dt on the Unit:$unit and the value is $val\n";
    }
}
print "*"x20; print "\n";
print "TotalCount=$i\n";

__DATA__
Node=01:FileName=A20200804.1815+0530-1816+0530_Network=NODE01_file.csv:Unit=R1,Meter=1 Vol 19,12,17,20,23,15,16,11,13,17
Node=02:FileName=A20200804.1830+0530-1831+0530_Network=NODE02_file.csv:Unit=R5,Meter=3 Vol 12,13,15,16,10,15,15,13,14,11

So, here we have 2 lines of data in input file which is giving output something like below:
********************
Node_1:Network=NODE01
Text_1:First occured on 2020-08-04 18:15:42 on the Unit:Unit=R1 and the value is 11
Node_2:Network=NODE02
Text_2:First occured on 2020-08-04 18:30:24 on the Unit:Unit=R5 and the value is 10
********************
TotalCount=2

So, logic in parser is each line data belongs to each node (node will be unique in the input file). Here you can see the Volume data which is generated based on the time. For example, NODE01 volume data it shows for 18:15 to 18:16 (10 volume values, that means each value is been generated in 6secs interval and its fixed through out all the node volume data).
From the list of volumes I should take the least number and its respective time with seconds. I am able to fetch as per the logic explained.
Here I need experts feedback on regex (which I am using) also there are couple of if conditions which looks really odd to me.
Is there any possiblity to simply the script?


texts:
I have a file of SQL (actually HiveQL) queries terminated by semicolon (;). I need to obtain a list of formatted queries from this file. Formatting includes replacing multiple spaces with single one and removing extra spaces in cases like '( ', ' )', ' ,'. So, the following is my approach and it looks monstrous:

fdHql = open(args.hql, 'r')
hql_file = fdHql.read()
fdHql.close()
queries = [re.sub('\s+', ' ', each.replace('\n', ' ').strip()).replace('( ', '(').replace(' )', ')').replace(' ,', ',') for each in hql_file.split(';')]

Is there a better way to implement same behavior?


texts:
I'm trying to use Python to solve the Project Euler problem regarding the Collatz sequence. With some research online, I have come up with the code below. However, it still takes a long time to find the maximum length of the Collatz sequence of the numbers from one to a million after the following improvements.

Using a list in order to keep track of numbers that are in the Collatz sequence of preceding numbers so that they won't be tested
Not testing any of the numbers in the lower half of interval and not testing any numbers that would make this expression true:

((f%9==2)or(f%9==4)or(f%9==5)or(f%9==8)or(f%8==5))

Any criticism is appreciated.

"""
The following iterative sequence is defined for the set of positive integers:

n → n/2 (n is even)
n → 3n + 1 (n is odd)

Using the rule above and starting with 13, we generate the following sequence:

13 → 40 → 20 → 10 → 5 → 16 → 8 → 4 → 2 → 1
It can be seen that this sequence (starting at 13 and finishing at 1) contains 10 terms. Although it has not been proved yet (Collatz Problem), it is thought that all starting numbers finish at 1.

Which starting number, under one million, produces the longest chain?

NOTE: Once the chain starts the terms are allowed to go above one million.
"""
a=[]
def collatz(n):
    if n%2==0:
        return int(n/2)
    else:
        return int(3*n+1)
def collatz_length(n):
    b=n
    c=0
    while collatz(b)!=1:
        a.append(b)
        b=collatz(b)
        c=c+1
        if collatz(b)==1:
            break
    return c
d=0
e=0
for g in range(500000,1000000,1):
    f=g+2
    if (f in a) == False and ((f%9==2)or(f%9==4)or(f%9==5)or(f%9==8)or(f%8==5)):
        print(len(a))
        print(f)
        if collatz_length(f)>e:
            d=f
            e=collatz_length(f)
print(d)
print(e)


texts: State machine for handling Telnet sequences for an FTP server

texts:
I've asked Code Climate to generate metrics for the ftpd Ruby gem.  It correctly identified the God class; I know what to do about that.  But one of the smaller classes has me stumped.  This is telnet.rb:

# -*- ruby encoding: us-ascii -*-

module Ftpd

  # Handle the limited processing of Telnet sequences required by the
  # FTP RFCs.
  #
  # Telnet option processing is quite complex, but we need do only a
  # simple subset of it, since we can disagree with any request by the
  # client to turn on an option (RFC-1123 4.1.2.12).  Adhering to
  # RFC-1143 ("The Q Method of Implementing TELNET Option Negiation"),
  # and supporting only what's needed to keep all options turned off:
  #
  # * Reply to WILL sequence with DONT sequence
  # * Reply to DO sequence with WONT sequence
  # * Ignore WONT sequence
  # * Ignore DONT sequence
  #
  # We also handle the "interrupt process" and "data mark" sequences,
  # which the client sends before the ABORT command, by ignoring them.
  #
  # All Telnet sequence start with an IAC, followed by at least one
  # character.  Here are the sequences we care about:
  #
  #     SEQUENCE             CODES
  #     -----------------    --------------------
  #     WILL                 IAC WILL option-code
  #     WONT                 IAC WONT option-code
  #     DO                   IAC DO option-code
  #     DONT                 IAC DONT option-code
  #     escaped 255          IAC IAC
  #     interrupt process    IAC IP
  #     data mark            IAC DM
  #
  # Any pathalogical sequence (e.g. IAC + \x01), or any sequence we
  # don't recognize, we pass through.

  class Telnet

    # The command with recognized Telnet sequences removed

    attr_reader :plain

    # Any Telnet sequences to send

    attr_reader :reply

    # Create a new instance with a command that may contain Telnet
    # sequences.
    # @param command [String]

    def initialize(command)
      telnet_state_machine command
    end

    private

    module Codes
      IAC  = 255.chr    # 0xff
      DONT = 254.chr    # 0xfe
      DO   = 253.chr    # 0xfd
      WONT = 252.chr    # 0xfc
      WILL = 251.chr    # 0xfb
      IP   = 244.chr    # 0xf4
      DM   = 242.chr    # 0xf2
    end
    include Codes

    def telnet_state_machine (command)
      @plain = ''
      @reply = ''
      state = :idle
      command.each_char do |c|
        case state
        when :idle
          if c == IAC
            state = :iac
          else
            @plain << c
          end
        when :iac
          case c
          when IAC
            @plain << c
            state = :idle
          when WILL
            state = :will
          when WONT
            state = :wont
          when DO
            state = :do
          when DONT
            state = :dont
          when IP
            state = :idle
          when DM
            state = :idle
          else
            @plain << IAC + c
            state = :idle
          end
        when :will
          @reply << IAC + DONT + c
          state = :idle
        when :wont
          state = :idle
        when :do
          @reply << IAC + WONT + c
          state = :idle
        when :dont
          state = :idle
        else
          raise "Unknown state #{state.inspect}"
        end
      end
    end

  end
end

Code Climate does not like the complexity of #telnet_state_machine.  I agree, but I don't know how to reduce the complexity without also making the state machine harder to follow.  State machines never seem to be all that readable as it is.  What would you suggest?

Note: If you want to try some refactoring, this class has rspec test coverage.  Just do "git clone" of the ftpd project.


texts:
Below is the implementation for the Floyd-Warshall algorithm, which finds all-pairs shortest paths for a given weighted graph.
The function floyd_warshall takes a graph as an input, which is represented by an edge list in the form of [source, destination, weight]
The path_reconstruction function outputs the shortest paths from each vertex that is connected to every other vertex.
Please provide suggestions for improvements of any sort.
import sys

INF = sys.maxsize

def floyd_warshall(graph):
    source_vertices = [column[0] for column in graph]
    destination_vertices = [column[1] for column in graph]
    vertices = list(set(source_vertices) | set(destination_vertices))

    distance = [[INF] * len(vertices) for i in range(len(vertices))]
    next_vertices  = [[0]   * len(vertices) for i in range(len(vertices))]

    for i in range(len(vertices)):
        distance[i][i] = 0
    for source, destination, weight in graph:
        distance[source-1][destination-1] = weight
        next_vertices[source-1][destination-1] = destination-1

    for k in range(len(vertices)):
        for i in range(len(vertices)):
            for j in range(len(vertices)):
                if distance[i][j] > distance[i][k] + distance[k][j]:
                    distance[i][j] = distance[i][k] + distance[k][j]
                    next_vertices[i][j]  = next_vertices[i][k]

    path_reconstruction(distance, next_vertices)

def path_reconstruction(dist, nxt):
    print("Edge \t\t Distance \t Shortest Path")
    for i in range(len(dist)):
        for j in range(len(dist)):
            if i != j:
                path = [i]
                while path[-1] != j:
                    path.append(nxt[path[-1]][j])
                print("(%d, %d) \t\t %2d \t\t %s"
                      % (i + 1, j + 1, dist[i][j], ' - '.join(str(p + 1) for p in path)))
    print()

def main():
    edge_list1 = [
        [1, 3, -2],
        [2, 1, 4],
        [2, 3, 3],
        [3, 4, 2],
        [4, 2, -1]
    ]
    edge_list2 = [
        [1, 2, 10],
        [1, 3, 20],
        [1, 4, 30],
        [2, 6, 7],
        [3, 6, 5],
        [4, 5, 10],
        [5, 1, 2],
        [5, 6, 4],
        [6, 2, 5],
        [6, 3, 7],
        [6, 5, 6]
    ]

    floyd_warshall(edge_list1)
    floyd_warshall(edge_list2)

if __name__ == '__main__':
    main()


texts:
Please review the following code for thread pool in C (I wrote it to implement a threaded web server for my personal project). I have been programming in C++ and Java but never did any serious programming in C.

threadpool.h

#ifndef THREAD_POOL_H
#define THREAD_POOL_H

#include <pthread.h>

#define MAX_THREAD 10

typedef struct {
    void *(*function) (void *);
} runnable_task;

typedef struct safe_queue_node {
    runnable_task *task;
    struct safe_queue_node *next;
} safe_queue_node;

typedef struct safe_queue{
    struct safe_queue_node *head;
    struct safe_queue_node *tail;
    pthread_mutex_t mutex;
} safe_queue;

typedef struct {
    pthread_t threads[MAX_THREAD];
    safe_queue *queue;
    int count;
    volatile int should_close;
} thread_pool;

runnable_task *
new_runnable_task(
        void *(*function) (void *));

thread_pool *
new_thread_pool();

void
free_thread_pool(
        thread_pool *pool);

void
add_task_to_pool(
        thread_pool *pool,
        runnable_task *task);

void
shutdown_thread_pool(
        thread_pool *pool);

#endif

threadpool.c

#include "threadpool.h"
#include <stdlib.h>

runnable_task *
new_runnable_task(
        void *(*function) (void *)) {
    runnable_task *task = malloc(sizeof(runnable_task));
    task->function = function;
    return task;
}

safe_queue_node *
_new_safe_queue_node(
        runnable_task *task) {
    safe_queue_node *node = malloc(sizeof(safe_queue_node));
    node->task = task;
    node->next = NULL;
    return node;
}

safe_queue *
_new_safe_queue() {
    safe_queue *queue = malloc(sizeof(safe_queue));
    pthread_mutex_init(&queue->mutex, NULL);
    queue->head = NULL;
    queue->tail = NULL;
    return queue;
}

void
_free_safe_queue(
        safe_queue *queue) {
    free(queue);
}

runnable_task *
_get_from_queue(
        safe_queue *queue) {
    runnable_task *task = NULL;

    pthread_mutex_lock(&queue->mutex);
    if (queue->head != NULL) {
        task = queue->head->task;
        queue->head = queue->head->next;
        if (queue->head == NULL)
            queue->tail = NULL;
    }
    pthread_mutex_unlock(&queue->mutex);

    return task;
}

void *
_run_task(
        void *arg) {
    thread_pool *pool = (thread_pool *) arg;
    while (!pool->should_close) {
        runnable_task *task = _get_from_queue(pool->queue);
        if (task == NULL)
            continue;
        task->function(NULL);
    }

    return NULL;
}

thread_pool *
new_thread_pool(
        int count) {
    thread_pool *pool = malloc(sizeof(thread_pool));
    pool->queue = _new_safe_queue();
    pool->count = count <= MAX_THREAD ? count : MAX_THREAD;
    pool->should_close = 0;
    for (int i = 0; i < pool->count; i++) {
        pthread_create(pool->threads + i, NULL, _run_task, pool);
    }

    return pool;
}

void
free_thread_pool(
        thread_pool *pool) {
    _free_safe_queue(pool->queue);
    free(pool);
}

void
_add_to_queue(
        safe_queue *queue,
        runnable_task *task) {
    pthread_mutex_lock(&queue->mutex);
    if (queue->head == NULL) {
        queue->head = queue->tail = _new_safe_queue_node(task);
    } else {
        queue->tail->next = _new_safe_queue_node(task);
        queue->tail = queue->tail->next;
    }
    pthread_mutex_unlock(&queue->mutex);
}

void
add_task_to_pool(
        thread_pool *pool,
        runnable_task *task) {
    _add_to_queue(pool->queue, task);
}

void
shutdown_thread_pool(
        thread_pool *pool) {
    while (pool->queue->head != NULL) ;

    pool->should_close = 1;

    for (int i = 0; i < pool->count; i++)
        pthread_join(pool->threads[i], NULL);
}


texts: POSIX-ly finding a specific Java process

texts:
In this code I find a list all of the running java processes and give the below function a name to look for, it will do its best. But since I find my approach a little too ugly, could some POSIX shell script writer have a look and possibly give me some simplification recommendations?

#!/bin/sh

# here is an ugly constant vuze java process name
readonly vuze_java_process_name='org.gudy.azureus2.ui.swt.Main'

is_java_program_running()
# expected arguments:
# $1 = java program name
{
    # there will always be at least one java process:
    # jdk.jcmd/sun.tools.jps.Jps, which is actually
    # the program giving us the list of java processes
    java_process_list=$( jps -l | awk '{print $2}' )

    # this behaves strangely if there is zero processes (needs verification)
    # but since there is always at least one, no problem here
    java_process_list_count=$(( $( printf '%s\n' "${java_process_list}" | wc -l ) ))

    # set the result value as if we did not find it
    result=false

    # POSIX-ly simulate FOR loop
    i=1; while [ "${i}" -le "${java_process_list_count}" ]
    do
        # here we take one line from the list on $i position
        java_process_entry=$( echo "${java_process_list}" | sed --posix --quiet "${i}{p;q}" )
        # compare the given process entry with given java program name
        if [ "${java_process_entry}" = "${1}" ]
        then
            # set the result value
            result=true
            # end this loop
            break
        fi
        # increase iterator
        i=$(( i + 1 ))
    done

    # depending on if we found vuze process running,
    # return positive or negative result value
    if [ "${result}" = true ]
    then
        return 0
    else
        return 1
    fi
}

###
### EXAMPLE on Vuze
###

# keep Vuze alive forever, check in 5 seconds interval
while true
do
    sleep 5s

    if ! is_java_program_running "${vuze_java_process_name}"
    then
        my_date_time=$(date +%Y-%m-%d_%H:%M:%S)
        printf '%s  %s\n' "${my_date_time}" "(re-)starting Vuze"
        ( /home/vlastimil/Downloads/vuze/vuze > /dev/null 2>&1 & )
    fi
done


texts: Calculate proper dosage of supplements to take

texts:
Well, that's my first "program" after couple days of working with Python and programming itself. That may be stupid since everything there is so basic but I wanted to ask if there are any spaces to improve it. Idea was to give the user proper dosage of 4 supplements regarding if this is training day or not.
Is there any way to achieve it faster, more simple, better? Appreciate all feedback!
Edit
Thanks for all your replies! I will go through all of them and learn from them what i can, still confused in programming world.
dayon = {"BCAA" : "10g",
  "White" : "50g",
  "Glutamine" : "20g",
  "Vitamins" : 10}

dayof= {"BCAA" : "5g",
    "White" : "25g",
    "Glutamine" : "10g",
    "Vitamins" : 5}

username = input("What is your name?\n")
trening = input("Are you going to the gym today?\n")

def dosage():
    if trening == "yes":
       return (username + ", you have to take: " +
        "\nBCAA in dosage of: " + str(dayon["BCAA"]) +
        "\nWhite in dosage of: " +str(dayon["White"]) +
        "\nGlutamine in dosage of: " + str(dayon["Glutamine"]) +
        "\nVitamins in number of: " +str(dayon["Vitamins"]))
    elif trening == "no":
        return (username + ", you have to take: " +
        "\nBCAA in dosage of: " + str(dayof["BCAA"]) +
        "\nWhite in dosage of: " + str(dayof["White"]) +
        "\nGlutamine in dosage of: " + str(dayof["Glutamine"]) +
        "\nVitamins in number of: " + str(dayof["Vitamins"]))
    else:
        print ("Please answer yes or no")

print (dosage())


texts: Finding correct format? Arrays and Modulation

texts:
I am fairly new to programming and I am having difficulty modulating the following code.

The program reads a file, selects certain requirements, and displays them.  I have tried to use passing arrays as arguments or functions as indicated in my textbook.  I have been using examples such as int getAges(int array[], integer).

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace Project_2_practice
{
    class Program
    {
       static void Main(string[] args)
        {

            //Parsing data into memory
            string content;
            using (StreamReader reader = new StreamReader(File.Open("Data.txt", FileMode.Open)))
            {
                content = reader.ReadToEnd();
            }
            string[] rows = content.Split('\n'); //Each row is on a new line
            string[][] table = new string[rows.Length][];
            for (int i = 0; i < rows.Length; table[i] = rows[i].Split(','), i++) ;

     //selecting information

            int[] districts = new int[rows.Length];
            int[] ages = new int[rows.Length];

            for (int i = 0; i < rows.Length; i++)
            {
                districts[i] = int.Parse(table[i][3]);
                ages[i] = int.Parse(table[i][0]);
            }
                //Analyzing selected information
                foreach (int district in districts.Distinct().OrderBy(x => x))
                Console.WriteLine("District {0} has {1} resident(s)", district, districts.Count(x => x == district));
                Console.WriteLine("Ages 0-18 : {0} resident(s)", ages.Count(x => x < 18));
                Console.WriteLine("Ages 18-30 : {0} resident(s)", ages.Count(x => x >= 18 && x <= 30));
                Console.WriteLine("Ages 31-45 : {0} resident(s)", ages.Count(x => x >= 31 && x <= 45));
                Console.WriteLine("Ages 46-64 : {0} resident(s)", ages.Count(x => x >= 46 && x <= 64));
                Console.WriteLine("Ages >=65 : {0} resident(s)", ages.Count(x => x >= 65));
        }
    }
}


texts: OpenMP loop parallel for loop with function calls and STL vector

texts:
I have a function initialize_path_statistics(). I have used openMP to make it parallel. I am not sure where certain lines such as

float length_enclosed = Nodes::get_length_enclosed(i);

need additional pragma like #pragma omp atomic.

void Path_Statistics :: initialize_Path_statistics()
{
    path_match_score.resize(no_of_valid_nodes);
    combinatorial_structures.resize(no_of_valid_nodes);
    node_path_matches.resize(no_of_valid_nodes);
    path_loop_indexes.resize(no_of_valid_nodes);
    node_path_energy.resize(no_of_valid_nodes);

    #pragma omp parallel for
    for(unsigned int i = 0;i < no_of_valid_nodes;i++)
    {
        int matches = node_matches[i];
        float length_enclosed = Nodes::get_length_enclosed(i);
        float match_density = float(matches)/length_enclosed;
        path_match_score[i] = match_density;

        int child_count = (adjacency_table_vector[i].second).size();
        if((adjacency_table_vector[i].second).empty())
        {
            combinatorial_structures[i] = 1;
        }
        else
        {
            combinatorial_structures[i] = child_count+1;
        }
        node_path_matches[i] = matches;

        int loop_start_position = node_start[i] + node_matches[i];
        int loop_end_position = node_end[i] - node_matches[i];

        path_loop_indexes[i].first = loop_start_position;
        path_loop_indexes[i].second = loop_end_position;

        //the size of the loop
        int loop_size = node_end[i] - node_start[i] - 2*node_matches[i] + 1;

        //if the node can form a valid loop node
        if(loop_size <= MAXIMUM_SIZE_OF_LOOP)
        {
            //the loop path energy will also have the energy of the node + loop formed
            float energy = get_loop_energy(i) + node_energy[i];
            node_path_energy[i] = energy;
        }
        else
        {
            node_path_energy[i] = float(INFINITE);

        }

    }

The code for nodes::get_length_enclosed(i) is:

//calculates the length enclosed by the given node
inline int Nodes :: get_length_enclosed(int node_id)
{
    int length = node_end[node_id] - node_start[node_id] +1;
    return(length);
}

Can I make it more parallel using sections somehow?  I tried #pragma omp parallel for sections, which doesn't work. Also, is this code thread safe?


texts: Indefinite loop in a coroutine vs. re-scheduling a coroutine

texts:
I recently started working with asyncio and coroutines. I have a coroutine that runs every 0.25 seconds to print "running ..." on screen indefinitely. When the script receives a SIGTERM or SIGINT it will exit gracefully.

I figured out that there are two ways to do that.

Method A: Run a while True: loop in the coroutine and have a helper-coroutine to stop the loop after my main coroutine finished running (leaves "pending" status).
Method B: Have the coroutine re-schedule itself.

While method A just calls the couroutine once, method 2 does not need a helper-coroutine to close the loop gracefully. Is there a suggested way on doing this? Are there any up or downsides to one or the other?

Method A

import asyncio
import signal

def main():
    loop = asyncio.get_event_loop()

    asyncio.async(my_coroutine_a())

    for sig in (signal.SIGINT, signal.SIGTERM):
        loop.add_signal_handler(sig, ask_exit)

    loop.run_forever()
    print("Closing event loop")
    loop.close()

@asyncio.coroutine
def my_coroutine_a():
    print("Coroutine started")
    while True:
        try:
            print("running ...")
            # print(channel_layer.receive(["my_channel"]))
            yield from asyncio.sleep(0.25)
        except asyncio.CancelledError:
            print("stopping ...")
            raise

@asyncio.coroutine
def exit_coro():
    loop = asyncio.get_event_loop()
    loop.stop()
    print("Coroutine stopped")

def ask_exit():
    for task in asyncio.Task.all_tasks():
        task.cancel()
    asyncio.async(exit_coro())

if __name__ == "__main__":
    main()

Method B

import asyncio
import signal

def main():
    loop = asyncio.get_event_loop()

    asyncio.async(my_coroutine_b())

    for sig in (signal.SIGINT, signal.SIGTERM):
        loop.add_signal_handler(sig, ask_exit)

    print("Coroutine started")
    loop.run_forever()
    print("Coroutine stopped")
    print("Closing event loop")
    loop.close()

@asyncio.coroutine
def my_coroutine_b():
    try:
        print("running ...")
        # print(channel_layer.receive(["my_channel"]))
        yield from asyncio.sleep(0.25)
    except asyncio.CancelledError:
        print("stopping ...")
        asyncio.get_event_loop().stop()
        raise

    asyncio.async(my_coroutine_b())

def ask_exit():
    for task in asyncio.Task.all_tasks():
        task.cancel()

if __name__ == "__main__":
    main()

Output Method A & B

Coroutine started
running ...
running ...
running ...
running ...
running ...
running ...
running ...
stopping ...
Coroutine stopped
Closing event loop

Process finished with exit code 0


texts: Simple console application that changes text color based on user input

texts:
I am learning C# like 1 or 2 months and I wanted to know if there is any possibility to shorten this code.

It is simple. It only changes color of the console text with while loop if you enter wrong input. When you enter it correctly it changes the color + asks you if you want to continue.

It looks weird for me when I have for each color duplicity of the code written before (in if and switch statements) But I have no idea if there is any way to make it cleaner and shorter, but I guess there is. Also I would like to know where is worth to use arrays and where normal strings and integers + if there is any reasonable difference. Also I find it very hard for orientation when I have a lot of strings or ints inside array, but easy to maintain. Thanks for answers

static void Main(string[] args)
{
    string[] Arrays = new string[3]{
        "Hello!", "Enter a color\n1 = blue\n2 = red\n3 = Magenta", "Render numbers"

    Console.WriteLine(Arrays[0]);

    bool Continue = true;
    while(Continue) {
        Console.WriteLine(Arrays[1]);

        string[] color = new string[4]{
            "Blue", "Red", "Magenta", "Render numbers : "
        };
        char EnterColor = Console.ReadKey().KeyChar;
        Console.WriteLine();
        switch (EnterColor) {
            case '1':
                Console.ForegroundColor = ConsoleColor.Blue;

                Console.WriteLine("Do you want to continue? y/n");
                string NextTask = Console.ReadLine();
                if (NextTask == "y") {
                    // set loop to repeat
                    Continue = true;
                }
                else {
                    Continue = false;

                }
                break;
            case '2':
                Console.ForegroundColor = ConsoleColor.Red;
                Continue = false;
                Console.WriteLine("Do you want to continue? y/n");
                string NextTaskRed = Console.ReadLine();
                if (NextTaskRed == "y") {
                    Continue = true;
                }
                else {
                    Continue = false;

                }
                break;
            case '3':
                Console.ForegroundColor = ConsoleColor.Magenta;
                Continue = false;
                Console.WriteLine("Do you want to continue? y/n");
                string NextTasMagenta = Console.ReadLine();
                if (NextTasMagenta == "y") {
                    // set loop to repeat
                    Continue = true;
                }
                else {
                    Continue = false;

                }
                break;
            // there will be render nums option in next case using for loop
        }
    }
}


texts:
This method allows me to filter by date a data structure list of hash that contains articles. I would like to have your opinion on the code:

=method article_by_date

    $articles->articles_by_date( month => 12 );

Return a list of articles filter by date specified:

    input: month (Int) : optional, month to match
           year (Int) : optional, year to match
    output: Hashref: Details of article

=cut

sub articles_by_date {
    state $check = compile(
        $invocant,
        slurpy Dict[
            month => Optional[Int],
            year  => Optional[Int],
        ]
    );
    my ($self, $arg) = $check->(@_);
    my $month = $arg->{month};
    my $year  = $arg->{year};

    if ( ! defined($year) ) {
        my $dt = DateTime->now;
        $year  = $dt->year;
    }

    my $date  = defined($month)
        ? qr/^\d\d\/$month\/$year\s\d\d:\d\d:\d\d$/
        : qr/^\d\d\/\d\d\/$year\s\d\d:\d\d:\d\d$/;

    my @articles;
    foreach my $article ( @{$self->_get_or_create_cache('articles')} ) {
        $article->{date} =~ $date
            and push(@articles, $article);
    }

    return \@articles;
}


texts: Insert values into two different but similar tables

texts:
I have a combobox with two items. And if one is selected I want to write data to "salary" table and if selected another, to "other" table.

The difference between two code blocks is only one word. I would like to know how I could avoid repeating same code twice.

string myConnection = "datasource=localhost; port=3306; username=root;password=root";
                if (comboBox4.SelectedItem.ToString() == "Salary")
                {
                    string insert = "insert into budget.salary (name, suma) values (@name, @price);";

                    using (var conDataBase = new MySqlConnection(myConnection))
                    using (var cmdDataBase = new MySqlCommand(insert, conDataBase))
                    {
                        cmdDataBase.Parameters.AddWithValue("@name", name);
                        cmdDataBase.Parameters.AddWithValue("@price", suma);
                        conDataBase.Open();
                        cmdDataBase.ExecuteNonQuery();

                        MessageBox.Show("Saved");
                    }
                }
                if (comboBox4.SelectedItem.ToString() == "Other")
                {
                    string insert = "insert into budget.other (name, suma) values (@name, @price);";

                    using (var conDataBase = new MySqlConnection(myConnection))
                    using (var cmdDataBase = new MySqlCommand(insert, conDataBase))
                    {
                        cmdDataBase.Parameters.AddWithValue("@name", name);
                        cmdDataBase.Parameters.AddWithValue("@price", suma);
                        conDataBase.Open();
                        cmdDataBase.ExecuteNonQuery();
                        MessageBox.Show("Saved");

                    }
                }


texts:
I have been practicing competitive coding for a while now and am using codeforces.com. I recently encountered a problem called "One Dimensional Japanese Crossword" on that site.
The problem is as follows:

The judge provides an integer (up to 100) and then a string with that many characters being either 'B' or 'W'. We need to output how many groups of 'B' there are and how many 'B's there are in each group. For example:

Input:

6
BBWBWB

Output:

3
2 1 1

After lots of tries and lots of fails, I was finally able to get the code accepted by the judge. However, for some reason I feel that my code is really inefficient and there might be an easier and better way to solve this problem.

#include<iostream>
#include<vector>
using namespace std;

int main()
{
    int n;
    cin >> n;
    string s;
    cin >> s;

    int bGroups = 0;
    int wGroups = 0;

    char initChar = s[0];

    for (int i = 1; i < s.length(); i++)
    {
        if (initChar == 'B')
        {
            if (s[i] != initChar)
            {
                bGroups++;
                initChar = 'W';
            }
        }
        else if (initChar == 'W')
        {
            if (s[i] != initChar)
            {
                wGroups++;
                initChar = 'B';
            }
        }

    }

    if (s[n - 1] == 'B')
    {
        bGroups++;
    }
    else if (s[n - 1] == 'W')
    {
        wGroups++;
    }

    char init = s[0];
    vector<int>grpSize(bGroups);
    int counter = 0;
    int i = 0;
    while (counter < bGroups)
    {
        if (init == 'B')
        {
            while (init == 'B')
            {
                grpSize[counter]++;
                i++;
                init = s[i];
            }
            counter++;
            while (init == 'W')
            {
                i++;
                init = s[i];
            }
        }
        else
        {
            while (init == 'W')
            {
                i++;
                init = s[i];
            }
            while (init == 'B')
            {
                grpSize[counter]++;
                i++;
                init = s[i];
            }
            counter++;
        }
    }

    cout << bGroups << endl;
    for (int i = 0; i < bGroups; i++)
    {
        cout << grpSize[i] << " ";
    }
}

So basically, in the first pass over the string, I count how many groups of 'B' and 'W' there are. Then I create an int vector to store the size of each 'B' group. Then on the second pass I fill in the values into the vector and then output the results.


texts: Minimization problem solving and its step limits

texts:
I am trying to solve the following minimization problem:

$$
\min\lvert\lvert{x}\rvert\rvert_1 + \beta\lvert\lvert{x}\rvert\rvert^2_2 s.t. \sum_{m = 1}^M (y - \lvert{c}^{H} . x\rvert^2)^2 \le \epsilon
$$

x: my unknown value (input) with complex elements and known size, here (4x1)
y: the output vector (known)
c: a 'skaling' vector

I am very new to this so my approach may seem basic. I simply loop over all combination of c (non-redundant) and according to the computed minimization value and condition I update my results.

My questions are the following:

Is this correct and is there a better approach to this?
This code fails with a small step due to the huge size of combinations, so how can I solve that?

from itertools import combinations
from random import randint
import numpy as np

def deg2rad(phase):
    return round(((phase*3.14)/180),3)

def excitation(amplitude, phase):
    return complex(round(amplitude * (np.cos(deg2rad(phase))),3), round(amplitude*(np.sin(deg2rad(phase))),3))

def compute_subject_equation_result(x):
    M            = 12
    difference   = []
    y            = [randint(10, 20) for i in range(M)]

    for m in range(0, M):
        c  = np.array([randint(0, 9), randint(10,20), randint(0, 9), randint(0,20)]).reshape(4,1)
        ch = c.conjugate().T
        eq  = (y[m] - (abs(np.dot(ch, x))[0])**2)**2
        difference.append(eq**2)
    return round(sum(difference)[0], 3)

def compute_main_equation_result(x, beta):
    norm1  = np.linalg.norm(x,1)
    norm2  = np.linalg.norm(x,2)
    return round(norm1 + beta*(norm2**2), 3)

def optimize(x, min_x, min_phi_x):
    min_result      = 10**25

    # compute the optimization formals and check for the min value
    main_equation_result    = compute_main_equation_result(c, beta)
    subject_equation_result = compute_subject_equation_result(c)

    # update min value if min detected'
    if subject_equation_result < epsilon and main_equation_result < min_result:
        min_result = main_equation_result
        min_x      = x
        min_phi_x  = phx
    return min_x, min_phi_x

# initialization
phases    = [alpha for alpha in range(0, 361, 90)]
beta      = 1
epsilon   = 10**25
min_x     = np.array([])
min_phi_x = np.array([])

phases_combinations = [list(comb) for comb in combinations(phases, 4)]

# start checking all combinations
for phx in  phases_combinations:
    phi1, phi2, phi3, phi4 = phx[0], phx[1], phx[2], phx[3]
    # build the hypothesis for the excitations vector c
    c = np.array([ excitation(1, phi1), excitation(1, phi2), excitation(1, phi3), excitation(1, phi4) ]).T.reshape(4,1)
    min_x, min_phi_x = optimize(c, min_x, min_phi_x)
    print('    --------------------------------------------------')
    print('-----> new_min_c     = ', list(min_x))
    print('-----> new_min_phi_c = ', min_phi_x)

Remark: When trying phases = [alpha for alpha in range(0, 361, 1)] I get a "memory error". I can avoid using a higher step. However I am not sure about my approach in general nor of the step change effect on the accuracy.


texts: Finding Second Largest Element in an Array

texts:
Here's my implementation using divide and conquer in C++.

What do you think of this implementation regarding running time ?

#include <iostream>
#include <tuple>
using namespace std;

tuple <int,int> largest_two_numbers(int *arr,int size)
{
    //The algorithm is based on returning a tuple with the largest two numbers in the array

    if (size==1)
        return tuple<int,int>(arr[0],arr[0]);
    if (size==2)
        return tuple<int,int>(arr[0],arr[1]);

    //Split the arr into two arrays
    int arr_1[size/2],arr_2[size/2+(size&1)];
    for (int i = 0; i < size/2; ++i)
    {
        arr_1[i]=arr[i];
        arr_2[i]=arr[i+size/2];
    }
    if (size&1) arr_2[size/2]=arr[size-1];

    //Return two tuples one for the right half and the other for the left
    tuple <int,int> right= largest_two_numbers(arr_1,size/2);
    tuple <int,int> left = largest_two_numbers(arr_2,size/2+(size&1));

    //Declare an array maxis with the values inside the two tuples combined and find the largest two numbers
    int maxis[]={get<0>(right),get<1>(right),get<0>(left),get<1>(left)};
    int max1=maxis[0],max2=maxis[0];
    for (int i = 0; i < 4; ++i)
    {
        if (maxis[i]>max1) max1=maxis[i];
    }
    for (int i = 0; i < 4; ++i)
    {
        if (maxis[i]>max2 && maxis[i]<max1) max2=maxis[i];
    }

    //Return a tuple with the largest two numbers
    return tuple<int,int>(max1,max2);
}

int main(){
    int arr[]={-1,98,22,1,0,301,112},n=7;

    //Print the second largest element in the array which is the second element in the tupple
    cout << get<1>(largest_two_numbers(arr,n));
}


texts: Deleting all the matching items in single linked list

texts:
I have the following code which I implemented to delete all the nodes for the matching value. My code handles all the 63 varieties of test case scenarios including scenarios like deleting 1 from linked list 1->1, leaving the linked list empty.

  public ListNode RemoveElements(ListNode head, int val) {
      if(head != null)
    {
        ListNode current = head;
        ListNode prevNode;
        while(current !=null && current.next != null)
        {
            prevNode = current;
            if(current.val == val)
            {
                current.val = current.next.val;
                current.next = current.next.next;
            }
            else
                current = current.next;
        }

        int count = 0;
        ListNode p = head;
        ListNode pBefore = null;
        while(p != null)
        {
            if(p.next != null)
                pBefore = p;
            p = p.next;
            count++;
                        }

        if(current.val == val)
        {
            if(count == 1)
             head = null;
             else if(count > 1)
                pBefore.next = null;
        }

    }
    return head;

}

I'm sure this can be optimized and it would be great if someone can share the best way to delete all the matching items in single linked list.

I tried searching on Google, but everywhere it is handled as part of a SingleLinked list custom class having head and tail node access. In my case, I am handling in a method and I have access only to the head of the list through the input parameter.


texts:
#include <iostream>
#include <memory>
using std::cout;
using std::endl;

template<typename T, int dimension = 1>
class Array
{
private:
    std::unique_ptr<T[]> pointer;
    int size[dimension];
    int realSize;

public:
    Array()
    {
    }

    template<typename... Ns>
    Array(Ns... ns)
    : realSize(1)
    {
        create(1, ns...);
    }

private:
    template<typename... Ns>
    void create(int d, int n, Ns... ns)
    {
        realSize *= n;
        size[d - 1] = n;
        create(d + 1, ns...);
    }

    void create(int d)
    {
        pointer = std::unique_ptr<T[]>(new T[realSize]);
    }

    int computeSubSize(int d) const
    {
        if (d == dimension)
        {
            return 1;
        }
        return size[d] * computeSubSize(d + 1);
    }

    template<typename... Ns>
    int getIndex(int d, int n, Ns... ns) const
    {
        return n * computeSubSize(d) + getIndex(d + 1, ns...);
    }

    int getIndex(int d) const
    {
        return 0;
    }

public:
    template<typename... Ns>
    T& operator()(Ns... ns) const
    {
        return pointer[getIndex(1, ns...)];
    }

    int getSize(int d = 1) const
    {
        return size[d - 1];
    }
};

int main()
{
    constexpr int N = 10;
    Array<int> a(N);
    for (int i = 0; i < a.getSize(); ++i)
    {
        a(i) = i + 1;
        cout << a(i) << ' ';
    }
    cout << '\n' << endl;
    Array<int, 2> a2(N, N * 2);
    for (int i = 0; i < a2.getSize(1); ++i)
    {
        for (int j = 0; j < a2.getSize(2); ++j)
        {
            a2(i, j) = i + j + 2;
            if (a2(i, j) < 10)
            {
                cout << '0';
            }
            cout << a2(i, j) << ' ';
        }
        cout << endl;
    }
    return 0;
}

Output

1 2 3 4 5 6 7 8 9 10

02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21
03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 22
04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 22 23
05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
08 09 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
09 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30


texts: Retrieve generic contract names for Managed Extensibility Framework

texts:
Edit
Found the original contract name resolution by .NET MEF, the code below is not useful anymore. See response!

My issue was to use existing code, to make a MEF ExportFactory, imported via [Import] attribute to a property, return instances of Moq mocks (for unit testing). Problem was, that the original code always used the Type.FullName property value as contract name. This worked fine for non-generic types, but not for generics.

Generic FullName is like:

My.Assembly.GenericType`1[My.Assembly.InnerType]

but MEF expects a name like:

My.Assembly.GenericType(My.Assembly.InnerType)

The complete unit test code actually extends the MEF ExportProvider class, to register ExportDefinition instances for an ExportFactory and it's ProductDefinition. The contract name goes to a metadata dictionary, using the key CompositionConstants.ExportTypeIdentityMetadataName.

This following code is only for the contract name conversion. It calls itself recursively, for generic arguments which are generic themselves. The regular expression matches by the `[digits] name extension, used by .NET for generic types. It would be nice to see a generally better way, or already existing functions from MEF, if such exists.

Edit: I added the incrementor and code for open (unspecified) generics, which have names with indexed curly brackets: instead of IMyType<string,int> IMyType<,>, resolved to contract name IMyType({0},{1}). Regex has also been changed to match, if no type names come after `[digits].

private static readonly Regex GenericRegex =
    new Regex(@"^(?<fullNameNonGeneric>\S+?)`\d+(\[.*\])*$",
        RegexOptions.Compiled);

public static string ResolveGenericMefContractName(this Type type)
{
    return ResolveGenericMefContractName(type, new IndexIncrementor());
}

private static string ResolveGenericMefContractName(Type type, IndexIncrementor incrementor)
{
    var fullName = type?.FullName;
    if (fullName == null)
    {
        return null;
    }
    var match = GenericRegex.Match(fullName);
    if (!match.Success)
    {
        return type.FullName;
    }

    var fullNameNonGeneric = match.Groups["fullNameNonGeneric"].Value;
    var genericArgs = type.GetGenericArguments();

    return fullNameNonGeneric + "(" +
        string.Join(",", genericArgs.Select(
            ga => ResolveGenericMefContractName(ga, incrementor)
            ?? "{" + incrementor.GetAndIncrementValue() + "}"))
        + ")";
}

private class IndexIncrementor
{
    private int _value;

    public int GetAndIncrementValue() => _value++;
}


texts:
As a toy project, I started evaluating the Neo4J graph database and its Rest interface. I'm trying to write a simple graph visualization in JavaScript. In daily business I'm a Java developer and maybe that's the reason why I'm not that happy with my current approach. In Java I would have written a Neo4J class, with inner (data) classes for Node and Relation as their id is tightly couple to the server (http://localhost:7474/db/data/node/0). Maybe they even would get a common parent class.

In JavaScript I don't get away from my object oriented mind. I need some ideas in relation to JavaScript best practice.

function Neo4J(server) {
    this.server = server;
}

function Node(connection, response) {
    this.id = connection.sanitizeId(response['self']);
    this.data = response['data'];
}

function Relation(connection, response) {
    this.id = connection.sanitizeId(response['self']);
    this.start = connection.sanitizeId(response['start']);
    this.end = connection.sanitizeId(response['end']);
    this.type = response['type'];
}

Neo4J.prototype = {
    sanitizeId: function (id) {
        return id.replace(this.server, "");
    },

    query: function (query, success) {
        return post(this.server + "/cypher", {"query": query, "params": {} }, success);
    },

    getAllNodes: function (callback) {
        var connection = this;
        this.query("MATCH n RETURN n", function (nodes) {
            $.each(nodes['data'], function (i, val) {
                callback(new Node(connection, val[0]));
            });
        });
    },

    getAllRelations: function (callback) {
        var connection = this;
        this.query("START r=rel(*) RETURN r", function (nodes) {
            $.each(nodes['data'], function (i, val) {
                callback(new Relation(connection, val[0]));
            });
        });
    },

    getNode: function (id, callback) {
        var connection = this;
        get(this.server + id + "/properties", function (data) {
            if (data == null) data = {data: {}};
            else data = {data: data};
            data['self'] = id;
            callback(new Node(connection, data));
        });
    },

    createNode: function (callback) {
        var connection = this;
        post(this.server + '/node', null, function (data) {
            callback(new Node(connection, data));
        });
    },

    setNodeProperty: function (node, key, value, callback) {
        put(this.server + node.id + '/properties/' + key, '"'+value+'"', function (data) {
            node.data[key] = value;
            callback(node);
        });
    },

    createRelation: function (start, target, type, callback) {
        var connection = this;
        post(this.server + start + '/relationships', {to: this.server + target, type: type}, function (data) {
            callback(new Relation(connection, data));
        });
    }

}

The post() and  put() are just ajax calls to the Neo4J server.


texts:
My project is using a specific version of JDK which is jdk-6 and the default JDK_HOME path will vary from distribution to distribution, so I wrote a script to guess it. Is there any way to do this better?

#!/bin/bash
JAVA_HOME=""
JDK_TEMP=""
shopt -s extglob

JDK_ROOT_DIR=( /usr/java/ /usr/java/jdk/  /usr/j2se/  /usr/j2se/ /usr/j2sdk/ /usr/jdk/ /usr/lib/java/ /usr/lib/j2se/ /usr/lib/j2sdk/ /usr/lib/jdk/ /usr/lib/jvm/java/ /usr/lib/jvm/j2se/ /usr/lib/jvm/j2sdk/ /usr/lib/jvm/jdk/ /usr/local/java/ /usr/local/java/jdk/ /usr/local/jdk/ /opt/java/ /opt/j2se/ /opt/j2sdk/ /opt/j2sdk/ /opt/jdki/ /usr/lib/jvm/ )
for sub_dir in "${JDK_ROOT_DIR[@]}"
do

#                                                 #
# For each subdirectory inside the root directory #
#                                                 #
#                                                 #
    # For openjdk                                 #
    for jdk_dir in $sub_dir/java-*6*-openjdk*!(common) ; do
        if [[ -d $jdk_dir ]]; then
            echo  $jdk_dir
            export JAVA_HOME=$jdk_dir
            exit 0
        fi
    done

    # for IBM Java                                #
    for jdk_dir in $sub_dir/java-1_6_0-ibm-!(common) ; do
        if [[ -d $jdk_dir ]]; then
            echo $jdk_dir
            export JAVA_HOME=$jdk_dir;
            exit 0
        fi
    done

    # for raspbian java                           #
    for jdk_dir in $sub_dir/jdk-8-oracle-arm32-!(common) ; do
        if [[ -d $jdk_dir ]] ; then
            echo  $jdk_dir
            export JAVA_HOME=$jdk_dir
            exit 0
        fi
    done
done

echo "JDK directory not found."


texts:
The code's purpose is to call to some function async given some condition was true. I've using the following code which is working as expected. Is there a way to write it better, maybe by not using the promise push array?

var _run = (req, res, oModule, oConfig, urlPath,action) => {

    var aPromises = [];
    //requested action to call

    for (var provider in oConfig.providers[0]) {
        if ((oConfig.providers[0][provider].val === action))
        {
            var fnName = oConfig.providers[0][provider].function;
            //Run on provided actions
            if (typeof oModule[oConfig.providers[0][provider].function] === "function") {
                try {
                    logger.info(`Function ${fnName} is called `);
                    aPromises.push(oModule[fnName](req, res));
                }
                catch (err) {
                    logger.error(`Error returned  ${err}`);
                }
            }
        }
    }
    return Promise.all(aPromises);
};

update:

This is the value of config object and in the code I need to call to the function according to the path I got...

{
  "providers": [
    {
      "run": {
        "path": "command1",
        "function": "fn1",
      },
      "save": {
        "path": "test2",
        "function": "fn2",
      }
    }
  ]
}


texts: Calculation of image offsets for performing cropping

texts:
I am using the java.awt.Rectangle class to construct subsets of a GEOTIFF file. In order to do this I would need to specify the x,y offsets, height and width of each subset image. In my particular case I would need to crop the original GEOTIFF image bottom to top. The java.awt.Rectangle class specifies that the origin point is to be found in the upper left hand corner.

Please let me know if the calculation of the image offsets are correct and/or there is a better way of calculating the image offsets. The crop(r) method is a proprietary method used to crop subsets of the original image.

int width = 40;
int height = 34;
int cellSize = 3600;
int xOffset = 0;
int yOffset = 0;
int pixelWidth = cellSize * width;
int pixelHeight = cellSize * height;
for (int i = 0 ; i < width; i++)
{
    for (int j = 0; j < height; j++)
    {
        yOffset = pixelHeight - cellSize *(j+1) ;
        Rectangle r = new Rectangle(xOffset,
                                    yOffset,
                                    cellSize,
                                    cellSize);
        crop(r);
    }
    xOffset = pixelWidth - cellSize * (i+1);
}


texts: Hackerrank "Queues: A Tale of Two Stacks" Javascript Solution

texts:
Here is the original problem, and below is my solution (passing). It's asking to implement a queue with 2 stacks, which means I cannot simply use Array.shift. I wonder if the solution can be improved. Is there a better way than this to implement a queue with 2 stacks?

function processData(input) {
    var inputs = input.split('\n')
    var cmd;
    var inQueue = [],
        outQueue = []
    var len;

    function inQueueToOutQueue() {
        if (outQueue.length === 0) {
            len = inQueue.length;
            while (len-- > 0) {
                outQueue.push(inQueue.pop())
            }
        }
    }

    for (var i = 1, max = inputs[0]; i <= max; i++) {
        cmd = inputs[i].split(' ');
        switch (cmd[0]) {
            case '1':
                inQueue.push(cmd[1]);
                break;
            case '2':
                inQueueToOutQueue();
                outQueue.pop()
                break;
            case '3':
                inQueueToOutQueue();
                console.log(outQueue[outQueue.length - 1])
                break;
            default:
        }
    }

}


texts:
I was asked to create a function that return first UNIQUE integer from given array of integers. In a case of success the function return the unique number in a case of failure return -1. The complexity should be \$O(n \log(n))\$. How can this be improved?

function solution(A) {

    var returnNumber = -1;
    var tempArray = new Array();;

   for(i=0; i < A.length; i++){

      var newIndex = A[i];
     if( tempArray[newIndex] === undefined){
        tempArray[newIndex] = 1;
     }
     else{
        tempArray[newIndex] += 1;
     }
    }
   for(j = 0; j < A.length; j++){
     if(tempArray[A[j]] == 1){
       returnNumber = A[j];
       break;
     }
   }
    return returnNumber;
}

//var A =  [1, 4, 3, 3, 1, 2, 0, 0]; //returns 4
var A =  [22, 25, 3, 3, 1, 2, 0, 0,100,22,25,1,2]; // returns 100
solution(A)


texts:
Like the title says, I made a very simple game of Blackjack using Python version 2.6.9. I am relatively new to python and programming so I would really appreciate some constructive criticism to help me improve.

from random import shuffle #this imports shuffle which shuffles the     deck

deck = list('234567890JQKA'*4)
for shu in range(0,3):
    shuffle(deck)
value = {'2':2, '3':3, '4':4, '5':5, '6':6, '7':7, '8':8,
         '9':9, '0':10, 'J':10, 'Q':10, 'K':10, 'A':1}      # Creates the shuffled deck

player = [deck.pop() for _ in range(2)]
AI = [deck.pop() for _ in range(2)]     # Deals the cards to the players

stay = False

def player_game():
    global stay
    print "Your hand: %s" % player
    hit = raw_input("Hit or Stay? ")
    if hit == "Hit":
        player.append(deck.pop())
    elif hit == "Stay":
        stay = True
        return stay
    else:
        print "I'm sorry. you need to input 'Hit or Stay'."

while 1:
    player_game()
    total = sum(map(value.get, player, AI))
    if total > 21:
        print "Hand: %s" % player
        print "You busted with a score of: %s" % total
        break
    elif total == 21:
        print player
        print "You win!"
        break
    if stay == True:
        print "You stayed."
        print "Final score: %s" % total
        break


texts:
Write a function Int -> Char -> Char -> [String] that will create the appropriate pattern.
For example: mapM_ putStrLn (pattern 48 '.' '+')
................................................
.+..+..+..+..+..+..+..+..+..+..+..+..+..+..+..+.
+.++.++.++.++.++.++.++.++.++.++.++.++.++.++.++.+
................................................

This idea is inspired by Writing nested for loops to produce certain output (but more general).
I am pretty satisfied with my code to solve this problem:
pattern :: Int -> Char -> Char -> [String]
pattern len a b = map (take len . cycle) [[a], [a, b, a], [b, a, b], [a]]

main :: IO()
main = mapM_ putStrLn (pattern 48 '.' '+')


texts:
I want my method to use a finally block so I can be ure that my EF entity is disposed after usage, even if an exception is thrown, but I would also like to not handle exceptions in that method.

The current code works but is it possible to omit the catch{} block? Would an exception from the try{} block be re-thrown or would it be forgotten?
Is it necessary to set tm_entity to null in the finally block, or will Dispose take care of everything?

Any other suggestions are welcome!

/// <summary>
/// Returns ID of the latest result database.
/// </summary>
/// <param name="managementEntity">EF Test Management entity.</param>
/// <returns>Latest result database ID.</returns>
public static int GetLatestDatabaseIteration(TEST_MANAGEMENTEntities managementEntity)
    {
        if (managementEntity == null)
        {
            throw new ArgumentNullException("Passed entity can not be null!.");
        }

        TEST_MANAGEMENTEntities tm_entity = managementEntity;
        int? latestDatabaseID = null;
        try
        {
            latestDatabaseID = (from trb in tm_entity.TestRunsDatabases
                                select trb.DatabaseID).Max();

            if (latestDatabaseID == null)
            {
                throw new Exception("Cannot evaluate latest Test Result Database ID.");
            }
        }
        catch (Exception ex) //Could I just omit this block?
        {
            throw ex;
        }
        finally
        {
            tm_entity.Dispose();
            tm_entity = null; //is it necessary?
        }
        return (int)latestDatabaseID;
    }

EDIT:

After making suggested changes my method looks like this.

public static int GetLatestDatabaseIteration(TEST_MANAGEMENTEntities managementEntity)
    {
        if (managementEntity == null)
        {
            throw new ArgumentNullException("Passed entity can not be null!.");
        }

        TEST_MANAGEMENTEntities tmEntity = managementEntity;

        int? latestDatabaseID = (from trb in tmEntity.TestRunsDatabases
                                 select (int?)trb.DatabaseID).Max();

        if (latestDatabaseID == null)
        {
            throw new NoRecordsFoundException("Cannot evaluate latest Test Result Database ID.");
        }

        return (int)latestDatabaseID;
    }

Changes I made:

I have renamed variables to match CamelCase.
I have removed .Dispose on a passed reference as it would also Dispose object in the Caller method.
I have abandoned calling generic exception and replaced it with custom one that more accurately describes this exception.

Calling .Max() if query return null may cause problems, but I will check it with UnitTests soon.


texts: Create an Array with n values that is able to use Array methods instantly

texts:
As it is impossible to use Array methods on new Array(n), e.g. new Array(5).map(/* [some callback] */), I deviced a pseudo static Array method.

The idea is to call an anonymous function that fills an empty Array with n times the value undefined. In its simplest form it returns an Array for which Array-methods are applicable.

If you supply parameters (a callback method (Function), the method identifier itself (String, default = 'map') and optionally an initial value, the  callback method mapCB is applied to the (Array)method, and the resulting Array is returned.

It looks like this:

window.addEventListener('load', function () {
    Array.create = function (n, mapCB, method, initial) {
                             method = method in [] ? method : 'map';
                             var nwArr = ( function (nn){
                                             while (nn--)
                                               this.push(undefined);
                                             return this; } )
                                           .call([],n);
                             return mapCB ? nwArr[method](mapCB, initial) : nwArr;
    };
    // usage examples
    var someArr0 = Array.create(100).map(function (v, i) {return i;});
    var someArr1 = Array.create(100, function (v, i) {return this + i;}, 'map', 5);
    var someArr2 = Array.create(100, function (p, n, i) {return p+i;}, 'reduce', 0);
    Helper.log2Screen('someArr0: [ ',someArr0.join(', '),' ]');
    Helper.log2Screen('someArr1: [ ',someArr1.join(', '),' ]');
    Helper.log2Screen('someArr2: ',someArr2,'');
});

Do you think it's useful, or are there better way to achieve this?

I'm aware of the Array.apply(undefined, Array(n)) to create a usable Array, but that will run into a maximum call stack error at some point with a large n used.

Based on the comments and given answer, a more readable approach would be:

    function createArrayWithNElements(nElements, defaultValue) {
      var arr = [];
      for (var i=0; i < nElements; i+=1) {
         arr.push(defaultValue);
      };
      return arr;
    }
    function createArrayWithNElementsAndApplyMethod(n, methodObj) {
      var arr = createArrayWithNElements(n);
      return arr[methodObj.method](methodObj.callback, methodObj.initialValue);
    }
    Array.create = createArrayWithNElements;
    Array.createAndApply = createArrayWithNElementsAndApplyMethod;
    // usage examples
    Array.create( 10, 0 ); //=> [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
    Array.createAndApply( 10, { method:'map',
                                callback: function (v, i) {return this + i;},
                                initialValue: 5 } );
    //=> [5, 6, 7, 8, 9, 10, 11, 12, 13, 14]


texts: Keep reading Command-line until you get the word END

texts:
I have to write a code which takes (integers) numbers from Command-line and keeps reading the terminal until it gets a word END

So I wrote the following; I feel its really bad. Is there any way I can improve below code

I updated my code from previously to below

func main() {
    buf := bufio.NewReader(os.Stdin)
    lines, err := buf.ReadBytes('\n')

    if err != nil {
        return
    }

    fmt.Printf(" %q \n", string(lines))
    line := strings.Replace(string(lines), "\n", "", -1)

    numbers := strings.Split(line, " ")
    fmt.Printf("numbers %q ", numbers)
    var sum int64
    for _, num := range numbers {
        num, err := strconv.ParseInt(num, 10, 0)
        if err != nil {
            fmt.Println(err)
            break
        }
        sum += num
    }
    fmt.Println("Sum of all numbers :", sum)

}