texts: Map price values to bins where bins are of a larger price range

texts:
I have two different pandas data frames where in the first data frame (price), I have two columns. The first column named value has some values in it and the second column amount has the available amount for each price. The second data frame (bins) has as index some price intervals which are produced from the price data frame. For each row of the price data frame I check each row of the value column to find the interval that it belongs from the bins data frame and if the value is in an interval I assign the available amount in the bins data frame. If another value is again in the same interval I sum up these amounts in the group_bins data frame.

import pandas as pd

bins = pd.DataFrame({
    'value': [1, 2, 5, 7, 8, 16, 20, 3, 9, 11, 35, 12, 54, 33, 3, 22, 23]
})

price = pd.DataFrame({
    'value': [2, 5, 7, 8, 16, 20, 3, 9, 11, 2.5, 3.4],
    'amount': [50, 112, 130, 157, 146, 148, 300, 124, 151, 100, 32]
})

bins['bins'] = pd.qcut(bins['value'], 12)
group_bins = bins.groupby(['bins']).sum()
group_bins['amount'] = 0
del group_bins['value']

for j in range(price.shape[0]):
    for i in range(group_bins.shape[0]):
        if price.loc[j, 'value'] in group_bins.index[i]:
            group_bins.loc[group_bins.index[i], 'amount'] += price.loc[j, 'amount']

            break

Expected Result:

                 amount
bins
(0.999, 2.333]        50
(2.333, 3.0]         400
(3.0, 5.0]           144
(5.0, 7.333]         130
(7.333, 8.667]       157
(8.667, 11.0]        275
(11.0, 13.333]         0
(13.333, 18.667]     146
(18.667, 22.0]       148
(22.0, 26.333]         0
(26.333, 34.333]       0
(34.333, 54.0]         0

My problem is that I have 100k data and all this process takes too long to finish.
Is there any elegant and much faster way to replace these nested for loops and the if condition?

The expected result is the final column in the group_bins amount column. Any help would be much appreciated! Thank you.


texts: Checking two text field for match and checking for null

texts:
Is this the most efficient way to do this?  Any suggestions on some thing I might have missed or can do better?

    func checkPasscodeMatch(){
    println(self.passCodetext1.text)
    println(self.passCodetext2.text)
    // check if pass codes match
    if self.passCodetext1.text == self.passCodetext2.text {
    //check if pass code 1 is blank
        if self.passCodetext1.text == "" {
            let alertView = UIAlertController(title: "ALERT!!", message: "Pass code can not be blank", preferredStyle: UIAlertControllerStyle.Alert)
            alertView.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: nil))

            self.presentViewController(alertView, animated: true, completion: nil)
        } else {
       defaults.setObject(passCodetext1.text, forKey: "passCode")//store pass code
        dispatch_async(dispatch_get_main_queue()) {
            self.performSegueWithIdentifier("setupTouchID", sender: self)
            }
        }
    } else {
        let alertView = UIAlertController(title: "ALERT!!", message: "Pass Codes do not match", preferredStyle: UIAlertControllerStyle.Alert)
        alertView.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: nil))

        self.presentViewController(alertView, animated: true, completion: nil)
        passCodetext1.text = ""
        passCodetext2.text = ""
        passCodetext2.resignFirstResponder()
        println("Pass codes do not match.")
    }
}


texts:
I am making a query in mysql to import users in our marketing system and need for this a lot of data like for example :

Date of last order
Date of last cheque created
...

This are all left joins where I just want the last result with conditions. For the moment I do just a select for this field but I don't know if this is the best option. Here you have the query that I'm currently usign:

select u.first_name, u.last_name, u.email, u.birthdate, u.id, u.sex, c.name, u.facebook_id, u.created_at, u.last_active, u.referrer_id,
IF(wants_email = 0, (select created_at from wants_email_logs where value = 0 and u.id = user_id order by id desc limit 1), NULL ) as DATEUNJOIN,
(select max(o.created_at) from orders o where o.user_id = u.id and o.state in ('paid','processing', 'shipped', 'completed')) as DATE_LAST_ORDER,
(select max(c.created_at) from cheques c where c.user_id = u.id and c.spent = 0) as cheque_date from users u
left join countries c on u.country_id = c.id ;


texts:
The following code removes all pictures that are placed into Column A. When running the code however I have noticed it runs fairly slow. This will be attached to a command button that will be located in A1, it is important that the deleting of pictures doesnt target this command button. Any suggestions?

    ' Clears All Pictures
    Sub DeleteAllPics()
    Columns("A:A").Replace What:="No Picture Found", Replacement:="", LookAt:=xlPart
    Dim pic As Object
    For Each pic In ActiveSheet.Pictures
    pic.Delete
    Next pic
    End Sub


texts:
The parts_sums function in the code takes a list as parameter and then returns sum of all sub-lists present in the list. e.g.
if, ls = [1, 4, 6, 4] then ls contains,

ls = [1, 4, 6, 4]
ls = [4, 6, 4]
ls = [6, 4]
ls = [4]

so the function should return a new list:
nsl = [15, 14, 10, 4]

def parts_sums(ls):
    nls, c = [], 0
    leng = len(ls)
    for n in ls:
        i, sum = 0, 0
        while not i == c + 1:
            i += 1
            sum += ls[leng - i]
        c += 1
        nls.insert(0, sum)
    return nls


texts: Prints Books from a HashMap that are complete or incomplete

texts:
This code is meant to display book titles that are incomplete. I have a HashMap with the book title and a number that represents the amount of the book that has been read.

I want the program to:

Check to see if there are any books in the HashMap
Check to see if there are any started, yet incomplete books
If there are any Started, yet incomplete books, it will print "You have x incomplete books. They are:"
Finally, it will print out a list of incomplete books

The code works, but I feel like it probably has too many loops and could be cleaned up a lot.

import java.util.HashMap;

public class Library {
  public Library () {

  }

public void getIncompleteBooks(HashMap<String, Integer> library) {
    int unfinished = 0;
    if (library.size() < 1) {
      System.out.println("Please add some books to your library.");
    } else {
      for (String book : library.keySet()) {
        if (library.get(book) < 100 && library.get(book) > 0) {
          unfinished++;
        }
      }
      if (unfinished > 0) {
          System.out.println("You have " + unfinished + " unfinished books. They are:");
        }
      for (String book : library.keySet()) {
        if (library.get(book) < 100 && library.get(book) > 0) {
          System.out.println(book);
        }
      }
    }
  }


texts:
I have an application that essentially "pings" all of the servers on my network.  I have about 100 servers, and this ping will happen every 10 seconds.

public class HealthChecker {
 private static List<InetSocketAddress> servers = new     ArrayList<InetSocketAddress>();
 public static void main(String[] args){
  // not shown: populating servers list
  new Thread(){
   public void run(){
    while (true){
     try {
      Thread.sleep(10*1000);
      for (final InetSocketAddress server : servers){
       new Thread(){
        public void run(){
         Socket connection = new Socket();
         try {
          connection.connect(server, 5*1000);
         } catch (IOException e) {
          servers.remove(server);
         }
        }
       }.start();
      }
     } catch (InterruptedException e) {
      e.printStackTrace();
     }
    }
   }
  }.start();
 }

So, do you think this code can be improved? I really feel like opening a new thread every time I make a connection isn't a good thing.

EDIT:
So looking over all the proposed solutions, they are all very good, and I will over the next week try and all and see which one appears to be the most efficient.


texts:
I solved this problem.

  Invert a binary tree.

     4
   /   \
  2     7
 / \   / \
1   3 6   9

  To this

     4
   /   \
  7     2
 / \   / \
9   6 3   1

This problem looked a lot harder at first and then I was able to come up with a recursive solution to this.

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    TreeNode* invertTree(TreeNode* root) {
        if((root == NULL) || (root->left == NULL && root->right == NULL) )
        {
            return root;
        }
        TreeNode *temp = root->left;
        root->left = root->right;
        root->right = temp;
        invertTree(root->left);
        invertTree(root->right);
        return root;
    }
};

When I submitted this solution, I found that my submission ran faster than just 0.2 % of other submission for this problem.

Is there a better and faster approach to this, maybe an iterative one?


texts: How can I solve my constructor injection code architecture?

texts:
The current code solves the issue I had when trying to use property injection.

Problem: Every module must use constructor injection because of a circular reference that occurs when not using constructor injection with my factories and trying to use property injection

Reason: A module requires a client and each client must have its own list of instantiated modules.

What I want: I want every module that derives from BaseModule to be able to not declare a constructor and allow BaseModule to have IIrcClient injected via a property.

But I'm not sure how to use Ninject to correctly do this without getting a circular reference. Is there a way so that for each client, a new list of modules are injected into that client (where all modules then have an injected reference of the client they belong to).

.ToFactory() is an extension method of Ninject which creates a proxy based on an interface that creates an object with a dependency.

public class BaseClient : IClient
{
    private readonly IEnumerable<IModule> modules;

    protected BaseClient(IModuleFactory moduleFactory)
    {
         // each client has its own instances of modules set
         // each module needs a reference to the client
         this.modules = moduleFactory.Create(this);
    }
}

public class BaseModule : IModule
{
    private readonly IIrcClient ircClient;

    // Factory will inject and create
    protected BaseModule(IIrcClient ircClient)
    {
        this.ircClient = ircClient;
    }
}

public class Bot
{
    // Injected factory
    public Bot(Context context, IrcClientFactory factory)
    {
        this.factory = factory;
        this.context = context;
    }

    public void Start()
    {
        List<Network> networks = context.Networks.ToList();

        foreach (var network in networks)
        {
            // create new client...but also
            // new client gets injected with module factory
            // module factory then populates modules based on client
            IIrcClient ircClient = this.ircClientFactory.Create();
            ircClient.Connect(network);
            this.clients.Add(ircClient);
        }
    }
}

public class Program
{
    public void Main()
    {
        kernel.Bind<IIrcClient>().To<DefaultIrcClient>();
        kernel.Bind<IIrcClientFactory>().ToFactory();

        kernel.Bind<IModule>().To<DiceModule>().WithPropertyValue("Name", "Dice Module");
        kernel.Bind<IModule>().To<ModuleOne>().WithPropertyValue("Name", "ModuleOne");
        kernel.Bind<IModule>().To<RubyModule>().WithPropertyValue("Name", "Ruby Module");
        kernel.Bind<IModule>().To<AdminModule>().WithPropertyValue("Name", "Admin Module");

        // Module Factory will generate IEnumerable<IModule>
        kernel.Bind<IModuleFactory>().ToFactory();

        var bot = kernel.Get<Bot>();
        bot.Start();
    }
}

A possible fix, but I would have to manaually set the property instead of letting Ninject inject the property:

public class BaseClient : IClient
{
    private readonly IEnumerable<IModule> modules;

    protected BaseClient(IModuleFactory moduleFactory)
    {
         // let the factory create new modules
         // but dont pass the instance of the client
         this.modules = moduleFactory.Create();

         foreach(var module in modules)
         {
               module.IrcClient = this; // don't want to do this, but I think it would fix it
         }
    }
}

This way, I could create tons of modules without needing to always implement the base constructor and pass in the IClient dependency:

public class ChildModule : BaseModule
{
    // client was injected via property

