texts: Serialize and deserialize binary tree with a lot of empty nodes

texts:
Here is my code to serialize and deserialize binary tree, which may have a lot of empty nodes. I am written in Python 2.7. Any advice on performance improvement in terms of algorithm time complexity, bugs or code style advice is appreciated.

My major idea is, serialize only non-empty nodes, with node ID information, where left node ID * 2 = parent node ID, and right node ID * 2 + 1 = parent node ID

Source code in Python 2.7,

from collections import defaultdict
class TreeNode:
    def __init__(self, value, left, right):
        self.value = value
        self.left = left
        self.right = right
    def serialize_tree(self, result):
        stack = []
        stack.append((self, 1))
        while len(stack) > 0:
            node, index = stack.pop(0)
            result.append((node.value, index))
            if node.left:
                stack.append((node.left, index*2))
            if node.right:
                stack.append((node.right, index*2+1))
    @staticmethod
    def deserialize_tree(source):
        result = []
        for (node_value, index) in source:
            node = TreeNode(node_value, None, None)
            result.append(node)
            if index == 1:
                continue
            elif index % 2 == 0:
                result[index / 2 - 1].left = node
            else:
                result[(index - 1) / 2 - 1].right = node
        return result[0]
    def print_tree(self, result):
        result.append(self.value)
        if self.left:
            self.left.print_tree(result)
        else:
            result.append('#')
        if self.right:
            self.right.print_tree(result)
        else:
            result.append('#')

if __name__ == "__main__":
    root = TreeNode(1, TreeNode(2, None, TreeNode(4, None, None)), TreeNode(3, None, None))
    result = []
    root.serialize_tree(result)
    print result
    new_root = TreeNode.deserialize_tree(result)
    result2 = []
    new_root.print_tree(result2)
    print result2


texts:
Input:
    Enter a decimal number: 101

Output:
    The binary number is : 1100101

I have solved this way->
#include <stdio.h>
int main(void){

int input=get_input();
long long complete_integer=binary_conversion(input);
reverse_digits(complete_integer);
}
int get_input() {
int number = 0;
printf("Enter a decimal number: ");
scanf("%d",&number);
return number;
}
int binary_conversion(int number) {
long long complete_integer = 0;
int base=2;

while (number != 0) {
//Take the last digit from the integer and push the digit back of complete integer
complete_integer = complete_integer * 10 + number%base;
number /= base;
}
printf("Completed integer number : %d\n",complete_integer);
return complete_integer;
}

int reverse_digits(long long complete_integer) {
    int binary = complete_integer;
    int last_digit = 0;

    while(binary != 0) {

        last_digit = last_digit * 10 + binary % 10;
        binary /= 10;
    }
    printf("The binary number is: %d",last_digit);
}

I am here for: What about my comments and indentations? Will I face any problem for some conditions? Would you propose a better simplification by using my program?


texts:
For the first time, I tried to use threads by myself in order to implement a parallel sieve of Eratosthenes. The trick is that each time a prime is found, a thread is spawned to eliminate all the multiples of this prime number from the boolean vector (the one that tells whether a number is a prime or not). Here is my code:

#include <cmath>
#include <functional>
#include <thread>
#include <vector>

// Invalidates the multiples of the given integer
// in a given boolen vector
template<typename Integer>
void apply_prime(Integer prime, std::vector<bool>& vec)
{
    for (Integer i = prime*2u ; i < vec.size() ; i += prime)
    {
        vec[i] = false;
    }
}

template<typename Integer>
auto sieve_eratosthenes(Integer n)
    -> std::vector<Integer>
{
    std::vector<bool> is_prime(n, true);
    std::vector<std::thread> threads;
    std::vector<Integer> res;

    auto end = static_cast<Integer>(std::sqrt(n));
    for (Integer i = 2u ; i <= end ; ++i)
    {
        // When a prime is found,
        // * add it to the res vector
        // * spawn a thread to invalidate multiples
        if (is_prime[i])
        {
            res.push_back(i);
            threads.emplace_back(apply_prime<Integer>,
                                 i, std::ref(is_prime));
        }
    }

    for (auto& thr: threads)
    {
        thr.join();
    }

    // Add the remaining primes to the res vector
    for (Integer i = end+1u ; i < is_prime.size() ; ++i)
    {
        if (is_prime[i])
        {
            res.push_back(i);
        }
    }
    return res;
}

The primes are added in two steps to the res vector: every prime \$ p \$ such as \$ p < \sqrt{n} \$ is added when the prime is found, before the corresponding thread is thrown. The other primes are added at the end the of the function. Here is an example main:

int main()
{
    auto primes = sieve_eratosthenes(1000u);

    for (auto prime: primes)
    {
        std::cout << prime << " ";
    }
}

I was pretty sure that I would get some problems due to parallelism, but for some reason, it seems to work. I got the expected results in the right order. Just to be sure, I would like to know whether my program is or correct or whether it has some threading issues that I couldn't see.

Note: I used many of the ideas from the answer to improve the code and wrote a follow-up question.


texts: Streamreader file.Readline properly closing the stream

texts:
Is this OK? (.Net 4.5)

try
{
    StreamReader sr = = new StreamReader(ValidFilePathName);
    line = file.ReadLine();
    While (line != null)
    {
        line = file.ReadLine();
    }
    sr.Close();
}
catch
{
    // blah Do nothing
}

I feel like there is something wrong with my pattern here. My concern is that when there is a file exception, does the stream get closed properly? I was taught to use using to set the stream, but Code Analysis tool does not like it. Perhaps there is something else. It seems to read the file OK, but I remember needing to use File stream and stream reader in the past... Was there a good reason for combining the two?


texts:
Please review my following code for DAO layer.

public List<Channel> getListOfChannels() throws DataAccessException {
        // will have the channel in form of List
        // to hold the channels list
        List<Channel> listChannels = null;
        Connection conn = null;
        Statement statement = null;
        ResultSet resultSet = null;

        try {
            // get the db connection from pool
                // this is DBCP lib on top doing this
            conn = ManageConnections.getConnection();
            statement = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
                    ResultSet.CONCUR_READ_ONLY);

            final String QUERY_STRING = "Select * from channel";
            resultSet = statement.executeQuery(QUERY_STRING);

            // is this good practice to put this ?
            if (isResultSetEmptyOrNull(resultSet)) {
                throw new DataAccessException(
                        "No more data of Channels found from db");
            }

            Channel channel = null;

            listChannels = new ArrayList<Channel>();

            while (resultSet.next()) {
                // get the object from the result set and

                listChannels.add(channel);
            }

            log.debug("getListOfChannels Got the list of channels "
                    + listChannels);

                } catch (SQLException ex) {
            throw new DataAccessException(SQL_EXCEPTION + ex, ex);
        } catch (DBConnectionException ex) {
            // re thrown, no logging
            throw new DataAccessException(ex);
        } catch (Exception ex) {
            // Generic exception thrown , now throw Custom Exceptionn
            throw new DataAccessException(GENERIC_EXCEPTION + ex, ex);
        } finally {
            try {
                if (conn != null) {
                    // this is DBCP lib on top doing this
                    ManageConnections.close(conn);
                }
                if (statement != null) {
                    statement.close();
                }
                if (resultSet != null) {
                    resultSet.close();
                }
            } catch (SQLException ex) {
                throw new DataAccessException(
                        "Exception while closing resource" + ex, ex);
            } catch (DBConnectionException ex) {
                throw new DataAccessException(
                        "Exception while closing resource" + ex, ex);
            }
        }

        return listChannels;


texts: Stopping a long-running asynchronous computation

texts:
I'm writing a program that will perform a long-running computation, gradually improving a solution. On top of that, there's a simple UI that basically allows the user to stop the computation (letting the worker finish a step it's working on) and shows the best solution.
Here's a simplified version of what I have, I'm using async/await for the first time. Is there anything you would improve, or any other comments?

Worker code

public class SearchEngine
{
    //...
    public async Task<IProblemSolution> Search(CancellationTokenSource cts)
    {
        await Task.Factory.StartNew(() => {
            BestSolution = Problem.RandomSolution();
            while (!cts.IsCancellationRequested)
            {
                IProblemSolution s = Problem.RandomSolution(); // for simplification
                if (s.ObjectiveValue() < BestSolution.ObjectiveValue())
                    BestSolution = s;
            }
        });
        return BestSolution;
    }
}

UI

    private async void StartButton_Click(object sender, RoutedEventArgs e)
    {
        if (CancelTokenSrc != null)
            return;

        CancelTokenSrc = new CancellationTokenSource();
        Engine = new SearchEngine(new SampleProblem());

        StopButton.IsEnabled = true;
        StartButton.IsEnabled = false;
        Task<IProblemSolution> t = Engine.Search(CancelTokenSrc);
        await t;

        ResultLabel.Content = t.Result.ObjectiveValue().ToString();
        StopButton.IsEnabled = false;
        StartButton.IsEnabled = true;
        CancelTokenSrc = null;
    }

    private void StopButton_Click(object sender, RoutedEventArgs e)
    {
        if (CancelTokenSrc != null)
            CancelTokenSrc.Cancel();
    }


texts:
I am trying to render in a leaflet map that should render a single marker. I am building the JavaScript as follows.

build the map
an even listener for when the user opens the page where the map is rendered.

I query as follows:
@company = Company.friendly.find_by(
                        slug: [ params[:id],
                        params[:company_id] ])
respond_to do |format|
      format.html
      format.json { render json:
        {
          type: "Feature",
          "geometry": {
            "type": "Point",
            "coordinates": [@company.longitude, @company.latitude] # this part is tricky
          },
          properties: {
            "title": @company.name,
            "address": @company.street_address,
          }
        }
      }
    end

I console log the steps and everything seems to "work". The data is loaded and data.responseJSON renders as follows:
geometry: {…}
coordinates: Array [ 1.5918642, 43.7189496 ]
type: "Point"
<prototype>: Object { … }
properties: Object { title: "Acme SaS", address: "xxx", "marker-color": "#FFFFFF", … }
type: "Feature"

However, the map does not render as wanted. Only a grey box shows up. If I provide with a lat, Lon array, the map renders a map.
function buildCompanyMap() {

  document.getElementById('company_map').innerHTML = "

";

  console.log("script #1: %o", document.getElementById('company_map'));
  console.log("script #2: %o", document.getElementById('map'));

  var data = $.ajax({
      url: "#companies/company.json",
      dataType: "json",
      success: console.log("company data successfully loaded."),
      error: function(xhr) {
          alert(xhr.statusText)
      }
  });

  console.log("script #3: %o", $);

  console.log("script #4: %o", data);

  $.when(data).done(function() {
    var map = new L.Map('map', {
        dragging: false,
        tap: false,
        scrollWheelZoom: false
      });

    var osmUrl = 'https://{s}.tile.osm.org/{z}/{x}/{y}.png',
        osmAttribution = 'Map data © OpenStreetMap contributors,' +
                        ' CC-BY-SA',
        osmLayer = new L.TileLayer(osmUrl, {maxZoom: 18, attribution: osmAttribution});

    map.addLayer(osmLayer);

    console.log("script #5: %o", data.responseJSON);

    var geojsonMarkerOptions = {
        radius: 8,
        fillColor: "#ff7800",
        color: "#000",
        weight: 1,
        opacity: 1,
        fillOpacity: 0.8
    };

    L.geoJSON(data.responseJSON, {
        pointToLayer: function (feature, latlng) {
            return L.circleMarker(latlng, geojsonMarkerOptions);
        }
    }).addTo(map);

  });
};

document.addEventListener("turbolinks:load", function() {
  if (document.getElementById('company_map') == null) {
    //console.log('true')
  }
  else {
    buildCompanyMap();
  }
});


texts: Counting terms in Collatz sequences until 1 is reached or a limit is exceeded

texts:
My friend and I are into competitive programming and we wrote two very similar programs for a problem. His got accepted with a runtime of 0.6 s while mine didn't get accepted even after 3 s.

I was hoping somebody could explain to me as to why the addition of one function slowed down my code so much.

Both programs produce the correct output. No issues on that front.

The Question: Given A, the initial value of a Collatz sequence, and some limit L, count the number of terms until either 1 is reached or L is exceeded.  A and L are both smaller than 231.

His Code

#include<iostream>

using namespace std;

int main(){
    long long A,L;
    int cont,caso=1;

    while(1){
        cin>>A>>L;
        if(A<0 && L<0) break;

        cout<<"Case "<<caso<<": A = "<<A<<", limit = "<<L<<", number of terms = ";
        caso++;

        cont=0;

        while(A<=L && A!=1){
            if(A%2==0) A/=2;
            else A=3*A+1;

            cont++;
        }

        if(A==1) cont++;

        cout<<cont<<endl;
    }

    return 0;
}

My Code

#include<iostream>

using namespace std;

bool even(int a)
{
    if(a%2==0)
        return true;
    else
        return false;
}

int main()
{
    int n=0;
    while(1)
    {
        long long int a, limit;
        cin>>a>>limit;
        if((a==-1) && (limit==-1))
            break;
        cout<<"Case "<<n<<": A = "<<a<<", limit = "<<limit<<", number of terms = ";
        int val=a;
        int count=0;
        while((val<=limit) && (val!=1))
        {
            if(even(val))
                val/=2;
            else
                val=(val*3) + 1;
            count++;
        }
        if(a==1)
            count++;
        cout<<count<<endl;
    }
    return 0;
}


texts: Count the number of cyclic words in an input

texts:
Cyclic Words

  Problem Statement

  We can think of a cyclic word as a word written in a circle. To
  represent a cyclic word, we choose an arbitrary starting position and
  read the characters in clockwise order. So, "picture" and "turepic"
  are representations for the same cyclic word.

  You are given a String[] words, each element of which is a
  representation of a cyclic word. Return the number of different cyclic
  words that are represented.

I have included my attempt below, and I'm not sure whether to be pleased with it or not (because I'm new to algos). I want to solve this problem in the most efficient way, preferably in an imperative language such as Java.

