texts:
This program converts glob files' tabs to spaces.
There is a special case to ignore content inside triple back ticks.

Example usage is ./tab_2_spaces.py *.md

Main Concern: Can I write the while loop better?

#!/usr/bin/env python3
"""
This program is used to convert markdown file's tab indentations to 2 spaces.
"""

import argparse
from pathlib import Path
import os
import io
import itertools
from multiprocessing import Pool

_TAB_2_SPACE = "  "

def fix_indent(filename):
    with io.open(filename, mode="r", encoding="utf-8") as h:
        text = h.read()

    lines = text.splitlines(True)
    c = len(lines)
    i = 0

    # Replace tab to spaces
    while i < c:
        line = lines[i]

        if line.startswith("```"):
            i += 1
            while i < c:
                if lines[i].startswith("```"):
                    break
                i += 1
            else:
                continue
            break
        elif line.startswith("\t"):
            lines[i] = line.replace("\t", _TAB_2_SPACE)

        i += 1

    with io.open(filename, mode="w", encoding="utf-8") as h:
        h.write("".join(lines))

def main():
    parser = argparse.ArgumentParser(description="Fix indent")
    parser.add_argument(
        "files", metavar="N", type=str, nargs="+", help="List of files to scan"
    )

    args = parser.parse_args()
    all_files = tuple(
        itertools.chain(
            *[
                (filename for filename in Path().glob("**/" + file_))
                for file_ in args.files
            ]
        )
    )

    with Pool(2) as process_pool:
        process_pool.map(fix_indent, all_files)

if __name__ == "__main__":
    main()


texts: Using Powershell to Copy Files to Several Locations

texts:
This code copies files to our Test server and places the executable on a file share for the tester to access.  I'm new to Powershell, so I'm sure I'm not doing this in the most efficient way.  Any criticisms would be appreciated.

# the destination that we are copying TO.
$codeToDeploy = "\\deployment_server\App-Shares\Developer_Area\Code to Deploy\";