    // override virtual methods as required.
}


texts: 2D matrix - splitting the matrix in two parts with equal number of elements

texts:
The elements in the matrix are either 'M', 'G', 'P' or '.' and the algorith must write out all possible ways of splitting the matrix so it has equal number of M, G and P on each side. It's a task we've been given to do at home. We also had to use use the matrix as a parameter in the function and use it as a pointer in it. What would you change to make it more optimized?

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

int field_split(char *k, int r, int s, int *ptrP, int *ptrG, int *ptrM){
    int i, j, numberP = 0, numberG = 0, numberM = 0;
    int splitNumber = 0;
    int tmpP = 0, tmpG = 0, tmpM = 0;

    for (i = 0; i < r*s; i ++){
        switch(k[i]){
            case 'P':
                numberP ++;
                break;
            case 'M':
                numberM ++;
                break;
            case 'G':
                numberG ++;
                break;
        }
    }

    for (i = 0; i < r; i++){
        for (j = 0; j < s; j ++){
            switch(k[i * s + j]){
                case 'P':
                    tmpP ++;
                    break;
                case 'M':
                    tmpM ++;
                    break;
                case 'G':
                    tmpG ++;
                    break;
            }
        }
        if(tmpP == numberP / 2 && tmpM == numberM / 2 && tmpG == numberG / 2)
            splitNumber ++;
    }

    tmpP = tmpM = tmpG = 0;

    for (j = 0; j < s; j++){
        for (i = 0; i < r; i ++){
            switch(k[i * s + j]){
                case 'P':
                    tmpP ++;
                    break;
                case 'M':
                    tmpM ++;
                    break;
                case 'G':
                    tmpG ++;
                    break;
            }
        }
        if(tmpP == numberP / 2 && tmpM == numberM / 2 && tmpG == numberG / 2)
            splitNumber ++;
    }

    *ptrP = numberP;
    *ptrG = numberG;
    *ptrM = numberM;

    return splitNumber;
}

int main()
{
    int r, s, i, j;
    int splitNumber;
    int numberP, numberM, numberG;
    int tmpP = 0, tmpM = 0, tmpG = 0;
    int count = 1;

    scanf("%d %d", &r, &s);
    char field[r][s];

    for (i = 0; i < r; i ++){
        for(j = 0; j < s; j ++)
            scanf(" %c", &field[i][j]);
    }

    splitNumber = field_split(&field[0][0], r, s, &numberP, &numberG, &numberM);

    if (splitNumber > 0 ){

        printf("Ways of splitting the field: %d", splitNumber);

        for (i = 0; i < r; i ++){
            for(j = 0; j < s; j ++){
                switch(field[i][j]){
                    case 'P':
                        tmpP ++;
                        break;
                    case 'G':
                        tmpG ++;
                        break;
                    case 'M':
                        tmpM ++;
                        break;
                }
            }
            if(tmpP == numberP / 2 && tmpG == numberG / 2 && tmpM == numberM / 2){
                printf("\n%d. Horizontally, between row  %d and %d", count, i + 1, i + 2);
                count ++;
            }
        }

        tmpP = tmpG = tmpM = 0;

        for (j = 0; j < s; j ++){
            for(i = 0; i < r; i ++){
                switch(field[i][j]){
                    case 'P':
                        tmpP ++;
                        break;
                    case 'G':
                        tmpG ++;
                        break;
                    case 'M':
                        tmpM ++;
                        break;
                }
            }
            if(tmpP == numberP / 2 && tmpG == numberG / 2 && tmpM == numberM / 2){
                printf("\n%d. Vertically, between column %d and %d", count, j + 1, j + 2);
                count++;
            }
        }
    }

    else
        printf("Can't be split 50-50.");

    return 0;
}


texts: Calculating neuron outputs and derivatives

texts:
This function runs very often.  cudaMemcpy is at the start and works very slowly. How can I change this function to avoid this? I already have inputs in device memory.

void OpenNNL::calculateNeuronsOutputsAndDerivatives(double * inputs, double * deviceOutputs, double * deviceDerivatives)
{
    int inputsCount = _inputsCount;

    double * deviceTemp;
    double * deviceInputs;

    cudaCall(cudaMalloc ( (void**)&deviceInputs, inputsCount*sizeof(double) ));

    cudaCall(cudaMemcpy ( deviceInputs, inputs, inputsCount*sizeof(double), cudaMemcpyDeviceToDevice ));

    for(int i=0;i<_layersCount;i++)
    {
        cudaCall(cudaMalloc((void**)&deviceTemp, _neuronsPerLayerCount[i]*inputsCount*sizeof(double)));

        dim3 threadsMul = dim3(BLOCK_SIZE, 1);
        int blocksCount = floor((double) _neuronsPerLayerCount[i]*inputsCount / threadsMul.x) + 1;
        dim3 blocksMul = dim3(blocksCount, 1);

        weighting<<<blocksMul, threadsMul>>>(deviceTemp, deviceInputs, _neuronsInputsWeights, _inputsInPreviousLayers[i], inputsCount, _neuronsPerLayerCount[i]);

        cudaCall(cudaFree(deviceInputs));

        cudaCall(cudaMalloc((void**)&deviceInputs, _neuronsPerLayerCount[i]*sizeof(double)));

        dim3 threadsSum = dim3(BLOCK_SIZE, 1);
        blocksCount = floor((double) _neuronsPerLayerCount[i] / threadsSum.x) + 1;
        dim3 blocksSum = dim3(blocksCount, 1);

        calculateOutputsAndDerivatives<<<blocksSum, threadsSum>>>(deviceOutputs, deviceDerivatives, deviceInputs, deviceTemp, _neuronsBiases, inputsCount, _neuronsPerLayerCount[i], _neuronsInPreviousLayers[i]);

        inputsCount = _neuronsPerLayerCount[i];

        cudaCall(cudaFree(deviceTemp));
    }

    cudaCall(cudaFree(deviceInputs));
}


texts: String of numbers to Integers (without using .to_i)

texts:
My exercise was to take a string of numbers, such as "1234" and return them as an integer 1234. However, I wasn't allowed to use #to_i, #to_f, Integer, etc.

def convert(int)
  x = 0
  array = int.split('')
  array.each.with_index do |y, i|
    x = (x + (y.hex))
    x = x * 10 unless i == array.length-1
  end
  return x
end

p convert('1234')
p convert('3225')
p convert('4321') == 4321
p convert('570') == 570

When I first started on this exercise, I wondered if I would be able to convert the String into a binary, octal, or other type of representation. Then, take that representation and convert it into integers.

Unfortunately, using #pack and #unpack resulted in more strings, and I couldn't really understand some of the methods that I could use with pack/unpack. Right now I don't have much knowledge in programming, so I couldn't really figure out how to take those strings and parse them into the Integers that I wanted. (My math kinda sucks too...)

Then I read about hex some more and realized that the hex representation
of numbers 0-9 are the same as the integers! So I simply converted each number to a hex, added it to a variable and multiplied it by 10 with each iteration of the loop.

I know there's probably a better way to do this, but this is what I came up with.

I know another way (and possibly simpler) is to make a hash of 10 numbers, 0 - 9, with the keys being the Stringed numbers and their values being Integers, then iterating through that.

Anyways, please let me know what you think of my code and my thought process, and suggest what you can.


texts:
This code allows calling a method while redirecting the IO to strings.  This is useful for unit testing where you have to direct something to the console or examine output that comes from it.  I assume these have been written a lot, but I couldn't find examples.

I'd like advice on how to make them generally useful and whether the style seems decent.  There are two methods-- one sends a string to System.in while leaving the output alone, the other redirects both input and output, with the option that if the input string passed is null, it leaves the input alone.  This covers all three cases.

Invocations look like this:

enterInput(inputString, callingClassString, methodString, typeStrings[], argsForCall ...);
captureIO(inputString, callingClassString, methodString, typeStrings[], argsForCall ...);

Code:

/**
 * Invoke the specified method using the specified string as console input.
 * Note that the calling class and types must be fully qualified.
 *
 * @param inputString               Console input to be fed to the method
 * @param callingClassString        Class of the method to invoke
 * @param method                    Name of the method to invoke
 * @param typeStrings               Types the method takes (to distinguish it)
 * @param args                      Arguments to pass to the method
 * @return                          The console output captured
 */
public static void enterInput(String inputString,
        String callingClassString, String method, String[] typeStrings,
        Object... args) {
    try {
        Class<?>[] typeClasses = new Class<?>[typeStrings.length];
        for (int i = 0; i < typeStrings.length; i++) {
            typeClasses[i] = Class.forName(typeStrings[i]);
        }

        Method m = Class.forName(callingClassString).getMethod(method, typeClasses);
        InputStream origIn = System.in;
        System.setIn(new ByteArrayInputStream(inputString.getBytes()));
        m.invoke(null, args);
        System.setIn(origIn);
    } catch (Exception e) {
        throw new Error(e);
    }
}

/**
 * Invoke the specified method and return its console output as a string.
 * If inputString is not null, it is used as console input.
 * Note that the calling class and types must be fully qualified.
 *
 * @param inputString               Console input to be fed to the method.
 *                                  If null, leaves this input stream alone
 * @param callingClassString        Class of the method to invoke
 * @param method                    Name of the method to invoke
 * @param typeStrings               Types the method takes (to distinguish it)
 * @param args                      Arguments to pass to the method
 * @return                          The console output captured
 */
public static String captureIO(String inputString, String callingClassString, String method,
        String[] typeStrings, Object ... args) {
    String output = null;

    try {
        Class<?>[] typeClasses = new Class<?>[typeStrings.length];
        for (int i=0; i<typeStrings.length; i++) {
            typeClasses[i] = Class.forName(typeStrings[i]);
        }

        Method m = Class.forName(callingClassString).getMethod(method, typeClasses);
        InputStream origIn = System.in;
        PrintStream origOut = System.out;

        if (inputString != null)
            System.setIn(new ByteArrayInputStream(inputString.getBytes()));
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        System.setOut(new PrintStream(baos));
        m.invoke(null, args);
        output = baos.toString();

        System.setOut(origOut);
        if (inputString != null)
            System.setIn(origIn);
    } catch (Exception e) {
        throw new Error(e);
    }
    return output;
}


texts: Any problems with this prime checker script?

texts:
I have just made what seems to me to be the first reliable prime-checking program that works.  However, I am not sure if it is completely reliable, or if there are problems.  It relies on list-making more than math, and it can be slow for bigger numbers.  Do you think there are any problems?

def primeChecker(x):
    if x <= 1 or isinstance(x,float) == True:
        return str(x) + " is not prime"
    else:
        div = ["tepi"] #tepi denotes test element please ignore
        for i in range(1,x+1,1):
            if x % i == 0:
                div.append("d") #d denotes divisible
            else:
                div.append("n") #n denotes not divisible
        if div[1] == "d" and div[x] == "d" and div.count("n") == x - 2:
            return str(x) + " is prime"
        else:
            return str(x) + " is not prime"

def primeCheckList(d,e):
    for i in range(d,e + 1):
        print primeChecker(i)

Here are some of the tools I used in primeChecker() to see if it was working right.

print div #these are testing tools
print range(1,x+1,1)
print div[1]
print div[x]
print div[2:x]
print div.count("n")
print x - 2

edit: Barry's feedback

OK, based on what Barry told me, i was able to clean up and otherwise format my code to be more concise, no more lists needed. it seems to run smoother, and is otherwise easier to read. here it is:

def isPrime(x):
    if x <= 1 or isinstance(x,float):
        return False
    else:
        for divisor in range(2,x,1):
            if x % divisor == 0:
                return False
        return True

def primeChecker(n):
    if isPrime(n):
        return "%d is prime" % n
    else:
        return "%d is not prime" % n

def primeCheckList(d,e):
    for i in range(d,e + 1):
        print primeChecker(i)

any more feedback to give?


texts: Avoiding nested callbacks when using MongooseJS

texts:
I'm diving into the world of nodejs and mongo. I am playing around with a simple app that uses MongooseJS to talk to Mongo. I have been looking at examples and some GitHub projects for references, but the pattern seems very sloppy to me. Is this approach considered normal, or is there a better way?

Here is a sample from the app I am building with my daughter. Those nested callbacks feel like an anti-pattern to me.  Am I wrong? Are there better ways to do it?

//userController.js when a new user registers an account is made and a document is cloned that will be their new "pet";

var Pet = require("models/pet.js");
var User = require("models/user.js");

exports.register = function (req, res, next) {
    var user = new User({
        username: req.body.username,
        password: req.body.password
    });

    user.save(function (err) {
        if (err) {
            next(err);
            return;
        }

        Pet.findOne({
            "name": "Egg",
            "ownerId": "<<system>>"
        }, function (err, pet) {
            if (err){
                next(err);
                return;
            }
            Pet.clonePetForUser(user._id, pet._id, function (err) {
                if (err) {
                    next(err);
                    return;
                }
                res.json({message: 'User created'});
            })
        });
    });
};


texts: Printing multiplication table to 12 × 12

texts:
Now, a while ago, I said in chat:

  I'm done with BF programming.

Except I guess I was lying. Here's a Brainfuck program I wrote, that prints out the multiplication tables up to 12. Fairly simple; what it does:

Loops through 1-12; let's say the current value we are at is x

Loop 12 times, adding x each time, and prints the result
Resets the number

The code:

Cell 0 is space
Cell 1 is newline
Cell 2 is outer counter
Cell 3 is outer number
Cell 4 is inner counter
Cell 5 is inner number
Cell 6 is copy workspace

>++++[<+++++ +++>-]                                 set cell 0 to space
+++++ +++++                                         set cell 1 to new line

>+++++ +++++ ++                                     set counter to 12
[                                                   while counter is not 0
    >+                                              increment number
    >+++++ +++++ ++                                 set inner counter to 12
    [                                               while inner counter is not 0
        <[>>+>+<<<-]>>>[<<<+>>>-]                   increment inner number

        >++++++++++<<[->+>-[>+>>]>[+[-<+>]>+>>]
        <<<<<<]>>[-]>>>++++++++++<[->-[>+>>]>
        [+[-<+>]>+>>]<<<<<]>[-]>>[>++++++
        [-<++++++++>]<.<<+>+>[-]]<[<[->-<]++++++
        [->++++++++<]>.[-]]<<++++++[-<++++++++>]
        <.[-]<<[-<+>]                               print number gotten off SO

        <<<<<<.                                     print space
        >>>>-                                       go to inner counter
    ]                                               end inner loop
    >[-]<                                           reset number
    <<<.                                            print new line
    >-                                              go to counter
]                                                   end outer loop

Compressed:

>++++[<++++++++>-]++++++++++>++++++++++++[>+>++++++++++++[<[>>+>+<<<-]>>>[<<<+>>>-]>+++++++
+++<<[->+>-[>+>>]>[+[-<+>]>+>>]<<<<<<]>>[-]>>>++++++++++<[->-[>+>>]>[+[-<+>]>+>>]<<<<<]>[-]
>>[>++++++[-<++++++++>]<.<<+>+>[-]]<[<[->-<]++++++[->++++++++<]>.[-]]<<++++++[-<++++++++>]<
.[-]<<[-<+>]<<<<<<.>>>>-]>[-]<<<<.>-]

Output:

1 2 3 4 5 6 7 8 9 10 11 12
2 4 6 8 10 12 14 16 18 20 22 24
3 6 9 12 15 18 21 24 27 30 33 36
4 8 12 16 20 24 28 32 36 40 44 48
5 10 15 20 25 30 35 40 45 50 55 60
6 12 18 24 30 36 42 48 54 60 66 72
7 14 21 28 35 42 49 56 63 70 77 84
8 16 24 32 40 48 56 64 72 80 88 96
9 18 27 36 45 54 63 72 81 90 99 108
10 20 30 40 50 60 70 80 90 100 110 120
11 22 33 44 55 66 77 88 99 110 121 132
12 24 36 48 60 72 84 96 108 120 132 144

Some notes:

The multiplication table is missing formatting. I realise that, and will add it some time later, if I can figure out how to compare two values.
I realise it doesn't work for multiplication tables of 16 or higher, due to BF cell sizes being only 8 bits, or up to 255. The value 16 * 16 would result in 256, setting the value of the cell to be 0. Is this unavoidable? Or is there a trick to it?

Concerns:

Does it make sense? (Considering it's Brainfuck, it shouldn't make sense...)
Do my "comments" make sense?
Are there redundant commands that I can remove/reduce?


texts:
I'm working on a small program to add or remove certain entries from the Windows registry, and I'm getting all tangled up in IF and TRY conditions. I've spent hours chasing bugs, usually logical ones, trying to accomplish what is conceptually very simple. The more I work on and "improve" the code so that it works in more and more conditions, the more tortured and complicated the IF tests get, until I can't tell which is up and down anymore. Surely there must be a better way! (even for my little brain)

This is all I'm trying to do:

When asked to install:

If our python version and installpath is in registry: do nothing.
If our python version and different installpath: do nothing.
If our python is not there, add it.

When asked to remove:

If our python is not there: do nothing
If our python version and different installpath: do nothing.
If our python version and installpath is in registry: remove.

But my code for just the removal part looks like the below (the whole thing is here). It works, more or less, but it just doesn't feel right. I don't know what to do to make it cleaner. Your viewpoints are appreciated. Thanks.

def remove():
    ''' see if any existing registrations match our python version and register ours if not '''

    if CurrentUser:
        match = True if our_version in CurrentUser else False
        versions = CurrentUser
    elif AllUsers:
        match = True if our_version in AllUsers else False
        versions = AllUsers
    else:
        print '\nOur version (%s) not registered to "%s", skipping...' % (our_version, versions[our_version])

    try:
        if match:
            print '\nVersion matches ours, calling deRegisterPy...'
            deRegisterPy(pycore_regpath,our_version)
    except:
        raise

def deRegisterPy(pycore_regpath, version):
    ''' remove this python install from registry '''
    pycore_regpath = pycore_regpath + version   # e.g. 'SOFTWARE\Python\Pythoncore\2.7'
    try:
        reg = OpenKey(HKEY_LOCAL_MACHINE, pycore_regpath)
        installpath = QueryValue(reg, installkey) # win32
        if installpath == our_installpath:
            print '\nexisting python matches ours, removing...\n'
            # print '(%s vs %s)' % (installpath, our_installpath)
            for subkey in ['\\InstallPath', '\\PythonPath']:
                DeleteKey(HKEY_LOCAL_MACHINE, pycore_regpath + subkey)
            DeleteKey(HKEY_LOCAL_MACHINE, pycore_regpath)
            print "--- Python %s, %s is now removed!" % (our_version, our_installpath)
        CloseKey(reg)
    except EnvironmentError:
        print 'EnvironmentError', EnvironmentError()
        raise
        return
    except WindowsError:
        print "Strange, we've hit an exception, perhaps the following will say why:"
        print WindowsError()
        raise
        return
    CloseKey(reg)

# main
if args['action']=='install':
    install()
elif args['action']=='remove':
    remove()


texts: Tkinter Application to Read & Update a CSV File

texts:
Background
I started learning Python about 3 months ago.
I feel like I learned a lot, but would like to receive some advices from the pros and some feedback about my code.
So I wrote a small GUI app. I would like to know if it's efficient, readable, fits the PEP8 rules, and if you would do it in a different way.
Code Purpose
A Tkinter application that is simply a login form.
You can choose to count the number of times you've logged in as a specific user.

CSV File Example

Shaked, 123456, 0
Ellen, pass123, 0

Code
'''
A Python Exercise: Reading CSV File & Tkinter Implementation
Including the subjects: Grid Layout, Tk Variables and Binding
'''
import Tkinter as tk
import csv

CSV_FILE = "users.csv"

# Functions
def popup(title, msg):
    '''Open popup window with title and msg'''
    w = tk.Toplevel(root)
    w.title(title)
    w.minsize(200, 200)
    tk.Label(w, text=msg).pack()
    tk.Button(w, text="Close", command=w.destroy).pack(pady=10)
    w.bind("<Return>", lambda f: w.destroy())

def read_from_file():
    '''Read csv file and return a list like: [[username, password, count]]'''
    try:
        with open(CSV_FILE, 'rb') as f:
            users = []
            reader = csv.reader(f)
            for row in reader:
                row[2] = int(row[2]) # Make the count an integer so it can increase later
                users.append(row)
            return users
    except IOError:
        popup("Error", "File not found!")

def write_to_file(users):
    '''Get a list of all users and write it to the csv file'''
    with open(CSV_FILE, 'wb') as f:
        writer = csv.writer(f)
        for row in users:
            row[2] = str(row[2])
        writer.writerows(users)

class App(tk.Frame):
    def __init__(self, master=None):
        tk.Frame.__init__(self, master)
        self.master = master
        self.pack(anchor="w")

        # Labels
        tk.Label(self, text="Username:").grid(sticky="w")
        tk.Label(self, text="Password:").grid(row=1, sticky="e")

        # Entries
        self.n_string = tk.StringVar()
        self.p_string = tk.StringVar()
        name = tk.Entry(self, textvariable=self.n_string, width=30)
        passw = tk.Entry(self, textvariable=self.p_string, show='*', width=20)
        name.grid(row=0, column=1, sticky="we")
        passw.grid(row=1, column=1, sticky="we")

        # Check Button
        self.check_var = tk.BooleanVar()
        check = tk.Checkbutton(self, text="Count Login attempts", variable=self.check_var)
        check.grid(row=2, column=1, sticky="w")

        # Login Button
        login = tk.Button(self, text="Login", command=self.login)
        login.grid(row=2, column=1, sticky="e")

        # Binding
        self.master.bind("<Return>", self.login)

    def login(self, event=None):
        '''Login attempt'''
        users  = read_from_file()
        if not users:
            return
        for row in users:
            if row[0] == self.n_string.get() and row[1] == self.p_string.get():
                msg =  "Welcome %s!\n\nYour login count is %d" % (row[0], row[2])
                popup("Welcome", msg)
                if self.check_var.get(): # Check if "Count Login attempts" button is checked
                    row[2] += 1 # add +1 login count
                    write_to_file(users)
                break
            elif row[0] == self.n_string.get():
                print "Password incorrect."
                break
        else: # If there isn't a match of the username
            print "User name incorrect!"

# GUI settings
root = tk.Tk()
app = App(root)
root.title("Login Form")
root.minsize(200, 200)

# Initalize GUI
root.mainloop()


texts:
A section of my page lists 'Workshops' and just uses objects from a queryset. The page/site uses bootstrap.

        {% if workshops|length %}

Learn through workshops

            {% for workshop in workshops %}

                          {{ workshop.name }}

in {{ workshop.start_date|timeuntil }}

            {% endfor %}

