Dialog multiple instantiations I have a site where there are lots of "jobs" that a user creates. The user has the option to Close any given job. I want a pop up warning dialog whenever the user clicks the Close button, and verify that they actually want to close the job.

There are many ways to do this, and I've implemented it this way (jsfiddle):

function openCloseDialog(item) {
    var jobid = $(item).attr("jobid");
    var closeLink = $(item).attr("value");

    if ($("#closeWarningModal").size() > 0) {
        $("#closeWarningModal").dialog({
            autoOpen: true,
            'modal': true,
            title: "Close Job",
            draggable: true,
            resizable: true,
            'buttons': {
                'Cancel': function () {
                    $(this).dialog('close');
                },
                'Close': function () {
                    // close
                    $(this).dialog('close');
                },
            }
        });
    } else {
        // close
    }
}

This seems to be working perfectly fine. The question I have is, is there any reason to NOT do it this way? At first I was curious if this implementation would cause multiple instantiations of the dialog, or if the user clicked the Close button a second time it would fail to open. But neither of those things are happening and it seems to work perfectly.

Can you see or find anything wrong with this code?

Looks OK to me. jQueryUI will take care of most of the low-level stuff like not letting you open several dialogs and such (by simply not letting you click "behind" the modal).

The code could be cleaned up though:

Store $(item) in a variable (same with the modal element)
No need to quote those option names
Most of the options you're setting are already the default options
Extract repeated code into functions
Don't use plain attributes to store "jobid" and certainly not "value" (since that's a real attribute for some elements). It's invalid markup. Use data-* attributes instead.
Don't use the onclick attribute either. You have jQuery: Use it.
Consider using a more semantically appropriate element for the close-job button. Like <a> or <button>. A div is semantically void; it doesn't mean anything. An a or a button, meanwhile, implies that it's clickable and will perform some sort of a action.

JavaScript

$('.close-job').on('click', function (event) {
  var button = $(this),
      job = button.data('job'),
      uri = button.data('uri'),
      modal = $('#closeWarningModal');

  function closeJob() {
    // ...
  }

  function dismissModal() {
    modal.dialog('close');
  }

  if(modal.length) {
    modal.dialog({
      modal: true,
      title: 'Close Job',
      buttons: {
        Cancel: dismissModal,
        Close: function () {
          closeJob();
          dismissModal();
        } // <-- there was an extra comma here; some versions of IE will choke on that
      }
    });
  } else {
    closeJob();
  }
});

HTML

<button class="close-job" data-uri="closeurl" data-job="jobid">Close</button>


Extension methods for translation engine Our application uses some singletons for localized strings. These calls used to be long and dirty. Therefore some co-worker created extensions for the int and string type to ease the usage of translations.

What does the code do: Find a translation string based on the key (the int value). If it cannot be found it falls back to the first provided string. The latter is a params[] string used in underlying string.Format() method as parameters.

const var warrantyDescription = "14";
var text = 4426.Translate("Garantietermijn {0} mnd", warrantyDescription);

However, I think this approach is bad because:

Bad SoC. Int and string have nothing todo with translations
This will result in unreadable and unmaintainable code from the perspective of other developers, encountering a extended int with specific functionality. Imagine a case where not only translations but xx other functionalities extend the int as it is a unique identifier.

Trying to provide him with a better approach, all I could think of was a struct using implicit operators as below. However, I think this casting is bad practise as well..

const string warrantyDescription = "14";
var text = ((TranslateId) 4426).Translate( "Garantietermijn {0} mnd", warrantyDescription );

To make this question complete, here is my code for the struct type.

public struct TranslateId
{
    private readonly int m_Value;

    public TranslateId (int value)
    {
        m_Value = value;
    }

    public int Value
    {
        get { return m_Value; }
    }

    public string Translate(string defaultString, params object[] parameters)
    {
        // TODO: Use the actual singleton to retrieve translation
        string translationResult = defaultString;

        // Return the formatted retrieved value
        return string.Format(translationResult, parameters);
    }

    public static implicit operator TranslateId(int value)
    {
        return new TranslateId(value);
    }

    public static implicit operator int(TranslateId id)
    {
        return id.Value;
    }
}

Any thoughts?

This is a horrible misuse of extension methods.  The only thing worse (and I'm sure you'll see it) is (n+5).Translate(...).  You're absolutely correct - the starting point for the mistake is in thinking of the integer as the base object for the translation.  There are a number of well-understood patterns for handling localization, and this isn't any of them.  Since we're talking C#, there's the obvious resource technique, but there are others as well.  The GNU Project pioneered the _("blah blah blah") mechanism, where the default string serves as a key in a locale-specific table of replacements (along with the Windows OS and MS Office, this is one of the most prevalent and successful translation systems).  And then there's the tried-and-true dictionary-indexed-by-a-named-constant (often an enum member), often encapsulated behind a Language class with a Translate(...) method.


Rock Paper Scissors in Python I'm a beginner in Python and I've just finished a Rock, Paper, Scissors simulator in Python. It asks the user to enter paper, rock, or scissors and the program will generate a random number which will convert it to paper, rock or scissors. The program will then print the corresponding result. It also keeps tracks of wins/losses/ties until the user wants to stop playing then prints the prints the results back to the user.

import random as r
print("Welcome to my Rock-Paper-Scissor Game")
print("The rules are as follow:")
print("     Paper beats Rock")
print("     Rock beats Scissors")
print("     Scissors beat Paper")
print()
win=0
ties=0
loss=0
i=0
while i==0:
    while True:
        user=input("Do you pick Rock, Paper, or Scissors? ")
        if user not in ("Scissors","scissors","paper","Paper","Rock","rock"):
            print("Please enter Rock, Paper or Scissors. ")
            continue
        else:
            break
    computer=r.randint(1,3)
    if computer==1:
        computer="Paper"
    if computer==2:
        computer="Rock"
    if computer==3:
        computer="Scissors"
    if (user=="Paper" or user=="paper"):
        print("You choose paper")
        if computer=="Paper":
            print('\033[0;32m' + "It's a tie! The program also choose paper")
            ties=ties+1
        if computer=="Rock":
            print('\033[1;31m' + "You won! The program choose rock")
            win=win+1
        if computer=="Scissors":
            print('\033[1;36m' + "You lost! The program choose scissors")
            loss=loss+1

    if (user=="Rock" or user=="rock"):
        print("You choose Rock")
        if computer=="Rock":
            print('\033[0;32m' + "It's a tie! The program also choose rock")
            ties = ties + 1
        if computer=="Scissors":
            print('\033[1;31m' + "You won! The program choose scissors")
            win = win + 1
        if computer=="Paper":
            print('\33[1;36m' + "You lost! The program choose paper")
            loss = loss + 1

    if (user=="Scissors" or user=="scissors"):
        print("You choose Scissors")
        if computer=="Scissors":
            print('\033[0;32m' + "It's a tie! The program also choose scissors")
            ties = ties + 1
        if computer=="Paper":
            print('\033[1;31m' + "You won! The program choose paper")
            win = win + 1
        if computer=="Rock":
            print('\033[1;36m' + "You lost! The program choose rock")
            loss = loss + 1
    while True:
        question=input('\033[0;0m' + "Would you like to play again? ")
        if question not in ("Yes","yes","Y","y","no","No","n","N"):
            print('\033[;1m' + "Please only enter yes or no. ")
            continue
        else:
            break
    if question in ("Yes","y","Y","yes"):
        i=0
    if question in ("No","n","no","N"):
        i=1
print()
print("Your final results are as follows")
print("Number of wins:",win)
print("Number of ties:",ties)
print("Number of losses:",loss)

Yes/no handling
Don't repeat yourself or reinvent the wheel. There already exists a distutils.util.strtobool that does exactly what you're trying to accomplish:

Convert a string representation of truth to true (1) or false (0).
True values are y, yes, t, true, on and 1; false values are n, no, f, false, off and 0. Raises ValueError if val is anything else.

You can convert the string to lowercase beforehand. Since strtobool raises a ValueError, your yes/no handling can be written succinctly like so:
while True:
    try:
        question=input('\033[0;0m' + "Would you like to play again? ")
        i = not strtobool(question)
        break
    except ValueError:
        print('\033[;1m' + "Please only enter yes or no. ")

Notice that strtobool returns 1 for truthy values, yet for some reason you have i == 0 represent "keep going", which is confusing. So I used not here, but I recommend either changing that or using proper bools here for readability.


Refactoring implementation in.NET I have implemented the following code:

class A
{
    abstract void f1(Object obj, Object data);
}

class A1:A
{
    void f1(Object obj, Object data)
    {
        m1(obj,data);
    }

    void m1(Object obj, Object data)
    {
    }
}

class A2:A
{
    void f1(Object obj, Object data)
    {
        m2(obj, data);
    }
    void m2(Object obj, Object data)
    {
    }
}

static class Factory
{
    public static A GetInstance(int i)
    {
        if (i == 1)
            return new A1();
        else if (i == 2)
            return new A2();
        else
            return null;
    }
}

Methods are being called from some other part of the application, as following:

var a = Factory.GetInstance(1);
a.f1(obj, data);

In the above code, the abstract method f1() has two parameters obj and data. While I reviewed the code, I found the parameter data can be determined from the first parameter obj itself. The area of the application from where the method f1() is being called, there the Libraries for getting data are not available. So I refactored the code further as following in order to send one parameter obj. Following is the implementation:

class A
{
    public Object data { get; set; }
    abstract void f1(Object obj);
}

class A1:A
{
    void f1(Object obj)
    {
        m1(obj,data);
    }

    void m1(Object obj, Object data)
    {
    }
}

class A2:A
{
    void f1(Object obj)
    {
        m2(obj, data);
    }
    void m2(Object obj, Object data)
    {
    }
}

static class Factory
{
    public static A GetInstance(int i)
    {
        if (i == 1)
            return new A1();
        else if (i == 2)
            return new A2();
        else
            return null;
    }
}

Now, I am calling the method as following:

var a = Factory.GetInstance(1);
a.data = GetData();
a.f1(obj);

Please let me know whether or not the refactoring is correct. Also, please suggest some ways for better refactoring.

The code still looks a bit strange to me.

obj.f1(obj);

Why are you passing the object as a parameter when the method already is a member? Skip the parameter and use this instead.

You should also try to minimize the number of method the user needs to call to perform one thing. Requiring obj.data to be set before calling obj.f1 is error prone. It would be better to let the obj constructor call GetData to extract the data from the obj.


Generating a range of ints as strings in Java 8 I'll have two integers and will want to generate an array of those two numbers and all the numbers in between as strings (I know the ranges are small).

i.e. given 1004 and 1008. I'd generate "1004", "1005", "1006", "1007", "1008"

I'm familiar with C# and there I'd do something like

var start = 1004;
var end = 1008;
var fullRange = Enumerable.Range(start, end - start + 1)
                          .Select(i => i.ToString())
                          .ToArray();