I would appreciate criticism of my code in terms of both function and form.

private static int countCyclicWords(String[] input) {
    HashSet<String> hashSet = new HashSet<String>();
    String permutation;
    int count = 0;

    for (String s : input) {
        if (hashSet.contains(s)) {
            continue;
        } else {
            count++;
            for (int i = 0; i < s.length(); i++) {
                permutation = s.substring(1) + s.substring(0, 1);
                s = permutation;
                hashSet.add(s);
            }
        }
    }

    return count;
}


texts: Creating SOLID immutable and mutable Location types

texts:
I have a Location type:

public abstract class Location implements Locatable {
    private int x, y;

    protected final void setX(int x) {
         this.x = x;
    }

    protected final void setY(int y) {
         this.y = y;
    }

    public final int getX() {
        return x;
    }

    public final int getY() {
        return y;
    }
}

interface Locatable {
    int getX();
    int getY();
}

Location has protected mutator methods, to ensure I can provide an MutableLocation type, but I'm not sure if this violates the Interface Seggregation principle when creating an ImmutableLocation.

I feel it doesn't, since the client will never have access to the setters through ImmutableLocation (cannot call it from an instance, cannot call it from a subclass of ImmutableLocation). So this was my attempt at a SOLID location type, which I plan on using in a project.

class ImmutableLocation extends Location {
    //...
 }

class MutableLocation extends Location {
    public void adjustX(int amount, IncremeantOperation op) {
        int x = op.adjust(x, amount);

        setX(x);
    }

    public void adjustY(int amount, IncremeantOperation op) {
        int y = op.adjust(getY(), amount);

        setY(y);
    }
}

enum IncremeantOperation {
    INCREASE {
        public int adjust(int target, int amount) {
             return target + amount;
        }
    },
    DECREASE {
        public int adjust(int target, int amount) {
            return target - amount;
        }
    };

    public int adjust(int target, int amount) {
        throw new UnsupportedOperationException("Cannot call adjust(int, int) on unknown operation");
    }
}

Please give your thoughts. My main concerns are:

I'm not sure if the enum is an overkill
If the setters are a violation of SOLID; I'm not sure how else I should do it.
If UnsupportedOperationException is best fit for the adjust method

interface Locatable {
    Location getLocation();
}

public abstract class Location {
    //may add fields, which explains the class

    public abstract int getX();
    public abstract int getY();
}

public final class ImmutableLocation extends Location {
    private int x, y;

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

    public int getX() {
        return x;
    }

    public int getY() {
        return y;
    }
}

public final class MutableLocation extends Location {
    private int x, y;

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

    public void adjustX(int x) {
         //adjust x
    }

    public void adjustY(int y) {
         //adjust y
    }

    public int getX() {
        return x;
    }

    public int getY() {
        return y;
    }
}

Locatable would be implemented by anything with a location, such as Entity:

abstract class Entity implements Locatable {
    private Location location;

    public Location getLocation() {
         return location;
    }
}


texts:
I am working on a JavaFX application where the user through a series of textfields and dropdown menus has to create some sort of report. The data from the user are written in an .xml file, I also convert the .xml file to HTML and display it with the Webview class.

The following code is the save method I use to help the user save her work in the desired directory. It is supposed to save both the .xml and the html file which it does very well.

/**
 * Method to save both xml and html file to desired location by the user
 */
@FXML
public void handleSave(){
    isSaved = true;

    try {
        Stage primaryStage = new Stage();
        FileChooser fileChooser = new FileChooser();

        // Set extension filter
        FileChooser.ExtensionFilter extFilter = new FileChooser.ExtensionFilter("XML files (*.xml)", "*.xml");
        fileChooser.getExtensionFilters().add(extFilter);

        // Show save file dialog
        File file = fileChooser.showSaveDialog(primaryStage);
        String fileLoc = file.getAbsolutePath();

        if (file != null) {
            // Make sure it has the correct extension
            if (!file.getPath().endsWith(".xml")) {
                System.out.println("Adding the extension");
                file = new File(file.getPath() + ".xml");
            }

            // creates the xml elements and writes them to the argument file
            xmlFromObjects(file);
            this.setXMLFileName(file.getAbsolutePath());

        }

        // convert the xml to html
        TransformerFactory tFactory = TransformerFactory.newInstance();
        javax.xml.transform.Source xslDoc = new StreamSource(getClass().getResourceAsStream("/lib/report.xsl"));
        javax.xml.transform.Source xmlDoc = new StreamSource(file);
        OutputStream html = new FileOutputStream(htmlFile);
        Transformer transformer = tFactory.newTransformer(xslDoc);
        transformer.transform(xmlDoc, new StreamResult(html));

        // the following happens if saved file has .xml extension
        int pos = fileLoc.lastIndexOf(".");
        if (pos > 0){
            // want to get the name of the saved xml file
            fileLoc = fileLoc.substring(0, pos);

            // moves the local html file to the location the xml file is
            htmlFile.renameTo(new File(fileLoc + ".html"));
            this.setHtmlFile(fileLoc + ".html");
        }else{
            htmlFile.renameTo(new File(fileLoc + ".html"));
            this.setHtmlFile(fileLoc + ".html");

        }
    }catch (Exception ex){
        System.out.println(ex.getMessage());
        ex.printStackTrace();
    }
}

I would like to know if my code can become better than it currently is, in terms of efficiency or modularity. Basically, feel free to judge my code.


texts:
I'm back at it again with an Hackerrank challenge-Inherited Code . I just learnt exception and I thought it will be a great idea to get a second opinion on my implemented BadLengthException struct .

  You inherited a piece of code that performs username validation for
  your company's website. The existing function works reasonably well,
  but it throws an exception when the username is too short. Upon
  review, you realize that nobody ever defined the exception.

  The inherited code is provided for you in the locked section of your
  editor. Complete the code so that, when an exception is thrown, it
  prints Too short: N (where \$N\$  is the length of the given
  username).

  Input Format

  The first line contains an integer, \$T\$ , the number of test cases.
  Each of the \$T\$ subsequent lines describes a test case as a single
  username string, \$ U\$ .

  Constraints

  \$ 1 \leq T \leq 1000\$
  \$ 1 \leq |U| \leq 100\$
  The username consists only of uppercase and lowercase letters.

  Output Format

  You are not responsible for directly printing anything to stdout. If
  your code is correct, the locked stub code in your editor will print
  either Valid (if the username is valid), Invalid (if the username
  is invalid), or Too short: N (where \$N\$ is the length of the
  too-short username) on a new line for each test case.

  Sample Input

3
Peter
Me
Arxwwz

  Sample Output

Valid
Too short: 2
Invalid

  Explanation

  Username Me is too short because it only contains  characters, so your
  exception prints Too short: 2 .  All other validation is handled by
  the locked code in your editor.

#include <iostream>
#include <string>
#include <sstream>
#include <exception>
using namespace std;

/* Define the exception here */
struct BadLengthException : public exception {
    int number;
    public :
        BadLengthException(int n){
            number = n;
        }

   const char * what () const throw () {
       std::stringstream ss;
       ss << number;
       return ss.str(). c_str();

   }
};

bool checkUsername(string username) {
    bool isValid = true;
    int n = username.length();
    if(n < 5) {
        throw BadLengthException(n);
    }
    for(int i = 0; i < n-1; i++) {
        if(username[i] == 'w' && username[i+1] == 'w') {
            isValid = false;
        }
    }
    return isValid;
}

int main() {
    int T; cin >> T;
    while(T--) {
        string username;
        cin >> username;
        try {
            bool isValid = checkUsername(username);
            if(isValid) {
                cout << "Valid" << '\n';
            } else {
                cout << "Invalid" << '\n';
            }
        } catch (BadLengthException e) {
            cout << "Too short: " << e.what() << '\n';
        }
    }
    return 0;
}

Final Thoughts

I thought it was a great idea to used a struct as opposed class as a struct is for small grouping
Just like the previous question, I have no access to change  the headers,  main() and checkUsername() so I couldn't remove the using namespace std


texts:
I was just looking for some feedback for my c# program to run Euler's method. I was just wondering on any possible improvements, refactoring, inefficiencies... the usual stuff you probably deal with here.

I am using YAMP, a math parser that can evaluate string inputs (so I can run things like calculating the derivative), and is capable of assignment operators (so I can replace x= with its actual value). Here is my code:

class Program
{
    static void Main(string[] args)
    {
        string derivativeinput;
        string[] xyvals;
        int xval;
        int yval;
        int numxval;
        int stepby;
        int stepto;
        derivativeinput = GetDerivative();
        xyvals = GetInitVals();
        Parser.Load();
        Console.WriteLine("Estimate what value of x?");
        stepto = int.Parse(Console.ReadLine());
        Console.WriteLine("Step by=?");
        stepby = int.Parse(Console.ReadLine());
        yval = Int32.Parse(xyvals[1]);
        xval = Int32.Parse(xyvals[0]);
        LoadInitVals(xval, yval);
        for (int i = 1; i <= stepto; i+= stepby)
        {
            int derivative = Int32.Parse(Parser.Parse(derivativeinput).Execute().ToString());

            yval = yval + derivative * stepby;
            Parser.Parse("y =" + yval.ToString()).Execute();

            xval = xval + stepby;
            Parser.Parse("x = " + xval.ToString()).Execute();
        }
        Console.WriteLine(yval);
        Console.ReadKey();
    }