        {% endif %}

In particular, I am wondering two things:

In order to show the 'speaker avatar' in the position I wanted, I just used a position: relative container in which I put the 'cover' and the avtar and set the div for the avatar as absolute. I want to know if there is a better to way to accomplish what I want.

Second, I needed the workshop title to wrap so it does not get hidden by the 'speaker avatar', but after some 'playing around' I just put it in a col-8 (boostrap) div. I am wondering about a better to handle wraping the title? What rearranging would I need to do if any to accomplish that?

Lastly, any advice on how to make this cleaner both structurally or syntactically would be welcome.


texts: Regex to parse semicolon-delimited fields is too slow

texts:
I have a file with just 3500 lines like these:

filecontent= "13P397;Fotostuff;t;IBM;IBM lalala 123|IBM lalala 1234;28.000 things;;IBMlalala123|IBMlalala1234"

Then I want to grab every line from the filecontent that matches a certain string (with python 2.7):

this_item= "IBMlalala123"
matchingitems =  re.findall(".*?;.*?;.*?;.*?;.*?;.*?;.*?"+this_item,filecontent)

It needs 17 seconds for each findall. I need to search 4000 times in these 3500 lines.  It takes forever.  Any idea how to speed it up?


texts:
I have a cookie on my site with the following value:

  eyJGIjp0cnVlLCJBIjp0cnVlLCJUIjpmYWxzZSwiUyI6ZmFsc2UsIkciOmZhbHNlLCJYIjpmYWxzZX0%3D

I use this function to retrieve the value from the site so I can use it in the applications my site uses to greenlight certain elements or to block them.

function getCookieLawSettings() {
    return document.cookie.split(';')
            .map(c => c.trim().split('='))
            .filter(c => c.shift() == 'cookie_law')
            .map(c => JSON.parse(atob(decodeURIComponent(c.pop())))).pop()
}

What kind of improvements could I make on this code? Stylistic and functional.
Are there things I missed/gotcha's I should account for?

sample with dummy data:

document.not_cookie = "_ga=GA1.2.431922604.1523436815; _gid=GA1.2.1579280874.1523436815; cookie_law=eyJGIjp0cnVlLCJBIjp0cnVlLCJUIjpmYWxzZSwiUyI6ZmFsc2UsIkciOmZhbHNlLCJYIjpmYWxzZX0%3D";
function getCookieLawSettings() {
    return document.not_cookie.split(';')
            .map(c => c.trim().split('='))
            .filter(c => c.shift() == 'cookie_law')
            .map(c => JSON.parse(atob(decodeURIComponent(c.pop())))).pop()
}
console.log(getCookieLawSettings());


texts: Phone number format and data entry restriction

texts:
I created a form that formats phone numbers, allows only allowable keys to be pressed, and converts a lettered entry into its corresponding phone keypad number. Is there some cleanup or better coding that can be done? There is no business need for international phone numbers as it is a local business.

function pageLoad() {
    $(".PhoneSelection").keypress(function (e) {
        // Only allow number entry
        var regex = new RegExp("^[0-9]+$");
        var key = String.fromCharCode(!e.charCode ? e.which : e.charCode);
        if (!regex.test(key)) {
            // If not a number, is it a letter?
            var regex2 = new RegExp("^[A-Za-z]+$");
            if (regex2.test(key)) {
                // Convert the letter typed to the number on the phone keypad
                $(this).val($(this).val() + letterPos(key));
                return false;
            }
            else { return false; }
        }
    });
    $(".PhoneNum").text(function (i, text) {
        // returns (999) 555-1234 from 9995551234
        return text.replace(/(\d{3})?(\d{3})(\d{4})$/,
            function ($0, $1, $2, $3) {
                var formatted = ""; if ($1) { formatted += "(" + $1 + ") "; } if ($2) { formatted += $2 + "-"; } if ($3) { formatted += $3; } return formatted;
            }
        );
    });
}
function letterPos(val) {
    var alphaMap = { 'ABC': '2', 'DEF': '3', 'GHI': '4', 'JKL': '5', 'MNO': '6', 'PQRS': '7', 'TUV': '8', 'WXYZ': '9' };
    var number = "";
    $.each(alphaMap, function (key, value) {
        if (key.toLowerCase().indexOf(val.toLowerCase()) > -1)
        { number = value; }
    });
    return number;
}

Here is how it is consumed in the view form:

9995551234

<input id="ContactPhone" class="PhoneSelection nextField" type="text" placeholder="Phone" value="9995551234"></input>

Results on display:

  (999) 555-1234


texts: Self-taught Pythonista: Any criticism welcome for this concurrent word count script!

texts:
I've been teaching myself Python - my first programming language - for about two years now.

I recently discovered the concurrent.futures module and wanted to do something with it. What do you think about this script?

import re
import shutil
import string

from collections import Counter
from concurrent.futures import ProcessPoolExecutor
from itertools import chain, islice, zip_longest
from urllib.request import urlopen

# Regex to use for splitting text into words, dropping everything but
# alphabetic characters.
REGEX = re.compile(r"[{}{}{}]+".format(
        string.whitespace, string.digits, string.punctuation))

# http://docs.python.org/3/library/itertools.html#itertools-recipes
def grouper(iterable, n, fillvalue=None):
    "Collect data into fixed-length chunks or blocks"
    # grouper('ABCDEFG', 3, 'x') --> ABC DEF Gxx"
    args = [iter(iterable)] * n
    return zip_longest(*args, fillvalue=fillvalue)

def split_and_clean(line):
    """Returns an iterator of the words in line.

    Example:
        >>> list(split_and_clean("3, Four, five'"))
        ['four', 'five']

    Args:
        line: A string.

    Returns:
        A filter of the alphabetic words in the line.

    Raises:
        TypeError: Your input was of type <>. Must be a string.
    """
    try:
        return filter(None, re.split(REGEX, line.lower()))
    except AttributeError:
        input_type_str = str(type(line))[8:-2]
        error_message = "Your input was of type {}. Must be a string.".format(
                input_type_str)
        raise TypeError(error_message)

def wc_some_lines(lines):
    """Return a Counter containing the word count of several lines.
    Excludes any digital numbers or punctuation.

    Example:
        >>> wc_some_lines(["Line 1.", "Another line."])
        Counter({'line': 2, 'another': 1})

    Args:
        lines: An iterable of strings.

    Returns:
        A collections.Counter mapping words to their word counts.

    Raises:
        TypeError
    """
    return Counter(chain(*map(split_and_clean, lines)))

def main(num_processes=5):
    """Fetch Shakespeare's complete works and perform a concurrent word count.
    """
    url = "http://www.gutenberg.org/files/100/100.txt"
    filename = "shakespeare_complete_works.txt"
    try:
        text = open(filename)
    except IOError:
        with open(filename, "wb") as f:
            r = urlopen(url)
            shutil.copyfileobj(r, f)    # write r to f
        text = open(filename)

    # exclude the small print at the beginning and the end
    relevant_part = islice(text, 181, 124379)
    # group text into blocks of 5000 lines
    blocks = grouper(relevant_part, 5000, "")

    # perform actual word count in concurrent processes
    result = Counter()
    with ProcessPoolExecutor(num_processes) as pool:
        for part in pool.map(wc_some_lines, blocks):
            result.update(part)

    # output results
    for word, count in result.most_common(20):
        print("{}: {}".format(word, count))

if __name__ == "__main__":
    main()


texts: Printing a directory's contents in a loop

texts:
I wrote a bash script to print contents of files in a given directory in a loop.

How can I improve command line parameters handling to the script? I feel the parameter processing as of now uses too much code and it is quite clumsy. I think I had to write too much code to validate the the option arguments are numeric.

The script takes either -c numeric_choice_id and/or -l time_in_seconds and keep printing the contents of the files.

only -c number: it cats the file and ends
only -l number: repeatedly cats all the files
-c num1 and -l num2: repeatedly cats that particular file every num2 seconds

#!/bin/bash

        SYSPATH="$PWD/"

        FILES="$PWD/file1
        $PWD/file2
        $PWD/file3"

        count=0
        for i in $FILES
        do
            (( count++ ))
            menu="${menu}\n${count}. `basename $i`"
            list="${list} `basename $i`"
        done

testNumeric()
{
        if ! echo "$1" | grep -q '^[0-9]\+$'
        then
                echo "$0 Non numeric argument supplied to choice or time"
                exit
        fi

}

usage()
{
        echo -e "`basename $0` -c numeric_choice [ -l  time in seconds ]\n
-c      numeric id for the choice
-l      print o/p every time seconds
-h      print this menu

choice could be: \n$menu"

        exit
}

# Test if any arguments have been provided
if [ "x$1" = "x" ] || [ "$1" = "-h" ]
then

        usage
fi

# Allow getopt to parse the options and report error if needed
args=`getopt "c:l:" "$@"`

if [ "$?" -ne "0" ]
then
        usage
fi

# Set positional parameters
set -- $args

for i;
do
  case "$i" in
    -c  )
          choice=$2
          testNumeric $choice
          shift
          shift ;;

    -l  ) repeatTime=$2
          testNumeric "$repeatTime"
          shift
          shift  ;;

    --  )
          break ;;
  esac
done

[ "x$choice" = "x" ] && choice=`seq $count`
[ "x$repeatTime" = "x" ] && repeatTime=0

set -- $list

while [ true ]
do

        if [ "$repeatTime" = "0" ]
        then
                for a in $choice
                do
                eval temp=\${${a}}
                        cat $SYSPATH${temp}
                done

                break;
        else
                for a in $choice
                do
                eval temp=\${${a}}
                        cat $SYSPATH${temp}
                done

                sleep $repeatTime
        fi

done


texts: Find SuburbName from latlong or location

texts:
I have create one class and interface for finding SuburbName based on Location or LatLong coordinates.

My interface

public interface IGeoCodeService
{
    string GetSuburbName(double latitude, double longitude);
    string GetSuburbName(string location);
    string GetGoogleStaticMapImageUrl(string location);
}

My Class

public class GeoCodeService : IGeoCodeService
{
    private static readonly string GoogleApiKey = "*****MyAPI KEY*****";
    private static readonly string GoogleStaticMapUrl = "http://maps.googleapis.com/maps/api/staticmap";

    public string GetSuburbName(string location)
    {
        if (!string.IsNullOrEmpty(location))
        {
            using (var clientService = new HttpClientService<GeoCodeResponse>("https://maps.googleapis.com"))
            {
                var param = new Dictionary<string, string>();
                param.Add("address", location);
                param.Add("components", "country:AU");
                param.Add("result_type", "locality");
                param.Add("key", GoogleApiKey);
                var apiResult = clientService.GetAPI("maps/api/geocode/json", param);
                return FindSuburbName(apiResult);
            }
        }
        return string.Empty;
    }

    public string GetSuburbName(double latitude, double longitude)
    {
        using (var clientService = new HttpClientService<GeoCodeResponse>("https://maps.googleapis.com"))
        {
            var param = new Dictionary<string, string>();
            param.Add("latlng", $"{latitude},{longitude}");
            param.Add("result_type", "locality");
            param.Add("key", GoogleApiKey);

            var apiResult = clientService.GetAPI("maps/api/geocode/json", param);
            return FindSuburbName(apiResult);
        }
    }

    private string FindSuburbName(GeoCodeResponse result)
    {
        var response = string.Empty;
        if (result != null || result.results != null && result.results.Count > 0)
        {
            var addressObj = result.results.FirstOrDefault();
            if (addressObj != null)
            {
                var component = addressObj.AddressComponents.Where(x => x.Types.Contains("locality")).FirstOrDefault();
                if (component != null)
                {
                    return component.LongName;
                }
            }
        }
        return response;
    }

    public string GetGoogleStaticMapImageUrl(string location)
    {
        return $"{GoogleStaticMapUrl}?size=350x200&markers={location}";
    }
}

And lastly the GeoCodeResponse class to store response from the google api call.