I need to do this in Java 8 and have come up with

 String[] fullRange = IntStream.range(start, end+1)
                        .mapToObj(String::valueOf)
                        .toArray(String[]::new);

But I'm new to Java and wondered if there's a better / more-readable way to achieve this in Java. Am I just cramming C# into Java?

Can you use a stream rather than an array in the rest of your application? If so I'd simply cut off the toArray bit at the end. Otherwise this looks exactly like what I'd expect in Java 8.


Improving excution time for list and sampling in Python Here is my code for generating edge list based on Price model algorithm. I think there have two points to reduce execution time:

use proper data type
use faster random sampling

Originally, I used list instead of NumPy array and then changed from extending array till c x n to setting initial fixed array (and change the initial values).

It made execution time faster but still way slower than same implementation written in Matlab.

import pickle
from random import random, sample
import numpy as np

def gen_edge_list(a, c, n):
    """
    Generate edge list based on 14.1.1
    """
    edge_list = np.zeros(c*n)
    p = float(c) / (float(c)+a) # % for preferential attachment edges
    edge_list[0] = 1            # edge from vertex 2 to 1
    idx = 1                     # point to the next index
    for t in range(3, n+1):
        if t <= c+1:
            """
            If network size is smaller than c+1,
            connect among all vertices.
            """
            edge_list[idx:idx+t-1] = [i for i in range(1, t)]
            idx = idx+t-1
        else:
            """
            decide preferential attachment or uniformly random attachment
            by given p
            """
            n_pref = len([True for i in range(c) if random() < p])
            edge_list[idx:idx+n_pref] = sample(edge_list[0:idx-1], n_pref)
            idx += n_pref
            edge_list[idx:idx+c-n_pref] = sample(range(1, t+1), c-n_pref)
            idx = idx + c - n_pref

if __name__ == "__main__":
    a = [1.5]
    c = [3]
    n = 10**6
    edge_lists = []
    for i in range(len(a)):
        edge_lists.append(gen_edge_list(a[i], c[i], n))
    output = open('edge_list.pkl', 'wb')
    pickle.dump(edge_lists, output)
    output.close()

My biggest concern is especially the following:

        """
        decide preferential attachment or uniformly random attachment
        by given p
        """
        n_pref = len([True for i in range(c) if random() < p])
        edge_list[idx:idx+n_pref] = sample(edge_list[0:idx-1], n_pref)
        idx += n_pref
        edge_list[idx:idx+c-n_pref] = sample(range(1, t+1), c-n_pref)
        idx = idx + c - n_pref

Here is my friends code written in Matlab:

a = [1.5];
c = [3];
n = 1^6;
edgelist = cell(numel(c),1);
for i = 1:numel(c)
    p = c(i)./(c(i)+a(i));
    edgelist{i} = zeros(1, c(i).*n);
    edgelist{i}(1) = 1;
    idx = 2;
    for t = 3:n
        if t <= c(i)+1
            edgelist{i}(idx:(idx+t-2)) = 1:(t-1);
            idx = idx+t-1;
        else
            pref_or_rand = rand(1,c(i)) < p;
            prefn = sum(pref_or_rand);
            edgelist{i}(idx:(idx+c(i)-1)) = [edgelist{i}(randi(idx-1,1,prefn)) randi(t,1,c(i)-prefn)];
            idx = idx+c(i);
        end
    end
end

I don't know what makes this huge difference on execution time between them. (40 sec in Matlab on mac book pro vs 40 min with Python code in recent i5 machine on Debian)

If you have any idea, please let me know.

I have changed sampling part and it took only 19 sec. I have realized that numpy's random sampling is way faster than python's built-in random sampling.

import pickle
import numpy as np
from numpy.random import randint, rand, choice

def gen_edge_list(a, c, n):
    """
    Generate edge list based on 14.1.1
    """
    edge_list = np.zeros(c*n)
    p = float(c) / (float(c)+a) # % for preferential attachment edges
    edge_list[0] = 1            # edge from vertex 2 to 1
    idx = 1                     # point to the next index
    for t in range(3, n+1):
        print t
        if t <= c+1:
            """
            If network size is smaller than c+1,
            connect among all vertices.
            """
            edge_list[idx:idx+t-1] = [i for i in range(1, t)]
            idx = idx+t-1
        else:
            """
            decide preferential attachment or uniformly random attachment
            by given p
            """
            n_pref = np.sum(rand(c) < p)
            edge_list[idx:idx+n_pref] = choice(edge_list[0:idx-1], n_pref)
            idx += n_pref
            edge_list[idx:idx+c-n_pref] = randint(1, t+1, c-n_pref)
            idx = idx + c - n_pref


Integer-to-string conversion using recursion Adapt the ideas of printd to write recursive version of itoa; that is, convert integer into a string by calling a recursive routine

Here is the implementation of printd:

void printd(int n) {
    if(n < 0)
        putchar('-');
    if(n / 10)
        printd(n / 10);
    putchar(n % 10 + '0')l
}

And here is my solution:

int itoa(int n, char s[]) {
    int i;

    if(n < 0) {
        n *= -1;
    }

    i = 0;
    if(n / 10) {
        i = itoa(n / 10, s);
    }
    s[i] = n % 10 + '0';
    s[++i] = '\0';

    return i; /* next free slot in array */
}

As you can see, my version of itoa is a little bit different than the one presented in the book. It returns a variable i that represents the index of the next free slot in array, at every step it fills the next empty slot with the null character. At the deepest level of recursion, it returns 1.

Could you review my exercise?

There are two bugs in printd():

The last character is an l instead of a semicolon.
If n is negative, it prints a negative sign before each digit.

Your itoa() also has a bug in handling negative input.  It always stringifies the absolute value of n.

Your strategy to use the return value to determine which array element to write to seems like a good idea.  I think it would be more user friendly, though, to say that you are returning the strlen() of the output.

int itoa(int n, char s[]) {
    int i = 0;

    if (n < 0) {
        s[0] = '-';
        return 1 + itoa(-n, s + 1);
    }

    if (n / 10) {
        i = itoa(n / 10, s);
    }
    s[i] = n % 10 + '0';
    s[++i] = '\0';

    return i; /* strlen(s), i.e. the next free slot in array */
}


C++11 Blocking connection pool with auto release Relatively new to C++. Please help me understand the potential issues with the following blocking object pool.

#pragma once
#include <vector>
#include <queue>
#include <memory>
#include <thread>
#include <mutex>
#include <condition_variable>
#include <future>
#include <functional>
#include <stdexcept>

template <typename T>
struct DefaultDeleter {
    DefaultDeleter() {};
    void operator()(T* p) const {
        delete p;
    }
};

/// \brief A blocking object pool containing objects of type T.
/// Objects burrowed from the pool are automatically returned to the pool when they
/// are out of scope.
/// \n
/// When the pool is empty calls to borrow objects blocks until a resource is returned to the pool.
template <typename T, typename Deleter = DefaultDeleter<T>>
class ObjectPool {
public:

    /// \brief Construct an object pool of size n.
    ///
    /// \param n The size of the pool.
    /// \param factory A factory method that returns a pointer to a resource.
    ObjectPool(size_t n, std::function<T*()> factory) {
        for(size_t i = 0; i<n; ++i) {
            resources.emplace_back(factory());
        }
    }

    /// \brief destruct the object pool and delete all resources using the provided deleter.
    ~ObjectPool() {
        Deleter d;
        for (auto it = resources.begin(); it != resources.end(); ++it) {
            d(*it);
        }
    };

    /// \typedef Alias for a function which returns a resource to the pool.
    using ObjectReturner = std::function<void(T*)>

    /// \brief burrow an object from the pool.
    /// When the borrowed pointer is out of scope the resource is returned to the pool.
    std::unique_ptr<T, ObjectReturner> borrow() {
        std::unique_lock<std::mutex> lock(mu);
        if (resources.empty()) {
            this->condition.wait(lock, [this]{return !this->resources.empty();});
        }
        auto resource = std::unique_ptr<T, ObjectReturner>(this->resources.front(), [this](T* t){
            std::unique_lock<std::mutex> lock(mu);
            resources.emplace_back(t);
            condition.notify_one();
        });
        this->resources.pop_front();
        return std::move(resource);
    }

private:
    std::deque<T*> resources;

    // synchronization
    std::mutex mu;
    std::condition_variable condition;
};