    static string GetDerivative()
    {
        Console.WriteLine("Dy/Dx=");
        return Console.ReadLine();
    }

    static string[] GetInitVals()
    {
        Console.WriteLine("Initial value: X,Y");
        var initval = Console.ReadLine();
        return initval.Split(',');
    }

    static void LoadInitVals(int initx, int inity)
    {
        Parser.Parse("x = " + initx.ToString()).Execute();
        Parser.Parse("y =" + inity).Execute();
    }

}

I realize there probably isn't much to evaluate (the parser does a lot of the work). I guess some of the things I'm interested in is handling input, converting (I believe this parser will only evaluate and output a string at the moment), and my methods (for instance, GetDerivative- do I return a string, like I am? Or do I go ahead and set the 'derivative' string to the derivative in the function).

Anything else is welcome as well.


texts:
Introduction.

It is commonly known that the worst form of torture is performing monotonous tasks ad nauseam. So I constructed this simple game I can give to my students when they misbehave.

Task.

The goal was to make a problem that could take in two numbers, and construct n distinct multiplication problems where the user is asked to answer what x * y is.

Challenge.

Where I struggled was with the part in cursive. How do I write a clear and readable code that produces distinct multiplication problems? I tried to do it with creating a sample of distinct numbers X, and then choose y such that y ≤ x where x is a member of X. Unsure if this is the best idea.

The code and some comments

I choose to do import random instead of importing the modules as it is a bit clearer where the modules comes from
As above, choose to include a short ___docstring___ more out of habit than necessity I guess..
As mentioned above, do not really like my method for forcing the questions to be distinct.
Tried to comply with pep8 for the long strings, looks a bit strange.

Here is the code

import random

QUESTIONS = 5
MIN_VAL = 2
MAX_VAL = 12

def arithmetic_game(val_1=MIN_VAL,
                    val_2=MAX_VAL,
                    num_of_problem=QUESTIONS):
    """ Ask the user a series of arithmetic questions
    and returns the number of correct answers.

    Args: val_1 (int): Defines the range of multiplication
    Args: val_2 (int): Defines the range of multiplication
    Args: number_of_problems (int): Defines the number of questions

    Return: correct_answers (int): number of correct math questions answered"""

    correct_answers = 0

    num_lst = random.sample(
            range(min(val_1, val_2), max(val_2, val_2)+1),
            num_of_problem)

    for num_1 in num_lst:
        num_2 = random.randint(2, num_1)
        print('\nWhat is {:d} times {:d}?'
              ''.format(num_1, num_2))
        answer = num_1*num_2

        try:
            if int(input()) == answer:
                print('Yes, the answer is {:d}'
                      ''.format(answer))
                correct_answers += 1
            else:
                print('No, the correct answer was {:d}'
                      ''.format(answer))
        except NameError:
            raise ValueError('I am sorry, you have'
                             'to write in a valid integer')

    return correct_answers

if __name__ == "__main__":

    correct_answers = arithmetic_game()
    print('\nYou got {:d} out of {:d} answers correct'
          ''.format(correct_answers, QUESTIONS))


texts:
The purpose of this SQL query would be to extract the record 10192 only, because the end_time is both in the past and its foreign counterpart in the Node table still has the status 1. I don't want to select the record 10111 because it hasn't expired.

I've just finished writing this SQL query, it works! Although I'm sure it can be written better and I'm interested to here what you have to say.

SELECT MAX(l.id) AS highestID, l.nid, n.status
                        FROM mbl AS l
                        INNER JOIN node AS n
                        ON l.nid = n.nid
                        WHERE n.status = 1
                        AND (   SELECT end_time
                                FROM mbl
                                WHERE id = (    SELECT MAX(id)
                                                FROM mbl
                                                WHERE nid = l.nid
                                                GROUP BY nid
                                            )
                            ) <= NOW()
                        GROUP BY l.nid

Mlb table data:

id  | nid | start_time | end_time

105 | 5 | 20/07/2014 01:00:00 | 24/07/2014 01:00:00

589 | 52 | 20/07/2014 01:00:00 | 31/07/2015 01:32:00

10108 | 874 | 20/07/2014 01:00:00 | 24/07/2014 01:00:00

10111 | 874 | 20/07/2014 01:00:00 | 24/07/2015 01:00:00

10156 | 967 | 20/07/2012 01:00:00 | 24/07/2013 01:00:00

10161 | 967 | 20/07/2013 01:00:00 | 20/07/2014 01:00:00

10192 | 967 | 20/07/2014 01:00:00 | 24/07/2014 01:00:00

Node table data:

nid  | status

5 | 0

52 | 1

874 | 1

967 | 1


texts: Unit testing a bash script manipulating the working directory path

texts:
bd is a bash script to conveniently jump multiple directory levels up from the current working directory instead of a tedious and possibly inaccurate cd ../../../..

Say, for example, that you are in the directory /home/user/project/src/org/main and you want to jump to project. Instead of counting the necessary levels to jump and typing cd ../../.., you can do bd -s pro (where -s is to match the start of the directory name, in this example "pro" for "project").

I came across this script in another question, and looking at the github repository I decided to jazz it up a little. But before going ahead and refactoring it, I wanted to make sure I'm not breaking anything, so I needed some sort of unit tests as a sane baseline first.

This is the main function in the bd script under testing,
and this is not for code review,
I'm including it here only for your reference in case it helps in some way:

# NOT for code review: the reference implementation under test
newpwd() {
  OLDPWD=$1
  if [ "$2" = "-s" ]
  then
    NEWPWD=`echo $OLDPWD | sed 's|\(.*/'$3'[^/]*/\).*|\1|'`
    index=`echo $NEWPWD | awk '{ print index($0,"/'$3'"); }'`
  elif [ "$2" = "-si" ]
  then
    NEWPWD=`echo $OLDPWD | sed 's|\(.*/'$3'[^/]*/\).*|\1|I'`
    index=`echo $NEWPWD | awk '{ print index(tolower($0),tolower("/'$3'")); }'`
  else
    NEWPWD=`echo $OLDPWD | sed 's|\(.*/'$2'/\).*|\1|'`
    index=`echo $NEWPWD | awk '{ print index($1,"/'$2'/"); }'`
  fi
}

What I'd like reviewed is my implementation of "unit tests" to verify the behavior of the newpwd function inside the bd script:

#!/bin/bash

# loading the "newpwd" function from the bd script, a necessary ugliness for now
. bd nonexistent > /dev/null

success=0
failure=0
total=0

assertEquals() {
    ((total++))
    expected=$1
    actual=$2
    if [[ $expected = $actual ]]; then
        ((success++))
    else
        ((failure++))
        echo "Assertion failed: $expected != $actual" >&2
        caller 0
        echo
    fi
}

sample=/home/user/project/src/org/main/site/utils/file/reader/whatever

# test run with no args
newpwd $sample
assertEquals $sample $NEWPWD
assertEquals 0 $index

# test run with exact match
newpwd $sample src
assertEquals /home/user/project/src/ $NEWPWD
assertEquals 19 $index

# test run with prefix but no -s so not found
newpwd $sample sr
assertEquals $sample $NEWPWD
assertEquals 0 $index

# test run with prefix found
newpwd $sample -s sr
assertEquals /home/user/project/src/ $NEWPWD
assertEquals 19 $index

# test run with prefix not found because case sensitive
newpwd $sample -s Sr
assertEquals $sample $NEWPWD
assertEquals 0 $index

# test run with prefix found thanks to -si
newpwd $sample -si Sr
assertEquals /home/user/project/src/ $NEWPWD
assertEquals 19 $index

sample='/home/user/my project/src'

# test run with space in dirname
newpwd "$sample" -s my
assertEquals '/home/user/my project/' "$NEWPWD"
assertEquals 11 $index

red='\e[0;31m'
green='\e[0;32m'
nocolor='\e[0m'

echo
[[ $failure = 0 ]] && printf $green || printf $red
echo "Tests run: $total ($success success, $failure failed)"
printf $nocolor
echo

My questions:

Is this easy to read? If not, how to improve it?
Is this a good way to test stuff in Bash? Is there a better way? I'd rather not add external dependencies to the project though, I'm looking for something ultra-light, or a technique
Are there any corner cases I missed?
Any other improvement ideas?


texts: PHP MVC implementation without a framework

texts:
I've been using PHP for years and in every project I've ever done I've included the HTML, PHP, SQL etc ... in the same page. Upon looking through Github at large projects like WordPress and MediaWiki it appears there are much better ways to lay out your code. I want to use MVC for my next project because I plan on making the code open source. I don't want to use a framework because I don't want lots of overhead and I don't want to have to learn a new framework to be honest.

I've started implementing what I think is a very simple MVC framework for my project. Can anyone who has experience with MVC tell me if I'm doing this correctly?

My project is called How, hence the class names.

The file structure of my project looks like this:

Root directory   -> index.php /includes/ .htaccess
In /includes/    -> /classes/ /controllers/ /routes/ /views/
In /classes/     -> _Globals.php How.php Route.php View.php
In /controllers/ -> Controller.php Root.php
In /Routes/      -> Route.php
In /views/       -> root.php

index.php

<?php
include_once( 'includes/classes/How.php' );

$how = new How();
$how->run();

/includes/classes/How.php

<?php
include_once( './includes/routes/Routes.php' );

class How {
    public function getRoute() {
    global $Routes;
    $uri = $_SERVER['REQUEST_URI'];

    if (!in_array($uri, $Routes)) {
        die("Invalid route.");
    }
    return $uri;
    }

    public function run() {
        try {
            $this->getRoute();
        } catch (Exception $e) {
            die("Failed to get route.");
        }
    }
}

/includes/classes/Route.php

<?php
include_once( '_Globals.php' );
class Route {

    private function registerRoute($route) {
        global $Routes;
        $Routes[] = BASEDIR.$route;
    }

    public static function set($route, $closure) {
        self::registerRoute($route);
        $closure->__invoke();
    }
}

/includes/classes/View.php

<?php
    class View {
        public static function make($view) {
            try {
                include( './includes/controllers/'.$view.'.php' );
                include('./includes/views/'.$view.'.php');
                return 1;
            } catch ( Exception $e ) {
                return 0;
            }
        }
    }

/includes/classes/_Globals.php

<?php
$Routes = array();
define( 'BASEDIR', '/how/' );

/includes/controllers/Root.php (Controller.php is currently blank)

<?php
class RootController {
    public static $username = "Francis";
}

/includes/Routes/Route.php

<?php
include_once( './includes/classes/Route.php' );
include_once( './includes/classes/View.php' );

Route::set('', function() {
    View::make('root');
});

Route::set("about-us", function() {
});

/includes/views/root.php

Welcome <?php echo RootController::$username; ?>!

.htaccess

RewriteEngine On
RewriteRule ^([^/]+)/? index.php?url=$1 [L,QSA]

It works like this:

The .htaccess redirects all requests to index.php.
Index.php calls how->run() which checks if the current route is valid.
Valid routes are stored in the global $Routes array, they are added to the $Routes array by the Route::set() method in the Routes/Route.php.
If the route is valid the View::make() method is called which loads the view from /includes/views/ and the ViewController is loaded from /includes/controllers/.


texts:
I need to figure out the best way to deal with memory pre-allocation

Below is pseudo-code for what I am doing now, and it seems to be working fine.

I am sure there is a better way to do this, I would like to see if anyone has any good idea.

In Thread A I need to allocate 300 MB of memory and zero it out:

Thread A:

char* myMemory = new char[10*30*1024*1024];

In Thread B I incrementally get 10 sets of data 30 MB each. As I get this data it must be written to memory

Thread B:

int index1 = 0;
char* newData = getData(...); // get a pointer to 30 MB of data
memcpy(&myMemory[index1*30*1024*1024], &newData[0], 30*1024*1024];
SetEvent(...) // tell Thread C that I have written new data

// use index i as circular Buffer
if (index1 < 10)
 index1++;
else
 index1 = 0;

In Thread C, when new data is written, I need to get it and process it

Thread C:

int index2 = 0;
char* dataToProcess[] = new char[30*1024*1024];
if (event Fires) // if event in Thread B is set
 memcpy(&dataToProcess[0], &myMemory[index2*30*1024*1024], 30*1024*1024];
 processData(dataToProcess)

// use index i as circular Buffer
if (index2 < 10)
 index2++;
else
 index2 = 0;


texts:
I have written a palindrome program. And I was just wondering if it correct? I checked using the words racecar and madam, and it says they are palindromes. I have also tested nonpalindrome words and it worked correctly.

Is my implementation correct? If it's not could you correct it for me. It it works correct, is there an easier way to implement this?

def is_palindrome(x):

    for i in range(0,len(x)):
        x = x.lower()
        if x[i::1] == x[::-1]:
            return("%s Is a palindrome" %(x))
        else:
            return("%s Is not a palindrome" %(x))

print(is_palindrome('racecar'))


texts:
Given

  Roy wanted to increase his typing speed for programming contests. So, his friend advised him to type the sentence "The quick brown fox jumps over the lazy dog" repeatedly, because it is a pangram. (Pangrams are sentences constructed by using every letter of the alphabet at least once.)
  After typing the sentence several times, Roy became bored with it. So he started to look for other pangrams. Given a sentence s, tell Roy if it is a pangram or not. Input Format Input consists of a line containing s.

Constraints

  Length of s can be at most 103 \$(1≤|s|≤103)\$ and it may contain spaces, lower case and upper case letters. Lower case and upper case instances of a letter are considered the same.

Solution 1

from collections import defaultdict
import string

def is_pangram(astr):
    lookup = defaultdict(int)

    for char in astr:
        lookup[char.lower()] += 1
    for char in string.ascii_lowercase:
        if lookup[char] == 0:
            return False
    return True

print "pangram" if is_pangram(raw_input()) else "not pangram"

Solution 2

from collections import Counter
import string

def is_pangram(astr):
    counter = Counter(astr.lower())
    for char in string.ascii_lowercase:
        if counter[char] == 0:
            return False
    return True

print "pangram" if is_pangram(raw_input()) else "not pangram"

Which is better in terms of running time and space complexity?


texts: ASP.Net Core WebAPI Authorization Policy for User or Admin

texts:
I have a controller that returns data about users. I want to set the authorization such that an admin can access this controller and retrieve data for any user, and a non-admin user can access the controller and retrieve data for themselves.

I've ruled out using [Authorize (Roles = "Admin")] because this means users can't get their own data. So I've inserted the following logic into the controller action:

var userId = _httpContextAccessor.HttpContext.User.FindFirst(ClaimTypes.Name).Value;
var roles = _httpContextAccessor.HttpContext.User.FindAll(ClaimTypes.Role);

var query = roles.Select(r => r.Value).Contains("Admin");

Customer customer =await _context.Customers.FindAsync(id);

if (!(customer.EmailAddress == userId || query))
 return Unauthorized();

This is roughly equivalent to this Stack Overflow answer, but for ASP.Net Core rather than MVC.

My question is, is there a way to do this with an Authorization Policy? Adding the RequireRole check is straightforward and covered in the MS Documentation as well as countless blogs, but I couldn't find or figure out a way to use a policy to check that the data the user is trying to access is their own.

I'm sure this isn't an uncommon requirement, is there a way to do this, or is what I'm currently doing OK? The only other approach I could think of was to have two separate endpoints, but both options seem inelegant.


texts: Python class hierarchy, extend ancestor data

texts:
I have a hierarchy of entities that should contain dictionaries with metadata. Any sub-class should inherit its ancestor dictionary and be able to add some key-values (delete inherit keys is not needed). The easiest solution I can think about is this:

class A(object):
    def __init__(self):
        self.doc = A.generate_doc()

    @staticmethod
    def generate_doc():
         return {'a': 0}

class B(A):
    def __init__(self):
        super().__init__()
        self.doc.update(B.generate_doc())

    @staticmethod
    def generate_doc():
        return {'b': 0}

class C(B):
    def __init__(self):
        super().__init__()
        self.doc.update(C.generate_doc())

    @staticmethod
    def generate_doc():
        return {'c': 0}

print(A().doc)  # {'a': 0}
print(B().doc)  # {'a': 0, 'b': 0}
print(C().doc)  # {'a': 0, 'b': 0, 'c': 0}

Is this a good design? Could the update() blocks be implicit maybe? I have more than one document in real code, so that would be nice.


texts: Classes for user registration and authentication

texts:
<?php
namespace Users;

use mysqli;

class Users {
    protected $db;
    public function __construct() {
        $this->db = new mysqli('localhost', 'root', 'php123', 'sms');
    }
    public function login($username, $password) {
        $query = $this->db->prepare("SELECT username, password FROM users WHERE username=? AND password=? LIMIT 1");
        $password = UserData::hash($password);
        $query->bind_param('ss', $username, $password);
        $query->execute();
        $query->bind_result($username, $password);
        $query->store_result();
        if($query->num_rows ==1) {
            while($query->fetch()) {
                $_SESSION['loggedin'] = 1;

                UserData::getAndSet($username);

                header("Location: dashboard.php");
            }
        } else {
            return false;
        }
        $query->free_result();
        $query->close();
    }
    public function register($username, $password, $rank, $name) {
        $errors = array();
        $query = $this->db->prepare("INSERT INTO users VALUES('', $username, $password, $rank, $name);");

        $password = UserData::hash($password);

        $query->bind_param('ssss', $username, $password, $rank, $name);

        if(strlen($username) < 3 || strlen($username) > 15) {
            $errors[] = "The length of the username can only range from 3 to 15 characters.";
        }
        if(strlen($password) < 3 || strlen($password) > 15) {
            $errors[] = "The length of the password can only range from 3 to 15 characters.";
        }
        if(strlen($name) < 3 || strlen($name) > 15) {
            $errors[] = "The length of the name can only range from 3 to 15 characters.";
        }

        $query->execute();
        $query->close();
    }
}
class UserData {
    protected $db;

    public $username;
    public $password;
    public $rank;
    public $name;

    public function __construct() {
        $this->db = new mysqli('localhost', 'root', 'php123', 'sms');
    }

    public function getAndSet($username) {
        $query = $this->db->prepare("SELECT username, password, rank, name FROM users WHERE username=?");
        $query->bind_param('s', $username);
        $query->execute();
        $query->bind_result($username, $password, $rank, $name);
        $query->store_result();
        while($query->fetch()) {
            $this->username = $username;
            $this->password = $password;
            $this->rank     = $rank;
            $this->name     = $name;
        }
        $query->free_result();
        $query->close();
    }
    public function hash($string) {
        $fSalt = "{z6Q9&2eHn69,9/cXa=<,Nm[?^^Tw-";
        $sSalt = ":L+;fwS<q%)3f?N_d)(Ta_*fN&ax}+";

        $sting = md5(md5($fSalt) . md5($string) . md5($sSalt));

        for($i=0; $i < 3; $i++) {
            $string = md5($string);
            $string = sha1($string);
            $string = bin2hex($string);
            $string = md5($string);
        }

        return $string;
    }
}
class UserUtil {
    protected $db;
    public function __construct() {
        $this->db = new mysqli('localhost', 'root', 'php123', 'sms');
    }
}

$Users    = new Users();
$UserData = new UserData();
$UserUtil = new UserUtil();

?>

This is the beginning of my project, "Student Management System" and before I proceed I want this code to be rated, and how can I improve this code with better ways.


texts:
I have such a method that performs a long query search against some data.

Task<List<SearchResult>> Search(string query){ ... }

I have tried various way to create an IObservable form of it but failed. At the end after some google help I wrote such a method.

private IObservable<SearchResult[]> Search(string query)
{
    return Observable.Create((IObserver<SearchResult[]> observer)=>
        {
            List<SearchResult> result = new List<SearchResult>();
            foreach (TestsGroupMeta group in Engine.Groups)
            {
                string name = group.ToString();
                if (name.IndexOf(query, StringComparison.InvariantCultureIgnoreCase) != -1)
                {
                    result.Add(new SearchResult{ Name = name, Type = "Group"});
                }

                foreach (TestMethodMeta method in group.Methods)
                {
                    name = method.ToString();
                    if (name.IndexOf(query, StringComparison.InvariantCultureIgnoreCase) != -1)
                    {
                        result.Add(new SearchResult {Name = name, Type = "Method"});
                    }
                }
            }

            observer.OnNext(result.ToArray());
            observer.OnCompleted();

            return () => {};
        });
}

Is such a method correctly written? If not, what would be correct?


texts: Infix to postfix Converter implementation

texts:
Please suggest some ways to improve my code for calculating a postfix expression from an infix expression entered by the user. The size of the input (Infix string) should not exceed 10 charaters since the maximum size of the input string mentioned in the code is 10.

#include<stdio.h>
#include<conio.h>
#include<ctype.h>

char Infix[10];
char Symbol[10];
char Postfix[10];

void Push();
void Pop();
int Preced(char, char);

void main()
{
   clrscr();
   printf("Enter a Infix Expression:");
   scanf("%s",&Infix);
   Push();
   printf("\nPostfix of Entered Expression: %s",Postfix);
   getch();
}

void Push()
{
   int i=0, j=0, k=0, s=0;
   while(Infix[i]!='\0')
   {
      if(Infix[i]=='('||Infix[i]==')'||Infix[i]=='*'||Infix[i]=='+'||Infix[i]=='-'||Infix[i]=='/'||Infix[i]=='%'||Infix[i]=='^')
      {
     Symbol[j++]=Infix[i];
      }
      else if(isalpha(Infix[i]))
      {
     Postfix[k++]=Infix[i];

      }
      if(Preced(Symbol[j-2],Symbol[j-1])==1)
      {
     Postfix[k++]=Symbol[j-2];
     Symbol[j-2]=Symbol[j-1];
     Symbol[j-1]=NULL;
     j=j-1;
      }
      if(Symbol[j-1]==')')
      {
    s=j-1;
    while(Symbol[--s]!='(')
    {
      printf("%c ",Symbol[s]);
      Postfix[k++]=Symbol[s];
      Symbol[s]=Symbol[s+1];
      Symbol[s+1]=NULL;
    }
      }
      i++;
   }
   while(--j>=0)
   {
     if(Symbol[j]=='^'||Symbol[j]=='*'||Symbol[j]=='/'||Symbol[j]=='%'||Symbol[j]=='+'||Symbol[j]=='-')
       Postfix[k++]=Symbol[j];
   }
}