public class GeoCodeResponse
{
    [JsonProperty("results")]
    public List<Results> results { get; set; }
    [JsonProperty("status")]
    public string status { get; set; }
}

public class Results
{
    public Results()
    {
        AddressComponents = new List<AddressComponent>();
    }
    [JsonProperty("address_components")]
    public List<AddressComponent> AddressComponents { get; set; }
}
public class AddressComponent
{
    [JsonProperty("long_name")]
    public string LongName { get; set; }
    [JsonProperty("short_name")]
    public string ShortName { get; set; }
    [JsonProperty("types")]
    public string[] Types { get; set; }
}

Can you please suggest me if what I have implemented is right or require any change. Your help will improve my code quality.

The HttpClientService class is used for call api


texts: Cellular automaton (Conway's Game of Life) in python

texts:
As a practice exercise, I implemented a cellular automaton (Conway's Game of Life) in python (with help from this tutorial).

I am very curious, if this code follows common best practices and I am wondering how to improve the code in terms of performance and readability.

import numpy as np
import matplotlib.pyplot as plt
from matplotlib import animation

arr = []

size_grid_x = 6
size_grid_y = 6
universe = np.zeros((size_grid_x, size_grid_y))
new_universe = np.copy(universe)

beacon = [[1, 1, 0, 0],
          [1, 1, 0, 0],
          [0, 0, 1, 1],
          [0, 0, 1, 1]]

universe[1:5, 1:5] = beacon

def update(universe, x, y):
    X = size_grid_x
    Y = size_grid_y

    neighbors = lambda x, y: [(x2, y2) for x2 in range(x - 1, x + 2)
                              for y2 in range(y - 1, y + 2)
                              if (-1 < x <= X and
                                  -1 < y <= Y and
                                  (x != x2 or y != y2) and
                                  (0 <= x2 <= X) and
                                  (0 <= y2 <= Y))]

    num_neighbours = sum([universe[i] for i in neighbors(x, y)])
    new_val = universe[x, y]

    if universe[x, y] and not 2 <= num_neighbours <= 3:
        new_val = 0

    elif num_neighbours == 3:
        new_val = 1
    return new_val

for i in range(100):
    for x in range(5):
        for y in range(5):
            new_universe[x, y] = update(universe, x, y)

    universe[:, :] = new_universe[:, :]
    arr.append(np.copy(universe))

fig = plt.figure()
i = 0
im = plt.imshow(arr[0], animated=True)

def update_figure(*args):
    global i
    if i < 99:
        i += 1
    else:
        i = 0
    im.set_array(arr[i])
    return im,

ani = animation.FuncAnimation(fig, update_figure, blit=True)
plt.show()


texts: Java code that takes user input of Zipcode and turns it into a bar code

texts:
This program works 100%. If someone could help me just separate it into two classes that would be really great. I have been working on it for a while and I can't seem to figure out how to make it happen. This is the full program that I have so far.

import java.util.Scanner;
public class BarCodeConverter {

public static void main(String[] args) {
    Scanner input = new Scanner(System.in);
    System.out.print("Enter a zip code: ");
    int zip = input.nextInt();
    input.close();
    int checkDigit = checkDigit(zip);

    String barcode = "|";
    barcode = dBarCode(checkDigit) + barcode;
    for (int i = 0; i < 5; i++) {
        barcode = dBarCode(checkDigit) + barcode;
        zip /= 10;
    }
    barcode = "|" + barcode;
    System.out.println(barcode);

}
 public static int checkDigit(int zip) {
    int remaining = zip;
    int sum = 0;
    while (remaining > 0) {
        sum += remaining % 10;
        remaining /= 10;
    }
    return 10 - (sum % 10);
}

public static String dBarCode(int digit) {

    if (digit == 1) {
        return ":::||";
    }
    if (digit == 2) {
        return "::|:|";
    }
    if (digit == 3) {
        return "::||:";
    }
    if (digit == 4) {
        return ":|::|";
    }
    if (digit == 5) {
        return ":|:|:";
    }
    if (digit == 6) {
        return ":||::";
    }
    if (digit == 7) {
        return "|:::|";
    }
    if (digit == 8) {
        return "|::|:";
    }
    if (digit == 9) {
        return "|:|::";
    }
    return "||:::";

  }

}


texts:
I'm modelling the core entities in a callcenter-related system that deals with Operators and groups ("pools") of them. While I've written some Python before, this is my first time building a larger project in it from scratch, and I'd like to know if my approach and code is pythonic enough or will get me into trouble later on.

I really like the idea of interfaces in general and for explorational design specifically, and while Python doesn't have those, ABCs seem like the next best equivalent thing. It there anything to be said about my use of them?

Any specific hints about my use of a MutableSet?

I'm a bit worried about file structures and putting every concrete class in its own file, as that results in from Foo.Bar.Baz import Baz; is that acceptable, or is the common wisdom to include more classes in a single module?

I'm also using a lot of type hinting; while I'm aware that it doesn't actually do anything in Python, it does help me keep the ducks straight in my head while typing and helps my IDE help me. Any concerns here?

# core/abstract_base_classes/operators.py

from abc import ABCMeta, abstractmethod
from core.abstract_base_classes.attributes import AttributeBag
from collections.abc import MutableSet
from uuid import UUID

class Operator(metaclass=ABCMeta):
    """
    An abstract class defining the interface for an Operator entity
    representing a call center agent.
    """

    @property
    @abstractmethod
    def id(self) -> UUID:
        pass

    @property
    @abstractmethod
    def status(self):
        pass

    @status.setter
    @abstractmethod
    def status(self, value):
        pass

    @property
    @abstractmethod
    def attributes(self) -> AttributeBag:
        pass

class Pool(MutableSet):
    """
    An abstract class defining the interface for an operator pool.
    """

    @abstractmethod
    def __contains__(self, operator: Operator):
        pass

    @abstractmethod
    def discard(self, operator: Operator):
        pass

    @abstractmethod
    def __iter__(self):
        pass

    @abstractmethod
    def add(self, operator: Operator):
        pass

    @abstractmethod
    def __len__(self):
        pass

# core/Entities/Operator.py

from core.abstract_base_classes.operators import Operator as AbstractOperator
from core.abstract_base_classes.attributes import AttributeBag as AbstractAttributeBag
from core.abstract_base_classes.attributes import AttributeTag as AbstractAttributeTag
from core.Entities.AttributeBag import AttributeBag
from core import status
from uuid import UUID, uuid4

class Operator(AbstractOperator):
    def __init__(self, attributes: AbstractAttributeBag=None):
        if not attributes:
            attributes = AttributeBag()

        super().__init__()
        self._id = uuid4()
        self._attributes = attributes
        self._status = status.INITIALIZED

    @property
    def id(self) -> UUID:
        return self._id

    @property
    def status(self):
        return self._status

    @status.setter
    def status(self, value):
        self._status = value

    @property
    def attributes(self) -> AbstractAttributeBag:
        return self._attributes

    @attributes.setter
    def attributes(self, attributes: AbstractAttributeBag):
        self._attributes = attributes

    def add_attribute(self, attribute: AbstractAttributeTag):
        self._attributes.add(attribute)

# core/Entities/OperatorPool.py

from core.abstract_base_classes import operators

class Pool(operators.Pool):
    def __init__(self):
        super().__init__()
        self._operators = set()

    def __iter__(self):
        return self._operators.__iter__()

    def __contains__(self, operator: operators.Operator):
        return operator in self._operators

    def discard(self, operator: operators.Operator):
        self._operators.remove(operator)

    def add(self, operator: operators.Operator):
        self._operators.add(operator)

    def __len__(self):
        return len(self._operators)


texts:
Write a method range that accepts an ArrayList of integers as a parameter and that returns the range of values contained in the list, which is defined as 1 more than the difference between the largest and smallest elements.

I feel like I'm beginning to understand conditionals, but for some reason this just makes me cringe. Is it good practice to have these conditionals as catch-alls in the beginning? Should I be using else ifs instead?

public static int range(ArrayList<Integer> list){
    if(list.size() == 0){
        return 0;
    }
    if(list.size() == 1){
        return 1;
    }

    int firstElement = list.get(1);
    int max = firstElement;
    int min = firstElement;

    for(int i = 0; i < list.size(); i++){
        int elementValue = list.get(i);
        if(max < elementValue){
            max = elementValue;
        }
        if(elementValue < min){
        min = elementValue;
        }
    }
return (max - min) + 1;
}


texts:
For the sections between count=1s and the start and end; combine overlapping positions and output the median of the counts.
Input
chr         start   stop   strand   count
chr1        0       13320   -       1
chr1        13320   13321   -       2
chr1        13321   13328   -       1
chr1        13328   13342   -       2
chr1        13342   13343   -       18
chr1        13343   13344   -       36
chr1        13344   13345   -       18
chr1        13345   13346   -       6
chr1        13346   16923   -       1
chr1        16923   16942   -       3
chr1        16942   16943   -       2

Output
chr1        13320   13321    2
chr1        13328   13346   18
chr1        16923   16943   2.5

For the second value:

Start 13328 - this is because the 4th value in the table has the start 13328.
This is the row after the second count=1.
Stop 13346 - this is because the 8th value in the table has the stop 13346.
This is the row before the third count=1.
Count 18 - this is the median of counts between the 4th and 8th inclusive.

Here is my code.
from pathlib import Path
import pandas as pd
file = Path("bed_file.bed")
# load with pandas
df = pd.read_csv(file, sep='\t', header=None)

# set colnames
header = ['chr','start','stop','strand','count']
df.columns = header[:len(df.columns)]

# index where count=1
col_count = df['count'].tolist()
li = [i for i, n in enumerate(col_count) if n == 1]

# create new dataframe
newDF = pd.DataFrame(columns=['chr','start', 'stop', 'count'])
# last position
end = df.index[-1]

# parse dataframe
for idx, elem in enumerate(li):
    if elem != li[-1]:
        next_elem = li[(idx + 1) % len(li)] # next element where count=1
        start = df.iloc[elem]['stop'] # start position
        stop = df.iloc[next_elem-1]['stop'] # stop position
        if next_elem - (elem+1) == 1: # cases where only one position and we cannot compute median
            count = df.iloc[elem+1]['count']
            #print(f"start={start}\tstop={stop}\tcount={count}")
        else:
            count = df.iloc[elem+1:next_elem]['count'].median()
            #print(f"start={start}\tstop={stop}\tcount={count}")
        newDF = newDF.append({
            'chr' : df.loc[0,'chr'],
            'start' : start,
            'stop' : stop,
            'count' : count

        },ignore_index=True)
    else: # last element in the list
        start = df.iloc[elem]['stop']
        stop = df.iloc[end]['stop']
        count = df.iloc[elem+1:end+1]['count'].median()
        #print(f"start={start}\tstop={stop}\tcount={count}")
        newDF = newDF.append({
            'chr' : df.loc[0,'chr'],
            'start' : start,
            'stop' : stop,
            'count' : count
        },ignore_index=True)

Is there a better way to do this? Is my code Pythonic?


texts: Usage of StringBuilder for returning copies of a string

texts:
Given a string and a non-negative int n, we'll say that the front of the string is the first 3 chars, or whatever is there if the string is less than length 3. Return n copies of the front:

frontTimes("Chocolate", 2) → "ChoCho"
frontTimes("Chocolate", 3) → "ChoChoCho"
frontTimes("Abc", 3) → "AbcAbcAbc"
frontTimes("X", 3) → "XXX"

I've solved above problem using following code but I'm using a new StringBuilder to store intermediate string result. Does it really needed can I optimize and remove the for loop in the else?

public String frontTimes(String str, int n) {

        StringBuilder sb = new StringBuilder(str);
        StringBuilder newsb = new StringBuilder();

        if(sb.length() >= 3)
        {
            for(int i = 0; i < n; i++)
            {
                newsb.append(sb.substring(0,3));
            }

            return newsb.toString();
        }
        else
        {
            for(int i = 0; i < n; i++)
            {
                newsb.append(sb.toString());
            }

            return newsb.toString();

        }

    }


texts:
I wrote this code over night for a little project that my friend and I have been working on.  This class template was created over a year ago during as a class assignment for C++ programming.  I recently reviewed this program and I saw that I created multiple instances of my classes in order to print out different data types in the output.

This is not efficient coding at all and I know it can be prone to bugs.  However, would anyone consider making abstract classes instead?  Please given me an opinion on how I should change this code in order for it to be efficient and reduce the creation of the same class.

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

using namespace std;

template<class T>

class BinaryTree
{
    struct Node
    {
        T data;
        Node* lChildptr;
        Node* rChildptr;

        Node(T dataNew)
        {
            data = dataNew;
            lChildptr = NULL;
            rChildptr = NULL;
        }
    };
    private:

    Node* root;

    void Insert(Node* newData, Node* &theRoot)
    {
        if(theRoot == NULL)
        {
            theRoot = newData;
            return;
        }
        else if(newData->data < theRoot->data)
            Insert(newData, theRoot->lChildptr);
        else
            Insert(newData, theRoot->rChildptr);;
    }

    void insertnode(T item)
    {
        Node *newData;
        newData= new Node(item);

        Insert ( newData, root);
    }

    void PrintTree(Node* &theRoot)
    {
        if(theRoot)
        {
            cout << theRoot->data << endl;
            PrintTree(theRoot->lChildptr); //<< The error is here
            PrintTree(theRoot->rChildptr);
        }
    }

    public:
    BinaryTree()
    {
        root = NULL;
    }

    void AddItem(T item)
    {
        insertnode(item);
    }

    void PrintTree()
    {
        PrintTree(root);
    }
};

int main()
{
    BinaryTree<string> *tree = new BinaryTree<string>();
    BinaryTree<int> *myBT = new BinaryTree<int>();
    BinaryTree<double> *mydouble = new BinaryTree<double>();
    BinaryTree<char> *mychar = new BinaryTree<char>();

    tree->AddItem("Erick");
    myBT->AddItem(7);
    mydouble->AddItem(9.99999);
    mychar->AddItem('@');

    tree->PrintTree();
    myBT->PrintTree();
    mydouble->PrintTree();
    mychar->PrintTree();

    system ( "pause");
}


texts: Is This F# Recursive Example Tail Recursive?

texts:
I have a payment/lockbox file archiving utility that is called several times per day and with different parameters depending on the files that need archiving.

I know I can flatten argv into a string using a simple method like the following:

let r = Array.toList(argv)

let a =
    r
    |> String.concat " "

so the utility can send me email with the parameters used to call it without all the brackets from a string [].

However, I wanted to see if I could flatten argv using tail recursion, so is the following example tail-recursive?

let squash_str_array (str_arg : string[]) =
    let array_len = str_arg.Length
    let rec inner_squash (inner_str_arg : string []) (build_up_list : string) idx =
        if idx = array_len then
            build_up_list
        else
            let build_up_list = inner_str_arg.[idx] + " " + build_up_list
            inner_squash inner_str_arg build_up_list (idx + 1)

    inner_squash str_arg "" 0

[<EntryPoint>]
let main argv =
    let test_array = [| "/mu"; "/al"|]
    let new_list = squash_str_array test_array
    .
    .
    .


texts: Verify that a path doesn't contain . or .. or // and doesn't end with /

texts:
This is actually a function from the first commit of the git source code, for the purpose stated in the title:

static int verify_path(char *path)
{
  char c;

  goto inside;
  for (;;) {
      if (!c)
          return 1;
      if (c == '/') {
inside:
          c = *path++;
          if (c != '/' && c != '.' && c != '\0')
              continue;
          return 0;
      }
      c = *path++;
  }
}

I was checking if there was an alternate way to implement this without the goto statement and ended up with this function:

static int verify_path(char *path)
{
    char c = '/';

    do {
        if (c == '/') {
            c = *path++;
            if (c == '/' || c == '.' || c == '\0')
                return 0;
        }
    } while ((c = *path++));

    return 1;
}

Do you see any problems with the new function? Is it missing anything from the original?

Let us please avoid discussing about goto.

Sample list of invalid path names:

/path/to/file
../path/to/file
path//to/file
path/../to/file
path/./to/file
path/to/.file
path/to/file/


texts:
My apology, I am quite new to posting a question in this forum.

I had a task where I was supposed to write a solution to sort entries(Name, score - in an array/list) in order of score and generate ranking based on higher score to lower scores.

I tried doing that, code is working what it was supposed to do but it seems very ambiguous and tightly coupled, I can't even write a unit test for it.

Could someone have a look and suggest do I need to minimize and simplify this class so that I can write a Unit Test class for this.

  I have pasted main method class, If anyone wants me to paste other
  relevent classes as well so do ask me please.

Any suggestion(s)/workaround(s) would be much appreciated.

Many thanks,

public class JournalAnalyzer {
    final static int LENGTH_OF_JOURNAL = 5; //Length Journal array
    static int count = 0;
    static Integer ranking = 1;
    static Journal[] journals = new Journal[LENGTH_OF_JOURNAL];
    static ArrayList<Journal> list = new ArrayList<Journal>();
    static Object[] scoreList = new Object[LENGTH_OF_JOURNAL];
    static String journalName;
    static Double journalScore;
    static Integer journalRank;
    static Boolean journalReview;

private static void initData(Journal[] journals) {
    journals[0] = new Journal(0, "Journal A", 5.6, false);
    journals[1] = new Journal(0, "Journal B", 2.6, false);
    journals[2] = new Journal(0, "Journal C", 3.2, false);
    journals[3] = new Journal(0, "Journal D", 4.1, false);
    journals[4] = new Journal(0, "Journal E", 1.6, false);
}

private static int fillJournalList(int count, Journal[] journals,
        int LENGTH_OF_JOURNAL, ArrayList<Journal> list) {

    for (int i = 0; i < LENGTH_OF_JOURNAL; i++) {
        journalRank = new Integer(journals[i].getRank());
        journalName = new String(journals[i].getJournal());
        journalScore = new Double(journals[i].getScore());
        journalReview = new Boolean(journals[i].getIsReviewed());

        if (!journalReview) {
            Journal value = new Journal(journalRank, journalName,
                    journalScore, journalReview);
            list.add(value);
            count++;
        } else {
            continue;
        }
    }
    return count;
}

private static void GenerateRanking(Integer ranking, int count,
        ArrayList<Journal> list, Object[] scoreList) {
    Double scoreComparatorOne;
    Double scoreComparatorTwo;

    Comparator<Journal> scores = new SortScore();
    Collections.sort(list, scores);

    for (int i = 0; i < count; i++) {
        scoreComparatorOne = (list.get(i)).getScore();
        if (i == 0) {
            scoreComparatorTwo = (list.get(i)).getScore();
        } else {
            scoreComparatorTwo = (list.get(i - 1)).getScore();
        }
        if (scoreComparatorOne.equals(scoreComparatorTwo)) {
            if (ranking == 0) {
                ranking += 1;
            } else {
                ranking = ranking;
            }
        } else {
            ranking = i + 1;
        }

        (list.get(i)).setRank(ranking);
        scoreList[i] = (list.get(i));

    }
}

private static void displayJournal(int counter, Object[] scoreList) {
    JournalOutput printer = new JournalOutput();
    printer.display(count, scoreList);
    System.exit(0);
}

public static void main(String[] args) throws IOException {
    initData(journals);
    count = fillJournalList(count, journals, LENGTH_OF_JOURNAL, list);
    GenerateRanking(ranking, count, list, scoreList);
    displayJournal(count, scoreList);
}
 }


texts:
I typically use high level programming languages like C# and JavaScript, but today I was doing the "99 bottles of beer" kata for an event using C. Below is my solution, which seems to work. Please let me know if there's any egregious mistakes or non-idiomatic pieces in there?

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

#define MAXBOTTLES 9999

#define MAX_NR_OF_DIGIT_OCCURENCES 2 // Max nr of placeholders in any of the sentence formats
#define SENTENCE_FORMAT_BASE "%i bottles of beer on the wall, %i bottles of beer\nTake one down, pass it around, %i bottles of beer on the wall...\n"
#define SENTENCE_FORMAT_1 "1 bottle of beer on the wall, 1 bottle of beer\nTake one down, pass it around, no more bottles of beer on the wall...\n"
#define SENTENCE_FORMAT_0 "No more bottles of beer on the wall, no more bottles of beer.\nGo to the store and buy some more, %i bottles of beer on the wall..."

int getNumberOfDigits(int number) {
    int numberWidth = 0;

    while (number) {
        numberWidth++;
        number /= 10;
    }

    return numberWidth;
}

char* createCouplet(const int i, char* format) {
    int length = getNumberOfDigits(i) * MAX_NR_OF_DIGIT_OCCURENCES + strlen(format);
    char* coupletBuffer = malloc(length * sizeof(char));

    sprintf(coupletBuffer, format, i, i, i-1);

    return coupletBuffer;
}

int main(int argc, char *argv[]) {
    int songSize = 13; // TODO: Retrieve from argv
    int limit = songSize + 1;

    if (songSize >= MAXBOTTLES) {
        return 42;
    }

    char* song[limit];

    for (int i = 2; i < limit; i++) {
        song[limit - i - 1] = createCouplet(i, SENTENCE_FORMAT_BASE);
    }

    song[limit - 2] = malloc(2500 * sizeof(char));
    strcpy(song[limit - 2], SENTENCE_FORMAT_1);

    song[limit - 1] = createCouplet(songSize, SENTENCE_FORMAT_0);

    for (int i = 0; i < limit; i++) {
        printf("%s\n", song[i]);
        free(song[i]);
    }

    return 0;
}

I welcome any feedback of course, but I'm particularly worried that I do silly things around buffers and handling memory correctly.


texts: Does Oracle have a mistake in their documentation regarding switch case formatting?

texts:
Here is a reference to how switch statements should be formatted (I've never seen this used at the two companies I've worked at):

And a contradictory one, which I am partial to (and is IntelliJ IDEA default):

The obvious discrepancy is in the tabbing of the case statement - whether it's
switch(case) {
case x:
}

or
switch(case) {
  case x:
}

Is there a right or wrong one?


texts: Game of Life rules in 14 lines of Python

texts:
I've attempted a functional solution to Conway's Game of Life in Python.

The example code allows you to see the next generation of the universe by calling the step() function, passing the current generation of the universe. The universe is represented as a set of live cells. Live cells are represented as a tuple of x, y coordinates.

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

Approach - is it functional? If not, why not?
Test cases - are there any test case I've missed that highlight a bug? Can it be done with less test cases while maintaining the same code coverage?
Python idioms and conventions
Making use of built-in functions and datatypes

import unittest

def get_neighbours(x, y):
    '''
    Returns the set of the given cell's (x,y) 8 eight neighbours.
    :param x: x coordinate of cell
    :param y: y coordinate of cell
    '''
    return {(x + dx, y + dy) for dx, dy in [(-1, -1), (-1, 0), (-1, 1), (0, -1), (0, 1), (1, -1), (1, 0), (1, 1)]}

def is_survivor(universe, x, y):
    '''
    Returns True if given cell will survive to the next generation, False otherwise.
    :param universe: set of live cells in the universe. A live cell is the tuple (x,y)
    :param x: x coordinate of cell
    :param y: y coordinate of cell
    '''
    num_live_neighbours = len(get_neighbours(x, y) & universe)
    return num_live_neighbours == 2 or num_live_neighbours == 3

def is_born(universe, x, y):
    '''
    Returns True if given cell will be born in the next generation, False otherwise.
    :param universe: set of live cells in the universe. A live cell is the tuple (x,y)
    :param x: x coordinate of cell
    :param y: y coordinate of cell
    '''
    return len(get_neighbours(x, y) & universe) == 3

def step(universe):
    '''
    Returns the new universe after a single step in the game of life.
    :param universe: set of live cells in the universe. A live cell is the tuple (x,y)
    '''
    survivors = { (x, y) for x, y in universe if is_survivor(universe, x, y) }
    list_of_neighbour_sets = [get_neighbours(x, y) for x, y in universe]
    flattened_neighbour_set = {item for subset in list_of_neighbour_sets for item in subset}
    dead_neighbours = flattened_neighbour_set - universe
    births = { (x, y) for x, y in dead_neighbours if is_born(universe, x, y) }
    return survivors | births

class Test(unittest.TestCase):

    def test_get_neigbours(self):
        self.assertEqual({(-1, -1), (0, -1), (1, -1), (-1, 0), (1, 0), (-1, 1), (0, 1), (1, 1)}, get_neighbours(0, 0))
        self.assertEqual({(4, 5), (4, 6), (4, 7), (5, 5), (5, 7), (6, 5), (6, 6), (6, 7)}, get_neighbours(5, 6))

    def test_is_survivour_should_return_true_if_cell_has_2_live_neighbours(self):
        self.assertTrue(is_survivor({(0, 0), (1, 0), (2, 0)}, 1, 0))

    def test_is_survivour_should_return_true_if_cell_has_3_live_neighbours(self):
        self.assertTrue(is_survivor({(0, 0), (1, 0), (0, 1), (1, 1)}, 0, 0))
        self.assertTrue(is_survivor({(0, 0), (1, 0), (0, 1), (1, 1)}, 1, 0))
        self.assertTrue(is_survivor({(0, 0), (1, 0), (0, 1), (1, 1)}, 0, 1))
        self.assertTrue(is_survivor({(0, 0), (1, 0), (0, 1), (1, 1)}, 1, 1))

    def test_is_survivour_should_return_false_if_cell_is_underpopulated(self):
        self.assertFalse(is_survivor({(0, 0)}, 0, 0))

    def test_is_survivour_should_return_false_if_cell_is_overpopulated(self):
        self.assertFalse(is_survivor({(-1, -1), (0, -1), (1, -1), (-1, 0), (1, 0), (-1, 1), (0, 1), (1, 1)}, 0, 0))

    def test_is_born_should_return_false_if_dead_cell_doesnt_have_exactly_3_live_neighbours(self):
        self.assertFalse(is_born({(0, 0)}, 0, 0))

    def test_is_born_should_return_true_if_dead_cell_has_exactly_3_live_neighbours(self):
        self.assertTrue(is_born({(0, 0), (1, 0), (0, 1)}, 1, 1))

    def test_L_becomes_block_after_step(self):
        self.assertEqual({(0, 0), (1, 0), (0, 1), (1, 1)}, step({(0, 0), (0, 1), (1, 1)}))

if __name__ == "__main__":
    unittest.main()


texts: Operating on a list of files using recursion

texts:
I'm starting just now with CoffeeScript and I found out that I can't solve problems like looping and recursives with just one line.  I would like to improve the code that I just wrote using built-in CoffeeScript helpers.

'use strict'
file_system = require 'fs'
Types       = require './types'

Extract =
  each_file: (index = 0) ->
    length  = @files.length
    file    = @files[index]
    if index < length
      Types.read file, @next.bind @
      @each_file index + 1

  next: (file) ->
    @result.push file
    if @result.length == @files.length
      return @cb.clean.call @cb, @result
    @each_file()
    return

  init: (files, cb) ->
    @files              = files
    @cb                     = cb
    @result             = []
    @each_file()
    return

module.exports = Extract

The script speaks for itself; I'm doing a recursive function to send files to Types.read, and I store the result in the result array.


texts:
Inspired by Hosch250, TopinFrassi, Legato and the recent milestone of having our 100th fizzbuzz question on Code Review I decided to add an ArnoldC FizzBuzz to the collection.

I haven't found any best practices about the language, but I assume the code needs to be VERBOSE. For those unfamiliar with the language, a small excerpt of the keywords:

True              NO PROBLEMO
ModuloOperator    I LET HIM GO
DeclareInt        HEY CHRISTMAS TREE
AssignVariable    GET TO THE CHOPPER

The challenge itself doesn't need introduction. Write all numbers from 1 up till and including 100, but:

Write Fizz instead of the number when divisible by 3
Write Buzz instead of the number when divisible by 5
Write FizzBuzz instead of the number when divisible by 15

LISTEN TO ME VERY CAREFULLY modulo
  I NEED YOUR CLOTHES YOUR BOOTS AND YOUR MOTORCYCLE dividend
  I NEED YOUR CLOTHES YOUR BOOTS AND YOUR MOTORCYCLE divisor
  GIVE THESE PEOPLE AIR
    HEY CHRISTMAS TREE quotient
      YOU SET US UP 0
    HEY CHRISTMAS TREE remainder
      YOU SET US UP 0
    HEY CHRISTMAS TREE product
      YOU SET US UP 0
    GET TO THE CHOPPER quotient
      HERE IS MY INVITATION dividend
      HE HAD TO SPLIT divisor
    ENOUGH TALK
    GET TO THE CHOPPER product
      HERE IS MY INVITATION divisor
      YOU'RE FIRED quotient
    ENOUGH TALK
    GET TO THE CHOPPER remainder
      HERE IS MY INVITATION dividend
    GET DOWN product
  ENOUGH TALK
  I'LL BE BACK remainder
HASTA LA VISTA, BABY

LISTEN TO ME VERY CAREFULLY divisible
  I NEED YOUR CLOTHES YOUR BOOTS AND YOUR MOTORCYCLE dividend
  I NEED YOUR CLOTHES YOUR BOOTS AND YOUR MOTORCYCLE divisor
  GIVE THESE PEOPLE AIR
    HEY CHRISTMAS TREE result
    YOU SET US UP 0
    GET YOUR ASS TO MARS result
    DO IT NOW modulo dividend divisor

    HEY CHRISTMAS TREE isZero
    YOU SET US UP 0
    GET TO THE CHOPPER isZero
    HERE IS MY INVITATION result
    YOU ARE NOT YOU YOU ARE ME 0
  ENOUGH TALK

  I'LL BE BACK isZero
HASTA LA VISTA, BABY

IT'S SHOWTIME
    HEY CHRISTMAS TREE maxValue
    YOU SET US UP @NO PROBLEMO
    HEY CHRISTMAS TREE n
    YOU SET US UP 0
    HEY CHRISTMAS TREE divisible
    YOU SET US UP @NO PROBLEMO
    HEY CHRISTMAS TREE multiple
    YOU SET US UP @NO PROBLEMO

    STICK AROUND maxValue
        GET TO THE CHOPPER n
        HERE IS MY INVITATION n
            GET UP 1
        ENOUGH TALK
        GET TO THE CHOPPER maxValue
            HERE IS MY INVITATION 100
            LET OFF SOME STEAM BENNET n
        ENOUGH TALK

        GET YOUR ASS TO MARS multiple
        DO IT NOW divisible n 15
            BECAUSE I'M GOING TO SAY PLEASE multiple
            TALK TO THE HAND "FizzBuzz"
            BULLSHIT
            GET YOUR ASS TO MARS multiple
            DO IT NOW divisible n 5
                BECAUSE I'M GOING TO SAY PLEASE multiple
                TALK TO THE HAND "Buzz"
                BULLSHIT
                GET YOUR ASS TO MARS multiple
                DO IT NOW divisible n 3
                    BECAUSE I'M GOING TO SAY PLEASE multiple
                    TALK TO THE HAND "Fizz"
                BULLSHIT
                    TALK TO THE HAND n
                YOU HAVE NO RESPECT FOR LOGIC
            YOU HAVE NO RESPECT FOR LOGIC
        YOU HAVE NO RESPECT FOR LOGIC
    CHILL
YOU HAVE BEEN TERMINATED


texts:
My use case is  I want a password generator that generates memorable and robust passwords for users, to give me a known minimum entropy.

For this - I'm approximating set of Consonant-Vowel-Consonant words, because then they are both memorable (ish) and have a known entropy level. The reason for this is because I'm not confident that when asked to pick a password, rules based 'systems' lead to at least some of the passwords being horribly weak.

So my core concern is whether the below has any security flaws - I believe that mapping /dev/urandom onto a flat character space should generally accomplish this, and the CVC groupings give me a known minimum entropy (44.9 bits in this case) over user-set passwords that I believe are often quite a lot worse across a whole set of user accounts.

cvc_gen.pl:

#!/usr/bin/env perl

use strict;
use warnings;

#uses /dev/urandom to fetch bytes.
#generates consonant-vowel-consonant groupings.
#each are 11.22 bits of entropy, meaning a 4-group is 45 bits.
#( 20 * 6 * 20 = 2400, which is 11.22 bits of entropy log2 2400
#log2(2400 ^ 4) = 44.91
#but because it's generated 'true random' it's a know entropy string.

my $num    = 4;
my $format = "CVC";

my %letters = (
    V => [qw ( a e i o u y )],
    C => [ grep { not /[aeiouy]/ } "a" .. "z" ],
);

my %bitmask_for;
foreach my $type ( keys %letters ) {
   #find the next power of 2 for the number of 'letters' in the set.
   #So - for the '20' letter group, that's 31. (0x1F)
   #And for the 6 letter group that's 7.  (0x07)
   $bitmask_for{$type} =  ( 2 << log ( @{$letters{$type}} ) / log 2 ) - 1 ;
}

open( my $urandom, '<:raw', '/dev/urandom' ) or die $!;

for ( 1 .. $num ) {
    for my $type ( split //, $format ) {
        my $value;
        while ( not defined $value or $value >= @{ $letters{$type} } ) {
            my $byte;
            read( $urandom, $byte, 1 );
            #byte is 0-255. Our key space is 20 or 6.
            #So rather than modulo, which would lead to an uneven distribution,
            #we just bitmask at '1F' giving 0-31, and discard and 'too high'.
            $value = (unpack "C", $byte ) & $bitmask_for{$type};
        }
        print $letters{$type}[$value];
    }
    print " ";
}
print "\n";
close($urandom);


texts: Different class name based on condition in React

texts:
I have a very simple component, which should be styled differently based on the passed condition.

I wonder if there is a better approach to refactor this piece of code?

function RandomComponent({ number, condition }) {
    let classNameToUse;

    switch (condition) {
        case 'high':
            classNameToUse = 'number number--high';
            break;
        case 'medium':
            classNameToUse = 'number number--medium';
            break;
        default:
            classNameToUse = 'number';
    }

    return
{number}
;
}


texts:
Im trying to teach myself enough to start using more OOP in php.  This is what Ive come up with. Is there any reason why any of this is done wrong, or should be done another way?

    class workers {
            private $name;

            function __construct($name){
                $this->name=$name;
            }

            function setName($name){
                $this->name=$name;
            }

            function doPrint($who){
                print $who->name . ' is ' . $who->isWhat() .'<br>';

            }

    }

    class boss extends workers{

            function isWhat(){
                return 'the boss';
            }

    }

    class bee extends workers{

            function isWhat(){
                return 'not the boss';
            }
    }

    $theboss =new boss('gordon');
    $thebee= new bee('johnny');

        workers::doPrint($theboss);
        workers::doPrint($thebee);

    $theboss->setName('johnny');
    $thebee->setName('gordon');

        workers::doPrint($theboss);
        workers::doPrint($thebee);

prints:

gordon is the boss
johnny is not the boss
johnny is the boss
gordon is not the boss


texts:
Count duplicate List<int> in List<List<int>>.
A duplicate is not order-dependent. { 1, 2, 3 } is a duplicate of { 2, 1, 3 }

Looking for speed without getting silly.

public static void CountListTest()
{
    List<List<int>> testData = new List<List<int>>
    {
            new List<int> { 7, 3, 4 },
            new List<int> { 1, 2, 3 },
            new List<int> { 2, 1, 3 },
            new List<int> { 6, 8, 3 },
            new List<int> { 9, 2, 4 },
            new List<int> { 6, 3, 8 },
            new List<int> { 7, 3, 4 },
    };
    List<List<int>> countList = CountList(testData);
    Debug.WriteLine("");
    testData = new List<List<int>>
    {
            new List<int> { 1, 2, 3 },
            new List<int> { 2, 1, 3 },
            new List<int> { 6, 8, 3 },
            new List<int> { 2, 1, 3, 9 },
            new List<int> { 6, 8, 3, 9 },
            new List<int> { 2, 1, 3, 9 },
            new List<int> { 9, 2, 4 },
            new List<int> { 6, 3, 8 },
            new List<int> { 7, 3, 4 },
    };
    countList = CountList(testData);
}
public static List<List<int>> CountList(List<List<int>> input)
{
    List<List<int>> returnListList = new List<List<int>>();
    foreach (List<int> list in input)
        list.Sort();
    HashSet<int> alreadyMatched = new HashSet<int>();
    int count = 0;
    bool match = true;
    int lastEval = 0;
    for (int i = 0; i < input.Count - 1; i++)
    {
        if (alreadyMatched.Contains(i))
            continue;
        returnListList.Add(input[i]);
        count = 1;
        lastEval = 0;
        for (int j = i+1; j < input.Count; j++)
        {
            if (alreadyMatched.Contains(j))
                continue;
            lastEval = j;
            if (input[i].Count() != input[j].Count())
                continue;
            match = true;
            for (int k = 0; k < input[i].Count(); k++)
            {
                if(input[i][k] != input[j][k])
                {
                    match = false;
                    break;
                }
            }
            if(match)
            {
                count++;
                alreadyMatched.Add(j);
            }
        }
        Debug.WriteLine("Count = {0}  List {1}", count, string.Join(", ", input[i]));
    }
    if (count == 1 && lastEval > 0)
    {
        Debug.WriteLine("Count = {0}  List {1}", 1, string.Join(", ", input[lastEval]));
        returnListList.Add(input[lastEval]);
    }
    return returnListList;
}


texts: Approximately matching strings to elements in an array

texts:
I have two datasets:

A list containing about 4200 string elements
A list containing about 119,000 string elements

I'm taking each element from list 1 and looping through each element in list 2 using the jaro-winkler algorithm to find a "good" match based on a desired confidence threshold. I know that this process will work, but it will take way too long. Does anyone have any suggestions on a better way to do this to speed the process up?

def get_jw_match(data, target):
    """Uses the jaro-winkler algorithm to match strings(names) from the   target(the set from which you want to find matches) to the data(the set for which you are trying to find matches."""
    temp_list = []
    for i, item_data in enumerate(target):
        max = 0
        temp_list.append(0)
        for j, item_target in enumerate(data):
            jw = jellyfish.jaro_winkler(item_data, item_target)
            if (jw > confidence):
                temp_list[i] = jw
    return temp_list


texts: The most elegant way to locate two enums

texts:
I have situation where user has got options to select, and after selected any option will appear next options. For example :
1 - Add car
2 - Add motorcycle.
3 - Print cars
4 - Print motorcycles

And after selected for example "1" console will show options like :
1 - Add passenger car,
2 - Add light commercial car.
At this moment i have two enum classes in two separated files that has got almost the same code inside, and same methods createFromInt() which returns Options according to int provided by the user, and toString().Exmple one of two enums(The second one is almost the same except the fields) :

enum Option {
ADD_CAR(0,"Add car"),
ADD_MOTORCYCLE(1,"Add motorcycle"),
PRINT_CARS(2,"Print cars"),
PRINT_MOTORCYCLES(3, "Print motorcyces"),

private int value;
private String description;

Option(int value, String description) {
    this.value = value;
    this.description = description;
}

@Override
public String toString() {
    return value + "-" + description;
}

public static Option createFromInt(int option) throws NoSuchOptionException {
    try {
        return Option.values()[option];
    }catch (ArrayIndexOutOfBoundsException ex) {
        throw new NoSuchOptionException("Brak opcji o ID: " + option);
    }
}

}

I was just wondering is it corectly locate these enums in two files or exists any more elegant way for example one file with two enums , or nested enums (if something like that at all exists).


texts: Evaluate mathematical expression in reverse Polish notation in C

texts:
This is a program exercise from The C Programming Language by Kernighan and Ritchie (Chap 5).

It is based on my earlier question here on Stack Overflow.

One user suggested to submit my code here, saying there's a whole
lot of bad coding practice in this snippet. Since most of the harmful
practice here originates from K&R, you might want to consider a better
source for learning C.

What are instances of bad coding practice in this program? How can it be improved or written in more compact form?

If The C Programming Language by Kernighan & Ritchie is not good way to start learning C programming, I'm open to suggestions on an alternative good read.

//Exercise 5-10. Write the program expr, which evaluates a reverse Polish
//expression from the command line, where each operator or operand is a
//separate argument. For example, expr 2 3 4 + *
//evaluates 2 x C+4).

//For multiplication character '*' is not working

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

#define MAXLINE 1000
#define NUMBER 0

int sign = 1;
char s[MAXLINE];

void calc (int type);

int main(int argc, char *argv[])
{
    if (argc < 4)
        printf("Usage: ./<programName> op1 op2 operator\n");
    else
    {
        int i, d;
        int c;

        while (--argc > 0 && (c = **++argv) != '\n')
        {
            i = 0;
            if (c == '+' || c == '-' || c == '*' || c == '/' || c == '=' || c == '\n')
            {
                if ((c == '+' || c == '-') && isdigit(d = *++(argv[0])))
                {
                    sign = (c == '-') ? -1 : 1;
                    c = d;
                    goto DOWN1;
                }
                else
                {
                    calc(c);
                    goto DOWN2; //To avoid re-executing calc(Number) which
                                //is outside any loop in main when operator
                                //is read and operation is performed.
                }
            }

DOWN1:      while (isdigit(c = *argv[0]))
            {
                s[i++] = c;
                c = *++(argv[0]);

                if (**argv == '.')
                {
                    s[i++] =  **argv;
                    while (isdigit(*++(argv[0])))
                        s[i++] = **argv;
                }
                s[i] = '\0';
            }
            calc(NUMBER);   //Outside while to get single push of s[]
                            //after reading the complete number
DOWN2:      ;
        }
    }
    return 0;
}

void push (double f);
double pop(void);

void calc (int type)
{
    double op2, res;
    switch(type)
    {
        case NUMBER:
            push(sign*atof(s));
            sign = 1;
            break;
        case '+':
            push(pop() + pop());
            break;
        case '-':
            op2 = pop();
            push(pop() - op2);
            break;
        case '*':
            push(pop() * pop());
            break;
        case '/':
            op2 = pop();
            push(pop() / op2);
            break;
        case '=':
            res = pop();
            push(res);
            printf("\t\t\t||Result = %lg||\n", res);
            break;
        case '\n':
            break;
        default:
            printf("\nError: Invalid Operator!\n");
            break;
    }
}

#define STACKSIZE 1000
double val[STACKSIZE];
int sp = 0;

void push(double f)
{
    if (sp >= STACKSIZE)
        printf("\nError: Stack Overflow!\n");
    else
        val[sp++] = f;
}

double pop(void)
{
    if (sp != 0)
    {
        double ret = val[--sp];
        return ret;
    }
    else
    {
        printf("\nError: Stack Empty!\n");
        return 0.0;
    }
}


texts:
I created this function  it is looking for the html tag  and replacing it with the ^value. It seems complicated wanted to know if there is a better way to do something like this.

  Will you review the syntax, structure, and logic of my code. It can be tested using the main.

Output

dsfsadfsad 58 dsfsadfsad
dsfsadfsad 5^8  dsfsadfsad

Code

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

            string source = "dsfsadfsad 58 dsfsadfsad";
            Console.WriteLine(source);
            source = superscriptRule(source);
            Console.WriteLine(source);

        }

        protected static string superscriptRule(string source)
        {
            if (!string.IsNullOrEmpty(source) == true)
            {
                if (source.Contains(""))
                {
                    Match m = Regex.Match(source, @"\s*(.+?)\s*", RegexOptions.IgnoreCase);
                    if (m.Success)
                    {
                        int i = 0;
                        string x = m.Groups[1].Value;
                        bool result = int.TryParse(x, out i);
                        if (result == true)
                        {
                            string replacestring = string.Format("{0}", x);
                            string newstring = string.Format("^{0} ", x);
                            source = source.Replace(replacestring, newstring);
                            return source;
                        }
                        else
                        {
                            return source;
                        }
                    }
                    return source;
                }

            }
            return source;

        }
    }
}