EDIT: Maybe ObjectPool is a bad term. The intention in here is that this is a ConnectionPool. A common use case looks like this

    struct CloseDb
    {
        void operator()(sqlite3* db) const
        {
            sqlite3_close(db);
        }
    };

    struct Resource {
        std::shared_ptr<ObjectPool<sqlite3, CloseDb>> sqlitePool;
         Resource() {
                std::function<sqlite3*()> factory = [=] ()
                {
                   sqlite3* db;

                    auto rc = sqlite3_open(sqlite3File.c_str(), &db);
                    if (rc)
                     {
                        sqlite3_close(db);
                        std::string err = sqlite3_errmsg(db);
                        sqlite3_close(db);
                        throw std::runtime_error(err);
                     }
                    return db;
              };

            sqlitePool = std::make_shared<ObjectPool<sqlite3, CloseDb>>(std::thread::hardware_concurrency(), factory);
    }

This is not what I would normally call an Object Pool (in the traditional sense of the term). That term I would use to refer to a pool of memory that returns "Uninitialized" memory (via a pointer) usually via an allocator so that a new operation could build the object (and the memory is returned after it is deleted).

I do like the term borrow() though as that is an accurate description of what is happening. You are temporarily giving ownership of objects that can be returned (in potentially a new state).

Your ownership semantics are wrong though. You return a unique_ptr<> indicating that ownership has been transferred to the borrower. But that is not actually true. The "pool" actually retains ownership as it calls the destructor on the object when it is destroyed (ONLY the owner of an object should try and delete it (reclaim the resource)).

Also if the "pool" is destroyed (thus destroying all the owned pointers); then the "borrowers" are left holding unqiue_ptr<> to objects that no longer exist (bad point 1). But when they do release them the "deleter" tries to put them back into a "pool" that no longer exists (bad point 2).

As it stands this code is just ill-advised.
You need to think some more about your ownership semantics.


Squares with different background colors Titles is an array populated by numbers (1, 2 and 3). Depending on the number, a Square component should have a different background colour. Now, I don't think that having that the switch statements are the best way to make the condition. I'm sure there's a better way to make Square's background depending on the mapped number.

import React, { Component } from 'react';
import { View, Text } from 'react-native';
import { connect } from 'react-redux';
//import { getStatus, getPosition, genGrid } from '../actions';
import { CardSection, Square } from './common';

class MainMaze extends Component {

  generateMaze() {
    const { tiles } = this.props.grid;
    return (
      tiles.map((sq, i) => {
        switch (sq) {
          case 3:
            return <Square key={i} style={{ backgroundColor: 'red' }}>{sq}</Square>;
          case 2:
            return <Square key={i} style={{ backgroundColor: 'blue' }}>{sq}</Square>;
          default:
            return <Square key={i} style={{ backgroundColor: 'green' }}>{sq}</Square>;
        }
      }
    ));
  }
  render() {
    const { grid, position, status } = this.props;

    return (
      <View>
        <CardSection>
          <Text>{grid.cols}</Text>
        </CardSection>
        <CardSection>
          {this.generateMaze()}
        </CardSection>
      </View>
    );
  }
}

const mapStateToProps = (state) => {
  return {
    status: state.status,
    position: state.position,
    grid: state.grid
  };
};

export default connect(mapStateToProps)(MainMaze);

The Square component:

import React from 'react';
import { View, Text } from 'react-native';

const Square = (props) => {
  return (
    <View style={[styles.containerStyle, props.style]}>
      <Text>
        {props.children}
      </Text>
    </View>
  );
};

const styles = {
  containerStyle: {
    borderWidth: 1,
    borderColor: '#ddd',
    elevation: 1,
    alignItems: 'center',
    justifyContent: 'center',
    margin: 0,
    height: 30,
    width: 30
  }
};

export { Square };

The output of generateMaze always will be the same each time, except for one thing, which is the backgroundColor property value of the Square component.
In this case, you don't need a function/method, which output is a maze component; you can create a method to handle the maze colors, dependent on the given parameter, e.g.:
class MainMaze extends Component {
  handleMazeColor(mazeID) {
    if (mazeID === 2) return "blue";
    else if (mazeID === 3) return "red";

    return "green";
  }

  render() {
    const { tiles } = this.props.grid;
    const { grid, position, status } = this.props;

    return (
      <View>
        <CardSection>
          <Text>{grid.cols}</Text>
        </CardSection>
        <CardSection>
          {tiles.map((sq, i) => (
            <Square
              key={i}
              style={{ backgroundColor: this.handleMazeColor(sq) }}
            >
              {sq}
            </Square>
          ))}
        </CardSection>
      </View>
    );
  }
}


Generate 2D array with set amount entries I want to generate an array where each row and column needs to have a random generated amount (between 2 and total size of dimension -1) of true values.

Currently I am running each row then columns and check if it validates. If it does not it regenerates and has to do another full loop to check if all rows and columns validate.

/**
 * Procedurally populates 2D array so that each line and row contains between 1 and .Length true values.
 */
public static boolean[][] generateTargetNumbers(int width, int height) {

    boolean[][] targetNumbers = new boolean[width][height];

    // keep looping trough rows and columns to validate and regenerate if necessary
    boolean finished = false;
    while (!finished) {
        finished = true;

        // check columns
        for (int x = 0; x < width; x++) {
            if (generateTargetColumn(x, width, height, targetNumbers)) {
                finished = false;
            }
        }

        // check rows
        for (int y = 0; y < height; y++) {
            if (generateTargetRow(y, width, height, targetNumbers)) {
                finished = false;
            }
        }
    }
    return targetNumbers;
}

/**
 * Checks if the column has a valid amount of targets and regenerates the column if nececary.
 * @param x
 * @param width
 * @param height
 * @param targetNumbers
 * @return returns true if the column is regenerated.
 */
private static boolean generateTargetColumn(int x, int width, int height, boolean[][] targetNumbers) {
    int minTargetCount = 2;
    int maxTargetCount = height - 1;

    // count targets on this column
    int currentCount = 0;
    for (int y = 0; y < height; y++) {
        if (targetNumbers[x][y]) currentCount++;
    }

    if (currentCount >= minTargetCount && currentCount <= maxTargetCount) return false;

    // Column needs regenerating

    // Reset column to false
    for (int y = 0; y < height; y++) {
        targetNumbers[x][y] = false;
    }

    // Amount of targets for this column.
    int targetCount = Random.nextInt(maxTargetCount - minTargetCount + 1) + minTargetCount;

    while (targetCount > 0) {
        int index = Random.nextInt(height);
        if (!targetNumbers[x][index]) {
            targetNumbers[x][index] = true;
            targetCount--;
        }
    }

    return true;
}

/**
 * Checks if the row has a valid amount of targets and regenerates the column if nececary.
 * @param y
 * @param width
 * @param height
 * @param targetNumbers
 * @return returns true if the row is regenerated.
 */
private static boolean generateTargetRow(int y, int width, int height, boolean[][] targetNumbers) {
    int minTargetCount = 2;
    int maxTargetCount = height - 1;

    // count targets on this row
    int currentCount = 0;
    for (int x = 0; x < width; x++) {
        if (targetNumbers[x][y]) currentCount++;
    }

    if (currentCount >= minTargetCount && currentCount <= maxTargetCount) return false;

    // Row needs regenerating

    // Reset column to false
    for (int x = 0; x < width; x++) {
        targetNumbers[x][y] = false;
    }

    // Amount of targets for this row.
    int targetCount = Random.nextInt(maxTargetCount - minTargetCount + 1) + minTargetCount;

    while (targetCount > 0) {
        int index = Random.nextInt(height);
        if (!targetNumbers[index][y]) {
            targetNumbers[index][y] = true;
            targetCount--;
        }
    }

    return true;
}

For my needs (5x5 to 9x9 arrays) it usually does it in just 2 loops so that is great. But the randomness is biased to a larger amount of true values since it adds additional true values to the rows when it encounters a invalid column. I would like to have more control over the amount/percentage of true values.

Besides that, the near identical bottom 2 methods are tickling my OCD senses. I'm sure someone knows a nice way of combining these and make it look cleaner.

boolean finished = false;
while (!finished) {
    finished = true;

    // check columns
    for (int x = 0; x < width; x++) {
        if (generateTargetColumn(x, width, height, targetNumbers)) {
            finished = false;
        }
    }

    // check rows
    for (int y = 0; y < height; y++) {
        if (generateTargetRow(y, width, height, targetNumbers)) {
            finished = false;
        }
    }
}

We're working with booleans here. I can directly assign the result to the variable...

boolean finished = false;
while (!finished) {
    finished = true;

    // check columns
    for (int x = 0; x < width; x++) {
        finished = !generateTargetColumn(x, width, height, targetNumbers) && finished;
    }

    // check rows
    for (int y = 0; y < height; y++) {
        finished = !generateTargetRow(y, width, height, targetNumbers) && finished;
    }
}

There's a lot of negations in here, so maybe we can flip the variable's meaning and get clearer code?

boolean busy = true;
while (busy) {
    busy = false;

    // check columns
    for (int x = 0; x < width; x++) {
        busy = generateTargetColumn(x, width, height, targetNumbers) || busy;
    }

    // check rows
    for (int y = 0; y < height; y++) {
        busy = generateTargetRow(y, width, height, targetNumbers) || busy;
    }
}

Sure, but "busy" is not really what we're looking for, after all, you say that

@return returns true if the column/row is regenerated.

So we should change the name to "gridChanged" or something like that.

boolean gridChanged = true;
while (gridChanged) {
    gridChanged = false;

    // check columns
    for (int x = 0; x < width; x++) {
        gridChanged = generateTargetColumn(x, width, height, targetNumbers) || gridChanged;
    }

    // check rows
    for (int y = 0; y < height; y++) {
        gridChanged = generateTargetRow(y, width, height, targetNumbers) || gridChanged;
    }
}

But now you have this weird thing where at the start, you say "I had changes", which seems wrong... and you always want to go in the loop at the start. So convert it to a do-while:

boolean gridChanged = true;
do {
    gridChanged = false;

    // check columns
    for (int x = 0; x < width; x++) {
        gridChanged = generateTargetColumn(x, width, height, targetNumbers) || gridChanged;
    }

    // check rows
    for (int y = 0; y < height; y++) {
        gridChanged = generateTargetRow(y, width, height, targetNumbers) || gridChanged;
    }
} while(gridChanged);


Comparing columns from two CSV files - follow-up This is the second part of a question, you can find the first part here:

Comparing columns from two CSV files

I've made some changes to the script and here is what it looks like now:

import csv, sys

def get_column(columns, name):
    count = 0
    for column in columns:
        if column != name:
            count += 1
        else:
            return(count)

def set_up_file(file, variable):
    columns = next(file)
    siren_pos = get_column(columns, 'SIREN')
    nic_pos = get_column(columns, 'NIC')
    variable_pos = get_column(columns, variable)
    return(siren_pos, nic_pos, variable_pos)

def test_variable(variable):
    with open('source.csv', 'r') as source:
        source_r = csv.reader(source, delimiter=';')
        sir_s, nic_s, comp_s = set_up_file(source_r, variable)
        line_s = next(source_r)
        with open('tested.csv', 'r') as tested:
            tested_r = csv.reader(tested, delimiter=';')
            sir_t, nic_t, comp_t = set_up_file(tested_r, variable)
            size = sum(1 for line in tested_r)
            tested.seek(0, 0)
            line_t = next(tested_r)
            line_t = next(tested_r)
            correct = 0
            try:
                while True:
                    if(line_s[sir_s] == line_t[sir_t]
                    and line_s[nic_s] == line_t[nic_t]):
                        if(line_s[comp_s] == line_t[comp_t]):
                            correct += 1
                        line_t = next(tested_r)
                        line_s = next(source_r)
                    elif(int(line_s[sir_s]) > int(line_t[sir_t])):
                        line_t = next(tested_r)
                    elif(int(line_s[sir_s]) < int(line_t[sir_t])):
                        line_s = next(source_r)
                    else:
                        if(int(line_s[nic_s]) > int(line_t[nic_t])):
                            line_t = next(tested_r)
                        else:
                            line_s = next(source_r)
            except StopIteration:
                return(correct / size * 100)

def main():
    with open('tested.csv', 'r') as file:
        file_r = csv.reader(file, delimiter=';')
        columns = next(file_r)
        found = test_variable('SIREN')
        for column in columns:
            print(column, '%.2f' % (test_variable(column) / found * 100))

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

There are no real performance issue in the new version but I feel like it could still be improved greatly.

Also, would it be possible to reduce the size of the test_variable function? I thought about cutting it right before the try statement but I'll end up passing about 7 parameters which is not really a clean solution in my opinion.

There is some duplication of code because you are handling two files.
When you need some data converted to int it would be best to do soon as you've read it to avoid sprinkling other logic with int() calls.
The two columns SIREN and NIC combined seem to form a sorting key to the file. You could simplify the if elif... part by performing the comparisons on (SIREN, NIC) tuples.

To address the above, I propose to organize the code like this:

def parse_file(file, variable):
    reader = csv.reader(file, delimiter=';')
    sir_s, nic_s, comp_s = set_up_file(reader, variable)
    for line in reader:
        key = int(line[sir_s]), int(line[nic_s])
        yield key, line[comp_s]

def test_variable(variable):
    with open('source.csv', 'r') as source, open('tested.csv', 'r') as tested:
        source_r = parse_file(source, variable)
        tested_r = parse_file(tested, variable)

        correct = 0
        try:
            line_s = next(source_r)
            line_t = next(tested_r)
            while True:
                key_s, comp_s = line_s
                key_t, comp_t = line_t
                if line_s == line_t:
                    correct += 1
                if key_s >= key_t:
                    line_t = next(tested_r)
                if key_s <= key_t:
                    line_s = next(source_r)

        except StopIteration:
            return correct

Note however that I've omitted the computation of size. This could be done by incrementing a variable after reading each line, but since lines are read at multiple places, and some may be left in the end if the other file ends first, it may be best to count the lines separately like you have done.


Maximum profit from buy and sell offers Given a list of sell offers and a list of buy offers for an item I want to determine how many units to trade for maximum profit.

Each offer consists of a price and a maximum amount of units being traded. Offers can be partially fulfilled (i.e. if a buyer/seller wants to trade 100 units, it's ok to trade only 10). However, buy orders can have a minimum amount, which means that the buyer will buy at least this amount of units or none at all.

# sell offers
sell = [Order(price=7.0, amount=120, min_amount=np.nan),
        Order(price=20.0, amount=80, min_amount=np.nan)]

# buy offers
buy = [Order(price=30.0, amount=100, min_amount=100),
       Order(price=15.0, amount=200, min_amount=50),
       Order(price=10.0, amount=20, min_amount=1)]

In this example 120 units are being sold at a price of 7.0 and 80 units at a price of 20.0. Buyers are willing to buy exactly 100 units for 30.0, between 50 and 200 units for 15.0, and up to 20 units for 10.0.

My code determines how many units to trade for maximum profit. It loops over the amount of units traded and computes the optimal buy and sell prices in each iteration. The idea is to get the item as cheaply as possible from sell orders and to sell them as expensively as possible to buy orders.

The optimal sell order price is relatively trivial to obtain. Get as many units as possible from the cheapest offer, and if that is exhausted advance to the next cheapest.

The minimum amount on buy orders makes computation of the optimal buy price more complicated. For example, when trading less than 100 units they cannot be sold as expensively than when trading more than 100 units.

This works reasonably well in the example, but is horribly inefficient when dealing with larger amounts (thousands-millions of units). I could certainly get better performance by using Cython or implementing in C, but I hope for a algorithmic optimization first.

Is there a better (faster) way to find the optimal profit?

import numpy as np
import matplotlib.pyplot as plt
from collections import namedtuple

Order = namedtuple('Order', ['price', 'amount', 'min_amount'])

if __name__ == '__main__':
    # sell offers
    sell = [Order(price=7.0, amount=120, min_amount=np.nan),
            Order(price=20.0, amount=80, min_amount=np.nan)]

    # buy offers
    buy = [Order(price=30.0, amount=100, min_amount=100),
           Order(price=15.0, amount=200, min_amount=50),
           Order(price=10.0, amount=20, min_amount=1)]

    max_n = 201

    sell = np.asarray(sell)
    buy = np.asarray(buy)

    # vectorized computation of sell prices
    amounts = np.zeros(1 + sell.shape[0])
    prices = np.zeros(1 + sell.shape[0])
    amounts[1:] = np.cumsum(sell[:, 1])
    prices[1:] = np.cumsum(sell[:, 1] * sell[:, 0])
    sellprices = np.interp(np.arange(max_n), amounts, prices)

    # performance hog: computation of buy prices
    buyprices = []
    for n in range(max_n):
        price = 0
        remaining = n
        for unit_price, amount, min_amount in buy:
            if remaining < min_amount:
                continue
            if remaining > amount:
                remaining -= amount
                price += amount * unit_price
            else:
                price += remaining * unit_price
                break
        buyprices.append(price)

    sellprices = np.array(sellprices)
    buyprices = np.array(buyprices)
    profits = buyprices - sellprices

    k = np.argmax(profits)

    plt.plot(sellprices, 'r', label='sell offers')
    plt.plot(buyprices, 'b', label='buy offers')
    plt.plot(profits, 'k', label='profit')
    plt.plot(k, profits[k], 'ko', label='optimum')
    plt.legend(loc='best')
    plt.xlabel('amount traded')
    plt.ylabel('price')
    plt.show()

1. Review

The code in the post does not always compute the highest profit. For example, suppose that I have these orders:

sell = [Order(price=1, amount=1, min_amount=np.nan)]
buy = [Order(price=1, amount=1, min_amount=1),
       Order(price=2, amount=1, min_amount=1)]
max_n = 2

Then the code computes:

buyprices = [0, 1]
profits = [0, 0]

In other words, the code sells to the first buyer, ignoring the second buyer who is prepared to pay more.
You clarified in comments that it's a requirement that the buyers be sorted by price. It would be more reliable if the code did any necessary sorting:

buy = buy[np.argsort(buy[:,0])]

Then you wouldn't have to worry about the order of the input.
Even if the input is sorted by price, the algorithm in the post still does not always compute the highest profit. For example, suppose that I have the following orders:

sell = [Order(price=1, amount=4, min_amount=np.nan)]
buy = [Order(price=6, amount=3, min_amount=3),
       Order(price=5, amount=2, min_amount=2),
       Order(price=5, amount=2, min_amount=2)]
max_n = 5

In this case, the code computes:

buyprices = [0, 0, 10, 18, 18]
profits = [0, -1, 8, 15, 14]

The highest profit it can find is 15, by selling three units to the first buyer. But if I sell two units to each of the second and third buyers, then I get a profit of 16.
Even with the orders given in the post, the code computes the wrong prices for some amounts. For example, you can see from the graph that the code thinks that it can sell 40 units for a price of 200. But there is no way to sell 40 units — you can sell 20 units to the third buyer, but no more than that, and the second buyer has a minimum order of 50.

Similarly, the code determines that it can sell 140 units for a price of 3200. But there is no way to make such a sale: if you sell 100 to the first buyer, then that leaves 40, and there is no way to sell 40 units (as discussed above). So you have to sell to the second buyer, in which case the best price you can get is 2100.

I believe that the correct graph looks like this, with a gap between 20 and 50, and lower profits betwen 120 and 150:

2. Correct algorithm

Before trying to speed up the code, it's important to implement a correct algorithm (even if it is slow), otherwise it will be hard to check that the faster algorithm is correct.

In the general case, the problem of finding the highest profit is NP-hard, by an easy reduction from SUBSET SUM. But this isn't a disaster, because problems like subset sum often have pseudo-polynomial algorithms using the tabular method (aka "dynamic programming").

So let's try the tabular method by building up a table of prices, using \$−∞\$ for impossible amounts:

def buy_prices(buy_orders, limit):
    """Return array containing the best price for each amount below limit,
    given an array of buy orders. The result is -inf for any amount
    that cannot be sold to any combination of buy orders.

    """
    prices = np.full((limit,), -np.inf)
    prices[0] = 0
    for price, amount, min_amount in buy_orders:
        p = prices.copy()
        for a in range(int(min_amount), int(amount) + 1):
            for i in range(a, limit):
                prices[i] = max(prices[i], p[i-a] + a * price)
    return prices

This has runtime \$Θ(mn^2)\$, where \$m\$ is the number of buy orders and \$n\$ is the maximum amount that can be traded.

We can speed this up by vectorizing the inner loop:

def buy_prices(buy_orders, limit):
    """Return array containing the best price for each amount below limit,
    given an array of buy orders. The result is -inf for any amount
    that cannot be sold to any combination of buy orders.

    """
    prices = np.full((limit,), -np.inf)
    prices[0] = 0
    for price, amount, min_amount in buy_orders:
        p = prices.copy()
        for a in range(int(min_amount), min(limit, int(amount) + 1)):
            q = p[:limit-a] + a * price
            prices[a:limit] = np.maximum(prices[a:limit], q)
    return prices

However, the runtime is still \$Θ(mn^2)\$ and so it will be unacceptable when \$n\$ is large.


Java parsing and extract String from pattern String I want to extract some string surrounded by certain patterns.

For Instance, the original String something like 1234@{78}dasdh@{1}fdsfs@{fdf}ad@{
and I want extract 78, 1, fdf from it.

Below is my code for the purpose

public class Test {

    // want to get "78", "1", "fdf"
    private static String targetStr = "1234@{78}dasdh@{1}fdsfs@{fdf}ad@{";

    public static void main (String[] args) throws Exception {

        List<String> parsed = new ArrayList<>();

        Pattern open = Pattern.compile("@\\{");
        Matcher oMatcher = open.matcher(targetStr);

        Pattern close = Pattern.compile("}");
        Matcher cMatcher = close.matcher(targetStr);

        while(oMatcher.find()) {
            if(cMatcher.find())  parsed.add(targetStr.substring(oMatcher.start() + 2, cMatcher.start()));
        }
        System.out.println(parsed);
    }
}

Is there anyway to complete this task? Some how it feels unsafe since use 2 iterator without any validation.

There's a simpler way:

Pattern p = Pattern.compile("\\w+@\\{(\\w+)\\}");
Matcher m = p.matcher(targetStr);
while (m.find()) {
    parsed.add(m.group(1));
}

Instead of matching the opening and closing braces separately, the above pattern matches a whole expression of the form aaa@{bbb} at once. And when it finds the expression, it remembers the part inside the braces. This is done via a capturing group (the parentheses).

To learn more about each of the characters in the pattern, read the Javadoc of the Pattern class.


Base64 string ↔ float array I need to convert f32 arrays with a fix length to base64 representation and back.

My current code looks like this. It works, but it feels way too complicated.

How can I improve it?

main.rs:

extern crate base64;

fn read_float_vec_from_byte_vec(v: Vec<u8>) -> Result<Vec<f32>, String> {
    match v.len() % 4 {
        0 => {
            use std::ptr;
            let p = v.as_ptr();
            let dest_len = v.len() / 4;
            let mut result = Vec::<f32>::with_capacity(dest_len);
            for i in 0..dest_len as isize {
                unsafe {
                    let f_ptr = p.offset(4 * i) as *const f32;
                    result.push(ptr::read::<f32>(f_ptr));
                }
            }
            Ok(result)
        }
        _ => Err("Number of bytes not divisible by 4.".to_string())
    }
}

fn float_vec_as_byte_vec(values: &Vec<f32>) -> Vec<u8> {
    let dest_len = values.len() * 4;
    let mut result = Vec::<u8>::with_capacity(dest_len);
    result.resize(dest_len, 0);
    for (i, x) in values.iter().enumerate() {
        let bytes: [u8; 4] = unsafe { std::mem::transmute(*x) };
        result[i*4..i*4+4].copy_from_slice(&bytes[..]);
    }
    result
}

fn show_base64_decode_error(e: base64::DecodeError) -> String {
    use std::error::Error;
    format!("{:?}", e.description())
}

fn base64_to_f32_16_array(base64_str: &str) -> Result<[f32; 16], String>
{
    base64::decode(base64_str
        ).map_err(show_base64_decode_error
        ).and_then(read_float_vec_from_byte_vec
        ).map(
        |float_vec| {
            let mut result: [f32; 16] = [0.0; 16];
            result.copy_from_slice(&float_vec[..]);
            result
        }
    )
}

fn f32_16_array_to_base64(vals: &[f32; 16]) -> String
{
    base64::encode(&float_vec_as_byte_vec(&vals.to_vec()))
}

#[cfg(test)]
mod tests {
    static VALUES: [f32; 16] = [-0.35, -0.97, 0.05, 0.49, 1.35, 1.08, -0.71, 0.27, -0.44, 0.22, -1.34, -1.17, 0.68, 0.02, -0.52, 0.83];
    static BASE64_STR: &str = "MzOzvuxReL/NzEw9SOH6Ps3MrD9xPYo/j8I1v3E9ij6uR+G+rkdhPh+Fq7+PwpW/exQuPwrXozy4HgW/4XpUPw==";
    #[test]
    fn base64_to_f32_16_array_test() {
        assert_eq!(super::base64_to_f32_16_array(&BASE64_STR), Ok(VALUES));
        assert_eq!(
            super::base64_to_f32_16_array("foo"),
            Err("Number of bytes not divisible by 4.".to_string()));
    }
    #[test]
    fn f32_16_array_to_base64_test() {
        assert_eq!(super::f32_16_array_to_base64(&VALUES), BASE64_STR);
    }
}

cargo.toml (for completeness):

[package]
name = "base64_f32_test"
version = "0.1.0"

[dependencies]
base64 = "0.9.0"

You should use iterators: when you use a line like this for i in 0..dest_len as isize, the compiler cannot optimize when going through the slice.

A better example:

fn read_float_vec_from_byte_vec(v: Vec<u8>) -> Result<Vec<f32>, &'static str> {
    #[inline(always)]
    fn float_from_u8_slice(s: &[u8]) -> f32 {
        let array = [s[0], s[1], s[2], s[3]];
        unsafe { std::mem::transmute(array) }
    }

    match v.len() % 4 {
        0 => Ok(v.chunks(4).map(float_from_u8_slice).collect()),
        _ => Err("Number not divisible by 4"),
    }
}

With the iteration over v.chunks(4).map(float_from_u8_slice).collect(), the code is smaller and more readable. Generally speaking, iterators are always better than indexing because indexing operation performs bounds checks.

Unfortunately, you cannot do the same with float_vec_as_byte_vec because (for now) arrays in Rust are not a first-class citizen. Due to the fact that genericity on integers does not exist, you cannot consume an array into an iterator. If it did, we could write something like:

// This code does not work currently
fn float_vec_as_byte_vec(s: &[f32]) -> Vec<u8> {
    s.iter().flat_map(|&f| unsafe { transmute::<f32, [u8; 4]>(f)).collect()
}

In this code, I accept the type &[f32], instead of &Vec<f32>. Slices are a view of memory, and that is what we want. &Vec<f32> does not really make sense, semantically.

In the first function I rewrote, I used &'static str and not String because we do not need an allocated string since it is literal.


Function to erase a character in a string void chrrem (char arr[], size_t len, size_t pos)
{
    memmove(arr + pos, arr + (pos + 1), (len - pos) + 1);
}

It is supposed to be just fast.
Erases the character pointed by pos (starting from 0)

Note that this function works with a statically allocated array like so:

char arr [256] = "Mystring";

// >>
chrrem (arr, strlen(arr), 0);
chrrem (arr, strlen(arr), 0);

printf(arr);

  Output:

sring

I am not a c programmer, and I know short, cryptic function and variable names are used in c for historical reasons, but I'll still comment that I don't like it one bit.  I'd name the function removeCharacter.

Given that the function is only intended to be used on c-strings, is the len parameter actually necessary?  Can't we eliminate that parameter and get the len in the same way your context code demonstrates calculating a c-string's length?

void removeCharacter(char string[], size_t index) {
     memmove(string+index, string + index + 1, strlen(string) - pos + 1);
}

Now we can actually justify the function wrapping the memmove.  It makes it easier to use because all we have to do now is pass our string and the index of the character we want removed.

Given the performance implications of moving memory like this, it might be a great idea to offer a companion function which allows the user to remove a range of characters.

void removeSubstring(char string[], size_t index, size_t length) {
    memmove(string+index, string+index+length, strlen(string)-index+1);
}

I think it'd certainly be worthwhile to have a Range struct which has an index and length member, and simply pass this struct as the second argument instead of the index and length arguments.

And of course, it's important to be sure your code is well documented so that users are clear on exactly what they're getting with the function.

Also, this seems like a pretty easy thing to unit tests for, so be sure to do that.


Create an Array with n values that is able to use Array methods instantly As it is impossible to use Array methods on new Array(n), e.g. new Array(5).map(/* [some callback] */), I deviced a pseudo static Array method.

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

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

It looks like this:

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

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

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

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

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

As the comments already say, I'd not put too much into such a function, that is, IMO creating the array with initial size and elements is probably enough to make a difference.

Array.create = function (n, initial) {
  var result = new Array (n);
  for (var i = 0; i < n; ++i)
    result[i] = initial;
  return result;
};

// Array.create (3);
// Array.create (5, "hi").map (...);

Which also could just be a regular function makeArray or so I guess. So you get one benefit without the rather cryptic calling convention (mapCB/method) you have at the moment. Sure, it's a matter of opinion, but I had to take a moment to understand what that is supposed to do, so arguably that is not a good choice if you want other people to read that later.

And good point about the apply, I wouldn't want to see that in real code as well.


Converting JDBC to CSV One of my first ever Jython scripts lets me get comma-separated values out of an RDBMS:

from java.lang import System
from java.sql import DriverManager, ResultSet
import csv
import cStringIO as StringIO
import sys
def doIt():
    if System.getProperty("jdbc.drivers") is None or System.getProperty("jdbc2csv.query") is None:
        try:
            System.setProperty("jdbc2csv.url", sys.argv[1])
            System.setProperty("jdbc2csv.query", sys.argv[2])
        except IndexError:
            print 'Usage: java -cp jython.jar:jdbc.jar -Djdbc.drivers=<jdbc.driver.class> -Djdbc2csv.query=<query> -Djdbc2csv.url-<jdbc.url> org.python.util.jython ' + sys.argv[0]
            exit()
    output = StringIO.StringIO()
    conn = DriverManager.getConnection(System.getProperty("jdbc2csv.url"))
    res = conn.createStatement().executeQuery(System.getProperty("jdbc2csv.query"))
    meta = res.getMetaData()
    header = ['row #']

    for i in range(0, meta.getColumnCount()):
        header.append(meta.getColumnName(i+1))

    writer = csv.writer(output, quotechar = '"', quoting = csv.QUOTE_ALL, escapechar = '\\', delimiter = ',')
    writer.writerow(header)
    i = 0

    while not res.isLast():
        res.next()
        i = i + 1
        row = [i]

        for column in range(1, meta.getColumnCount()+1):
            row.append(res.getString(column))
        writer.writerow(row)

    conn.close()
    print output.getvalue()

if __name__ == '__main__':
    doIt()

One thing I can immediately see as a potential issue is utilising the optparse module to handle options in addition to JVM properties instead of sys.argv. But, I await others ripping it apart.

Some JDBC-related notes:

use getColumnLabel() instead of getColumnName()
using islast() as part of the ResultSet loop is unconventional (and potentially slow, and potentially not supported). The intended use pattern is while res.next(): ( next() returns true when successful).
you should have a symmetrical mechanism for accessing both the column names, as well as the column values. In your header row, you looped the range(0, meta.getColumnCount()): and in the column values you loop the range range(1, meta.getColumnCount() + 1):. You shoudl pick one, and stick with it (also, yes, everyone agrees with you that JDBC should have been zero-based with column indexes... like ... really?).
In general, do not use ResultSet.getString() unless you know it is a String in the column. In this specific case though, the effort required to check whether the values are numeric, etc. are overkill. Still, do not get in the habit of getString().
This is a short&sweet program, but even then, you should observe the best-practices for JDBC. You shoud close the Statement instance properly (which means you will need to store it in a variable), and also close the ResultSet. In this case, you close the Connection and that may clean things up nicely, but the protocol is to close things in reverse order to opening them.


Rotate and translate a 2D point N times This is a C++ program that rotates a point initially located at origin by a given angle A (degree) counterclockwise and L translate its x-coordinate (sum L to it).

Here is my program:

Firstly it reads the number of test cases.
Each test case has 2 real numbers and 1 integer that represents a rotation, translation and how many times the operation of rotate and translate must be applied.

#include <cstdio>
#include <utility>
#include <cmath>

#define gc getchar_unlocked()
inline double getDouble() {
    double v;
    scanf("%lf",&v);
    return v;
}

#define CONST 0.01745329251994329576922 //3.14159265358979323846/180 = 0.01745329251994329576922
std::pair<double, double> rotate(std::pair<double, double> p, double a){
    double rad = a*CONST;
    return std::make_pair(p.first*std::cos(rad) - p.second*std::sin(rad), p.first*std::sin(rad) + p.second*std::cos(rad));
}

int main(void){
    int t = (int) getDouble();

    for (int i = 0; i < t; ++i) {
        double a = getDouble(),l = getDouble();
        int v = (int) getDouble();

        std::pair<double, double> p(0,0);
        while (v--) {
            p = rotate(p, a);
            p.first += l;
         }
        //for cases like 30 1.5 121... the printf just put -0.00
        if(std::abs(p.first) < 0.005)
            p.first = 0;
        if(std::abs(p.second) < 0.005)
            p.second = 0;
        printf("%.2lf %.2lf\n",p.first,p.second);
    }

    return 0;
}

Sample input:

  4
  90 10 1
  90 10 2
  90 10 3
  30 1.5 1000000000

Sample output:

  10.00 0.00
  10.00 10.00
  0.00 10.00
  3.55 3.55

How to make it faster ?

CONST is not a name; it doesn't convey any meaning. Call it something like rads_per_degree. If you feel you need to comment on the value, better do the calculation explicitly (take advantage of \$\pi\$ being defined for you in cmath):

const double rads_per_degree = M_PI / 180;

Each time you rotate, you recalculate radian measure, sin and cos. Within the test case these values do not change. You may safely precompute them:

double rads = rads_per_degree * angle;
double sin = std::sin(rads);
double cos = std::cos(rads);
while (v--) {
    do_math(x, y, sin, cos, L);
}

I am not sure why you special cased small values.
getDouble is somewhat dubious. It would've make sense to have such a function to sanitize input. As written, it is meaningless. Also, you should not read integer as double.


The ListenHear Game - Listen and type the word What it does:

Speak a random word chosen from an array and ask the user to type the word in the box for 15 seconds

If right, +1pts, reset the timer and go to next word.
If wrong: do nothing.
After 15 seconds: game over.

    body {background-color: black; color: white;}
    .center {
      width: 50%;
      height: 50%;
      position: absolute;
      top:0;
      bottom: 0;
      left: 0;
      right: 0;

      margin: auto;
    }
    .hidden {
      display: none;
    }

    The ListenHear
Game

<button class="w3-btn w3-green" onclick="play()">Play</button><button class="w3-btn w3-red" onclick="exit()">Exit</button>

<x class="w3-red">There was an error.</x>

For those who are complaining the code is broken, the SpeechSynthesisAPI (the code depends on) doesn't have good browser support.

Your game() calls c=setInterval(…), which is balanced by clearInterval(c) in check().  However, giveup() does not call clearInterval(c).  As a result, if you just start the game but do nothing, then it gets ridiculously faster and faster.


Optimize simple C++ function to minimize copying I've been coding C for almost 20 years and figured I should learn C++. As a starting point I wrote the following trivial code to generate the powerset of a set. I'm hoping that some experienced C++ coder could help me with three things:

Identify non-idiomatic constructions.
Explain where I'm doing unnecessary copying of objects
Any other simplifying comments.

#include <iostream>
#include <vector>

using namespace std;

template<typename T>
vector<vector<T>> powerset(vector<T> s)
{
  // Return the powerset containing the empty set
  if(s.size() == 0) {
    vector<int> dummy;
    return vector<vector<T>> { dummy };
  }

  T v = s.back();
  s.pop_back();

  // Recursively generate powerset for s setminus v
  vector<vector<T>> pss = powerset<T>(s);
  // This is the basis for the current powerset set
  vector<vector<T>> ps = pss;

  for(auto&& i : pss) {
    // Add a set with v added for each set
    i.push_back(v);
    ps.push_back(i);
  }

  return ps;
}

int main(void)
{
  vector<int> v = {1,2,3,4};

  vector<vector<int>> ps = powerset<int>(v);

  cout << "Powerset contains the following elements:" << endl;
  for(auto&& i : ps) {
    for(auto&& j : i) {
      cout << j << " ";
    }
    cout << endl;
  }

  return 0;
}

A few things about your code that you could improve:

There is an error in powerset: while it works fine with your test case, you specifically try to return an std::vector<int> when size is 0 while you should be returning an std::vector<T>.
You don't even need the dummy vector. You can take advantage of uniform initialization and brace initialization in a return statement to simply write this:

return { {} };

Using s.size() == 0 in a condition is fine, but the idiomatic way to do it would be to use s.empty(). While it does not make a big difference for std::vector, some implementations of std::list still implement a \$O(n)\$ size while empty will always be \$O(1)\$ (C++11 requires std::list::size to be \$O(1)\$ but not all implementations are up-to-date). Using empty will be better if you ever need to change the kind of collection you use.
Since pss won't be used after the last for loop of powerset, you can safely move the elements out of it instead of copying them:

for(auto&& i : pss) {
  // Add a set with v added for each set
  i.push_back(v);
  ps.push_back(std::move(i));
}

The vectors in pss will be moved into ps, but left in a valid state, so you don't have to fear errors or undefined behaviour.
Every time you call powerset, you copy a full std::vector while you only need to read the elements. Instead of a vector, you could pass iterators so that you don't have to endlessly copy vectors that you only need to read:

template<typename T>
vector<vector<T>> powerset(typename vector<T>::iterator first, typename vector<T>::iterator last)
{
  // Return the powerset containing the empty set
  if(std::distance(first, last) == 0) {
    return { {} };
  }

  --last;
  T v = *last;

  // Recursively generate powerset for s setminus v
  vector<vector<T>> pss = powerset<T>(first, last);
  // This is the basis for the current powerset set
  vector<vector<T>> ps = pss;

  for(auto&& i : pss) {
    // Add a set with v added for each set
    i.push_back(v);
    ps.push_back(std::move(i));
  }

  return ps;
}

This is not the prettiest in the world, but it works, and you should even be able to generalize the agorithm so that it takes any BidirectionalIterator instead of mere std::vector<T>::iterator.


Putting a matrix from a text file into a list I'm trying to read a text file with matrix and put it in a list, but I am using two loops here and I want my function to be faster.

def read_file(path_to_file):
    mylist=[]
    for eachLine in open(path_to_file,'rt'):
        mylist.append([int(eachRow) for eachRow in eachLine.split()])
    return mylist

Not sure if it's possible to make this faster. But it can be better:

with open(path_to_file, 'rt') as fh:
    return [[int(value) for value in line.split()] for line in fh]

First of all, you should always use a with ... context manager when working with files. That way you cannot forget to close the file handle after you are done reading from it.

Other improvements:

More natural variable names
Simpler and more compact writing style using a list comprehension

Also keep in mind PEP8, the Python style guide.


Reverse a doubly linkedlist Reverse a doubly linkedlist. Looking for code review, optimizations and best practices.

public class ReverseDoublyLinkedList<T> implements Iterable<T> {

    private Node<T> first;
    private Node<T> last;
    private int size;

    public ReverseDoublyLinkedList() { };

    public ReverseDoublyLinkedList(List<T> c) {
        for (T item : c) {
            add(item);
        }
    };

    public void add (T t) {
        final Node<T> l = last;
        final Node<T> node = new Node<T>(null, t, null);
        last = node;
        if (first == null) {
            first = node;
        } else {
            l.right = node;
            node.left = l;
        }
        size++;
    }

    private static class Node<T> {
        Node<T> left;
        T item;
        Node<T> right;

        public Node(Node<T> left, T item, Node<T> right) {
            this.left = left;
            this.item = item;
            this.right = right;
        }
    }

    public void reverse() {
        if (first == null) {
            throw new IllegalArgumentException("The root cannot be null.");
        }

        Node<T> node = first;
        while (node != null) {
            Node<T> temp = node.left;
            node.left = node.right;
            node.right = temp;

            node = node.left;
        }

        Node<T> temp = last;
        last = first;
        first = temp;
    }

    @Override
    public Iterator<T> iterator() {
        return new ListItr();
    }

    private class ListItr implements Iterator<T> {
        private int count;
        private Node<T> currentNode;

        public ListItr() {
             this.currentNode = first;
        }

        @Override
        public boolean hasNext() {
            return count < size;
        }

        @Override
        public T next() {
            if (!hasNext()) {
                throw new NoSuchElementException();
            }

            T item = currentNode.item;
            currentNode = currentNode.right;
            count++;
            return item;
        }

        @Override
        public void remove() {
            currentNode.left.right = currentNode.right;
            currentNode.right.left = currentNode.left;
        }
    }

    public static void main(String[] args) {
        ReverseDoublyLinkedList<Integer> foo = new ReverseDoublyLinkedList<Integer>();
        foo.add(10);
        foo.add(20);
        foo.add(30);

        foo.reverse();

        Iterator<Integer> itr = foo.iterator();
        while (itr.hasNext()) {
            System.out.println(itr.next());
        }
    }
}

The name ReverseDoublyLinkedList is not so good.  Just stick to DoublyLinkedList.

It would make more sense if the reverse method returned a new instance of the list.  Actually, I would have defined a static method that takes a list and return a reversed list.


Mock Entity or DTO for unit tests Is this good approach, to mock some domain object, for example javax.persistence.Entity, or DTO (data transfer object)? Below is simplified source code:

@Entity
public class Entity {
    @Id
    private int id;
    private String name;
    // getters and setters
}

//Spring repo for example
@Repository
public interface EntityRepo {
    Entity findOne(int id);
}

@Component
public class SomeProcessing {
    private EntityRepo entityRepo;

    public SomeProcessing(int id) {
        entityRepo.findOne(id);
        //some logic which would be tested
    }

}

@RunWith(MockitoJUnitRunner.class)
public class SomeProcessingTest {
    @Mock
    private EntityRepo entityRepoMock;
    @Mock
    private Entity entityMock; //it this ok? Or better not to mock it and use just "new Entity()" with getters/setters

    @Test(){
        given(entityMock.getName()).willReturn("text");
        given(entityRepoMock.findOne(anyInt())).willReturn(entityMock);

        //here is other testing stuff
    }
}

Is my understanding correct, that this is refer to Classical vs Mockist testing? Or, there is any other issues not to use mocked Entity or DTO objects?

You don't need to mock the Entity/DTO object . Good practice is to create a new instance of DTO object and set data using setters .


Dynamically create ordered list in outlook from Excel I have working code for this project, but I am now in need of some help to create a dynamic ordered list within Outlook from Excel.

I am trying to format comments that a user will enter into a UserForm in Excel and pass those comments into an ordered list via a collection; the issue I run into is that the number of comments can vary and I need to account for that when it comes to setting up the ordered list.  I know I cannot create dynamic variables, so right now I am stuck on how to loop through the collection and adjust the size of the ordered list dynamically.

Below is the code that is working outside of the fact that the ordered list is not dynamic.  Im wondering if maybe passing that Collection into a Class Module would be beneficial, but I am not really proficient with those yet.  Please note that Option Explicit is defined in this module.

Dim strComment As String, commentColl As Collection
Dim arr As Variant

strComment = SheetData.Range("Notes_For_Doc_Reviewer")
arr = Split(strComment, ",")

Set commentColl = New Collection

Dim a

For Each a In arr
    commentColl.Add Trim(a)
Next a

'Dim x As Variant, i As Long

'For Each x In commentColl
'    Debug.Print CStr(x)
'Next x

Count = commentColl.Count

Application.ScreenUpdating = False
Application.DisplayAlerts = False

ZackEmail = "ZackE@nothing.com"
currDir = MLAChecklist.path
hyperlink = "" & currDir & ""

strBody = "Hello Zack," & _
          "
Please complete the closing document review for the following file:" & "&nbsp" & "&nbsp" & hyperlink & "

" & vbCrLf & _
          "Items to make note of in the file." & _
          "
" & _
            "
" & commentColl(1) & "
" & _
            "
" & commentColl(2) & "
" & _
            "
" & commentColl(3) & "
" & _
            "
" & commentColl(4) & "
" & _
            "
" & commentColl(5) & "
" & _
          "
" & _
          "
"

EDIT:  Output of getCheckListHTML per request

Hello Zack,

Please complete the closing document review for the following file:
&nbsp&nbsp
Z:\Projects\Excel Projects\MLA UserForm Checklist

Items to make note of in the file.

Test run

items list

run through things

test number

blah blah

Thank You,

There is no reason to convert arr to a collection.  Join() can quickly build a tag list from a 1 Dimensional array.  The trick is to have Join()  insert a closing tag + open tag between each element.

"
" & Join(arr, "

") & "
"

Join Demo

Dim arr As Variant
Dim n As Long
ReDim arr(6)
For n = 1 To 7
    arr(n - 1) = WeekdayName(n)
Next

Debug.Print "
" & Join(arr, "

") & "
"
Debug.Print "
" & Join(arr, "
" & vbNewLine & "
") & "
"

You could also avoid creating the array in the first using the same tring to replace the commas with a close tag + an open tag:

Your code is building a hyperlink, filling an ordered list, and creating the message htmlBody and will probably do several other tasks before it is complete.  There is no way to test any single process without running the entire code.  The fewer tasks that a method performs the easier it is to modify and debug.

Notice how easy it was to test my Refactored Code in the immediate window.

Refactored Code

Note: I find that using an ArrayList is the easiest way to create and modify dynamic html.

Function getCheckListItems() As String
    getCheckListItems = "
" & Replace(SheetData.Range("Notes_For_Doc_Reviewer").Value, ",", "
" & vbNewLine & "
") & "
"
End Function

Function getChecklistHTML(HyperlinkTag As String, CheckListItems As String) As String
    Const Delimiter As String = vbNewLine
    Dim list As Object
    Set list = CreateObject("System.Collections.ArrayList")
    list.Add ""
    list.Add ""
    list.Add "Hello Zack"
    list.Add "
Please complete the closing document review for the following file:"
    list.Add "&nbsp&nbsp"
    list.Add HyperlinkTag
    list.Add "

"
    list.Add "Items to make note of in the file."
    list.Add "
"
    list.Add CheckListItems
    list.Add "
"
    list.Add ""
    list.Add ""

    getChecklistHTML = Join(list.ToArray, Delimiter)

End Function

Function getCurrentPathHyperlink(Wb As Workbook)
    Const DefaultLink As String = "@currDir"

    Dim currDir As String
    currDir = Replace(Wb.Path, " ", "%20")

    getCurrentPathHyperlink = Replace(DefaultLink, "@currDir", currDir)
End Function

Edit:

My original post was using an open tag instead of a closing tag in getCheckListItems().  Many thanks to Ryan Wildry!


Only using randint, create a random list of unique numbers There are many sorting algorithms, so how about unsorting algorithms?

But how could one go about creating a random list of unique elements while not using shuffle, NumPy or any other ready made tools to do it?

def get_un_sorted(limit):
    numbers = list(range(limit))
    shuffled = [0] * limit
    for i in range(limit):
        index = randint(0, len(numbers) - 1)
        shuffled[i] = numbers[index]
        numbers.pop(index)
    return shuffled

def main():
    not_sorted = get_un_sorted(2 * 10 ** 4)

if __name__ == '__main__':
    main()

It doesn't seem so nifty to me and it is very slow, but it gets the work done.

Your question reminds me of a beautiful page that visually explains the efficacy of shuffling.

But here are the two main problems with your algorithm:

Your memory usage is bad, this is as you're not performing the shuffle in-place.
As you have to make a new list, to keep the old intact and to make the new you need \$O(n)\$ memory.
If you instead performed the shuffle in-place then you'd only need \$O(1)\$ memory.
You're removing from the middle of an array. As Pythons lists are internally arrays,
when you remove anything that is not the item at the end, you have to shift all the previous data.
This leads to list.pop having a worst case of \$O(n)\$ performance.

If you take this with the fact that you have to perform this action \$n\$ times, then you can quickly see this algorithm is \$O(n^2)\$.

Both the problems above have the solution of performing the shuffle in-place.
To do this you want to swap the chosen item with the current index.
So if we're on the first item, and we randomly pick the index four,
then we'll swap the item at index zero and four.
Or in Python:

i, j = 0, 4
numbers[i], numbers[j] = numbers[j], numbers[i]

Now that we can perform the swapping efficiently,
you'd have to change what indexes you pick, when using randint.
If we're on index 4 of 8, then you'd not want to pick an index below four.

I'd change your program to have a function shuffle that takes an array as input, swaps it in-place and returns None.
And for you to use this rather than get_un_sorted.

And so you should be able to get something like, the Fisher–Yates shuffle:

def shuffle(l):
    for i in range(len(l) - 1):
        j = randint(i, len(l) - 1)
        l[i], l[j] = l[j], l[i]

Finally you could use randrange rather than randint as it's a short hand for having the upper bound be non-inclusive.


Basic web app that returns a JSON of information My web application can take URL-encoded strings and return a JSON that contains information, like API calls.

My main concerns are with security. I need a cheap and easy (but secure) way to do certain commands. This part is handled by the adminhandle section of the code. My code is currently designed to be able to be deployed on a heroku app, but simply changing:

port = int(os.environ.get('PORT', 17995))

at line 12 to:

port = 80

should be fine, allowing you to access this server from http://localhost. Inside the code itself contains a hashed password and a salt. The password I use I generated with the random module (perhaps it is worth noting, since there are "more secure" RNGs out there).

My server is currently operational at here.

from twisted.web.server import Site
from twisted.web.resource import Resource
from twisted.internet import ssl, reactor
from twisted.python.modules import getModule
import urllib.parse
import cgi
import json
import os
import hashlib
admin_salt = ''
realpass = ''
port = int(os.environ.get('PORT', 17995))
class FormPage(Resource):
    isLeaf = True
    def render_GET(self, request):
        out = {}
        print(request.uri)
        x = (request.uri).decode('ascii')
        x = x[1:]
        x = todi(x)
        request.setHeader('Content-Type', 'text/plain; charset=UTF-8')
        valid = False
        if 'adminaccess' in x:
            vlr = adminhandle(x)
            out.update({'ADMIN':vlr[0]})
            if len(vlr) != 1:
                out.update({'CMDRES':vlr[1]})
        if 'key' in x:
            if x['key'] == 'chess':
                valid = True
                out.update({'my_name':'Bob'})
        out.update({'success':valid})
        return json.dumps(out).encode('UTF-8')

##    def render_POST(self, request):
##        x = request.content.read()
##        print(x)
##        return x

def todi(st):
    if len(st) == 0:
        return '{}'
    if st[len(st)-1] == '/':
        st = st[:-1]
    if len(st) == 0:
        return '()'
    if st[0] == '?':
        st = st[1:]
    st = urllib.parse.parse_qsl(st)
    return dict(st)

def adminhandle(di):
    rawupass = (admin_salt+di['adminaccess']).encode('ascii')
    hashupass = hashlib.sha512(rawupass).hexdigest()
    result = [False]
    if hashupass == realpass:
        #access granted!
        del result[0]
        result.append(True)
        if 'command' in di:
            if di['command'] == 'listdir':
                result.append(str(os.listdir(os.getcwd())))
    return result

#certData = getModule(__name__).filePath.sibling('server.pem').getContent()
#certificate = ssl.PrivateCertificate.loadPEM(certData)
factory = Site(FormPage())
reactor.listenTCP(port, factory)
#reactor.listenSSL(443, factory, certificate.options())
reactor.run()

The first problem is the function todi. I'm assuming a better name for it would be to_dict. If that is the case it does not make sense, that it sometimes returns the string "{}", sometimes "()" and sometimes an actual dictionary. I think this would be equivalent/better:

def to_dict(st):
    st = st.strip("/?")
    if not st:
        return dict()
    return dict(urllib.parse.parse_qsl(st))

This strips of any "/" or "?" from the beginning or end of the string and returns an empty dictionary if the string is empty.

Your function adminhandle should take the parameters it needs as parameters, not retrieve them on its own from data. It can also be slightly simplified by using the fact that lists are mutable, so you can just write result[0] = True instead of del result[0]; result.append(True):

def adminhandle(adminaccess, command):
    result = [False, ""]
    if adminaccess is not None:
        rawupass = (admin_salt+adminaccess).encode('ascii')
        hashupass = hashlib.sha512(rawupass).hexdigest()

        if hashupass == realpass:
            #access granted!
            result[0] = True
            if command == 'listdir':
                result[1] = str(os.listdir(os.getcwd()))
    return result

x is also a really bad name. At least name it data or something telling the reader what it actually is.

    data = to_dict(request.uri.decode('ascii')[1:])

Your placeholder variable valid is also not necessary. As is writing out.update({'success': valid}). out['success'] = valid is sufficient. I would also use the fact that dictionaries have a dict.get method, that returns None if the key does not exist.

    out = {'success': False}
    adminaccess, command = data.get('adminaccess'), data.get('command')
    out['ADMIN'], out['CMDRES'] = adminhandle(adminaccess, command)
    if not out['CMDRES']:
        del out['CMDRES']
    if data.get('key') == 'chess':
        out['my_name'] = 'Bob'
        out['success'] = True
    return json.dumps(out).encode('UTF-8')


Project Euler #3 - checking only up to sqrt(input) I know it's possible for the largest factor of a number to be greater than the sqrt (e.g., for 14, 7 is the largest). Why then does almost every solution for the problem check only up to the square root? Also, I have a nagging feeling that boolean[] is not the best data structure to use here, since in this case the number is much smaller than the size of the array. What alternative data structure would be recommended in this case?

public static int largestPrime(long n)
{
    int limit=(int)Math.sqrt(n)+1;
    boolean [] numbers = new boolean[limit];
    Arrays.fill(numbers,true);
    int largestPrimeFactor=1;
    for(int count=2;count<limit;count++)
    {
        if(numbers[count]==true)
        {
            for(int i=2;i*count<limit;i++)
                numbers[count*i]=false;
            if(n%count==0)
                largestPrimeFactor=count;
        }

    }
    return largestPrimeFactor;
}

Edit: Hmm, looks like it's incorrect to only check for primes up to the square root of the input (at least without checking if the complementary factor is prime).

This is what I originally wanted to implement, but the number was too large to create a boolean array of that size.

public static int largestPrime(int n)
{
    int largestPrime = 2;
    // Worse case scenario: largest prime n is divisible by is itself
    int limit = n;
    // Create an boolean array of index up to n
    boolean[] numbers = new boolean[limit + 1];
    Arrays.fill(numbers, true);

    for (int count = 2; count <= limit; count++)
    {
        // if count is a prime number
        if (numbers[count])
        {
            // set all multiples of count to false
            for (int i = 2; i * count <= limit; i++)
                numbers[count * i] = false;
            // Check if the input number is divisible by count
            if (n % count == 0)
            {
                // The largest possible prime is the complementary factor
                limit = n / count;
                largestPrime = count;
            }
        }
    }
    return largestPrime;
}

I guess my second question is, is there a better alternative to a boolean array, and if not, what to change in the program so that it works with large numbers?

This implementation is not correct: for your example 14 it incorrectly returns 2 instead of 7.

You don't need to check == true of boolean expressions, you can use them directly, for example:

if (numbers[count]) { ... }

The formatting doesn't follow Java standards. In Eclipse, if you select your function and press Control-Shift-f it will change it this, which is more pleasant to read:

public static int largestPrime(long n) {
    int limit = (int) Math.sqrt(n) + 1;
    boolean[] numbers = new boolean[limit];
    Arrays.fill(numbers, true);
    int largestPrimeFactor = 1;
    for (int count = 2; count < limit; count++) {
        if (numbers[count]) {
            for (int i = 2; i * count < limit; i++) {
                numbers[count * i] = false;
            }
            if (n % count == 0) {
                largestPrimeFactor = count;
            }
        }
    }
    return largestPrimeFactor;
}

A simple way to fix the implementation is to re-implement following the same logic you do in math class:

Start from d = 2
Divide the target number by d as many times as possible without remainder
Increment d, return to step 2, until target is reduced to 1

This is pretty simple, correct, without using a boolean array:

public static long largestPrimeFactor(long n) {
    long d = 2;
    long target = n;
    while (target > 1) {
        while (target % d == 0) {
            target /= d;
        }
        ++d;
    }
    return d - 1;
}

To make this faster, after the ++d you can insert this check:

        if (d * d > target) {
            return target;
        }


Registration and login script This is a registration and login script I have made in Python 3. It uses a MySQL database. In the future I might use it with my Blackjack game and add a row called money, but for now I would like to hear your opinion about this script since I have little to no experience in SQL.

import cymysql
from getpass import getpass

def get_user_info():
    while True:
        email = input("Input your Email address (max. 64 chars.): ")
        password = getpass("Input a password (max. 64 chars.): ")
        if len(email) < 64 and len(password) < 64:
            return email, password

def register(cur, email, password):
    cur.execute("INSERT INTO `users` (`Email`, `Password`) VALUES (%s, %s)", (email, password))
    print("You've succesfully registered!")

def login(cur, email, password):
    cur.execute("SELECT * FROM `users` WHERE `Email`=%s AND `Password`=%s LIMIT 1", (email, password))
    rows = cur.fetchall()
    if rows:
        print("You've succesfully logged-in!")
    else:
        print("You failed logging-in!")

def check_account(cur, email):
    cur.execute("SELECT * FROM `users` WHERE `Email`=%s LIMIT 1", (email,))
    row = cur.fetchone()
    return row

def main():
    conn = cymysql.connect(
        host='127.0.0.1',
        user='root',
        passwd='',
        db='david'
    )
    cur = conn.cursor()
    email = ''
    password = ''
    email, password = get_user_info()
    check = check_account(cur, email)
    if check:
        login(cur, email, password)
    else:
        register(cur, email, password)
    cur.close()
    conn.close()

if __name__ == '__main__':
    main()

cymysql.connect is a context manager and so you should use it in a with statement.
conn.cursor isn't a context manager. Which is very fishy, even more so that the original version of cymysql, pymysql, is.
Seperate SQL interactions from UI interactions. This is as multiple parts of the UI may need to use the same SQL interactions, however since they're mangled, it'll lead to code duplication or errors in your UI.
You don't need to do email = '', if you want to tell people it's a string then you can do email: str. A better thing to do however is use typing and make your code fully typed.
You may want to verify that the email is a valid email address. It doesn't look like your SQL does that, but I don't know enough about it.

import cymysql
from getpass import getpass

def get_user_info():
    while True:
        email = input("Input your Email address (max. 64 chars.): ")
        password = getpass("Input a password (max. 64 chars.): ")
        if len(email) < 64 and len(password) < 64:
            return email, password

def register(cur, email, password):
    cur.execute("INSERT INTO `users` (`Email`, `Password`) VALUES (%s, %s)", (email, password))

def login(cur, email, password):
    cur.execute("SELECT * FROM `users` WHERE `Email`=%s AND `Password`=%s LIMIT 1", (email, password))
    return bool(cur.fetchall())

def check_account(cur, email):
    cur.execute("SELECT * FROM `users` WHERE `Email`=%s LIMIT 1", (email,))
    return bool(cur.fetchone())

def main():
    conn = cymysql.connect(
        host='127.0.0.1',
        user='root',
        passwd='',
        db='david'
    )
    with conn:
        cur = conn.cursor()
        email, password = get_user_info()
        check = check_account(cur, email)
        if check:
            loggedin = login(cur, email, password)
            if loggedin:
                print("You've succesfully logged-in!")
            else:
                print("You failed logging-in!")
        else:
            register(cur, email, password)
            print("You've succesfully registered!")
        cur.close()

if __name__ == '__main__':
    main()


Copying and pasting from MS Project to MS Excel This copies data from a project into Excel to be calculated into a final report. The code runs pretty slowly at this point and I would like it to be a little bit faster. Are there any blatant coding mishaps that are slowing the calculations down?

Sub Update_Schedule()
Dim appProj As MSProject.Application
Dim aProg As MSProject.Project
Dim sel As MSProject.Selection
Dim ts As Tasks
Dim t As Task
Dim rng As Range
Dim rng2 As Range
Dim ws As Worksheet
Dim ws2 As Worksheet

Application.DisplayAlerts = False

'Clear current contents

Set ws2 = Worksheets("Final Report")

Set ws = Worksheets("Master")
Set rng = ws.Range("A:F")
rng.ClearContents
Set ws = Worksheets("Resource List")
Set rng = ws.Range("A:B")
rng.ClearContents

'Open the Project file when it asks to open resource pool, press yes

Set appProj = CreateObject("Msproject.Application")

appProj.DisplayAlerts = False

appProj.FileOpen "File_1.mpp" 'also opens file 2

Set aProg = appProj.Projects("File_1.mpp")

appProj.Visible = True

WindowActivate WindowName:=aProg

'Copy the project columns and paste into Excel

Set ts = aProg.Tasks
SelectTaskColumn Column:="Name"
OutlineShowAllTasks
OutlineShowAllTasks
EditCopy
Set ws = Worksheets("Master")
Set rng = ws.Range("A:A")
ActiveSheet.Paste Destination:=rng
SelectTaskColumn Column:="Duration"
EditCopy
Set rng = ws.Range("B:B")
ActiveSheet.Paste Destination:=rng
SelectTaskColumn Column:="Start"
EditCopy
Set rng = ws.Range("C:C")
ActiveSheet.Paste Destination:=rng
SelectTaskColumn Column:="Finish"
EditCopy
Set rng = ws.Range("D:D")
ActiveSheet.Paste Destination:=rng
SelectTaskColumn Column:="Resource Names"
EditCopy
Set rng = ws.Range("E:E")
ActiveSheet.Paste Destination:=rng
SelectTaskColumn Column:="Project"
EditCopy
Set rng = ws.Range("F:F")
ActiveSheet.Paste Destination:=rng
WindowActivate WindowName:="\\File_2.mpp"
SelectResourceColumn Column:="Name"
EditCopy
Set ws = Worksheets("Resource List")
Set rng = ws.Range("A:A")
ActiveSheet.Paste Destination:=rng
SelectResourceColumn Column:="Category"
EditCopy
Set rng = ws.Range("B:B")
ActiveSheet.Paste Destination:=rng

'Populates formula in Master sheet
Application.Visible = True

Set ws = Worksheets("Master")
Set rng = ws.Range("G2")
Set rng2 = ws.Range("G2:G9223")
rng.AutoFill Destination:=rng2, Type:=xlFillDefault
Set rng = ws.Range("H2")
Set rng2 = ws.Range("H2:H9223")
rng.AutoFill Destination:=rng2, Type:=xlFillDefault

Calculate

ws2.Visible = True

Application.DisplayAlerts = True
appProj.DisplayAlerts = True
End Sub

A few things here:

Read this. Its lists things to do when copying large amounts of data
Did you set Application.Calculation = xlCalculationManual? Your manually calling Calculate, but you never turn off autocalcualtion.
Did you set Application.ScreenUpdating = FALSE? That can speed things up.


Give me some change as asked in interview Description:

The goal in this problem is to find the minimum number of coins needed
to change the input value (an integer) into coins with denominations 1,
5, and 10
The input consists of a single integer m.
1≤m≤103
Output the minimum number of coins with denominations 1, 5, 10 that changes m.

Code:
import java.util.*;
import java.lang.*;
import java.io.*;

/* Name of the class has to be "Main" only if the class is public. */
class Main
{

  public static int CountChange(int m) {
    if (m <= 0) return 0;

    int[] denomenations = new int[]{10, 5, 1};
    int change = 0;

    for (int i : denomenations) {
      while (m - i >= 0) {
        m -= i;
        change++;
      }
    }

    return change;
  }

    public static void main (String[] args) throws java.lang.Exception
    {
      // edge cases
      System.out.println(CountChange(0));  // 0
      System.out.println(CountChange(-1)); // 0
      System.out.println(CountChange(Integer.MIN_VALUE)); // 0
      System.out.println(CountChange(Integer.MAX_VALUE));

      System.out.println(CountChange(1));  // 1 = 1
      System.out.println(CountChange(2));  // 2 = 1 + 1
      System.out.println(CountChange(5));  // 1 = 5
      System.out.println(CountChange(10)); // 1 = 10
      System.out.println(CountChange(28)); // 6 = 10 + 10 + 5 + 1 + 1 + 1
    }
}

Questions

This seems exponential algorithm to me but what is the correct approach for finding the running time of this algorithm?
I put some thoughts on testing strategies in this problem, since the input is integer I had few number of edge cases also the problem description doesn't cover edge cases (e.g.: maximum integer) but then also I thought to test it, is this the correct approach?
For m = 0 the algorithm works fine but still I gave a guard condition for readability, don't know if this is a good strategy.
I think that a better algorithm can be developed and suggestions are welcome.

I think that a better algorithm can be developed and suggestions are welcome.

Yes! The core of the algorithm is the following:

for (int i : denomenations) {
  while (m - i >= 0) {
    m -= i;
    change++;
  }
}

What this does is looping through all the possibles denominations in descending order, removing them as long as necessary. This is the right idea: for a given number, like 36, this subtracts 10 three times, then 5 one time and then 1 one time.

This can be done in a faster way. You know in advance how many times you will need to loop. It is precisely m / i (with an explicit integer division).

Given 36, you want to know how many times 10 fits in there. This is the quotient of the integer division of 36 by 10, which is 3, result of 36 / 10.
Then, what remains in m is the remainder of the integer division of 36 by 10, which is 6, result of 36 % 10.

As such, you can have:

for (int i : denomenations) {
    change += m / i;
    m %= i;
}

without a single inner while loop.

I am not so sure about the initial time complexity of the algorithm, but with this revision, you clearly have a linear algorithm in terms of the denominations, which is probably the same as the original but will effectively be faster.

  I put some thoughts on testing strategies in this problem, since the input is integer I had few number of edge cases also the problem description doesn't cover edge cases (eg: maximum integer) but then also I thought to test it, is this the correct approach?

Testing edge cases is always welcomed, and I would encourage it. Do note that unit tests should typically sit in a dedicated test class run with a testing framework, like JUnit for example.

  For m = 0 the algorithm works fine but still I gave a guard condition for readability, don't know if this is a good strategy.

This is perfectly fine. You have an early return for negative values so you can add 0 to it since the results would already be known in advance.

A couple of other comments:

Beware of typos: denomenations should be denominations.
Since they are constants, you might also want to turn them explicitly into constants. A better alternative would be to let the CountChange method take the array of denomination as argument; this way, it is completely independant of actual values.
The method name should be countChange, not CountChange, with regard to Java naming conventions.
Consider having more descriptive names than m and i. One letter variables can be fine if their scope is really tight, but here, a longer name would be appropriate.