int Preced(char c1, char c2)
{
  if(c1=='^'&&c2=='^')                                           //equal priorities.
  {
    return 1;
  }
  else if((c1=='+'||c1=='-')&&(c2=='+'||c2=='-'))                      //equal
  {
    return 1;
  }
  else if((c1=='*'||c1=='/'||c1=='%')&&(c2=='*'||c2=='/'||c2=='%'))     //equal
  {
    return 1;
  }
  else if(c1=='^'&&(c2=='*'||c2=='/'||c2=='+'||c2=='-'||c2=='%'))
  {
    return 1;
  }
  else if((c1=='*'||c1=='/'||c1=='%')&&(c2=='+'||c2=='-'))
  {
    return 1;
  }
  else
  {
    return -1;
  }
}


texts:
Please keep in mind I am new and still learning when reading the following.

What I am doing

I have the following code which pulls a sport, tournament and round NR, from a DB table called event where the event is still active.

The Problem

The code works and does what I want it to do, but my problem is looking at the code makes me sick, I know there are more efficient ways to achieve what I am trying to do but I am unsure of where to start to improve the code below, I would like to move to a more object orientated or at least a more efficient way of coding.

I would appreciate it if one of the more experienced members of the community could give the code a look and provide some pointers.

$date = date('Y-m-d');
//get sport & tournament
$sql = "Select distinct sport, tournament, round FROM event WHERE date > $date AND active = 'y'";
$result = mysqli_query($conn,$sql) or die(mysqli_error($conn));
while($row = mysqli_fetch_array($result)){
    $sport[] = $row['sport'];
    $tournament[] = $row['tournament'];
    $round[] = $row['round'];
}
//make form with tournament & sport
?>
<form name="select" name="sport" method="post">
<!--GET SPORT ON SELECT  -->
<select name="sport">
<?php
//get sport
foreach($sport as $index => $sportCode){
    echo '<option value="'. $sport[$index].'">'.$sport[$index].'</option>';
}
?>
</select>
<!--GET TOURNAMENT ON SELECT  -->
<select name="tournament">
<?php
//get tournament
foreach($tournament as $index => $tournamentCode){
    echo '<option value="'. $tournament[$index].'">'.$tournament[$index].'</option>';
}
//get round
?>
</select>
<select name="round">
<?php
foreach($round as $index => $roundNr){
    echo '<option value="'. $round[$index].'">'.$round[$index].'</option>';
}
//get round
?>
</select>
</form>


texts:
I decided to try out Python (3.x) two or so weeks ago, and this is my first real script using it. The program I've written below is slow, clunky, inefficient, inaccurate, and probably poorly coded! But it produces what I want most of the time, and it was really just a project to become accustomed to different Python techniques.

What it should do is, recieve a string, one that looks like a tag from a social media site (#socialmedia, #20000leaguesunder, etc.), and then based on a dictionary, split the string into logical words.

So "#volunteeringtoday" becomes "volunteering today" and so on.

I understand my algorithm is poor, so any help with the actual Python and formatting would be preferred.

import re

class Splitter():

    input = ''
    clean = ''
    words = []

    def __init__(self, string):
        '''
        Set the input string
        '''
        self.input = string

    def split(self):
        '''
        Split the input string. Get the clean version then start the separation loop.
        '''
        self.clean = self.cleanString(self.input)
        return self.separateString(self.clean)

    def separateString(self, inp):
        '''
        Separate the string input. Break apart and look for matches in a dictionary.
        '''
        # Index each character in the input string
        for ind in range(len(inp)):
        # Build a segment
        built = self.partition(inp, ind)
        #print('"'+built+'"') # Add for details
        # If only one letter remains, steal a letter from the previous match
        if len(built) == 1:
            built = self.words[-1][-1] + self.lastLarge
            self.words[-1] = self.words[-1][0:-1]
            return self.separateString(built)
        # Check if segment ends with a digit. Separate it if it does.
        if re.match('\d+$', built):
            built = re.sub("([^\d])\d", "", built)
            self.words.append(built)
            return self.separateString(inp.replace(built, '', 1))
        # It does not end with a digit
        else:
            # Iterate over each line in the dictionary
            for word in open('word.txt', 'r'):
                if self.cleanString(word) == built:
                    self.words.append(built)
                    # Check if list of separations joined together is equal to original
                    if ''.join(self.words) == self.clean:
                        return ' '.join(self.words)
                    else:
                        # Loop back through to separate more
                        self.lastLarge = inp.replace(built, '', 1)
                        return self.separateString(inp.replace(built, '', 1))

    def partition(self, value, index):
        '''
        Break apart string. Length from right
        '''
        return value[0:len(value) - index]

    def cleanString(self, string):
        '''
        Remove all non-alphabetic and non-digit characters.
        '''
        return re.sub("[^\d[a-z]]*", "", string.lower().strip())

And then you can sample it with something such as:

splitter = Splitter(input('Hashtag: '))
print('\nFinal:',splitter.split())

word.txt is a text file with roughly 60k words. One on each line. The list can be found here.

Any tips on making it more professional?


texts: Method to check if TicTacToe board has a winner

texts:
I have a class called TicTacToeBoard that has a [3][3] array of TicTacToeBoardCells.  Doc neck if board has a winner, I check if any of the 8 possible combinations have 3 of these are type.

Is there any way to make the check of the 8 states more elegant? I am not looking for optimizations like reducing number of checks using a hash table or using check of an earlier nomination, but more about ideas on how I can make my checks more elegant.

TicTacToeBoardCell.h

typedef NS_ENUM(NSInteger,TicTacToeStates)
{
    playerA=-1,
    notSet,
    playerB
};

@interface TicTacToeBoardCell : NSObject

@property TicTacToeStates state;

@end

TicTacToeBoard.h

@interface TicTacToeBoard : NSObject
{
    TicTacToeBoardCell* cells[3][3];
}

-(BOOL) checkForWinner;
-(void) changeStateOfPoint:(CGPoint)cell toState:(TicTacToeStates)state;

@end

TicTacToeBoard.m

//Can this be made more elegant?
-(BOOL) checkForWinner
{
    int sum;

    for (int x=0; x<3; x++)
    {
        sum = 0;
        for(int y=0; y<3;y++)
        {
            sum += cells[x][y].state;
        }
        if (sum == -3 || sum == 3)
        {
            return TRUE;
        }
    }

    for (int y=0; y<3; y++)
    {
        sum = 0;
        for(int x=0; x<3;x++)
        {
            sum += cells[x][y].state;
        }
        if (sum == -3 || sum == 3)
        {
            return TRUE;
        }
    }

    sum = cells[0][0].state + cells[1][1].state + cells[2][2].state;
    if (sum == -3 || sum == 3)
    {
        return TRUE;
    }

    sum = cells[2][0].state + cells[1][1].state + cells[0][2].state;
    if (sum == -3 || sum == 3)
    {
        return TRUE;
    }

    return FALSE;
}


texts: Updating state with React and Websockets

texts:
I'm working on a React app with websocket. In this app there is a socket event listener which returns 3 types: add, change, and remove. Certain state update operations will be performed based on the type received.

Do I properly mutate the users state? I'm not sure whether it follows the principle of React regarding updating states.

ws.on("connect", () => {
  console.log("connected");

  ws.emit("load");
});

ws.on("feed", response => {
  const prev = response.old_val;
  const next = response.new_val;
  const type = response.type;
  setUsers(users => {
    let currentUser = [...users];
    let index;
    switch (type) {
      case "add":
        return [...users, next];
      case "change":
        index = users.findIndex(u => u.id === next.id);
        currentUser[index].name = next.name;
        return currentUser;
      case "remove":
        index = users.findIndex(u => u.id === prev.id);
        currentUser.splice(index, 1);
        return currentUser;
      default:
        return currentUser;
    }
  });
});


texts:
I have wrote simple class that allowing database selection and inserts.Could you please tell me does this a right way to use __call method with any useful advantage of it ?

 <?php
class _getDatabase
{
    public $db;

   public function __construct(PDO $connection)
    {
        $this->db = $connection;
    }
  public function __call($function, $args) {

          if ($function == 'getSelect') {
            $sql = $this->db->prepare($args[0]['query']);
            $sql->execute(array(
                $args[0]['parameters']
            ));
            return $sql->fetchALL(PDO::FETCH_OBJ);
          }

           if ($function == 'getInsert') {
            $sql = $this->db->prepare($args[0]['query']);
            $result = $sql->execute($args[0]['parameters']);
            return $result;
          }
  }
}

$dbh = new PDO("mysql:host=127.0.0.1;dbname=" . DATABASE, USERNAME, PASSWORD, array(
    PDO::ATTR_PERSISTENT => true
));
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // Set Errorhandling to Exception
$dbFactory = new _getDatabase($dbh);
$select = array();
$insert = array();
$select['query'] = 'SELECT * FROM `branches` WHERE B_CODE = ?';
$select['parameters'] = 'AMB';

$insert['query'] = 'INSERT INTO `commition`(`date`, `reg`, `com`, `oper`) VALUES (?,?,?,?)';
$insert['parameters'] = array('2014-02-20','86869','DITEC','Asuntha');
var_dump($dbFactory->getSelect($select));
var_dump($dbFactory->getInsert($insert));
?>


texts:
class EmptyStackError(Exception):
    def __init__(self):
        super().__init__('Stack is empty. Invalid operation')

class FullStackError(Exception):
    def __init__(self):
        super().__init__('Stack is full. Cannot push')

class Stack:
    """ Stack with a specified size """
    def __init__(self, size):
        self.head = None
        self.size = size
        self.current_size = 0

    def push(self, data):
        """ Push data to the top of the stack """
        if self.current_size == self.size:
            raise FullStackError
        node = Node(data)
        if not self.head:
            self.head = node
        else:
            node.next_node = self.head
            self.head = node
        self.current_size += 1

    def pop(self):
        """ Remove data from the top of the stack and return it """
        if not self.head:
            raise EmptyStackError
        data = self.head.data
        self.head = self.head.next_node
        self.current_size -= 1
        return data

    def peek(self):
        """ Take a look at the current item at the top of stack, but do not return it"""
        if not self.head:
            raise EmptyStackError
        data = self.head.data
        return data

    def get_size(self):
        """ Return the current size of the stack """
        return self.current_size

opening_brackets = '([{'
closing_brackets = ')]}'

def check_balance(input_string: str) -> bool:
    answer = True
    stack = Stack(100)
    for char in input_string:
        if char in opening_brackets:
            stack.push(char)
        else:
            try:
                top_item = stack.peek()
            except EmptyStackError as e:
                answer = False # if it's with closing brackets, it's not balanced
                break
            if tuple([top_item, char]) not in zip(opening_brackets, closing_brackets):
                answer = False
                break
            else:
                stack.pop()
    if stack.get_size() != 0:  # there shouldn't be any items remaining in the stack if it's balanced
        answer = False
    return answer

""" Testing """
strings = ['', '[({})]', '[', '}']
[True, True, False, False] == list(map(check_balance, strings))

I have a stack implementation (along with the EmptyStackError).
I didn't want to add to make easier visually, but it might be relevant.
I'm finding the code lacking in grace and elegance.
Any way to improve on this code?
Any bug I cannot see?

Note: I've added the try clause (which I tend to find not that easy on the eyes) to fix a bug when starting with a closing bracket, I get an EmptyStackError which is internal to the stack implementation.

Note: I'm using jupyter lab if that's relevant in any way :)