texts: Python interactive console which automatically reload modules

texts:
I just started to program Python. As my first application I implemented an interactive console which automatically python modules before a new code block is evaluated. Here is the code:

### module "module_reloading_console.py"
import sys
import code
import imp
import readline
import os

class ModuleReloadingConsole(code.InteractiveConsole):

    def __init__(self):
        super().__init__()
        readline.parse_and_bind("tab: complete")
        self.stored_modifier_times = {}
        self.check_modules_for_reload()

    def runcode(self, code):
        self.check_modules_for_reload()
        super().runcode(code)
        self.check_modules_for_reload() # maybe new modules are loaded

    def check_modules_for_reload(self):
        for module_name, module in sys.modules.items():
            if hasattr(module, '__file__'):
                module_modifier_time = os.path.getmtime(module.__file__)

                if module_name in self.stored_modifier_times:
                    if module_modifier_time > self.stored_modifier_times[module_name]:
                        imp.reload(module)
                    self.stored_modifier_times[module_name] = module_modifier_time
                else:
                    self.stored_modifier_times[module_name] = module_modifier_time

ModuleReloadingConsole().interact("Welcome to ModuleReloadingConsole")

Usage:

~: python3 module_reloading_console.py
Welcome to ModuleReloadingConsole
>>> import test
>>> test.foo
23
>>> test.foo # in the meanwhile change foo to '42' in test.py
42

Because I am really new to Python I want to now which improvements you have for the above code. Are there common Python conventions I have not considered?

marginal note: this code recipe (automatically upgrade class instances on reload()) would be a good improvement. Maybe also this article about dynamically reloading a python code might improve the code...