# all the local folders we'll need
$myProjectFolder = "C:\MTS\ProjectFolder\Project\";
$myLocalOurProjectName =  ($myProjectFolder + "OurProjectName\bin\Debug\");
$myLocalLauncher = ($myProjectFolder + "OurProjectName_Launcher\bin\Debug\");
$myLocalWcfService = ($myProjectFolder + "ProjectWCFService\bin\");
$myLocalWebsite = ($myProjectFolder + "MTSWebsite\bin\");

#----------------------------------------------------------------
# 1. prep the "code to deploy" folder on the server to receive files
#----------------------------------------------------------------

# set our current folder
Set-Location $codeToDeploy

# create the name of the new top level folder with today's date
$datedFolderName = "MM " + (get-date -Format "yyyy-MM-dd") + "\";

# create the date-named folder - overwrite if it already exists
New-Item $datedFolderName -ItemType directory -Force;

# set our current folder to the date-named folder
Set-Location $datedFolderName;

# create the sub folders
New-Item "OurProjectName Client" -ItemType directory -Force;
New-item "OurProjectName Launcher" -ItemType directory -Force;
New-item "ProjectWCFService\front end" -ItemType directory -Force;
New-item "Website\front end" -ItemType directory -Force;

#----------------------------------------------------------------
# 2. copy all the files from local debug to the target folders
#----------------------------------------------------------------

# copy to the MM Client folder
$destination = ($codeToDeploy + $datedFolderName + "OurProjectName Client\");
Set-Location $myLocalOurProjectName
Copy-Item *.dll,OurProjectName.exe $destination -Force;

# copy to the Launcher Folder
$destination = ($codeToDeploy + $datedFolderName + "OurProjectName Launcher\");
Set-Location $myLocalLauncher;
Copy-Item OurProjectName_Launcher.exe $destination -Force;

# copy to the Service Folder
$destination = ($codeToDeploy + $datedFolderName + "ProjectWCFService\");
Set-Location $myLocalWcfService;
Copy-Item *.dll $destination -Force;
Set-Location -Path ..
Copy-Item AllService.svc -Destination ($destination + "front end\") -Force;

# copy to the Website Folder
$destination = ($codeToDeploy + $datedFolderName + "Website\");
$frontEnd = ($destination + "front end\")
Set-Location $myLocalWebsite;
Copy-Item *.dll $destination -Force;
Set-Location -Path ..
Copy-Item *.aspx,*.master,CSS,SiteImages $frontEnd -Recurse -Force;

#----------------------------------------------------------------
# 3. copy all the files from local debug to the server's
#    "client install\binaries" location for serving up to the launcher
#----------------------------------------------------------------

# copy to the MM Client folder
$destination = "\\app-ttps2-tst\App-Shares\Project\Client Install\Binaries\OurProjectName\";
Set-Location $myLocalOurProjectName
Copy-Item *.dll,OurProjectName.exe -Destination $destination -Force;

#----------------------------------------------------------------
# 4. copy all the files from local debug to the UI Testing location
#----------------------------------------------------------------

$folders = Get-ChildItem "\\nw\data\TnFS\Project\ProjectFolder\UI TESTING\MM *" | Sort-Object

#save the latest config file for later
#$latestConfigFile = $folders | Select-Object -Last  | Get-ChildItem OurProjectName.exe.config

# copy to the MM Client folder
$destination = "\\nw\data\TnFS\Project\ProjectFolder\UI TESTING\" + $datedFolderName;
New-Item $destination -ItemType directory -Force;

Set-Location $myLocalOurProjectName
Copy-Item *.dll,OurProjectName.exe -Destination $destination -Force;


texts:
I have written a recursive method for a partition sort that sorts the array. However, when I use an array of more than 10-20 elements the program takes a really long time to complete. (On my computer a bubble sort of a 100,000 int array will take about 15-20 seconds, but with an array of only 30 ints my partition sort is taking around 45 seconds to be sorted.)

public static int[] partitionSortRecursive(int[] array, int beginning, int end)
{
    if (end < beginning)
        return array;

    int pivot = (array[beginning] + array[end]) / 2;
    int firstUnknown = beginning;
    int lastS1 = beginning - 1;
    int firstS3 = end + 1;

    while (firstUnknown < firstS3)
    {
        if (array[firstUnknown] == pivot)
        {
            firstUnknown++;
        }
        else if (array[firstUnknown] > pivot)
        {
            firstS3--;
            int temp = array[firstUnknown];
            array[firstUnknown] = array[firstS3];
            array[firstS3] = temp;
        }
        else
        {
            lastS1++;
            int temp = array[firstUnknown];
            array[firstUnknown] = array[lastS1];
            array[lastS1] = temp;
            firstUnknown++;
        }

    }

    partitionSortRecursive(array, 0, lastS1);
    partitionSortRecursive(array, firstS3, end);

    return array;
}


texts: Can this recursive binary search in C be made more concise?

texts:
Can someone please let me know if they see glaring issues with this code? I tested a handful of cases and it seems to work but in other threads.  I often see much more concisely written versions of this.  I just want to know if anything I have done is superfluous or just stylistically poor form.

#include <stdio.h>

int value = 5;
int values[] = {2,4,5,12,23,34};
int n = 6;

int re_search(int value, int values[], int n);

int main(void)
{

    re_search(value, values, n);
    return 0;
}

int re_search(int value, int values[], int n)
{
    int first = 0;
    int last = n-1;
    int middle = (first+last)/2;

    while (first <= last)
    {
        if (value == values[middle])
        {
            printf("Found it!\n");
            return 0;
        }
        else if (value > values[middle])
        {
          first = middle + 1;
          middle = (first + last) / 2;
          return re_search(value, &values[middle], last-first);
        }
        else
        {
            last = middle - 1;
            return re_search(value, &values[middle], last-first);
        }
        middle = (first + last) / 2;

    }
    printf("Did not find it\n");
    return 0;
}


texts: Graph implementation in C++ using adjacency list

texts:
there is my final code for implementing a Graph in C++ using adjacency list and Object-oriented. I got some help from StackOverflow and it was really helpful, but now I would ask about some advice for improving and a possible way of implementing two functions: isPath( v, w ) for finding if two nodes are connected and isConnected(graph) returning "yes" if the graph is strongly connected otherwise "no".

The code:

#include <iostream>
#include <vector>

using namespace std;

struct Edge {
    int source;
    int target;
};

class Graph
{
private:
    int numOfNodes;
    vector<vector<int>> baseVec;

public:
    Graph(int numOfNodes) : numOfNodes(numOfNodes), baseVec(numOfNodes) {}

    void newEdge(Edge edge) {
        if (edge.source >= numOfNodes || edge.target >= numOfNodes
            || edge.source < 0 || edge.target < 0) {
            cout << "Invalid edge!\n";
            return;
        }
        baseVec[edge.source].emplace_back(edge.target);
        baseVec[edge.target].emplace_back(edge.source);
    }

    void display() {
        for (vector<vector<int>>::size_type i = 0; i < baseVec.size(); i++) {
            cout << "\n Adjacency list of vertex " << i << "\n head: ";
            for (vector<int>::size_type j = 0; j < baseVec[i].size(); j++)
                cout << baseVec[i][j] << " ";
            std::cout << std::endl;
        }
    }
};

int main() {
    int vertex;
    cout << "Enter number of nodes: ";
    cin >> vertex;

    Graph graph(vertex);

    while (true) {
        int source, target;
        cout << "Enter edge ex.1 2 (-1 -1 to exit): \n";
        cin >> source >> target;
        if ((source == -1) && (target == -1))
            break;
        graph.newEdge({ source, target });
    }
    graph.display();
    return 0;
}

I really can't find many things to change, so I wrote the isConnected() function. Maybe it has some weaknesses or errors. Hope it's useful and I'm still waiting for advice. Thank you!

Code inside the class:

    bool isConected(std::vector<int> nodeVec)
        {

            for (st

d::vector<std::vector<int>>::size_type i = 0; i < baseVec.size(); i++)
        {
            if (baseVec[i].empty())
            {
                return false;
            }
        }
        for (std::vector<std::vector<int>>::size_type i = 0; i < baseVec.size(); i++)
        {
            for (std::vector<int>::size_type j = 0; j < baseVec[i].size() + 1; j++)
            {
                if (baseVec[i][j] == nodeVec[j + 1])
                {
                    return true;
                }
            }
        }
    }

The line in main:

std::vector<int> nodeVec;
    for (int i = 0; i < vertex; i++)
    {
        nodeVec.emplace_back(i);
    }

And:

if (graph.isConected(nodeVec) == true)
{
    std::cout << "Yes\n";
}
else
{
    std::cout << "No\n";
}


texts: Implementation of C Standard Library Function ntohl()

texts:
This is an implementation of ntohl() that I wrote as an exercise. ntohl() takes a uint32_t value and returns it unchanged if the host architecture is network-byte-order (big-endian), otherwise the value is converted to host-byte-order.

My version converts to little-endian; is it always the case that host-byte-order is taken to mean little-endian? This appears to be the case, from what I have read, but what if the host architecture is middle-endian? Do real implementations of ntohl() detect other byte-orders, or strictly big- and little-endian?

I am also interested in any comments about the use of a union to detect endianness on the host machine, suggestions and comparison with other methods, and similarly, comments and suggestions relating to the use of bitwise operators to perform the conversion from big-endian to little-endian.

#ifndef _STDINT_H
#include <stdint.h>
#endif

uint32_t my_ntohl(uint32_t netlong)
{
    union {
        uint16_t num;
        uint8_t bytes[2];
    } endian_test = { .bytes = { 0x01, 0x00 }};

    if (endian_test.num == 0x0001) {
        netlong = (netlong << 24) | ((netlong & 0xFF00ul) << 8) |
            ((netlong & 0xFF0000ul) >> 8) | (netlong >> 24);
    }

    return netlong;
}


texts:
I've been working on our application (CQRS and DDD) for awhile now. The application architecture is well layered and thought through.

However we are having difficulties in decide where to put the below code, in such a way that it makes sense from an architectural point of view.

What the code does: It's a generic method which executes a query against the dataset, specified by the generic parameter which inherits a particular interface.
Note: we are not using repositories, since the query is, as the name indicates, for our read layer.

The interface, used by the generic method:

public interface IOrganisationalDbEntry
{
    string OrganisationLevelId { get; set; }
    OrganisationLevelDbEntry OrganisationLevel { get; set; }
}

The generic method, which lives inside our Entity Framework DbContext:

public IList<TDbEntry> GetByOrganisationLevel<TDbEntry>(Guid? organisationLevelId,
    Func<TDbEntry, bool> filter = null)
    where TDbEntry : class, IOrganisationalDbEntry
{
    var organisationLevel = organisationLevelId.HasValue ? organisationLevelId.Value.ToString() : null;

    var query = filter == null ? Set<TDbEntry>() : Set<TDbEntry>().Where(filter);

    IList<TDbEntry> result = query.Where(x => x.OrganisationLevelId == organisationLevel).ToList();

    // If there are no results for the current organisation level
    // => recursive check for entries for parent organisation level
    if (!result.Any() && !string.IsNullOrWhiteSpace(organisationLevel))
    {
        // Get parentOrganisationLevel
        var parentOrganisationLevelId = Set<OrganisationLevelDbEntry>()
            .Where(x => x.Id == organisationLevel)
            .Select(x => x.ParentOrganisationLevelId)
            .SingleOrDefault();

        return
            GetByOrganisationLevel<TDbEntry>(
                string.IsNullOrWhiteSpace(parentOrganisationLevelId)
                    ? (Guid?)null
                    : new Guid(parentOrganisationLevelId), filter);
    }

    return result;
}

As you may be thinking, we have several EF Entities inheriting the IOrganisationalDbEntry. What comes to mind first, is a base Repository. But We do not want to use repositories in our query side, since we want this layer to be as flat as possible.

The next thing that comes to mind is a specific query and queryhandler for this query. Tho this is not acceptable since this method accepts a Func parameter to be able to add extra filter criteria while calling this method, to make it more flexible.

At this moment, this method is living as method on our IDbContext and DbContext implementation. However we are not satisfied with this.  We are wondering whether there is a specific pattern or approach for our case.  Imagine we have more of these methods, I do not want to keep expanding our context. Since this is not what the DbContext should be used for.

EDIT: Everywhere you read CQRS in the above question , replace it by CQS. I didn't want to modify the question since it would make some comments irrelavant.


texts:
This is a simple program to convert miles, yards, feet, and inches appropriately. Everything intended for works but I feel my program is very redundant. How can I make it more efficient and less lines of code? I tried % but failed to find way to increment next values.

#include <iostream>
using namespace std;

//NO GLOBAL VARIABLES

int main()
{
    int m, y, f, i;
    int a, b, c;
    cout << "Enter: ";
    cin >> m >> y >> f >> i;
    cout << "You enter: " << m << "miles " << y << "yards "<< f << "feet " << i    << "inches " << endl;
    cout << "Convert the distance" << endl;

    // 2miles 1761yards 4feet 27inches
    // = 3miles 2yards 3feet 3inches

    //ensure mile is zero or positive
    if(m<0)
    {
        return 0;
    }

    //yard to mile conversion
    for(a=0; a<100; a++)
    {
        if(y<0)
        {
             return 0;
        }
        if(y>1760)
        {
            m++;
            y -= 1760;
        }
        if(y==1760)
        {
            y = 0;
            m++;
        }
        if(y<1760)
        {
            y = y;
        }
    }

    //feet to yard conversion
    for(b=0; b<100; b++)
    {
        if(f>3)
        {
            y++;
            f -= 3;
        }
        if(f==3)
        {
            y++;
            f= 0;
        }
        if(f<3)
        {
            f = f;
        }
        if(f<0)
        {
            return 0;
        }
    }

    //inches to feet conversion
    for(c=0; c<100; c++)
    {
        if(i>12)
        {
            f++;
            i -=  12;
        }
        if(i==12)
        {
            f++;
            i = 0;
        }
        if(i<0)
        {
            return 0;
        }
    }

    cout << "After conversion: " << m << "miles " << y << "yards "<< f << "feet  "   << i << "inches" << endl;
    return 0;
}


texts:
Image transcription:
A company registers for an IPO. All shares are available on the website for bidding during a time frame called the bidding window. At the end of the bidding window an auction logic is used to decide how many available shares go to which bidder until all shares have been allocated, or all the bidders have received the shares they bid for, whichever comes first.
The bids arrive from users in the form of [userid, # shares, bidding price, timestamp] until the bidding window is closed.
The auction logic assigns shares as follows:

The bidder with the highest price gets the # of shares they bid for

If multiple bidders have bid at the same price, the bidders are assigned shares in the order in which they places their bids (earliest bids first)

List the userids of all the users who didn't get even 1 share after all shares have been allocated.
Input

bids
list of lists of ints representing [userid, # shares, $bid, timestamp]
totalShares
total # of shares to be distributed.

Todo
distribute shares amongst bidders and return userids of bidders that got 0 shares.
Share distribution logic:

bidder with highest offer gets all the shares they bid for, and then
if there are ties in $ bid price, assign shares to earlier bidder.

I feel like the solution I came up with is relatively simple. It seems to pass all edge cases I can think of.
Question
I have found a questionable situation:
Bid price and times are the same and there aren't enough shares for all bidders ie: bids is [[0,2,10,0], [1,2,10,0]] and totalShares is 2. It's unclear if 1 share should be given to each, or if userid 0 just gets both.
Code
Can my solution be optimized in anyway?
def getUnallocatesUsers(bids, totalShares):
  s = 0
  for b in bids:
      s += b[1]
  if totalShares >= s: return []  # no losers because enough shares to go around

  bids.sort(key = lambda x: (-x[2],x[3]))  # sort by highest bid, then timestamp for ties
  losers = []
  for b in bids:
    if totalShares <= 0: losers.append(b[0])
    else:
      totalShares -= b[1]
  return losers


texts: Project Euler #4 Largest Palindrome Product

texts:
I'm kinda new to Java (<1 year) but have some background in C and Python.

I've come up with a working solution to Project Euler Problem 4 - Largest Palindrome Product. However, I'm not confident this is "Effective Java"...

All suggestions for improvement are welcome. I'd especially like feedback on the following:

Java language usage
Java library usage
Algorithm performance

/**
 * Palindrome Integer is a whole number which reads the same both ways.
 */
public class PalindromeInteger {

    /**
     * Predicate to determine whether the given number is a palindrome.
     * @param integer
     * @return true if palindrome, false otherwise.
     */
    public static boolean isPalindrome(int integer) {
        String integerStr = String.valueOf(integer);
        StringBuilder sb = new StringBuilder();
        sb.append(integerStr);
        String integerStrReversed = sb.reverse().toString();
        return integerStrReversed.equals(integerStr);
    }

    /**
     * Returns a Set of the palindrome integers which can be made from the product of the given integers.
     * @param multiplicand
     * @param multiplier
     * @return a Set of palindrome integers.
     */
    public static Set getPalindromeProducts(int multiplicand, int multiplier) {
        Set palindromes = new HashSet();
        for (int i = multiplicand; i >= 0; i--) {
            for (int j = multiplier; j >= 0; j--) {
                int product = i * j;
                if (isPalindrome(product))
                    palindromes.add(product);
            }
        }
        return palindromes;
    }

    /**
     * Returns the largest Palindrome integer possible from the product of the two given integers.
     * @param multiplicand
     * @param multipler
     * @return palindromic integer e.g. 9009
     */
    public static int getLargestPalindromeProduct(int multiplicand, int multipler) {
        Set palindromes = getPalindromeProducts(multiplicand,
                multipler);
        return (int)Collections.max(palindromes);
    }
}


texts:
I have created a Java program which generates a key (for activating a piece of software for example) my code works correctly however there are parts of it that I know can be improved. In particular inside the createKey method were I have repeated an if statement in multiple places.

I would appreciate if you can take some time to look at and spots ways to improve my code.I would rather learn first and foremost ways to refine the program in its current form.  Also, if you see any bad habits, let me know.

I plan to save each key to a file and build a validator that allows input and references the file.

  Description

  Creates a key of 20 letters and numbers - the letters and numbers are
  set a weighting, if two is returned as a weight for a letter and
  three for numbers.

  AA232BC433 ... so two letters then three numbers and so on.

  10 numbers and 10 letters are then selected.

  Each is chosen through a loop that runs 10 times and randomly assigns
  a value from each final array into a set of 'chosen' values.

  The create key method then cycles through various loops which use the
  weights to add a further random selection of the chosen values -
  checks are added which ensure that the string builder stops adding new
  values when the length is 20.

public class KeyTestDrive {

public static void main(String[] args) {
    Key key = new Key();
    key.createKey();
}

}

import java.util.Random;

public class Key {

private final int[] possibleNumbers = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
private final char[] possibleLetters = { 'A', 'B', 'C', 'D', 'E', 'F', 'G',
        'H', 'I', 'J', 'K', 'L', 'M', 'O', 'P', 'Q', 'R', 'S', 'T', 'U',
        'V', 'W', 'X', 'Y', 'Z' };

Random randomNum = new Random();
StringBuilder key = new StringBuilder();

public void createKey() {
    int letterWeighting = determineLetterWeigthing();
    int numberWeighting = determineNumberWeigthing();

    int[] chosenNumbers = selectNumbers();
    char[] chosenLetters = selectLetters();

    int randomIndex;

    boolean isSizeTwenty = false;

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

        if(isSizeTwenty == true){
            break;
        }

        for (int j = 0; j < letterWeighting; j++) {
            randomIndex = randomNum.nextInt(9);
            key.append(chosenLetters[randomIndex]);

            if(key.length() == 20){
                isSizeTwenty = true;
                break;
            }
        }

        if(isSizeTwenty == true){
            break;
        }

        for (int k = 0; k < numberWeighting; k++) {
            randomIndex = randomNum.nextInt(9);
            key.append(chosenNumbers[randomIndex]);

            if(key.length() == 20){
                isSizeTwenty = true;
                break;
            }
        }

        if(isSizeTwenty == true){
            break;
        }

    }
    System.out.println(key.length());
    System.out.println(key);
}

private char[] selectLetters() {
    char[] chosenLetters = new char[10];

    for (int j = 0; j < 10; j++) {
        int randomIndex = randomNum.nextInt(possibleLetters.length);

        chosenLetters[j] = possibleLetters[randomIndex];
    }

    return chosenLetters;
}

private int[] selectNumbers() {
    int[] chosenNumbers = new int[10];

    for (int j = 0; j < 10; j++) {
        int randomIndex = randomNum.nextInt(possibleNumbers.length);

        chosenNumbers[j] = possibleNumbers[randomIndex];
    }

    return chosenNumbers;
}

private int determineLetterWeigthing() {
    int letterWeighting;
    letterWeighting = randomNum.nextInt(4) + 1;

    return letterWeighting;
}

private int determineNumberWeigthing() {
    int numberWeighting;
    numberWeighting = randomNum.nextInt(4) + 1;

    return numberWeighting;
}
}


texts: Sum of multiples of 3 or 5 below 1000 in Scala

texts:
I'm in the process of learning Scala, and started working through a series of coding puzzles that I've done previously in other languages.

For example, this solution, coded in Erlang:

sum_multiples(Max, Max, Acc) -> io:format("The sum of all the multiples of 3 or 5 below ~p: ~p~n", [Max, Acc]);
sum_multiples(Current, Max, Acc) when (Current rem 3 == 0) or (Current rem 5 == 0) -> sum_multiples(Current + 1, Max, Current + Acc);
sum_multiples(Current, Max, Acc) -> sum_multiples(Current + 1, Max, Acc).

Now, doing this same problem in Scala, I wrote this:

val max = 1000
println(s"The sum of all the multiples of 3 or 5 below ${max}: " + sum_multiples_recursive(1, max, 0))
def sum_multiples_recursive(current: Int, max: Int, acc: Int): Int = {
  if(current < max){
    if(current % 3 == 0 || current % 5 == 0){
      sum_multiples_recursive(current + 1, max, current + acc)
    } else {
      sum_multiples_recursive(current + 1, max, acc)
    }
  } else {
    acc
  }
}

I'd like to see what an experienced Scala coder might write, what Scala idioms might come into play.


texts: Is this a proper way of "loading" views in PHP?

texts:
As a learning exercise, I'm developing my own PHP framework. I'm looking for a way to "load views" (kinda like CodeIgniter does it), without polluting my general scope.

I came up with the following, basic, example:

$data['test'] = 'Hello world';

$str = load_view($data, true);
echo $str;

function load_view($data, $store = false) {
    extract($data);

    ob_start();
    include('view.php');

    if($store)  return ob_get_clean();
    else        ob_end_flush();
}

// End of file

view.php

<?php echo $test; ?>

I could also use load_view($data), which would output the contents of view.php immediately.

Edit: I'm mostly worried about performance. As Peter pointed out, I'm aware that the function should be a class method that's seperate from the logic.


texts:
We have the following equation (weighted phase Laplacian):

\$c_{i,j} = U(i,j)\Delta^{^x}_{i,j} - U(i-l, j)\Delta^{x}_{i-1,j} + V(i,j)\Delta^{y}_{i,j} - V(i,j-1)\Delta^{y}_{i,j-1}\$

Where

\$U(i,j) = min(w^2_{i+1}, w^2_{i+1})V(i,j) = min(w^2_{j+1}, w^2_{j+1})\$

with \$U, V, \Delta \$ (N,N) matrices

I coded the following code:

def compute_Weights(w):
    U = np.zeros_like(w)
    V = np.zeros_like(w)
    U = np.minimum(w[1:, :]**2, w[:-1, :]**2)
    V = np.minimum(w[:, 1:]**2, w[:, :-1]**2)

    """add the last ones rows and cols
    """
    U = np.vstack((U, U[-1]))
    V = np.vstack((V.T, V.T[-1])).transpose()

    return U, V

def Gradient(p1, p2):
    r = p1 - p2
    if r > np.pi:
        return r - 2 * np.pi
    if r < -np.pi:
        return r + 2 * np.pi
    return r
"""
    phase is not flattened
    wts are flattened
"""
def ComputePhaseLaplacian(phase, U, V):
    rows, cols = phase.shape
    phi = phase.flatten()
    rho = np.zeros_like(phi)

    for j in range(rows):
        for i in range(cols):
            k = j * rows + i
            k1 = k + 1 if i < cols - 1 else k - 1
            k2 = k - 1 if i > 0 else k + 1
            k3 = k + cols if j < rows - 1 else k - cols
            k4 = k - cols if j > 0 else k + cols

            w1 = U[k]
            w2 = U[k-1] if i > 0 else U[k]
            w3 = V[k]
            w4 = V[k-cols] if j > 0 else V[k]

            rho[k] = w1 * Gradient(phi[k], phi[k1]) \
                + w2 * Gradient(phi[k], phi[k2]) \
                + w3 * Gradient(phi[k], phi[k3]) \
                + w4 * Gradient(phi[k], phi[k4])

    return rho

I want to know if there is a "pythonic way" to write this. I'm a C/C++ programmer so this was my perspective. Maybe something to avoid to work with flattened arrays, and to work with 2D arrays.

I.e:

phase = np.load('phase.npy') #phase 512x512 float array
U,V = ComputeWeigths(W) #W 512x512 float array with values in (0,1)
uphase = ComputePhaseLaplacian(phase, U, V) #uphase 512x512 float array


texts: What do you think of this improvement of Linq's GroupBy method?

texts:
Linq already has a set of GroupBy methods for enumerable, which returns IEnumerable<IGrouping<TKey, TSource>>. I dislike this return type because it means I have to do a where query everytime I want to find a group. I try to make something that returns a dictionary instead, as below:

 public static class GroupByExtension
    {
        public static Dictionary<TKey, List<TSource>> GroupToDictionary<TSource, TKey>(
            this IEnumerable<TSource> source,
            Func<TSource, TKey> keySelector)
        {
            return source.GroupBy(keySelector).ToDictionary
                (grouping => grouping.Key, grouping => grouping.ToList());
        }
    }

I can test it like this

List<int> list = new List<int>() { 1, 2, 33, 4, 20, 43, 21, 93, 26, 31, 113 };
Dictionary<int, List<int>> numbersGroup = list.GroupToDictionary(i => i / 10);
//group number by result of division by ten.

So, I can call numbersGroup[1], numbersGroup[3], etc. as opposed to the more clumsy and less efficient Where's clauses if I only have IEnumerable<IGrouping<TKey, TSource>>

IEnumerable<IGrouping<int, int>> numbersGroup2 = list.GroupBy(i => i / 10);
IGrouping<int, int> group =
            numbersGroup2.Where(grouping => grouping.Key == 3).First();
//and this only returns an IGrouping, not a proper list,
//and where can be expensive for large list because it uses O(n) IIRC
//the first() could have also been avoided because we know that the keys are unique

What do you think of this code? What drawback do you see? And what is the reason Microsoft use  IEnumerable<IGrouping<TKey, TSource>>


texts:
I have written a basic PHP upload script a few years ago and recently I discovered some phishing html pages in the website's root.

This website is located in /www/sitename, while I upload the files to /gstorage/sitename, which can't be accessed from the web.

I have found a lot of html files in /www/sitename and it seems like they somehow came through the upload.php file, as I've found a POST from a specific ip to this file in the logs before the files appeared and then that IP started sending post to those files.

Here's the code:

include('inc.php');
$disallowed = array('php', 'php5');

if(isset($_FILES['upl']) && $_FILES['upl']['error'] == 0){

    $extension = pathinfo($_FILES['upl']['name'], PATHINFO_EXTENSION);

    if(in_array(strtolower($extension), $disallowed)){
        echo '{"status":"error", "message":"no PHP"}';
        exit;
    }
    $url = findNewURL();
    $size = formatSizeUnits($_FILES['upl']['size']);
    if(move_uploaded_file($_FILES['upl']['tmp_name'], '/gstorage/edited/'.$url)){
        try {
            $stmt = $db->prepare("INSERT INTO files(url, filename, size, type) VALUES(:url,:filename,:size, :type)");
            $stmt->execute(array(":url" => $url, ":filename" => $_FILES['upl']['name'], ":size" => $size, ":type" => $_FILES['upl']['type']));
        } catch(PDOException $ex) {
            echo 'Error!';
            echo $ex->getMessage();
        }

        echo '{"status":"success", "link": "http://edited.org/'.$url.'"}';
        exit;
    }
}
echo '{"status":"error"}';
exit;

Where could the vulnerability be?


texts:
I am using MVC+Angular. In MVC, I created partial views for search, listing, etc. I show them using:

@Html.Partial("_Search")

@Html.Partial("_Featured")

@Html.Partial("_Listing")

Previously each partial view had an ng-app and ng-controller.

Now I combined them all into one ng-app. I added ng-app to master page, and I just used the ng-controller in every partial view.

 <div ng-controller="Search" class="slide">
some ng-repeat goes here
</div>

Angular code:

angular.module("ProductListing", [])
.controller("Search", function ($scope,$templateCache, $http) {
    $(document).on("keyup", ".txtTempleSearch", function () {
        var searchTerm=$(this).val();
        $.get(configUrl + "SearchGrouped/" + searchTerm, function (data) {
            $scope.Results = JSON.parse(data)[0].result;
                $scope.$apply();
        });
    });
})
.controller('featured', function ($scope) {
    $.get(configUrl + 'Featured', function (data) {
        $scope.featuredTemples = data;
        $scope.$apply();
    });
})

Is this approach correct or is it better in terms of maintainability/performance/best practice to have a different ng-app for different partial views and use angular.bootstrap?


texts: Implementing binary output to a file in C++11

texts:
I would like to have a class which supports outputting bits into a file. This is what I came up with but I fear there are many poor decisions. Should I inherit from a std::ofstream instead of keeping it as a data member?

class OFBitStream final
{
    static const std::size_t bitset_size = 8 * sizeof(unsigned long);
    std::bitset<bitset_size> bitset;
    std::size_t current_bit;

    std::ofstream &_stream;

    void flush() {
        for (auto i = current_bit; i < bitset_size; ++i) {
            bitset[i] = false;
        }

        auto buffer = bitset.to_ulong();
        while (buffer != 0) {
            _stream.write(reinterpret_cast<char *>(&buffer), 1);
            buffer >>= 8;
        }
    }
 public:
    OFBitStream(std::ofstream &stream)
        : bitset(0), current_bit(0), _stream(stream) {}

    ~OFBitStream() {
        flush();
        _stream.close();
    }

    friend OFBitStream &operator<<(OFBitStream &dst, const bool &data)
    {
        dst.bitset[dst.current_bit++] = data;

        if (dst.current_bit == dst.bitset_size) {
            dst.flush();
            dst.current_bit = 0;
        }

        return dst;
    }
};


texts: Graceful way to find combinations in JavaScript

texts:
I'm looking for combinations, not permutations, and have found some really great examples ranging from using flatMap such as https://stackoverflow.com/a/54329187/669843

The result of ['a', 'b', 'c'] would be an array of arrays of 3 (a, b, and c). The result I'm looking for would also contain arrays of length 1 and 2.

Example:

['a']
['b']
['c']
['a', 'b']
['a', 'b', 'c']
['a', 'c']
...

I'm accomplishing the results with something like this but this seems extraordinarily awful and requires de-duplication.

for(let i = 0; tci < combo.length; tci++) {
  let newcombo = [allitems[item]].concat(combo.slice(tci, combo.length));
  ...
  push newcombo;


texts: C++ Generic Callback class with removable listeners by unique id

texts:
I'm quite new to the STL.
Does this make sense? Is there a better way of removing the listeners instead of using shared_ptr while keeping the code short and simple? Is there something in the STL to replace this?
Class:
template<class ... Arguments>
class Callback
{
    using Function = std::function<void(Arguments ...)>;
    using FunctionPtr = std::shared_ptr<Function>;
    using Functions = std::vector<FunctionPtr>;

public:
    FunctionPtr addListener(Function f) {
        FunctionPtr fp = std::make_shared<Function>(f);
        _functions.push_back(fp);
        return fp;
    }

    void removeListener(FunctionPtr fp){
        _functions.erase(std::find(_functions.begin(), _functions.end(), fp));
    }

    void operator()(Arguments ... args) const{
        for (auto & f : _functions)
            f.get()->operator()( args ... );
    }

private:
    Functions _functions;
};

Use case:
int main()
{
    Callback<int> callback;

    callback.addListener([](int i){
        std::cout << "Listener 1 -> Input is " << i <<  std::endl;
    });

    auto id = callback.addListener([](int i){
        std::cout << "Listener 2 -> Input is " << i <<  std::endl;
    });

    callback.addListener([](int i){
        std::cout << "Listener 3 -> Input is " << i <<  std::endl;
    });

    callback.removeListener(id);

    callback(71);
}

Output is:
Listener 1 -> Input is 71
Listener 3 -> Input is 71


texts: Cracking the Coding Interview — 1.5 One Away

texts:
I would like to know any suggestions about to improve my code solution and your rating of my approach to the problem, I based my code on the fact that if the strings have different length removing one character from the longer string is equal to add one character to the shorter one.

Description

  One away : There are three types of edits that can be performed on
  strings: insert a character, remove a character and replace a
  character. Given two strings, write a function to check if they are
  one edit (or zero edits) away.

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

static int helper_one_way(const char *str1, const char * str2,
                          size_t len1, size_t flag) {
    size_t nchars = 0;
    size_t i, j;

    for (i = 0, j = 0; i < len1; ++i, ++j) {
        if (str1[i] != str2[j]) {
            if (++nchars > 1) return 0;
            if (flag && i) --i;
        }
    }
    return 1;
}

/* check if str1 can be obtained from string2 adding, deleting, replacing
 * at last one char */
int one_way(const char *str1, const char *str2) {
    size_t len1 = strlen(str1), len2 = strlen(str2);
    size_t diff = abs(len1 - len2);

    if (diff > 1) return 0;
    if (!diff) return helper_one_way(str1, str2, len1, 0);
    if (len1 > len2) return helper_one_way(str2, str1, len2, 1);
    return helper_one_way(str1, str2, len1, 1);
}

int main(void) {
    printf("%d\n", one_way("pale", "ple"));
    printf("%d\n", one_way("pales", "pale"));
    printf("%d\n", one_way("pale", "bale"));
    printf("%d\n", one_way("pale", "bake"));
    return 0;
}


texts: Better card validity check in JS card game

texts:
I am writing a card game in Javascript. The game is played with a 32 card deck.

When a card is selected to be played by a user, i do a validity check on the server to check whether it matches the games rules.

These are

A card may be played when it matches either the color or the value of the last card on the stack
If a 7 is played, the next player must either draw 2 cards or counter with another 7. If he draws, he may play another card that complies the rule above.
A jack may be played anytime when there is no 7 to be countered or the player has drawn. It does not have to match the color or value of the last card. When a player plays a jack, he may decide the color of the next card to be played.

I created a class of game that, amongst others, implements a function iscardLegal()

Game.prototype.isCardLegal = function(card,player){

    if(player.flags.forcedDraw > 0 && card.value !== '7'){
        player.setTask('forced draw');
        return false;
    }

    // A jack may be played anytime if there is no 7 on top of the stack
    if(card.value === 'J'){
        return true;
    }

    if(this.forcedColor && this.forcedColor !== card.color){
        player.setTask('color mismatch');
        return false;
    }

    // If there is a forced color due to the playing of a jack, we must ignore the stack#s top card color
    if(this.forcedColor && this.forcedColor === card.color){
        return true;
    }

    if(this.lastCardOnStack().color !== card.color && this.lastCardOnStack().value !== card.value){
            player.setTask('invalid card');
            return false;
    }

    return true;

};

I am unhappy with this function because I end up with a chunk of if rules that need to be in a certain order to match all the rules. If I imagine writing a slightly more complex game, I think this would be unmaintainable.

I am looking for ideas and / or examples of better implemenations of this functionality.


texts: Inverted index in Clojure - performance vs. idiomatic code

texts:
I have this code to create an inverted index from a directory of text files:

(def p (re-pattern #"[^\p{L}&&[^\p{M}]]"))

(defn invert[file]
  (let [f (.getName file)
        tokens (.split p (lower-case (slurp file)))]
        (into {} (mapcat #(hash-map % #{f}) tokens))))

(defn build-index[dirname]
  (reduce #(merge-with union %1 %2) (map invert (.listFiles (java.io.File. dirname)))))

Can you improve it / make it more idiomatic? My concern is performance. I'm testing it with 10k files of 10k in size, and I can make it about 20-30% faster if I use transients like this:

(defn add![idx file]
  (let [f (.getName file)]
    (loop [idx idx
           tokens (.split p (lower-case (slurp file)))]
      (if-not (seq tokens) idx
              (recur (assoc! idx (first tokens) (union (idx (first tokens)) #{f})) (rest tokens))))))

(defn build-index[dirname]
  (loop [files (.listFiles (java.io.File. dirname))
         idx (transient {})]
    (if-not (seq files) (persistent! idx)
            (recur (rest files) (add! idx (first files))))))

Full code including test file generator here:

https://github.com/dbasch/closearch

Any feedback is welcome.


texts:
After reading way too much into what fizzbuzz was I though PowerShell could easily have its way with this.

Function Get-FizzBuzz{
    param(
        [Parameter(Position=0,ValueFromPipeline=$true)]
        [int]$Number
    )

    process{
       $result = switch($Number){
            {$_ % 3 -eq 0}{"Fizz"}
            {$_ % 5 -eq 0}{"Buzz"}
            default{$_}
       }
       -join $result

    }
}

What we have is a function that accepts pipeline input. For each number that is passed we run it through a switch. Be default it will check against both clauses. So when it hit 15 it will run for Fizz and Buzz. If neither are matched then the number just continues on without being converted. Since FizzBuzz must appear on the same line we capture the $result and use -join to concatenate the elements. This only has an effect on the $result when it has more than element.

Sample Output

PS C:\Windows\system32> Get-FizzBuzz -Number 15
FizzBuzz

PS C:\Windows\system32> 1..15 | Get-FizzBuzz
1
2
Fizz
4
Buzz
Fizz
7
8
Fizz
Buzz
11
Fizz
13
14
FizzBuzz

Not sure what could be done beyond this. I suppose you could argue that a filter as supposed to a function would be more terse. I leave that to a reviewer to chew on.


texts: Parsing CSV file with BufferedReader vs Scanner

texts:
I have to parse a file line-by-line and in single line I have split by ",". The first string is the name and the second is the count.

Finally, I have to display the Key and Count, for example:

Peter,2
Smith,3
Peter,3
Smith,5

I should display as Peter 5 and Smith 8.

I confused about choosing between BufferedReader vs Scanner.  I went through this link and came up with these two approaches. I would like to get your reviews.

BufferedReader

private HashMap<String, MutableLong> readFile(File file) throws IOException {
    final HashMap<String, MutableLong> keyHolder = new HashMap<>();
    try (BufferedReader br = new BufferedReader(new InputStreamReader(
            new FileInputStream(file), "UTF-8"))) {
        for (String line; (line = br.readLine()) != null;) {
            // processing the line.
            final String[] keyContents = line
                    .split(KeyCountExam.COMMA_DELIMETER);
            if (keyContents.length == 2) {
                final String keyName = keyContents[0];
                final long count = Long.parseLong(keyContents[1]);
                final MutableLong keyCount = keyHolder.get(keyName);
                if (keyCount != null) {
                    keyCount.add(count);
                    keyHolder.put(keyName, keyCount);
                } else {
                    keyHolder.put(keyName, new MutableLong(count));
                }
            }

        }
    }
    return keyHolder;
}

private static final String COMMA_DELIMETER = ",";
private static volatile Pattern commaPattern = Pattern.compile(COMMA_DELIMETER);

I have used MutableLong, since I don't want to create a BigInteger each time. Again, it may be a very big file and I don't have control on how max a key can occur.
Scanner and two delimiters

private static final String LINE_SEPARATOR_PATTERN = "\r\n|[\n\r\u2028\u2029\u0085]";
private static final String LINE_PATTERN = ".*(" + LINE_SEPARATOR_PATTERN
        + ")|.+$";
private static volatile Pattern linePattern = Pattern.compile(LINE_PATTERN);

I have went through the hasNext in Scanner, and to me, there is no harm in switching the Pattern. And I believe from Java 7, Scanner does have a limited buffer and can be enough for this kind of file.

Does anyone prefer Approach 2 over Approach 1, or do we have any other option than this?  I just did sop for testing purpose. Obviously the same code in approach 1 would replace here. Using split in Approach 1 would create multiple String instances, which can be avoided here, by scanning a char sequence.

private HashMap<String, BigInteger> readFileScanner(File file)
            throws IOException {
        final HashMap<String, BigInteger> keyHolder = new HashMap<>();
        try (Scanner br = new Scanner(file, "UTF-8")) {
            while (br.hasNext()) {
                br.useDelimiter(commaPattern);
                System.out.println(br.next());
                System.out.println(br.next());
                br.useDelimiter(linePattern);
            }
        }
        return keyHolder;
    }


texts: Changing attributes in Django Objects outside of iteration

texts:
I'm adding three attributes to a Django QuerySet that represents a hierarchical tree structure:

a display_name which is added to all objects
the id of the object's parent (or immediate_parent) which is added to all objects based on a condition
a boolean is_parent field that should be added if and only if the object has children in the hierarchy.

The first two proved to be pretty simple to add while iterating over the QuerySet. The third proved more difficult because I was trying to modify an element outside of the one in the iteration. I tried to modify using both the .get() and the .filter() methods from the QuerySet API, but it didn't work to modify the original object. You can read more about that in the original stack overflow question.

Eventually I came up with this solution that involves iterating over the QuerySet 3 times:

causelist_data = CauseHierarchy.objects.filter(cause_set_version_id=cause_set_version_id).extra(order_by=['sort_order']).prefetch_related('cause_id','parent_id')
for c in causelist_data:
    c.display_name = c.cause_id.cause_name + " (" + c.cause_id.acause + ")"
    if len(c.path_to_top_parent.split(',')) == 1:
        c.immediate_parent = c.path_to_top_parent.split(',')[-1]
    else:
        c.immediate_parent = c.path_to_top_parent.split(',')[-2]
parents = []
for c in causelist_data:
    parents.append(int(c.immediate_parent))
for c in causelist_data:
    if int(c.cause_id_id) in parents:
        c.is_parent = True

This is pretty slow. Is there any way I can modify the parent object in the original iteration? (Any other suggestions welcome as well)


texts: Generating all size-k consecutive subsets in Haskell

texts:
I am interested in splitting any list into consecutive subsets based on a k-value.  For example, [1,2,3,4,5] splits into [[1,2],[2,3],[3,4],[4,5]] when k=2.  If k is bigger than the entire list, then an empty list will be returned.

I am unhappy with my current solution and would like to have suggestions on how to improve it.  Specifically I would like to be able to code a more terse solution.  I find that terseness in functional programming languages, such as Haskell, is important to keep in mind.  I feel that there is a way of expressing my Haskell solution using a fold possibly, but I just cannot see how at this moment.

consSizeK :: Int -> [a] -> [[a]]
consSizeK _ [] = []
consSizeK k list@(_:tail)
    | k > length list = []
    | otherwise = (take k list) : consSizeK k tail


texts: Find number of neighbour pairs in the input tree

texts:
My code works with small binary tree but with big ones (around 10000 nodes) it takes 15 sec to process.

For small binary tree I'm always getting correct answer and it is fast.

How can I make my program faster for big binary tree?

  (x, y) is a neighbour pair when the depth of x and y is the same, the
  node color of x and y is the same, the node key of x and y are equal
  and there is no other node of the same node color between x and y on the horizontal line connecting x and y in standard drawing..

  Input

  The first line of input contains number of nodes and root node. Next,
  each line describes each node.

  The first value is the node label, the second value is the node key,
  the third and the fourth values represent the labels of the left and
  right child respectively, and the fifth value represents the node
  color, white is 0, black is 1. If any of the children does not exist
  there is value 0 instead of the child label at the corresponding place

  Output

  number of neighbour pairs in the input tree

My code

from collections import defaultdict
def read_input(inputstring):
    inputs = inputstring.split(" ")
    nodes_number = int(inputs[0])
    root_node = int(inputs[1])
    input_tree = [list(map(int, input().split())) for _ in range(nodes_number)]
    tree = {}
    result = {}
    def depth(node, count):
        for i in input_tree:
            node_label = i[0]
            if node_label == node:
                tree.setdefault(count, []).append(i)
                l_node, r_node = i[2], i[3]
                if l_node != 0 and r_node != 0:
                    depth(l_node, count+1)
                    depth(r_node, count+1)

                elif l_node != 0:
                    depth(l_node, count+1)

                elif r_node != 0:
                    depth(r_node, count+1)
    depth(root_node, 0)

    def neighbour_pair(input_tree):
        for value in input_tree.values():
            for i in range(len(value)):
                for j in range(len(value)):
                    if j > i:
                        if value[i][1] == value[j][1] and value[i][4] == value[j][4]:
                            result.setdefault(value[i][0], []).append(value[j][0])
    neighbour_pair(tree)
    return len(result)
if __name__ == '__main__':
    print(read_input(input()))

Example of small input

13 5
7 50 0 0 1
2 70 10 11 0
4 30 9 0 0
6 70 0 0 0
1 90 8 12 0
9 90 0 2 1
13 90 0 6 0
5 30 4 3 0
12 80 0 0 1
10 50 0 0 1
11 50 0 0 0
3 80 1 13 0
8 70 7 0 1

Its associated representation:

The labels are written in the yellow rectangle at the corresponding nodes. Their key is the number in the black or white oval. For this example, the neighbour pairs are (1, 13), (2, 6), (10, 7).

As such, the output of the program for this tree is:

3


texts:
I'm new to python and created this small program. It's basically a skeleton for a simple text-based RPG. The program is one menu that allows you to:

Create a Character
View Character Stats/Attributes
Load Character
Battle
Save
Quit

I'm looking for constructive criticism from any angle, be that if I comment too much, if I'm not comment to specific, if my variables are to implicit, or any other flaws in my programming. Perhaps a better way for a menu but this time using tuples or dictionaries. Perhaps you noticed a redundancy in my code.

I'd also appreciate if someone can give me some direction if my goal is to make a top-side RPG. Should I use tkinter? PyGame? Tmxlib? Or should I just focus on the programming aspect for now until I'm a bit more experienced before tackling a library?

# Pickle for object serialization, OS to check if character data file exist
import pickle
import os

class Character(object):
    def __init__(self, name, exp):
        self.name = name
        self.exp = exp
        self.lvl = self.exp/100

    # Simple character statistic display using the new format technique instead of %
    def stats(self):
        print ("Character stats: {}, you are level {} with {} experience points!".format(self.name,self.lvl,self.exp))

    # Simple battle program, has one paramter for the amount of EXP
    # self.lvl is necessary to update the self.lvl variable with the actual level
    def battle(self,exp):
        self.exp = self.exp + exp
        self.lvl = self.exp/100
        print ("Successful battle! {} experienced gained!".format(exp))
        self.stats()

# Not sure what to comment for starting variables? "Global variables?" "Initial variables"?
# sets menu on loop and player sees the main menu
loop_menu = True
menu_choice = "main"

# error prevention
new_character = None
fileCheck = "charData"

# menu_display
# 1 = menu with input
# "new" = input
menu_display = 1

# menu_error
# None = no error yet
# 1 = invalid input received
menu_error = None

while loop_menu == True:
    if menu_display == 1:
        print("New Character, Stats, Load, Battle, Save or Quit?")
        menu_choice = (input("Input your choice: ")).lower()
        menu_display = 0

    if menu_display == "new" and menu_error == None:
        menu_choice = (input("What would you like to do now?: ")).lower()

    if menu_display == "new" and menu_error == 1:
        menu_choice = (input("Please type a real answer, what now?: ")).lower()
        menu_error = None

    # Text Formatting
    print ("\n", end="")

    if menu_choice == "new":
        chardata = ["Foo", 300]
        new_character = Character(*chardata)
        print ("New character created!")
        new_character.stats()

    elif menu_choice == "stats":
        if new_character == None:
            print ("Sorry, you can't check your stats, you haven't made a new/loaded a character yet!")

        else:
            new_character.stats()

    elif menu_choice == "load":
        if os.path.exists(fileCheck):
            print("Load successful!")
            inFile = open("charData", "rb")
            new_character = pickle.load(inFile)
            inFile.close()

        else:
            print("You can't load yet! Data file not created!")
            print("You can use the \"save\" feature after you've created a character to automatically create a save file!")

    elif menu_choice == "battle":
        if new_character == None:
            print("You can't battle, you haven't made a character")

        else:
            new_character.battle(100)

    # Saving character to data file
    elif menu_choice == "save":
        print ("Character saved!")
        outFile = open("charData", "wb")
        pickle.dump(new_character, outFile)
        outFile.close()

    elif menu_choice == "quit":
        print ("Quitting program...")
        break

    else:
        menu_error = 1

    # Text Formatting
    print ("\n", end="")

    # Skips the instructions and goes straight to the input
    menu_display = "new"


texts: ReactJS Calling an API and rendering results

texts:
I am currently learning JS Frameworks, right now exploring React and wanted to make sure I keep everything in order, as in: the logic of working with React, code quality, any shortcomings, good/bad practices etc?

The code renders a simple Search panel that will allow to call an API, get the results (if any) and render the results on the page.

import React from "react";
import "./App.css";
import axios from "axios";

var Style = {
  marginRight: "22px"
};

var Style2 = {
  display: "none"
};

const API_CALL = "xxx";

class SearchForm extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      value: "",
      errorValue: "",
      countryCode: "",
      VATNumber: "",
      valid: "",
      name: "",
      address: "",
      isLoading: false,
      isSubmitted: false
    };

    this.handleChange = this.handleChange.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
  }

  renderField() {
    return (
      <form onSubmit={this.handleSubmit}>
        Search VAT:
        <input type="text" onChange={this.handleChange} style={Style} />
        <input type="submit" value="Submit" />
      </form>
    );
  }

  render() {
    return (

Reference: EE100247019

        {this.renderField()}

        <Loader loading={this.state.isLoading} />
        {this.state.isSubmitted && (
          <Result
            country={this.state.countryCode}
            number={this.state.VATNumber}
            name={this.state.name}
            address={this.state.address}
            error={this.state.errorValue}
            valid={this.state.valid}
            loading={this.state.isLoading}
          />
        )}

    );
  }

  handleChange(event) {
    this.setState({ value: event.target.value.trim() });
  }

  handleSubmit(event) {
    this.setState({ isLoading: true, isSubmitted: false });
    Style2 = {
      listStyleType: "none",
      textAlign: "left",
      display: "block",
      border: "1px solid white",
      marginTop: "50px"
    };
    axios
      .get(API_CALL + this.state.value)
      .then(res =>
        this.setState({
          countryCode: res.data.CountryCode,
          VATNumber: res.data.VATNumber,
          name: res.data.Name,
          address: res.data.Address,
          valid: res.data.Valid,
          isLoading: false,
          isSubmitted: true
        })
      )
      .catch(error =>
        this.setState({
          valid: false,
          errorValue: this.state.value,
          isLoading: false,
          isSubmitted: true
        })
      );

    event.preventDefault();
  }
}

function Loader(props) {
  if (!props.loading) {
    return null;
  }
  return
 Loading ...
;
}

function Result(props) {
  if (!props.valid) {
    return (

        Invalid value "{props.error}"

        Please enter valid VAT Number

    );
  } else {
    return (

          Country code:
          {props.country}

          VAT Number:
          {props.number}

          Product name:
          {props.name}

        Address:
        {props.address}

    );
  }
}

export default SearchForm;


texts: Parsing length of work experience using Composite design pattern

texts:
I want to get a number from given text (if it exists) which is about work experience in months. I assumed that number is in months when in the text one writes for example "27 miesięcy" or "27 miesiecy" or "27miesięcy" or "27miesiecy, and in years if one writes "3 lat" or "3lat".

Class ExperienceAlg0 is mainly responsible for that. I wanted to make it flexible and open for adding another rules/algorithms "how to find the number of months in the text". I tried to use composite design pattern.

The algorithm works well, but is the design OK according to OOP and Uncle Bob?

import java.util.ArrayList;
import java.util.List;

import org.junit.Test;

import junit.framework.TestCase;

public class TestExperienceAlg0 extends TestCase {

/*
**
** this test class unit test show how app works
**
*/
    @Test
    public void testCalc1() {
        // Given:
        String text = "programuję od 5 lat.";

        // When:
        List<ExperiencePattern> patternList = new ArrayList<>();
        patternList.add(new ExperiencePatternMonths());
        patternList.add(new ExperiencePatternYears());
        ExperienceAlg0 alg = new ExperienceAlg0(patternList);
        int result = alg.calc(text);

        // Then:
        assertEquals(0, result);
    }
}

public interface ExperiencePattern {

    public int getPattern(String text);

}

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class ExperiencePatternMonths implements ExperiencePattern{

    @Override
    public int getPattern(String text) {
        int result = 0;
        Pattern p = Pattern.compile("\\d+miesi[e|ę]cy|\\d+ miesi[e|ę]cy");
        Matcher m = p.matcher(text);

        while (m.find()) {
            String tmp = m.group();
            tmp = tmp.replaceAll("\\D", "");
            int x = Integer.parseInt(tmp);
            if (x < (40 * 12)) { // assuming that the max experience is 40
                                    // years.
                result = x;
                ;
            }
        }
        return result;
    }

}

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class ExperiencePatternYears implements ExperiencePattern{

    @Override
    public int getPattern(String text) {
        int result = 0;
        Pattern p = Pattern.compile("\\d+lat|\\d+ lat");
        Matcher m = p.matcher(text);

        while (m.find()) {
            String tmp = m.group();
            tmp = tmp.replaceAll("\\D", "");
            int x = Integer.parseInt(tmp);
            if (x < 40) { // assuming that the max experience is 40 years.
                result = x * 12;
            }
        }
        return result;
    }

}

public interface Algorithm <T> {

    public T calc(String textToLower);

}

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class ExperienceAlg0 implements Algorithm<Integer> {

    List<ExperiencePattern> listPatterns;

    public ExperienceAlg0(List<ExperiencePattern> list){
        listPatterns = list;
    }

    @Override
    public Integer calc(String text) {
        List<Integer> result = new ArrayList<>();

        for(ExperiencePattern ep : listPatterns){
            result.add(ep.getPattern(text));
        }

        Collections.sort(result, new DescendingComparator());
        return result.get(0);
    }

}

import java.util.Comparator;
public class DescendingComparator implements Comparator<Integer>{

    @Override
    public int compare(Integer x1, Integer x2) {

        return x2 - x1;
    }

}


texts: Are these MySQL Abstraction Classes safe from SQL Injection?  Can they be made safe?

texts:
I was looking at this website:

http://www.devshed.com/c/a/MySQL/Creating-User-Models-in-PHP-and-MySQL/1/
and
http://www.devshed.com/c/a/MySQL/Creating-User-Models-in-PHP-and-MySQL/2/

In the first one they have methods such as:

/**
     * Perform a SELECT statement
     */
    public function select($table, $where = '', $fields = '*', $order = '', $limit = null, $offset = null)
    {
        $query = 'SELECT ' . $fields . ' FROM ' . $table
               . (($where) ? ' WHERE ' . $where : '')
               . (($limit) ? ' LIMIT ' . $limit : '')
               . (($offset && $limit) ? ' OFFSET ' . $offset : '')
               . (($order) ? ' ORDER BY ' . $order : '');
        $this->query($query);
        return $this->countRows();
    }

    /**
     * Perform an INSERT statement
     */
    public function insert($table, array $data)
    {
        $fields = implode(',', array_keys($data));
        $values = implode(',', array_map(array($this, 'quoteValue'), array_values($data)));
        $query = 'INSERT INTO ' . $table . '(' . $fields . ')' . ' VALUES (' . $values . ')';
        $this->query($query);
        return $this->getInsertId();
    }

then in the second page:

/**
     * Fetch all users
     */
    public function fetchAll()
    {
        // try to fetch users data from the cache system
        if ($users = $this->_cache->get('all')) {
            return $users;
        }
        // otherwise fecth users data from the database
        $this->_adapter->select('users');
        $users = array();
        while ($user = $this->_adapter->fetch()) {
            $users[] = $user;
        }
        if (count($users) !== 0) {
           $this->_cache->set('all', $users);
        }
        return $users;
    }

    /**
     * Insert new user data (the cache is cleared also)
     */
    public function insert(array $data)
    {
        if ($insertId = $this->_adapter->insert('users', $data)) {
            $this->_cache->clear();
            return $insertId;
        }
        return false;
    }

    /**
     * Delete the table row corresponding to the specified user (the cache is cleared also)
     */
    public function delete($id)
    {
        if ($affectedRow = $this->_adapter->delete('users', "id = $id")) {
            $this->_cache->clear();
            return $affectedRow;
        }
        return false;
    }

Is this a bad way of doing things?  Is this opening me up to sql injection just like anything else where I construct the sql on the fly would?  I want to build my models "right."  Does that mean I need to have all stored procedures or prepared statements?


texts: Saving web search results for EANs to CSV

texts:
This is my first program in Python. Following code is taken from different posts (mostly this site) and combined together so that I can automate my routine task.

It's working properly but I need opinion from experts to enhance it further.

import mechanize
from bs4 import BeautifulSoup
import numpy as np
import csv
import os

# reading file
np.genfromtxt('EAN.txt', delimiter ='\n')
dtype=str
with open('EAN.txt') as f:
    lines = f.read().splitlines()

new_dictionary = {}
count = 0

for line in lines:
    count += 1
    new_dictionary['sequence_{}'.format(count)] = line

# searching items

print "Running..."

for i in new_dictionary:
    myean = new_dictionary[i]
    url = "https://mysite"
    br = mechanize.Browser()
    br.set_handle_robots(False)
    br.open(url)
    br.select_form(id="searchForm")
    br["q"] = myean
    res = br.submit()
    content = res.read()
    with open("mechanize_results.html", "a") as f:
        f.write(content)
    soup = BeautifulSoup(open("mechanize_results.html"),'html.parser')

    for div in soup.findAll('div', {'class': 'small-12 columns product-title'}):
        a = div.findAll('a')[1]

    #writing file

    if a is None:

        with open('Results.csv', 'ab') as csvfile:
            spamwriter = csv.writer(csvfile, delimiter='|',
                                    quotechar='|', quoting=csv.QUOTE_MINIMAL)
            spamwriter.writerow([myean, "Rejected"])
            #, title.string])

    else:
       #print myean, '|', a.text.strip()
       with open('Results.csv', 'ab') as csvfile:
            spamwriter = csv.writer(csvfile, delimiter='|',
                                    quotechar='|', quoting=csv.QUOTE_MINIMAL)
            spamwriter.writerow([myean, "Approved", a.text.strip()])
            #, title.string])

        #deleting file

    os.remove("mechanize_results.html")
    a=None
    i =+ 1

print "%d items Searched" %count
new_dictionary.clear()
raw_input("Press any key to continue...")

Although this code is running perfectly but I was wondering that when I used pyinstaller to create exe file, size became around 400+MB. Is it because, I am importing complete package of 'mechanize', 'numpy', 'csv' and 'os'?


texts:
I made a very simple calculator in C that allows the user to perform calculations like addition, subtraction, multiplication and division. This is my first C program that I've made outside of my University course. It would be great to get some feedback on this program so that I can avoid bad practices early on in my coding.

//Calculator program
#include <stdio.h>
#include <stdlib.h>

int main()
{
    int menu; //Variable for the number the user inputs
    float num1, num2, result; //Float variables for the user input and output, used floats in case the user enters e.g. 14.7

    printf("Enter a number from the list below\n\n");

    printf("1. Addition\n"); //Calculator menu, user must enter a value from 1 - 4 for the program to work
    printf("2. Subtraction\n");
    printf("3. Multiplication\n");
    printf("4. Division\n\n");

    printf("Enter number: "); //User input for the calculator menu
    scanf("%d", &menu);

    printf("\n");

    switch(menu) //switch statement for menu
    {
    case 1:
        printf("You entered Addition\n\n");

        printf("Enter first number: "); //User input for first number
        scanf("%f", &num1);

        printf("Enter second number: "); //User input for second number
        scanf("%f", &num2);

        printf("\n");

        result = num1 + num2; //Addition calculation

        printf("%.2f + %.2f = %.2f\n", num1, num2, result); //Addition output
        break;
    case 2:
        printf("You entered Subtraction\n\n");

        printf("Enter first number: "); //User input for first number
        scanf("%f", &num1);

        printf("Enter second number: "); //User input for second number
        scanf("%f", &num2);

        printf("\n");

        result = num1 - num2; //Subtraction calculation

        printf("%.2f - %.2f = %.2f\n", num1, num2, result); //Subtraction output
        break;
    case 3:
        printf("You entered Multiplication\n\n");

        printf("Enter first number: "); //User input for first number
        scanf("%f", &num1);

        printf("Enter second number: "); //User input for second number
        scanf("%f", &num2);

        printf("\n");

        result = num1 * num2; //Multiplication calculation

        printf("%.2f * %.2f = %.2f\n", num1, num2, result); //Multiplication Output
        break;
    case 4:
        printf("You entered Division\n\n");

        printf("Enter first number: "); //User input for first number
        scanf("%f", &num1);

        printf("Enter second number: "); //User input for first number
        scanf("%f", &num2);

        printf("\n");

        result = num1 / num2; //Division calculation

        printf("%.2f / %.2f = %.2f\n", num1, num2, result);
        break;
    default:
        printf("Enter correct number e.g 1 - 4\n"); //Outputted if the user enters a value other than 1 - 4
        break;
    }
    return 0;
}
//End of code


texts: ASP.NEt Core thread safe global variable

texts:
I have a .net core razor app that has a special use case where I need to have a global counter that will be incremented by every request, and yet it should remain thread-safe.

Also at web application load, this counter will be read from a database using entity framework.

I don't think that static variables are threadsafe for this scenario (since it can be read by a request then be modified after another request read its previous value).

So I was wondering if a locking mechanism is needed, or should a concurrent dictionary with a Lazy<T> be used?

public static void PrintValueLazy(string valueToPrint)
{
var valueFound = _lazyDictionary.GetOrAdd("key",
            x => new Lazy<string>(
                () =>
                    {
                        Interlocked.Increment(ref _runCount);
                        Thread.Sleep(100);
                        return valueToPrint;
                    }));
Console.WriteLine(valueFound.Value);
}


texts: Web Scraping, Serializing and Deserializing in Python

texts:
I scraped data from a local .html page and the below code is working. I am a newbie to scraping, just tried with a simple HTML page. It takes 10 sec to complete execution and print data. If I did anything wrong or need improvements, please let me know.
from bs4 import BeautifulSoup
import json
import pyodbc
import datetime

class JsonClass:
    def __init__(self, Date, DocumentType, Procedure, NoOfPages):
        self.Date = Date
        self.DocumentType = DocumentType
        self.Procedure = Procedure
        self.NoOfPages = NoOfPages

def json_to_db(json_string):
    conn = pyodbc.connect('Driver={SQL Server};' 'Server=xyz-PAVILION;' 'Database=jsondata;' 'Trusted_Connect=yes')
    conn.autocommit = True
    cursor = conn.cursor()
    try:
        cursor.execute('EXEC prcJsonInsertData @json = ?',
                   json_string)  # Passing Json Data to DB via Stored Procedure(SP)
        print('Data inserted')
    except pyodbc.Error as error:
        print('Error : %s' % error)
        return False
    except:
        print('Operation Failed')
        return False
    conn.close()
    return True

def json_serialize(dict_list):
    with open('html_to_json.json', 'w') as file_out:
        json.dump(dict_list, file_out, indent=4)  # Serializing dict_list and writing in  .json file
    return json.dumps(dict_list)

def json_deserilaize(json_string):
    with open('html_to_json.json', 'r') as file_out:
    json_data = json.load(file_out)  # Deserialization Data
    json_class = [JsonClass(**i) for i in json_data]  # Binding Json_data to Json_Class
    print('********* After Deserialization *******************')
    print('-------------------------------------')
    for i in json_class:
        print('Date : ' + i.Date)
        print('DocumentType : ' + i.DocumentType)
        print('Procedure : ' + i.Procedure)
        print('NoOfPages : ' + i.NoOfPages)
        print('-------------------------------------')

def html_data():
    my_file = open("C:/Users/xyz/Downloads/sample.htm", 'r')
    soup = BeautifulSoup(my_file, 'html.parser', from_encoding="UTF-8")
    t_body = soup.find('tbody')
    rows = t_body.find_all('tr')
    dict_list = []
    for row in rows:
        column = row.find_all('td')
        column = [x.text for x in column]
        record = dict()
        date_obj = datetime.datetime.strptime(column[1], '%d.%m.%Y')
        record['Date'] = date_obj.date().isoformat()
        record['DocumentType'] = column[2]
        record['Procedure'] = column[3].replace('\u00a0/\u00a0', '/').replace('\u00a0', '/')
        record['NoOfPages'] = column[4]
        dict_list.append(record)
    json_string = json_serialize(dict_list)  # Func - 1
    if json_to_db(json_string):  # Func - 2
        json_deserilaize(json_string)  # Func - 3

if __name__ == '__main__':
    html_data()


texts: How can I speed up this solution to the "Rock-Paper-Scissors Tournament"

texts:
As I have recently been selected to participate in my country's final preselection to the IOI -- this took me aback -- I have decided to get a bit more serious about competetitive programming.

The Rock-Paper-Scissors Tournament is an old question form the Waterloo Programming Contest 2005-09-17, available on kattis.

What it asks you to do is:

You first get two numbers n and k for the number of participants and the number of games played in the tournament.
And then you get k lines detailing every one of those games.
Using this data you have to output the winrate for each contestant in three decimal places.
A player that has not played a single game throughout the tournament should get a '-' as output.

A zero for the number of players terminates the program.

2 4
1 rock 2 paper
1 scissors 2 paper
1 rock 2 rock
2 rock 1 scissors
2 1
1 rock 2 paper
0

Should give the output

0.333
0.667

0.000
1.000

As far as I know my solution, which follows below, solves this problem perfectly, but, sadly, it is too slow.

My question is, does anyone see where I made a suboptimal choice in the datatype I used or how I calculated a result that causes my program to fail to beat the timelimit? I hope that understanding what I could have done better here allows me to become a better programmer in the future.

#include <iostream>
#include <iomanip>
#include <vector>
#include <unordered_map>

std::unordered_map< std::string, std::unordered_map<std::string, int> >
result(
{
   {
       "rock",
        {
            {"rock", 0},
            {"paper", -1},
            {"scissors", 1}
        }
   },
   {
        "paper",
        {
            {"rock", 1},
            {"paper", 0},
            {"scissors", -1}
        }
   },
   {

        "scissors",
        {
            {"rock", -1},
            {"paper", 1},
            {"scissors", 0}
        }
   }
});

int main() {
    int n,
        k,
        p1,
        p2;

    std::string m1,
                m2;

    while (1) {
        std::cin >> n;

        if (n == 0) {
            break;
        }

        std::cin >> k;

        std::vector<int> wins(n, 0);
        std::vector<int> losses(n, 0);

        while (k--) {
            std::cin >> p1;
            std::cin >> m1;
            std::cin >> p2;
            std::cin >> m2;

            int v = result[m1][m2];

            if (v == 1) {
                wins[p1-1]++;
                losses[p2-1]++;
            } else if (v == -1) {
                losses[p1-1]++;
                wins[p2-1]++;
            }
        }

        std::cout << std::fixed;
        std::cout << std::setprecision(3);
        for (int i = 0; i < n; i++) {
            float numOfWins = (float)wins[i];
            float numOfGames = (float)(wins[i]+losses[i]);
            if (numOfGames != 0) {
                std::cout << numOfWins/numOfGames << std::endl;
            } else {
                std::cout << '-' << std::endl;
            }
        }
        std::cout << std::endl;

    }
    return 0;
}


texts: Calculating a specific entry in a Pascal’s triangle recursively

texts:
Our task was to calculate the entry of a Pascal’s triangle with a given row and column recursively. The triangle was specified in a way that the tip of the triangle is column = 0 and row = 0. That said, column 0 has always the entry 1.

My concerns are that the way I initialize the triangle as an array and filling in the entries are not so super.

class EntryOfPascalsTriangle {
    public static void main(String[] args) {
        validateInput(args);

        int row = 0;
        row = parseInteger(args[0]);

        int column = 0;
        column = parseInteger(args[1]);

        // A Pascal’s triangle expands quadratic.
        // There are never entries at a position greater column length
        if (column > row) {
            handleError("There can't be entries in a column that doesn't exist in a Pascal's triangle.");
        }

        // We know already that the first and last entries in a row are always 1
        if (column == 0 || column == row) {
            System.out.println(1);
            System.exit(0);
        }

        int pascalsTriangle[][] = initPascalsTriangle(row);

        // initPascalsTriangle() takes care of the cases `0` and `1` already …
        if (row > 1) {
            // … so we can start to fill the rows starting from 2.
            pascalsTriangle = fillPascalRows(pascalsTriangle, 2);
        }

        System.out.println(pascalsTriangle[row][column]);
    }

    /**
     * Initializes a Pascal’s triangle with all cells filled with `0`
     * except for the first and last cell in a row which are `1`
     */
    private static int[][] initPascalsTriangle(int rows) {
        int[][] pascalsTriangle = new int[rows+1][];

        // Iterate over the columns of the rows of pascalsTriangle
        for (int cell = 0; cell < pascalsTriangle.length; cell++) {
            pascalsTriangle[cell] = new int[cell+1];

            // Fill the first cell of each row with `1`
            pascalsTriangle[cell][0] = 1;

            // Also fill the last cells with `1`
            pascalsTriangle[cell][cell] = 1;
        }

        return pascalsTriangle;
    }

    /**
     * Fills in the cells of Pascal’s triangle recursively
     */
    private static int[][] fillPascalRows(int[][] pascalsTriangle, int row) {
        for (int cell = 1; cell < pascalsTriangle[row].length-1; cell++) {
            pascalsTriangle[row][cell] = pascalsTriangle[row-1][cell-1] + pascalsTriangle[row-1][cell];
        }

        if (row < pascalsTriangle.length-1) {
            fillPascalRows(pascalsTriangle, row+1);
        }

        return pascalsTriangle;
    }

    /**
     * We need to make sure that two arguments are provided
     * and fail with a helpful message if they weren’t.
     */
    private static void validateInput(String[] args) {
        if (args.length < 2) {
            handleError("Not enough arguments.");
        }

        if (args.length > 2) {
            handleError("Too many arguments.");
        }
    }

    /**
     * Small wrapper to parse strings as integers.
     */
    private static int parseInteger(String arg) {
        int result = 0;

        try {
            result = Integer.parseInt(arg);
        } catch (NumberFormatException nfe) {
            handleError("'" + arg + "' was not an integer.");
        }

        return result;
    }

    /**
     * Small wrapper to produce error messages
     */
    private static void handleError(String errorMessage) {
        String basicUsage = "Please enter the column and the row of a Pascal's triangle.";
        System.out.println(errorMessage);
        System.out.println("\n" + basicUsage);
        System.exit(1);
    }
}


texts: Simple factory retrieving object by name

texts:
Despite the fact that this code works, I would like to know if there's any situation I did not anticipated, and/or if what I am trying to do is some what wrong.

-std=C++11 flag needed

#include <iostream>
#include <string>
#include <map>
#include <typeinfo>
#include <functional>

class object
{
    public:

    virtual ~object(){}

    virtual std::string to_string() = 0;
};

class SomeObject : public object
{
    public:

    SomeObject(){}
    virtual ~SomeObject(){}

    virtual std::string to_string()
    {
        return "I am a type of SomeObject";
    }
};

class SomeOtherObject : public object
{
    public:

    SomeOtherObject(){}
    virtual ~SomeOtherObject(){}

    virtual std::string to_string()
    {
        return "I am a type of SomeOtherObject";
    }
};

std::map<std::string, std::function<object*()> > types;

template<typename O>
inline
static void register_type(const std::string & name)
{
    types[name] = [](){ return new O; };
}

static object * get_object(const std::string & object_name )
{
    return types[object_name]();
}

int main()
{
    register_type<SomeObject>("SomeObject");
    register_type<SomeOtherObject>("SomeOtherObject");

    object * some = get_object("SomeObject");
    object * some_other = get_object("SomeOtherObject");

    std::cout << "::" << some->to_string() << std::endl;
    std::cout << "::" << some_other->to_string() << std::endl;

    delete some;
    delete some_other;

    std::cout << "exit" << std::endl;

    return 0;
}


texts:
I'm using this way to load a combo box with branch names, but it's taking more time if there is more number of data.

Is there a better way to do this, like binding in PHP?

<select name="CmbBr" id="CmbBr">
  <?php
     include ("dbcon_.php");
     $sql = mysql_query("SELECT BranchName FROM TblBranch ORDER BY BranchName ASC");
     if(!mysql_num_rows($sql) == 0)
     {
        while($row = mysql_fetch_array($sql))
       {
           ?>
              <option value="<?php echo $row["BranchName"];?>"><?php echo $row["BranchName"]; ?></option>
           <?php
       }
     }
  ?>
</select>


texts: Reverse each word in the string. All spaces in the string should be retained

texts:
This was part of a code challenge.  I use them to help me learn c++/c# along with tutorials and guides.  Basically I was taking a string...

  The quick brown fox jumps over the lazy dog.

...and reversing the words in the string like this.

  ehT kciuq nworb xof spmuj revo eht yzal .god

The following code works and compiles.  However, I feel like this was a verbose way to achieve the objective.

  split

This function was a copy paste from another Stack Overflow page.  I'm not sure if this is idiomatic in c++, but it feels like an overkill.  I just used it because it worked when I tested it on single word strings.

  vector_to_string

I came up with this function because I had forgotten how to do this in c++.  I recall a built in function somewhere in its library.

  reverse_words

This was the provided function for the challenge.  Everything inside of the {} is what I came up with.

Everything in the int main() I came up as well for testing.  Test are provided, but I haven't quite learned how to implement this offline yet.  Following is my code, with the test after that.

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

using namespace std;

vector<string> split(string s, string delimiter)
{
    size_t pos_start = 0, pos_end, delim_len = delimiter.length();
    string token;
    vector<string> res;

    while ((pos_end = s.find(delimiter, pos_start)) != string::npos)
    {
        token = s.substr(pos_start, pos_end - pos_start);
        pos_start = pos_end + delim_len;
        res.push_back(token);
    }

    res.push_back(s.substr(pos_start));
    return res;
}

string vector_to_string(vector<string> v)
{
    string s;

    for (auto &e : v)
    {
        reverse(e.begin(), e.end());
        s += e + " ";
    }

    return s;
}

string reverse_words(string str)
{
    vector<string> v = split(str, " ");
    string s = vector_to_string(v);
    return s.substr(0, s.length() - 1);
}

int main()
{
    cout << reverse_words("The quick brown fox jumps over the lazy dog.") << endl;
    cout << reverse_words("apple") << endl;
    cout << reverse_words("a b c d") << endl;
    cout << reverse_words("") << endl;
    cout << reverse_words("ab   ba   cd") << endl;
}

I was provided with these tests:

Describe(Tests)
{
  It(Sample_Test_Cases)
  {
    Assert::That(reverse_words("The quick brown fox jumps over the lazy dog."), Equals("ehT kciuq nworb xof spmuj revo eht yzal .god"));
    Assert::That(reverse_words("apple"), Equals("elppa"));
    Assert::That(reverse_words("a b c d"), Equals("a b c d"));
    Assert::That(reverse_words("double  spaced  words"), Equals("elbuod  decaps  sdrow"));
    Assert::That(reverse_words(""), Equals(""));
    Assert::That(reverse_words("ab   ba   cd"), Equals("ba   ab   dc"));
  }
};

Anyhow, any advice on this is much appreciated and thank you for your help.  Again, I feel like this is a verbose way to solve this problem and I suspect it can be greatly optimized as well.


texts: `set_includes` (string subsequence-containment) in Python 2

texts:
I've implemented C++'s std::includes algorithm in Python, so that I can use it to efficiently implement a Scrabble "can I make this word" function:

def word_can_be_made_from_rack(word, rack):
    return set_includes(sorted(rack), sorted(word))

Here's the implementation, with some test cases:

def set_includes(haystack, needle):
    j = 0
    hn = len(haystack)
    for c in needle:
        while j != hn and haystack[j] < c:
            j += 1
        if j == hn:
            return False
        if haystack[j] > c:
            return False
        j += 1
    return True

assert set_includes('abcdef', 'af')
assert set_includes('abcdef', 'bce')
assert set_includes('abcdef', 'abcdef')
assert set_includes('aaaaa', 'a')
assert set_includes('aaaaa', 'aa')
assert set_includes('aaaaax', 'ax')
assert set_includes('abbbcxx', 'abc')

This is similar to Find if one list is a subsequence of another except that it assumes (and requires) that the two input strings are sorted.

The manual management of index j in this code doesn't feel very Pythonic. Am I missing an easier way to write this algorithm?

itertools one-liners will be accepted as answers, especially if they're more performant. :)


texts:
I am terrible with writing JavaScript code that outputs HTML. So, here's how a string literal looks like in a project that I'm working on:

tweet = '
'

+ '
'

+ '
'

+ ''
+ ''
+ '	'

+ ''
+ '
'
+ ''
+ '
' + from_user + '
';
})(item.from_user)
+ ''
+ '
' + item.text.twitterify() + '
'
+ '
'
+ '	'

+ '
'

+ '
'

+ '' + item.created_at + ''
+ '
';

How would I go about to improve this?


texts: AES encryption/decryption in rust: performance and best practices

texts:
I wrote a small rust library available on github that can encrypt/decrypt a 16 bytes block using either 128, 192 or 256 bit passwords. This implementation is tested with the test data provided in the standard description. Since I'm pretty new to rust and this was mainly an exercise to learn to use this language I would love to get feedback regarding code style and best practices. Also, I would be very interested in knowing how I could optimize it or in resources concerning that.

The function I feel could somehow use optimization the most is the mix_column transformation in the AES matrix:

    /**
     * Basically the inverse_mix_columns sets the bytes in each column to:
     *
     * col[0] = (col[0] * 0x02) xor (col[1] * 0x03) xor col[2] xor col[3]
     * col[1] = col[0] xor (col[1] * 0x02) xor (col[2] * 0x03) xor col[3]
     * col[2] = col[0] xor col[1] xor (col[2] * 0x02) xor (col[3] * 0x03)
     * col[3] = (col[0] * 0x03) xor col[1] xor col[2] xor (col[3] * 0x02)
     *
     * With '*' meaning the multiplication in the GF2 field as described by the AES standard
     */
    fn mix_column_8(bytes: &mut [u8; 16], offset: usize) {
        let mut column_bytes = [
            bytes[offset],
            bytes[offset + 1],
            bytes[offset + 2],
            bytes[offset + 3],
        ];
        for index in 0..4 {
            bytes[offset + index] = Math::x_time(column_bytes[0])
                ^ Math::multiplication_by_03(column_bytes[1])
                ^ column_bytes[2]
                ^ column_bytes[3];
            let temp = column_bytes[0];
            column_bytes[0] = column_bytes[1];
            column_bytes[1] = column_bytes[2];
            column_bytes[2] = column_bytes[3];
            column_bytes[3] = temp;
        }
    }

With the two external functions called being:

pub fn x_time(val: u8) -> u8 {
        if val > 0x7f {
            (val << 1) ^ 0x1b
        } else {
            val << 1
        }
}

pub fn multiplication_by_03(val: u8) -> u8 {
    (val ^ Self::x_time(val))
}

This is my first post on here so I hope that it fits the rules, otherwise I'll be happy to edit it.


texts:
I'm coming from the Java world and making my first steps on Python and see how good it is to express more with less code. I'd like to know if, via Python, the size of the following code could be reduced:

column_entropy = 0
for k in frequencies.keys():
    p = frequencies[k] / 10
    column_entropy += p * log(p, 2) if p > 0 else 0
column_entropy = -column_entropy


texts:
I've written a simple binary heap in C# and I want to know if it has any problems or if I can make it better.

public enum HeapType
{
    MinHeap,
    MaxHeap
}

public class Heap<T> where T : IComparable<T>
{
    List<T> items;

    public HeapType MinOrMax { get; private set; }

    public T Root
    {
        get { return items[0]; }
    }

    public Heap(HeapType type)
    {
        items = new List<T>();
        this.MinOrMax = type;
    }

    public void Insert(T item)
    {
        items.Add(item);

        int i = items.Count - 1;

        bool flag = true;
        if (MinOrMax == HeapType.MaxHeap)
            flag = false;

        while(i > 0)
        {
            if ((items[i].CompareTo(items[(i - 1) / 2]) > 0) ^ flag)
            {
                T temp = items[i];
                items[i] = items[(i - 1) / 2];
                items[(i - 1) / 2] = temp;
                i = (i - 1) / 2;
            }
            else
                break;
        }
    }

    public void DeleteRoot()
    {
        int i = items.Count - 1;

        items[0] = items[i];
        items.RemoveAt(i);

        i = 0;

        bool flag = true;
        if (MinOrMax == HeapType.MaxHeap)
            flag = false;

        while(true)
        {
            int leftInd = 2 * i + 1;
            int rightInd = 2 * i + 2;
            int largest = i;

            if (leftInd < items.Count)
            {
                if ((items[leftInd].CompareTo(items[largest]) > 0) ^ flag)
                    largest = leftInd;
            }

            if (rightInd < items.Count)
            {
                if ((items[rightInd].CompareTo(items[largest]) > 0) ^ flag)
                    largest = rightInd;
            }

            if (largest != i)
            {
                T temp = items[largest];
                items[largest] = items[i];
                items[i] = temp;
                i = largest;
            }
            else
                break;
        }
    }

    public T PopRoot()
    {
        T result = items[0];

        DeleteRoot();

        return result;
    }
}


texts:
I'm returning to C++ after more than 10 years.  The code I wrote for a simple quadtree style class has a ton of new elements I haven't used.  I'm looking for comments on the design and not necessarily the quadtree implementation.

The code in its current state will work for my needs, with the exception of error catching.  Can I improve it? Am I making any design mistakes?

#include <array>

template <typename T>
class Quadtree
{
public:
    typedef std::array<Quadtree, 4> Quadrants; // class scope typedef

    T data; // the template data
    Quadtree* parent;

    Quadtree(T _data) // constructor
    {
        data = _data;
    }

    void Split(Quadrants nodes)
    {
        quadrants = &nodes;

    }

    Quadtree operator[](int _index) // keeps syntax consistent with std::array
    {
        return (*quadrants)[_index];
    }
private:
    Quadrants* quadrants;
};

Usage looks like this:

Quadtree<int> tree(5);
Quadtree<int> node(3);
Quadtree<int>::Quadrants quadrant = { *new Quadtree<int>(1), *new Quadtree<int>(2), *new Quadtree<int>(4), node };
tree.Split(quadrant);

int value = tree[3].data;
// value now equals 89


texts: Project Euler # 48 Self powers in Python

texts:
The series, \$1^1 + 2^2 + 3^3 + \ldots + 10^{10} = 10405071317\$.
Find the last ten digits of the series, \$1^1 + 2^2 + 3^3 + \ldots + 1000^{1000}\$.

def self_power(n):
    """returns sum of self powers up to n."""
    total = 0
    for i in range(1, n + 1):
        total += i ** i
    return str(total)[-10:]

if __name__ == '__main__':
    print(self_power(1000))


texts: Return Kth to Last: Implement an algorithm to find the kth to last element of a singly linked list

texts:
Implement an algorithm to find the kth to last element of a singly linked list.

Any comments or feedback regarding this?

I came up with another algorithm that uses HashMap to find the kth to the last element in a LinkedList.

public static int getKthToLastElement(LinkedListNode head, int k){
    LinkedListNode n = head;

    if(head == null || k < 0)
        return -1;

    int index = 0;
    HashMap<Integer,Integer> map = new HashMap<Integer, Integer>();
    while (n != null){
        map.put(index,n.data);
        index++;
        n = n.next;
    }

    if(k > map.size() -1){
        return  -1;
    }
    return map.get(map.size() - 1 - k);
}


texts: Apply function to every subset combination and return square matrix

texts:
I do not know how to do this without four nested for loops.

I'd like to apply a function to every possible combination of subsets for hour and day, return that value, and then pivot the data frame into a square matrix. However, these for loops seem excessive so I'm looking for a more efficient way to do this. The data I have is fairly large so any gain in speed would be beneficial.

I took a stab at compression lists but that seems excessive too.

The following code runs fine with smaller groups (days=1:2 and hours=1:2) but with large groups, say years of data, performance is lost.

Note: I'm requesting help given any custom function, not just a cross-product solution as suggested here, Performant cartesian product (CROSS JOIN) with pandas

Sample data

import pandas as pd
import numpy as np
dat = pd.DataFrame({'day': {0: 1, 1: 1, 2: 1, 3: 1, 4: 1, 5: 1, 6: 1, 7: 1, 8: 1, 9: 1, 10: 2, 11: 2, 12: 2, 13: 2, 14: 2, 15: 2, 16: 2, 17: 2, 18: 2, 19: 2}, 'hour': {0: 1, 1: 1, 2: 1, 3: 1, 4: 1, 5: 2, 6: 2, 7: 2, 8: 2, 9: 2, 10: 1, 11: 1, 12: 1, 13: 1, 14: 1, 15: 2, 16: 2, 17: 2, 18: 2, 19: 2}, 'distance': {0: 1.2898851269657656, 1: 0.0, 2: 0.8371526423804061, 3: 0.8703856587273138, 4: 0.6257425922449789, 5: 0.0, 6: 0.0, 7: 0.0, 8: 1.2895328696587023, 9: 0.0, 10: 0.6875527848294374, 11: 0.0, 12: 0.0, 13: 0.9009031833559706, 14: 0.0, 15: 1.1040652963428623, 16: 0.0, 17: 0.0, 18: 0.0, 19: 0.0}})0}})

Code

def custom_fn(x, y):
    x = pd.Series(x)
    y = pd.Series(y)
    x = x**2
    y = np.sqrt(y)
    return x.sum() - y.sum()

# Empty data.frame to append to
dmat = pd.DataFrame()

# For i, j = hour; k, l = day
for i in range(1, 3):
    for j in range(1, 3):
        for k in range(1, 3):
            for l in range(1, 3):
                x = dat[(dat['hour'] == i) & (dat['day'] == k)].distance
                y = dat[(dat['hour'] == j) & (dat['day'] == l)].distance

                # Calculate difference
                jds = custom_fn(x, y)

                # Build data frame and append
                outdat = pd.DataFrame({'day_hour_a': f"{k}_{i}", 'day_hour_b': f"{l}_{j}", 'jds': [round(jds, 4)]})
                dmat = dmat.append(outdat, ignore_index=True)

# Pivot data to get matrix
distMatrix = dmat.pivot(index='day_hour_a', columns='day_hour_b', values='jds')

Output

> print(distMatrix)

 day_hour_b     1_1     1_2     2_1     2_2
day_hour_a
1_1        -0.2609  2.3782  1.7354  2.4630
1_2        -2.1118  0.5273 -0.1155  0.6121
2_1        -2.4903  0.1488 -0.4940  0.2336
2_2        -2.5557  0.0834 -0.5594  0.1682