texts: Concurrent stack implementations in Ruby (relative performance of mutexes/CAS?)

texts:
This code is very simple, but it is intended as an experiment in the relative performance of mutexes/CAS on different platforms. The latest version can always be found at:

https://github.com/alexdowad/showcase/blob/master/ruby-threads/concurrent_stack.rb

It comes with a built-in benchmarking script. Please try running and post the results, along with your OS, version of Ruby, and CPU. Please also post if you can find any way to improve style or performance.

For convenience the first version of the code is reproduced below:

# 3 thread-safe stack implementations
# Written by Alex Dowad

# Usage:
# stack.push(1)
# stack.peek    => 1 (1 is not removed from stack)
# stack.pop     => 1 (now 1 is removed from stack)

require 'rubygems' # for compatibility with MRI 1.8, JRuby
require 'thread'
require 'atomic'   # atomic gem must be installed

# The easy one first
class ThreadSafeStack
  def initialize
    @s,@m = [],Mutex.new
  end
  def push(value)
    @m.synchronize { @s.push(value) }
  end
  def pop
    @m.synchronize { @s.pop }
  end
  def peek
    @m.synchronize { @s.last }
  end
end

# a non-locking version which uses compare-and-swap to update stack
class ConcurrentStack
  Node = Struct.new(:value,:next)

  def initialize
    @top = Atomic.new(nil)
  end
  def push(value)
    node = Node.new(value,nil)
    @top.update { |current| node.next = current; node }
  end
  def pop
    node = nil
    @top.update do |current|
      node = current
      return if node.nil?
      node.next
    end
    node.value
  end
  def peek
    node = @top.value
    return if node.nil?
    node.value
  end
end

# same as ConcurrentStack, but additionally recycles popped nodes
# (to reduce load on GC)
# a global free list is used, and is also updated using CAS,
#   in exactly the same way as the stacks themselves
class RecyclingConcurrentStack
  Node      = Struct.new(:value,:next)
  FREE_LIST = Atomic.new(nil)

  def initialize
    @top = Atomic.new(nil)
  end
  def push(value)
    node = get_node(value)
    @top.update { |current| node.next = current; node }
  end
  def pop
    node = nil
    @top.update do |current|
      return if (node = current).nil?
      node.next
    end
    result = node.value
    FREE_LIST.update do |current|
      node.next = current
      node
    end
    result
  end
  def peek
    node = @top.value
    return if node.nil?
    node.value
  end

  private
  def get_node(val)
    # if contention causes the CAS to fail, just allocate a new node
    node = FREE_LIST.value
    if node && FREE_LIST.compare_and_swap(node,node.next)
      node.value = val
      node
    else
      Node.new(val,nil)
    end
  end
end

# Test driver
if __FILE__ == $0
  require 'benchmark'
  ITERATIONS_PER_TEST = 1000000
  QUEUE,MUTEX = ConditionVariable.new,Mutex.new

  def wait_for_signal
    MUTEX.synchronize { QUEUE.wait(MUTEX) }
  end
  def send_signal
    MUTEX.synchronize { QUEUE.broadcast }
  end

  def test(klass)
    test_with_threads(klass,1)
    test_with_threads(klass,5)
    test_with_threads(klass,25)
  end

  def test_with_threads(klass,n_threads)
    stack = klass.new
    iterations = ITERATIONS_PER_TEST / n_threads
    puts "Testing #{klass} with #{n_threads} thread#{'s' if n_threads>1}, iterating #{iterations}x each"

    threads = n_threads.times.collect do
                Thread.new do
                  wait_for_signal
                  iterations.times do
                    stack.push(rand(100))
                    stack.peek
                    stack.pop
                  end
                end
              end
    n_gc = GC.count
    sleep(0.001)

    result = Benchmark.measure do
      send_signal
      threads.each { |t| t.join }
    end
    puts result
    puts "Garbage collector ran #{GC.count - n_gc} times"
  end

  test(ThreadSafeStack)
  test(ConcurrentStack)
  test(RecyclingConcurrentStack)
end


texts:
I'm pretty new to OCaml, so any feedback is appreciated. The goal is to implement a trie that efficiently stores and sorts strings.

module CharMap = Map.Make(Char)

(* count of members of the set that end at this node * mapping from
   next char => children *)
type trie = Node of int * trie CharMap.t

let empty = Node (0, CharMap.empty)

(* Add a string to the trie *)
let rec add (Node (count, children) : trie) = function
  | "" -> Node (count + 1, children)
  | str ->
    let firstChar = String.get str 0 in
    let lastChars = String.sub str 1 ((String.length str) - 1) in
    let newTrie = if CharMap.mem firstChar children
      then add (CharMap.find firstChar children) lastChars
      else add empty lastChars in
    let newChildren = CharMap.add firstChar newTrie children in
    Node (count, newChildren)

let addAll (trie : trie) (strs : string list) : trie =
  List.fold_left (fun trieAcc str -> add trieAcc str) empty strs

(* Get all the strings of a trie *)
let traverse (trie : trie) : string list =
  let rec helper (Node (count, children) : trie) (prevChar : char option)
      : string list =
    let string_of_char chr =
      match chr with
        | None -> ""
        | Some ch -> String.make 1 ch in
    let perChild = List.map (fun (chr, child) ->
      (helper child (Some chr))) (CharMap.bindings children) in
      let fromChildren = List.flatten perChild in
    let withPrev =
      List.map (fun str -> (string_of_char prevChar) ^ str) fromChildren in
    let rec clone str count =
      if count = 0 then [] else str::(clone str (count - 1))
    in (clone (string_of_char prevChar) count) @ withPrev in
  helper trie None

let sort (strs: string list): string list =
  traverse (addAll empty strs)

What do you think?


texts: Clarification on "if" statement - Digital Clock Tutorial C#

texts:
I am building a digital clock in C# after watching a tutorial. The code in the tutorial I need help understanding looks like this:

if (hh < 10) {
    time += "0" + hh;
}
else {
    time += hh;
}
time += ":";

Can anyone explain to me why hh < 10? Should it not be at least 12?

My end  game is to make a timer that starts at 9am and stops at 5pm. Ongoing applications under development. Looking at time money management.


texts:
I'm writing a simple JavaScript game, which uses a 2-dimensional array as the main data structure. I wrote this function-class-thing that allows me to give any two integers, positive or negative.  This class should "wrap" those integers back onto the game grid.

For example:

var g = new Grid(10, 10)
g.set(15, -2, "hello")
g.get(5, 8); //should be "hello"

Anyway, I'm striving to improve my JavaScript, so I'm wondering if there are any improvements (performance, "javascriptness", etc.) that I might be able to make.

var Grid = (function(w, h){
    this._width = w;
    this._height = h;
    this._grid = new Array((this._width * this._height) | 0);
    this.get = function(x, y){
            var coords = _normalize(x, y);
            return this._grid[(coords.y * coords.x) + coords.x];
    }
    this.set = function(x, y, item){
            var coords = _normalize(x, y);
            this._grid[(coords.y * coords.x) + coords.x] = item;
    }
    this._normalize = function(x, y){
            if(x < 0) x = (this._width + x) % this._width;
            else if(x >= this._width) x = x % this._width ;
            if(y < 0) y = (this._height + y) % this._height;
            else if(y >= this._height) y = y % this._height;
            return {'x': x, 'y': y};
    }
});


texts:
I have written a caching wrapper method for some of my services. The actual wrapper method is written as follows:

public T GetFromCache<T>(string key, Func<T> defaultValuePredicate, object cacheLock, TimeSpan duration)
{
    lock (cacheLock)
    {
        var result = _cache[key] is T ? (T)_cache[key] : default(T);
        if (Equals(default(T), result))
        {
            result = defaultValuePredicate();
            if (!Equals(default(T), result))
            {
                _cache.Add(key, result, null,
                            DateTime.Now.Add(duration),
                            System.Web.Caching.Cache.NoSlidingExpiration,
                            System.Web.Caching.CacheItemPriority.Default,
                            (cacheKey, value, reason) =>
                            Debug.WriteLine(string.Format("{0} Dropped from cache becasue {1}", cacheKey, reason)));
            }
        }

        return result;
    }
}

A typical use case is this:

public class SomeService
{
    private static readonly object _lock = new object();

    public string GetSomeValue()
    {
         return GetFromCache("SomeService_GetSomeValue", () =>
                            {
                                //Expensive operation here
                            },
                            _lock,
                            TimeSpan.FromSeconds(600));
    }

}

In all the example code that I've seen floating around the web people never seem to lock around expensive, but cached operations. The reason I lock is to prevent the same operation kicking off twice, duplicating the effort.

Is this approach reasonable and robust, or does it need serious modification to make it more reliable?


texts: How to speed up this IP sweep, Port scanner python

texts:
I am looking for a way to speed up my basic IP scanner/port scanner in Python 3.8.
My IP portion works, the port scan work, I just want to speed it up, in a format that someone learning python would understand.
#testing scanner.py
import socket
import subprocess
import sys
from datetime import datetime
def scan():
    # Ask for the IP address to scan, for this its a single IP
    remoteServer = input("Enter a Starting IP: ")
    remoteServerend = input("Enter the Ending IP: ")
    print ("Starting Scan at: ",remoteServer)
    print ("Ending Scan at: ",remoteServerend)
    # change DNS to IPmail
    #remoteServerIP = socket.gethostbyname(remoteServer)
    #print ("remoteServerIP is ",remoteServerIP)
    # Ask for starting port
    startport = int(input("What port number do you want to start with? "))
    # Ask for ending port
    endport = int(input("What is the ending port number? "))
    # Print 50 *'s to make a top border
    print ("-" * 50)
    # print wait here is the IP we are scanning
    print ("Please wait, scanning remote host", remoteServer)
    # print the bottom border
    print ("-" * 50)
    # Check what time the scan started
    t1 = datetime.now()
    # lets try the try statment for some error handeling and see if it can help?
    try:
    # trying our 1st port to our last port and replying if it is open, we don't care about closed ports
        for port in range(startport,endport):
            sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            result = sock.connect_ex((remoteServer, port))
            if result == 0:
                print ("Port {}:     Open".format(port))
            sock.close()
    # you got tied of waiting and quit
    except KeyboardInterrupt:
        print( "You pressed Ctrl+C")
        sys.exit()
    # failed DNS lookup
    except socket.gaierror:
        print( 'Hostname could not be resolved. Exiting')
        sys.exit()
    # no route to server?
    except socket.error:
        print( "Couldn't connect to server")
        sys.exit()
    # get ending time
    t2 = datetime.now()
    # calculate how long did the script run?
    total =  t2 - t1
    # Printing the information to screen
    print( 'Scanning Completed in: ', total)

scan()


texts: Finding the maximum of a given list of data in GNU Assembly x86 (32 bit)

texts:
I am following the book Programming from the Ground Up and as an answer to a question in the Use the Concepts section of chapter 4:

  Convert the maximum program given in the Section called Finding a Maximum
  Value in Chapter 3 so that it is a function which takes a pointer to several values
  and returns their maximum. Write a program that calls maximum with 3
  different lists, and returns the result of the last one as the program’s exit status
  code.

I wrote the following code:

maxfunc.s

# NAME:     maxfunc.s
# PURPOSE:  A modular approach of finding the maximum of lists

    .section .data
    # The data section has three lists for testing, change the code
    # highlighted in the text section to change the list passed.
data_1:
    .long 1, 2, 3, 4, 5, 6, 7, 8, 9, 0
data_2:
    .long 23, 45, 62, 13, 87, 54, 0
data_3:
    .long 1, 2, 3, 3, 3, 7, 6, 5, 8, 1, 1, 0

# VARIABLES:
# 1. %edi - Will be our index variable, to access the items
# 2. %ebx - The element we're looking at currently
# 3. %eax - The maximum value we've found so far
# 4. %ecx - To store the address of the list

    .section .text
    .globl _start
_start:
    # Push the address of the list we want to find the maximum of
    pushl   $data_3
    #             ^
    #             +---> Change this to select your list

    call    maximum
    addl    $4, %esp    # Reset the stack

    movl    %eax, %ebx
    movl    $1, %eax
    int     $0x80

    .type   maximum, @function
maximum:
    # Setup
    pushl   %ebp
    movl    %esp, %ebp

    # The initial setup:
    # Get the address of the list
    # Set the index to 0
    # Get the first item from the list
    # The first item is currently the largest
    movl    $0, %edi
    movl    8(%ebp), %ecx
    movl    (%ecx, %edi, 4), %ebx
    movl    %ebx, %eax

max_loop:
    cmpl    $0, %ebx
    je      exit_loop

    incl    %edi
    movl    (%ecx, %edi, 4), %ebx

    cmpl    %eax, %ebx
    jle     max_loop

    # %ebx is greater than %eax, therefore, update max
    movl    %ebx, %eax
    jmp     max_loop

exit_loop:
    # Tear down
    movl    %ebp, %esp
    popl    %ebp
    ret

It compiles and works as intended. I'm compiling it as a 32 bit binary on my 64 bit machine, so that I can follow the book.

I'd like suggestions on the proper use of conventions, and everything in general.


texts:
I came across this question from LeetCode OJ where I am given a string containing parentheses and I need to find out if the string contains valid matching parentheses or not.

  Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.

  The brackets must close in the correct order, "()" and "()[]{}" are all valid but "(]" and "([)]" are not.

This is the code I wrote (it got accepted and passed all the test cases.)

/** Java program to check if input string contains matching parameters
    or not.
 *  @author     :       Anish
 *  @date       :       01-11-2017
 */
 import java.util.Stack;

 class Solution
 {
    public boolean isValid(String str)
    {
        Stack<Character> stack  =   new Stack<Character>();

        char top    =   ' ';
        int len     =   str.length();

        for (int i = 0; i < len; i++)
        {
            char ch    =   str.charAt(i);

            if (ch == '(')
                stack.push(')');

            else if (ch == '[')
                stack.push(']');

            else if (ch == '{')
                stack.push('}');

            else if (!stack.empty())
            {
                top   =   stack.peek();

                if (top == ch)
                    stack.pop();
                else
                    stack.push(ch);
            }
            else if (stack.empty())
            {
                stack.push(ch);
            }
        }
        if (stack.empty())
        {
            return true;
        }
        return false;
    }
 }

ANALYSIS

Time Complexity : \$O(n)\$

Run Time : 9ms (on the leetcode OJ)

ISSUES

Even though my time is \$O(n)\$, yet my percentile is 70.4 which effectively means there are better and faster solutions out there. In that case, how do I optimize the above code to make it faster?
I have been using the Stack API provided by Java to solve the problem. Rather, if I were to redesign my own stack API and then use it to solve the problem, would I get faster runtime and better performance?
If the above point is true, then does it mean that in general, user designed APIs are faster than what is provided by the Java libraries? (assuming the user designed API is clean and bug free)


texts: This recursive function encrypts a string

texts:
Is there a way to rewrite these last 2 recursive functions with fewer arguments (preferably 2) while keeping them recursive?
The entire code can be seen here: https://github.com/GirkovArpa/hutton-typescript
Maybe it's perfectly standard to have so many arguments.  I don't know.
Also, the encrypt and decrypt functions are so similar, maybe they should be combined into one that accepts a parameter to tell it whether to encrypt or decrypt?
But then the function would take 6 arguments!
'use strict';

type char = string;

const ALPHABET: string = 'abcdefghijklmnopqrstuvwxyz';
const ALL_LOWER_CASE: RegExp = /[a-z]/g;
const ENTIRELY_LOWER_CASE: RegExp = /^[a-z]*$/;

const validate = (...args: string[]): void => {
  args.forEach((s: string) => {
    if (!ENTIRELY_LOWER_CASE.test(s))
      throw new Error(`String must consist of lowercase letters only. Received ${JSON.stringify(s)}.`);
  });
}

const mod = (n: number, m: number): number => ((n % m) + m) % m;

const rotate = (s: string): string => {
  const [c]: char = s;
  const sliced: string = s.slice(1);
  const rotated: string = sliced.concat(c);
  return rotated;
}

const swap = (s: string, i: number, j: number): string => {
  let a: string[] = [...s];
  [a[i], a[j]] = [a[j], a[i]];
  const swapped: string = a.join('');
  return swapped;
}

const nothingIfIn = (set: Set<char>) => (c: char): string => set.has(c) ? '' : c;

const permutate = (key: string): string => {
  const set: Set<char> = new Set(key);
  const uniques: string = [...set].join('');
  const diff: string = ALPHABET.replace(ALL_LOWER_CASE, nothingIfIn(set));
  const perm: string = uniques.concat(diff);
  return perm;
}

const encrypt = (pt: string, pw: string, k: string, ct: string = '', perm: string = permutate(k)): string => {
  validate(pt, pw, k, ct, perm);
  const [pwC]: char = pw;
  const pwC_i: number = ALPHABET.indexOf(pwC);
  const [permC]: char = perm;
  const permC_i: number = ALPHABET.indexOf(permC);
  const shift: number = (pwC_i + permC_i + 2);
  const [ptC]: char = pt;
  const ctC_i: number = (shift + perm.indexOf(ptC)) % ALPHABET.length;
  const ctC: char = perm[ctC_i];
  const ptC_i: number = perm.indexOf(ptC);

  const ptSlice: string = pt.slice(1);
  const pwRotated: string = rotate(pw);
  const ctNew: string = ct.concat(ctC);
  const permSwapped: string = swap(perm, ptC_i, ctC_i);

  return (pt.length === 0) ? ct : encrypt(ptSlice, pwRotated, k, ctNew, permSwapped);
}

const decrypt = (ct: string, pw: string, k: string, pt: string = '', perm: string = permutate(k)): string => {
  validate(pt, pw, k, ct, perm);
  const [pwC]: char = pw;
  const pwC_i: number = ALPHABET.indexOf(pwC);
  const [permC]: char = perm;
  const permC_i: number = ALPHABET.indexOf(permC);
  const shift: number = -(pwC_i + permC_i + 2);
  const [ctC]: char = ct;
  const ptC_i: number = mod((shift + perm.indexOf(ctC)), ALPHABET.length);
  const ptC: char = perm[ptC_i];
  const ctC_i: number = perm.indexOf(ctC);

  const ctSlice: string = ct.slice(1);
  const pwRotated: string = rotate(pw);
  const ptNew: string = pt.concat(ptC);
  const permSwapped: string = swap(perm, ctC_i, ptC_i);

  return (ct.length === 0) ? pt : decrypt(ctSlice, pwRotated, k, ptNew, permSwapped);
}

Usage example:
const plaintext = 'helloworld';
const password = 'foo';
const key = 'bar';
const ciphertext = encrypt(plaintext, password, key);

console.log(ciphertext); // pwckfenttc

console.log(decrypt(ciphertext, password, key)); // helloworld

Here's a link describing how the cipher works (as explained to someone performing it by hand): https://hutton-cipher.netlify.app/howto.html


texts:
I know that stringstreams are the C++ recommended way to create formatted text.  However, they can often become quite verbose, especially when compared to the succinct format strings of printf and family.  However, the printf family can lead to its own issues, with buffer overflow issues, and so I would rather not use these functions directly

My goal was to make a function to behave similarly to snprintf, but return a std::string, avoiding any chance of buffer overflow.  Knowing that there are many pitfalls to string manipulation in C++, have I exposed myself to any errors in using this function?

#include <cstdio>
#include <cstdarg>
#include <string>

std::string string_sprintf(const std::string& format, ...){
  static const int initial_buf_size = 100;
  va_list arglist;
  va_start(arglist, format);
  char buf1[initial_buf_size];
  const int len = vsnprintf(buf1,initial_buf_size,format.c_str(), arglist) + 1;
  va_end(arglist);

  if(len<initial_buf_size){
    return buf1;
  } else {
    char buf2[len];
    va_start(arglist,format);
    vsnprintf(buf2,len,format.c_str(),arglist);
    va_end(arglist);
    return buf2;
  }
}


texts:
After reading the book from which this example is from I started using APIs like this

typedef struct stack {
    char **items;
    int len;
} stack;

stack *stack_new() {
    stack *out = malloc(sizeof(stack));
    //initialize  the struct
    *out = (stack) {};
    return out;
}

void add(stack *in, char *val) {
    in->len++;
    in->items = realloc(in->items, in->length * strlen(val));
    in->items[in->length-1] = val; //<- actually this would be better with strcpy, but you get the idea
}

problem is that valgrind hates it. I've been trying to fix the various memory leaks that structs similar to this one (and to the dictionary of the link) are creating, until I started wondering if it's a good pattern at all.


texts: Combining ADD and VOLUME on a nodejs Dockerfile

texts:
I have a node project. My scripts section of package.json looks like this:

"scripts": {
  "postinstall": "gulp",
  "start": "node index.js",
  "test": "node ./node_modules/mocha/bin/mocha test"
},

My Dockerfile looks like this

FROM node:6.11-alpine

RUN mkdir -p /code
ADD . /code
WORKDIR /code
VOLUME /code

RUN npm install -g -s --no-progress yarn && \
    yarn && \
    yarn run test && \
    yarn cache clean

My docker-compose.yml looks like this:

version: "3"

services:
  web:
    build: .
    volumes:
      - .:/code
    command: "npm start"
    ports:
      - "8080:8080"
    networks:
      - internal

networks:
  internal:

This combination of ADD and VOLUME seems to give me what I need in terms of the javascript being there during the build stage and changes getting picked up in real time. However, I'm scared I'm doing something terribly wrong.


texts:
I have two dataframes I need to map over and combine into one. The first data frame contains NBA players. The headers are 'Date', 'Player', 'Team', 'Position', 'Salary', 'Pos_ID', 'Minutes', 'FPTS', 'USG'. I then have a second dataframe that's the first dataframe but grouped by date and team. The headers for this df are 'Date', 'Team', 'Minutes', 'FGA', 'FTA', 'To'. I'm trying to calculate USG rate for every player in the first dataframe. To do this I need to know what the total minutes, field goal attempts, free throw attempts, and turnover are for each team in each game for a given date. I then divide the same player's stats by the team's total stats. I have a working solution, but it's really slow and doesn't seem to be the most efficient way of doing this.
Here is the code:
import pandas as pd

player_df = pd.read_csv('Sample Data') # replace with sample data file

no_dups = player_df.drop_duplicates()
no_dups.loc[:, 'USG'] = pd.Series(dtype=float)
no_dups = no_dups[no_dups.Minutes != 0]

grouped_teams = no_dups.groupby(['Date', 'Team']).agg({'Minutes':['sum'], 'FGA': ['sum'], 'FTA': ['sum'], 'TO': ['sum'] })
grouped_teams.columns = ['Minutes', 'FGA', 'FTA', 'TO']
grouped_teams = grouped_teams.reset_index()

for index, row in no_dups.iterrows():
    for i, r in grouped_teams.iterrows():
        if no_dups.at[index, 'Team'] == grouped_teams.at[i, 'Team'] and no_dups.at[index, 'Date'] == grouped_teams.at[i, 'Date']:
            no_dups.at[index, 'USG'] = (100*((no_dups.at[index, 'FGA'] + 0.44 * no_dups.at[index, 'FTA'] + no_dups.at[index, 'TO'])*(grouped_teams.at[i, 'Minutes']/5))) / (no_dups.at[index, 'Minutes']*(grouped_teams.at[i, 'FGA']+0.44*grouped_teams.at[i, 'FTA']+grouped_teams.at[i, 'TO']))

final_df = no_dups[['Date', 'Player', 'Team', 'Position', 'Salary',  'Minutes', 'FPTS', 'USG']]

print(final_df)

I have removed all players who didn't play and there are duplicates because the same player can play in multiple contests in a single night so I removed those. I then create a df called grouped_teams which is every single team in the df grouped by date and team name. I then iterate over the first df using iterrows and the second df the same way. I need to find each players team and specific date and divide his stats by the calculated total to get the usage rate. The column for that is no_dups.at[index, 'USG']. There are 73k rows in my df so iterating over each one is taking a very long time.
Sample Data


texts: City Construction Solution times out for large input

texts:
Problem

  The country of Hackerland has n cities connected by m
  uni-directional roads. The cities are numbered from 1 to n.
  Recently the government decided to build new cities in Hackerland.

  Your task is to simulate q events. An event can have two types as
  described below:

  1 x d : A new city n + 1 is constructed in the Hackerland and it is connected to city x. If d = 0 the direction of the new road
  is from x to n + 1. If d = 1 the direction of the new road is
  from n + 1 to x.
  2 x y : Print Yes if it's possible to move from city x to city y, print No otherwise.

Constraints

  0 < n, m <= 50000

  0 < q <= 10000

  x, y always correspond to an existing city in the Hackerland.

  Total number of cities in the Hackerland wont exceed 50000

You can find a full description of the problem here

My Effort

I tried to use a BFS here but all the test cases but the default are failing due to a timeout. For those test cases n >= 4000. m >= 20000.

Code

from collections import defaultdict, deque

n, m = map(int, input().split())

adjacentNodes = defaultdict(set)
for _ in range(m):
    u, v = map(int, input().split())
    adjacentNodes[u].add(v)

q = int(input())
for _ in range(q):
    c, x, d = map(int, input().split())

    if c == 1:
        n += 1
        y = n

        if d == 0:
            adjacentNodes[x].add(y)
        else:
            adjacentNodes[y].add(x)
    else:
        y = d
        visited = set()
        current = deque()
        current.append(x)
        answer = "No"
        while current:
            parent = current.popleft()
            if parent == y:
                answer = "Yes"
                break
            if parent in adjacentNodes:
                for i in adjacentNodes[parent]:
                    if i not in visited:
                        visited.add(i)
                        current.append(i)
        print (answer)

Question

Does anyone have a suggestion how to optimise the solution?


texts:
I'm follow this article about "common opponent in tennis", my goal is to script it in the most efficient way. Below you can find my code but is so slow. To calculate the result of 1 match my laptop spent 120seconds more or less, and I have a dataset of 150k of rows to calculate.

The article: (PDF)

I need your help to clean and improve my code. Links to the data used:

tableA

tableB

data_tennis_co

data_tennis_co = read.table("test_co.csv", header=FALSE, sep=",", fill = TRUE)
A = read.table("tableA.csv", header=FALSE, sep=",", fill = TRUE)
B = read.table("tableB.csv", header=FALSE, sep=",", fill = TRUE)

#BASIC FUNCTIONS
G<-function(p){res<- p^4*(15-4*p-((10*p^2)/(1-2*p*(1-p))))}
d<- function(p,q) {res<- p*q*(1-(p*(1-q)+(1-p)*q))^-1}
TB <- function(p,q) {res <- foreach(i = seq_along(1:28), .combine = sum) %dopar% {tb<-A[i,1]*p^A[i,2]*(1-p)^A[i,3]*q^A[i,4]*(1-q)^A[i,5]*d(p,q)^A[i,6]}}
S <- function(p,q) {res <- foreach(i = seq_along(1:21), .combine = rbind) %dopar% {s<-B[i,1]*G(p)^B[i,2]*(1-G(p))^B[i,3]*G(q)^B[i,4]*(1-G(q))^B[i,5]*(G(p)*G(q)+(G(p)*(1-G(q))+(1-G(p))*G(q))*TB(p,q))^B[i,6]} sum(res)}
M3 <- function(p,q) {res <- S(p,q)^2*(1+2*(1-S(p,q)))}
DELTA_AB <- function(spwAC,rpwAC,spwBC,rpwBC) {res <- (spwAC-(1-rpwAC))-(spwBC-(1-rpwBC))}
PR<- function(spwAC,rpwAC,spwBC,rpwBC) {res <- (M3(0.6+DELTA_AB(spwAC,rpwAC,spwBC,rpwBC),(1-0.6))+M3(0.6,(1-(0.6-DELTA_AB(spwAC,rpwAC,spwBC,rpwBC)))))/2}

#COMMON OPPONENTS
MAL<-function(id1,id2){
prova<- subset(data_tennis_co, V3 == 1 & V4==2)
  previous<-subset(data_tennis_co, V2 < prova$V2)
  s1 <- subset(previous, V3 == 1 | V4==1)
  s2 <- subset(previous, V3 ==2 | V4==2)
  s1$opp <- ifelse(s1$V3==1, s1$V4, s1$V3)
  s2$opp <- ifelse(s2$V3==2, s2$V4, s2$V3)
  inn<- intersect(s1$opp,s2$opp)
  common1<-s1[s1$opp %in% inn,]
  common2<-s2[s2$opp %in% inn,]
  # fare media se id non unico
  COM <- merge(common1, common2,by=c("opp"))
  COM$OMALLEY <- unlist(mapply(PR, COM$V5.x, COM$V6.x, COM$V7.y, COM$V8.y))
  COM$OMALLEY[is.nan(COM$OMALLEY)] <- 0.5
  return(tryCatch(sum(COM$OMALLEY)/nrow(COM), error=function(e) NaN))
}

RESA<-MAL(1,2)


texts: Python Rock-Paper-Scissors via a class to handle the game

texts:
Original inspiration was by this Python beginner, and it prompted me to rewrite a bunch of stuff with my flair and my Python experience: First attempt: Python Rock Paper Scissors

Okay, so I looked at the aforementioned post, and was bored and needed to kill an hour at work.  So I killed an hour - I took their RPS game and turned it into a class, and made it look less evil/ugly.

While this is by no means a fully-fledged program that I've cleanly created and really thoroughly tested, this is something that I can at least ask for input on.

Runs pretty cleanly, and uses a lot of strings that the OP of the original inspiration post had.  But, it has a lot of docstrings, too.  And the entire game resides in a class, and calls via the class and such.

Because this version uses f-strings, you must have Python 3.6 or newer to use this program/code.

rps.py:

import random

class RockPaperScissors:
    """
    Class to handle an instance of a Rock-Paper-Scissors game
    with unlimited rounds.
    """

    def __init__(self):
        """
        Initialize the variables for the class
        """
        self.wins = 0
        self.losses = 0
        self.ties = 0
        self.options = {'rock': 0, 'paper': 1, 'scissors': 2}

    def random_choice(self):
        """
        Chooses a choice randomly from the keys in self.options.
        :returns: String containing the choice of the computer.
        """

        return random.choice(list(self.options.keys()))

    def check_win(self, player, opponent):
        """
        Check if the player wins or loses.
        :param player: Numeric representation of player choice from self.options
        :param opponent: Numeric representation of computer choice from self.options
        :return: Nothing, but will print whether win or lose.
        """

        result = (player - opponent) % 3
        if result == 0:
            self.ties += 1
            print("The game is a tie! You are a most worthy opponent!")
        elif result == 1:
            self.wins += 1
            print("You win! My honor demands a rematch!")
        elif result == 2:
            self.losses += 1
            print("Haha, I am victorious! Dare you challenge me again?")

    def print_score(self):
        """
        Prints a string reflecting the current player score.
        :return: Nothing, just prints current score.
        """
        print(f"You have {self.wins} wins, {self.losses} losses, and "
              f"{self.ties} ties.")

    def run_game(self):
        """
        Plays a round of Rock-Paper-Scissors with the computer.
        :return: Nothing
        """
        while True:
            userchoice = input("Choices are 'rock', 'paper', or 'scissors'.\n"
                               "Which do you choose? ").lower()
            if userchoice not in self.options.keys():
                print("Invalid input, try again!")
            else:
                break
        opponent_choice = self.random_choice()
        print(f"You've picked {userchoice}, and I picked {opponent_choice}.")
        self.check_win(self.options[userchoice], self.options[opponent_choice])

if __name__ == "__main__":
    game = RockPaperScissors()
    while True:
        game.run_game()
        game.print_score()

        while True:

            continue_prompt = input('\nDo you wish to play again? (y/n): ').lower()
            if continue_prompt == 'n':
                print("You are weak!")
                exit()
            elif continue_prompt == 'y':
                break
            else:
                print("Invalid input!\n")
                continue

Any suggestions and input are welcome, as this is a rough attempt.  :)


texts:
From the code metrics in VS it says that the maintainability index is 64.
I think the code is really easy written.

How can I get a higher Maintainability Index?

public void ExportProjectFolderToZip()
{
    Log4NetLogger.Logger.Info("Start of Method ExportProjectFolderToZip");
    var startPath = new Uri(Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase)).LocalPath; //get current directory (Release/Debug)
    var zipPath = new Uri(@"" + startPath + "-" + DateTime.Now.ToString("yyyy-MM-dd-hh-mm") + ".zip").LocalPath;  //zip filename
    try
    {
        CreateFromDirectory(startPath, zipPath, CompressionLevel.Fastest, true); //create zip folder
    }
    catch (Exception ex)
    {
        Log4NetLogger.Logger.Error("Error: " + ex.Message);
    }
    Log4NetLogger.Logger.Info("End of Method ExportProjectFolderToZip");
}


texts: Hackerrank Sparse Arrays Solution in Java

texts:
I've just solved this problem and I hope you guys give me any feedback to make my code be better.

  Problem: There are N strings. Each string's length is no more than 20 characters. There are also Q queries. For each query, you are given a string, and you need to find out how many times this string occurred previously.

  Input Format

  The first line contains N, the number of strings. The next N lines each
  contain a string. The N + 2nd line contains Q, the number of queries. The
  following Q lines each contain a query string.

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

public class Solution {

    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        int n = scan.nextInt();
        String[] stringArr = new String[n];

        for (int i = 0; i < n; i++){
                stringArr[i] = scan.next();
            }

        int q = scan.nextInt();
        for (int i = 0; i < q; i++){
                String stringQue = scan.next();

                int occNum = 0;
                for (int j = 0; j < n; j++){
                    if (stringQue.equals(stringArr[j])) occNum++;
                }
             System.out.println(occNum);
        }
    }
}