texts: Implementation of Dijkstra's algorithm in Python

texts:
I have implemented Dijkstra's algorithm for my research on an Economic model, using Python.
In my research I am investigating two functions and the differences between them. Every functions takes as input two parameters:
F(a,b) and Z(a,b).
Every cell of the matrix is defined as: $$M[a][b]=|F(a,b)-Z(a,b)|$$
The purpose of this is to find the path of minimal difference between the equations that will be correct for every input a
Online implementations of Dijkstra's algorithm were all using weighted edges whereas I have weighted vertices.
Pseudo-code:
function Dijkstra(Graph, source):

    create vertex set Q

    for each vertex v in Graph:
        dist[v] ← INFINITY
        prev[v] ← UNDEFINED
        add v to Q
    dist[source] ← 0

    while Q is not empty:
        u ← vertex in Q with min dist[u]

        remove u from Q

        for each neighbor v of u:           // only v that are still in Q
            alt ← dist[u] + length(u, v)
            if alt < dist[v]:
                dist[v] ← alt
                prev[v] ← u

    return dist[], prev[]

Input:

2d array where each cells value is its weight
source tuple (x, y)

Output:

distance matrix where each cell contains distance from source to vertex (i, j)

prev matrix where each cell contains its parent. By tracebacking from (98,98) I can find the shortest path.

Implementation:
MAX_DISTANCE = 99999
RANGE_ARR = [x for x in range(1, 1001)]

def dijkstra_get_min(Q, dist):
    min = MAX_DISTANCE + 1
    u = None
    for vertex in Q:
        if dist[vertex[0], vertex[1]] <= min:
            min = dist[vertex[0], vertex[1]]
            u = vertex
    return u

def dijkstra(graph, src=(0, 0)):
    dist = np.array([np.array([0 for x in RANGE_ARR], dtype=float) for y in RANGE_ARR])
    prev = np.array([np.array([(0, 0) for x in RANGE_ARR], dtype='i,i') for y in RANGE_ARR])
    Q = []

    for i in RANGE_ARR_0:
        for j in RANGE_ARR_0:
            dist[i, j] = MAX_DISTANCE
            prev[i, j] = (0, 0)
            Q.append((i, j))

    dist[0][0] = 0

    while Q:
        u = dijkstra_get_min(Q, dist)
        Q.remove(u)
        moves = [x for x in ( (u[0], u[1] + 1), (u[0] + 1, u[1]), (u[0] + 1, u[1] + 1) ) if x in Q]
        for v in moves:
            alt = dist[u[0]][u[1]] + graph[v[0]][v[1]]
            if alt < dist[v[0]][v[1]]:
                dist[v[0], v[1]] = alt
                prev[v[0], v[1]] = u
    return dist, prev

Any opinions about its correctness?


texts:
I have an HTML template that contains a letter in two languages, EG German & English. I should fill in the same data in both languages.

Excerpt from template:

Datum:
{4,date,yyyy. MM. dd}
....
Date:
'{4,date,d MMMM yyyy}'

I use this code fill in data:

public static String fillIn( final String template, final Object... array )
{
    final MessageFormat f = new MessageFormat( template, Locale.DE );
    final String temp = f.format( array );
    f.setLocale( Locale.UK );
    f.applyPattern( temp );
    return f.format( array );
}

It does not seem to be the best solution.
Is there any better way?


texts: Reusable webdriver framework using SOLID design principles

texts:
I am trying to design some classes which I intent to use as a framework. I would like them to be compliant to SOLID design principles.

I had a basic structure and then I implemented Strategy design pattern and tried adding dependency injection as well.

Would like this to be reviewed so that I know if my understanding is correct or can still be made better.

public interface IBrowser
{
    IWebDriver GetWebDriver(string webDriverFolderPath);
}

public class EdgeBrowser : IBrowser
{
    public IWebDriver GetWebDriver(string webDriverFolderPath)
    {
        var options = new EdgeOptions()
        {
            PageLoadStrategy = PageLoadStrategy.Eager,
            UseInPrivateBrowsing = true
        };

        return new EdgeDriver(webDriverFolderPath, options, TimeSpan.FromSeconds(60));
    }
}

public class IEBrowser : IBrowser
{
    public IWebDriver GetWebDriver(string webDriverFolderPath)
    {
        var options = new InternetExplorerOptions()
        {
            IntroduceInstabilityByIgnoringProtectedModeSettings = true
        };

        return new InternetExplorerDriver(webDriverFolderPath, options, TimeSpan.FromSeconds(60));
    }
}

public interface IConfiguration
{
    string GetConfiguration(string key);
}

public class AppSettingsConfiguration : IConfiguration
{
    public string GetConfiguration(string key)
    {
        return ConfigurationManager.AppSettings[key].ToString();
    }
}

public class WebDriver
{
    private static Dictionary<Enums.Browsers, IBrowser> Browsers = new Dictionary<Enums.Browsers, IBrowser>();
    private static Dictionary<string, Enums.Browsers> BrowserMapper = new Dictionary<string, Enums.Browsers>();
    private static AppSettingsConfiguration _AppSettingsConfiguration;

    static WebDriver()
    {
        Browsers.Add(Enums.Browsers.Edge, new EdgeBrowser());
        Browsers.Add(Enums.Browsers.IE, new IEBrowser());
        Browsers.Add(Enums.Browsers.Chrome, new ChromeBrowser());
        Browsers.Add(Enums.Browsers.Firefox, new FirefoxBrowser());

        BrowserMapper.Add("Edge", Enums.Browsers.Edge);
        BrowserMapper.Add("IE", Enums.Browsers.IE);
        BrowserMapper.Add("Internet Explorer", Enums.Browsers.IE);
        BrowserMapper.Add("Chrome", Enums.Browsers.Chrome);
        BrowserMapper.Add("Firefox", Enums.Browsers.Firefox);
        BrowserMapper.Add("edge", Enums.Browsers.Edge);
        BrowserMapper.Add("ie", Enums.Browsers.IE);
        BrowserMapper.Add("internet explorer", Enums.Browsers.IE);
        BrowserMapper.Add("chrome", Enums.Browsers.Chrome);
        BrowserMapper.Add("firefox", Enums.Browsers.Firefox);
        BrowserMapper.Add("internetexplorer", Enums.Browsers.IE);
        BrowserMapper.Add("InternetExplorer", Enums.Browsers.IE);
    }

    public WebDriver(AppSettingsConfiguration appSettingsConfiguration)
    {
        _AppSettingsConfiguration = appSettingsConfiguration;
    }

    public IWebDriver GetWebDriver(string browser)
    {
        var browserName = BrowserMapper[browser];

        return Browsers[browserName].GetWebDriver(_AppSettingsConfiguration.GetConfiguration("WebDriverFolderPath"));
    }
}

public void Initialize()
{
    if (WebDriver == null)
    {
        WebDriver = new WebDriver(new AppSettingsConfiguration()).GetWebDriver(BaseData.Browser);
    }
}


texts: Converting HTML input characters to asterisks after a given time

texts:
I tried for fun implementing a function that converts HTML input characters to asterisks after a given time. What do you think about my approach and how would you do it?

const passwordEl = document.querySelector('#password');
const showPassEl = document.querySelector('#show-password');

const replaceAt = (string, index, replace) => {
  return string.slice(0, index) + replace + string.slice(index + 1);
}

const insertAt = (string, index, insert) => {
  return string.slice(0, index) + insert + string.slice(index);
}

const removeAt = (string, index) => {
  let strArr = string.split('');
  strArr.splice(index, 1);
  return strArr.join('');
}

let plainPass = '';
passwordEl.addEventListener('input', e => {
  const valueLen = passwordEl.value.length;
  if (e.inputType === 'deleteContentBackward') {
    plainPass = removeAt(plainPass, e.target.selectionStart);
  } else {
    plainPass = insertAt(plainPass, e.target.selectionStart - 1, e.data);
    if (showPassEl.checked) {
     passwordEl.value = plainPass;
     return;
    }
    // immediately convert previous character to * if user typed fast
    if (valueLen > 1 && passwordEl.value[valueLen - 2] !== '*') {
      passwordEl.value = replaceAt(passwordEl.value, valueLen - 2, '*');
    }
    setTimeout(() => {
      passwordEl.value = replaceAt(passwordEl.value, e.target.selectionStart - 1, '*');
    }, 500);
  }
});

showPassEl.addEventListener('click', () => {
  passwordEl.value = showPassEl.checked ? plainPass : '*'.repeat(passwordEl.value.length);
});
<input type="text" id="password">
<input type="checkbox" id="show-password">
<label for="show-password">show password</label>


texts:
I made a PHP script to check value before update. This script is working fine. But, I wonder how to simplify this. If there are hundreds of columns to be checked then it's hundreds of PHP lines.

This is used for saving a log file for update. So, if data is updated then it stores a log in a table.

public function edit_project_master(){
$no_pro     = 'PRJ-2017-501'; //
$na_pro     = $this->input->post('na_pro'); //value for edit
$ja_pro     = $this->input->post('i_metode'); //value for edit

$check_pro  = $this->MProject->get_det_pro($no_pro); //get data form table

//checking script
foreach($check_pro as $res_check_pro){

    if($na_pro != $res_check_pro['NAMA_PROJECT']){  //IF VALUE DIFFERENT
        $col_name;

        foreach($res_check_pro as $key_pro => $val_pro){
            if($res_check_pro['NAMA_PROJECT'] == $val_pro){
                $col_name = $key_pro;            //GET COLUMN NAME
            }
        }

        $data['ACTIVITY']       = "UPDATE";
        $data['OLD_VALUE']      = $res_check_pro['NAMA_PROJECT'];
        $data['NEW_VALUE']      = $na_pro;
        $data['COL_AFFECTED']   = $col_name;
        $data['TABLE_AFFECTED'] = "PM_REQUIREMENT_PROJECT";  //How to get table name automatically??
        $data['ANNOTATION']     = NULL;
        $data['EXECUTOR']       = $this->session->userdata('nip');
        $data['CHANGED_ON']     = date("Y-m-d H:i:s");
        $data['CHANGED_BY']     = $_SERVER['REMOTE_ADDR'];
        $data['STATUS']         = 1;

        $this->MProject->ins_system_log($data);
    }

    if($ja_pro != $res_check_pro['JADWAL_PROJECT']){
        $col_name;

        foreach($res_check_pro as $key_pro => $val_pro){
            if($res_check_pro['JADWAL_PROJECT'] == $val_pro){
                $col_name = $key_pro;
            }
        }

        $data['ACTIVITY']       = "UPDATE";
        $data['OLD_VALUE']      = $res_check_pro['JADWAL_PROJECT'];
        $data['NEW_VALUE']      = $na_pro;
        $data['COL_AFFECTED']   = $col_name;
        $data['TABLE_AFFECTED'] = "PM_REQUIREMENT_PROJECT"; //How to get table name automatically??
        $data['ANNOTATION']     = NULL;
        $data['EXECUTOR']       = $this->session->userdata('nip');
        $data['CHANGED_ON']     = date("Y-m-d H:i:s");
        $data['CHANGED_BY']     = $_SERVER['REMOTE_ADDR'];
        $data['STATUS']         = 1;

        $this->MProject->ins_system_log($data);
    }

}

}


texts: Help optimizing this query with multiple where exists

texts:
In the application I'm building, the user is able to define 'types' where each 'type' has a set of 'attributes'.

The user is able to create instances of products by defining a value for each attribute the product's type has.

A pic of the schema:

I'm creating the query where the user specifies the attributes values and the product type and with that I should return all the product id's that meets the query.

The problem I see in my query is that I'm performing a whole select * from attributes_products ... for each attribute that the product's type has.

Is there a way to optimize this?
If I create an index in the column attributes_products.product_id would this query be actually optimal?

Example of a query where I'm looking for a product whose type has 3 attributes:

select p.id
from Products as p
where
exists(
    select * from attributes_products
    where
        product_id = p.id AND
        attribute_id = 27 AND
        value = 'some_value'
) AND
exists(
    select * from attributes_products
    where
        product_id = p.id AND
        attribute_id = 28 AND
        value = 'other_value'
) AND
exists(
    select * from attributes_products
    where
        product_id = p.id AND
        attribute_id = 29 AND
        value = 'oother_value'
)

Many thanks.

Conclusions

So, Gareth Rees (selected answer) proposed another solution which involves multiple Joins.
Here is the explanation of its query (done by PGAdmin):

This is the explanation of the original query:

I believe that the selected answer is slightly faster, but consumes a lot more memory (because of the triple join).
I believe that my original query is slightly slower (very slightly, since there's an index on the attributes_products table) but a lot more efficient in memory.


texts: Check sum of all primes under two million

texts:
I'm exploring ruby by writing a code that checks the sum of all prime numbers under two million. As I am still in the process of learning ruby, I'm unfamiliar with all the standards and best practices. What I have so far works, but I am certain it can be improved. Where can I improve my code for both readability and speed?

def is_prime(n)
    range = n
    i = 2

    while i < range do
        return false if (n % i == 0)
        range = n / i
        i += 1
    end
    true
end

sum = 2
(3..2000000).each do |num|
    if (is_prime(num))
        #puts "#{num}"
        sum += num
    end
end

puts "#{sum}"


texts: Checking if a text contains N consecutive repeating characters

texts:
I want to check a text for consecutive repeating characters. For example, with a minimum of 3 consecutive chars, this should match:

Okeee
OOOkee
Alsoook

This should not match:

No not okee, oh no

This is my code:

public static bool HasConsecutiveChars(string source, int sequenceLength)
        {
            if (string.IsNullOrEmpty(source))
            {
                return false;
            }

            if (source.Length == 1)
            {
                return false;
            }

            int charCount = 1;

            for (int i = 0; i < source.Length - 1; i++)
            {
                char c = source[i];
                if (c == source[i + 1])
                {
                    charCount++;

                    if (charCount >= sequenceLength)
                    {
                        return true;
                    }
                }
                else
                {
                    charCount = 1;
                }
            }

            return false;
        }

It works but I feel there should be a cleaner solution to this problem.


texts: Print the number of movies that was watched by more than 3 people

texts:
I want to create a program that can print the number of movies that was watched by more than 3 people (data stored in a nested list as below ).

list_movies = [('Spiderman 3', ['John', 'jake','Ronald']),('Gravity',['james','jake','john','gerald']),
               ('Terminator',['Anne','Johnny','Peter','Ronald','Neville'])]

count2 = 0
for (movie,name) in list_movies:
    count = 0
    for (name) in list_movies:
        if name != '':
            count += 1
    if count > 3:
        count2 += 1

print(count)
print(count2)


texts:
I wrote this class in order to not having to write tag every time (because of code duplication and risk of typos).

public class TaggedLogger {

    public static final TaggedLogger GLOBAL = new TaggedLogger("Global");

    private final String tag;

    public static TaggedLogger forClass(Class<?> someClass) {
        return new TaggedLogger(someClass.getName());
    }

    public TaggedLogger(String tag) {
        this.tag = tag;
    }

    public void debug(String message) {
        Log.d(tag, message);
    }

    public void info(String message) {
        Log.i(tag, message);
    }

    public void exception(String message) {
        Log.e(tag, message);
    }

    public void exception(String message, Throwable exception) {
        Log.e(tag, message, exception);
    }

    // skipped

}

Using:

public class MainActivity extends Activity {
    private static final TaggedLogger LOGGER = TaggedLogger.forClass(MainActivity.class);

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        LOGGER.debug("Initialization: start");
        init(savedInstanceState);
    }

    // skipped

}

What do you think? Maybe this class is useless?

Help me choose a more appropriate name for this class (if TaggedLogger isn't good) ?


texts: Read strings from a standard input, and find the most duplicated word

texts:
Write a program to read strings from standard input looking for duplicated words.
The program should find places in the input where one word is followed immediately by itself.
Keep track of the largest number of times a single repetition occurs and which word is repeated.
Print the maximum number of duplicates, or else print a message saying that no word was repeated.

For example, if the input is

how now now now brown cow cow

the output should indicate that the word now occurred three times.

#include <iostream>
#include <string>

int main()
{
    using std::cin; using std::cout; using std::endl;
    using std::string;

    // running median
    string most_duplicated_str;
    int most_duplicated_count = 0;

    // loop variables
    string prev_str;
    string new_str;
    int new_duplicate_count = 1;

    while(cin >> new_str)
    {
        if (new_str != prev_str)
        {
            // check and update median
            if (new_duplicate_count > most_duplicated_count)
            {
                most_duplicated_str = prev_str;
                most_duplicated_count = new_duplicate_count;
            }

            // update prev_str
            new_duplicate_count = 1;
            prev_str = new_str;
            continue;
        }

        ++new_duplicate_count;
        prev_str = new_str;
    }

    // check and update median for last word
    if (new_duplicate_count > most_duplicated_count)
    {
        most_duplicated_str = prev_str;
        most_duplicated_count = new_duplicate_count;
    }

    // print result
    if(most_duplicated_count == 0)
        cout << "# No Duplicated Words #\n";
    else
        cout << "Most duplicated word: " << most_duplicated_str << ", " << most_duplicated_count << " times.\n";
}


texts: Finding the differences between two revisions (or objects)

texts:
This detects the difference between two objects (or revisions):

var A = {A: 10, B: 20, C: 30, D: 90, BB: 5, CC: 4, AA: 2};
var B = { B: 22, C: 30, L: 4, KK: 444, A:15};

var difference = diff(A, B);
console.log(difference);
document.write("<pre>"+JSON.stringify(difference, 0, 3)+"</pre>");

function diff(a, b) {
    var result = {removed: "", changed: "", created: "", notChanged: ""};

    var str1 = JSON.stringify(a);
    str1 = str1.slice(1, str1.length - 1);
    var arr1 = str1.split(',');
    var str2 = JSON.stringify(b);
    str2 = str2.slice(1, str2.length - 1);
    var arr2 = str2.split(',');

    var keys1 = Object.keys(a);
    var keys2 = Object.keys(b);
    while (arr1.length || arr2.length) {
        var key1 = keys1[0];
        var key2 = keys2[0];
        var findIndex = keys2.indexOf(key1);
        var findIndex2 = keys1.indexOf(key2);

        if (findIndex >= 0 && findIndex2 >= 0) {
            if (a[key1] == b[keys2[findIndex]]) {
                arr2.splice(findIndex, 1);
                keys2.splice(findIndex, 1);
                keys1.shift();
                result.notChanged += (result.notChanged && ", ") + arr1.shift();
            } else {
                arr1.shift();
                keys1.shift();
                keys2.splice(findIndex, 1);
                result.changed += (result.changed && ", ") + arr2.splice(findIndex, 1);
            }
        } else {
            if (findIndex === -1 && keys1.length) {
                keys1.shift();
                result.removed += (result.removed && ", ") + arr1.shift();
            }
            if (findIndex2 === -1 && keys2.length) {
                keys2.shift();
                result.created += (result.created && ", ") + arr2.shift();
            }
        }
    }
    result.removed = JSON.parse("{" + result.removed + "}");
    result.notChanged = JSON.parse("{" + result.notChanged + "}");
    result.changed = JSON.parse("{" + result.changed + "}");
    result.created = JSON.parse("{" + result.created + "}");

    return result;

}

Is there anything wrong with my snippet? Do you know of another great way?


texts:
I'm brand-new (just joined today) to code review and I am super excited to share my tic tac toe game code with all of you! Please let me know what I could fix up in my program to make it more efficient. Thanks in advance!
P.S. I'm also not sure how to add an actual board to this game (an actual board rather than the way I have done here)
Code:
import time

# Initialize board
board = {1: ' ', 2: ' ', 3: ' ',
         4: ' ', 5: ' ', 6: ' ',
         7: ' ', 8: ' ', 9: ' '}

# Initialize variables
count = 0  # counter to track number of filled slots
winner = False  # boolean to check if anyone won
play = True  # boolen to check if the game should continue
tie = False  # boolean to check if there is a tie
curr_player = ''  # variable to store current player identifier
player_details = []  # list to store player identifier and marker

# Helper functions
def get_player_details(curr_player):
    """Function to get player identifier and marker"""
    if curr_player == 'A':
        return ['B', 'O']
    else:
        return ['A', 'X']

def print_board():
    """Function to print the board"""
    for i in board:
        print(i, ':', board[i], ' ', end='')
        if i % 3 == 0:
            print()

def win_game(marker, player_id):
    """Function to check for winning combination"""
    if board[1] == marker and board[2] == marker and board[3] == marker or \
            board[4] == marker and board[5] == marker and board[6] == marker or \
            board[7] == marker and board[8] == marker and board[9] == marker or \
            board[1] == marker and board[4] == marker and board[7] == marker or \
            board[2] == marker and board[5] == marker and board[8] == marker or \
            board[3] == marker and board[6] == marker and board[9] == marker or \
            board[1] == marker and board[5] == marker and board[9] == marker or \
            board[3] == marker and board[5] == marker and board[7] == marker:

        print_board()
        time.sleep(1)
        print("Player", player_id, "wins!")
        return True

    else:
        return False

def insert_input(slot_num, marker):
    """Function for capturing user inputs"""
    while board[slot_num] != ' ':
        print("spot taken, pick another no.")
        slot_num = int(input())
    board[slot_num] = marker

def play_again():
    """Function to check if player wants to play again"""
    print("Do you want to play again?")
    play_again = input()

    if play_again.upper() == 'Y':
        for z in board:
            board[z] = ' '
        return True
    else:
        print("Thanks for playing. See you next time!")
        return False

# Main program
while play:

    print_board()

    player_details = get_player_details(curr_player)
    curr_player = player_details[0]
    print("Player {}: Enter a number between 1 and 9".format(curr_player))
    input_slot = int(input())

    # Inserting 'X' or 'O' in desired spot
    insert_input(input_slot, player_details[1])
    count += 1

    # Check if anybody won
    winner = win_game(player_details[1], curr_player)
    if count == 9 and not winner:
        print("It's a tie!!")
        tie = True
        print_board()

    # Check if players want to play again
    if winner or tie:
        play = play_again()
        if play:
            curr_player = ''
            count = 0


texts: Multiple 'using' statements in method implementation

texts:
I'm learning WebAPI framework for ASP.NET and C#. Is the following way of handling incoming data correct?

    [HttpPost]
    [ExpiredCookieCheck]
    public IHttpActionResult Auth([FromBody]AuthenticationData authenticationData)
    {
        try
        {
            if (authenticationData == null)
                using (var responseManager = new ResponseManager())
                    return responseManager.PrepareMessage(
                        HttpStatusCode.Unauthorized,
                        "No authentication model was provided in request body.",
                        null,
                        ResponseManager.ResponseType.InterfacePlainText
                    );

            using (var authenticationHandler = new AuthenticationHandler())
            {
                var validationData = authenticationHandler.CheckAuthenticationDataFromWeb(authenticationData);

                if (!validationData.Key)
                    using (var responseManager = new ResponseManager())
                        return responseManager.PrepareMessage(
                            HttpStatusCode.Unauthorized,
                            "Incorrect credentials for authentication.",
                            null,
                            ResponseManager.ResponseType.InterfacePlainText
                        );

                using (var cookieManager = new CookieManager())
                using (var responseManager = new ResponseManager())
                {
                    var authenticationCookie = cookieManager.CreateAuthenticationCookieHeader(Request.RequestUri.Host);
                    cookieManager.SaveAuthenticationCookie(validationData.Value.Id, authenticationCookie);

                    return responseManager.PrepareMessage(
                        HttpStatusCode.OK,
                        null,
                        authenticationCookie,
                        ResponseManager.ResponseType.InterfacePlainText
                    );
                }
            }
        }
        catch (Exception exception)
        {
            using (var responseManager = new ResponseManager())
                return responseManager.PrepareMessage(
                    HttpStatusCode.Unauthorized,
                    exception.ToString(),
                    null,
                    ResponseManager.ResponseType.InterfacePlainText
                );
        }
    }

I'm thinking that I'm using something not correctly. I dislike my way of defining using statements. Maybe it's miles better to define at the beginning of the method all required using statements and then only call internal methods of objects from those using statements.

Also, is it correct to use try/catch block of code in Web API controller method? I'm thinking that it could be incorrect to handle some possible errors in Web API method, couldn't it?


texts:
I recently started using the builder pattern in one of my projects:

public final class DataKey {

    private final long userId;
    private final String uuid;
    private final String deviceId;
    private final int clientId;
    private final long timeout;
    private final FlowEnum flow;

    private DataKey(Builder builder) {
        this.userId = builder.userId;
        this.uuid = builder.uuid;
        this.deviceId = builder.deviceId;
        this.clientId = builder.clientId;
        this.timeout = builder.timeout;

        if (userId == 0 && uuid != null && uuid.isEmpty() && deviceId != null
                && deviceId.isEmpty()) {
            throw new IllegalStateException("You have to pass at least one"
                    + " of the following: userId, uuid or deviceId");
        }
        if (userId != 0) {
            this.flow = FlowEnum.USERFLOW;
        }
        else {
            this.flow = FlowEnum.DEVICEFLOW;
        }
    }

    public static class Builder {
        protected long userId;
        protected String uuid;
        protected String deviceId;
        protected final int clientId;
        protected long timeout = 200L;

        public Builder(int clientId) {
            this.clientId = clientId;
        }

        public Builder setUserId(long userId) {
            this.userId = userId;
            return this;
        }

        public Builder setUuid(String uuid) {
            this.uuid = uuid;
            return this;
        }

        public Builder setDeviceId(String deviceId) {
            this.deviceId = deviceId;
            return this;
        }

        public DataKey build() {
            return new DataKey(this);
        }
    }

    public long getUserId() {
        return userId;
    }

    public String getUuid() {
        return uuid;
    }

    public String getdeviceId() {
        return deviceId;
    }

    public FlowEnum getFlow() {
        return flow;
    }

    public int getclientId() {
        return clientId;
    }

    public long getTimeout() {
        return timeout;
    }
}

I also have an enum which determines whether userId or uuid/deviceId is being used. If userId is present, then the flow type is USERFLOW, otherwise it's DEVICEFLOW.

public enum FlowEnum {
    USERFLOW, DEVICEFLOW
}

While making keys using the Builder class, I will always pass clientId  will pass at least one ID key from these - userId, uuid and deviceId. If by any chance, all the ID keys are missing, then I need to throw an illegal state exception.

I need to prioritize the IDs as well if we are passing multiple IDs instead of one then userId takes the priority first, then uuid and then deviceId.

Can a validation check be done in the build() method? Also, is it thread-safe?

DataKey keys = new DataKey.Builder(100).setUserId(1234L).setUuid("aaaa").setDeviceId("sssss").addTimeout(100L).build();

System.out.println(keys.getFlow());


texts:
I am working on an rc4 encryption implementation for s3fs and I'd like to better optimize my design so I'd like feedback on my encryption/decryption here.

Below is the code which accepts a file descriptor of an open file for a parameter:

void crypty(int fd){
    // Initial steps, read the file into a buffer
    ssize_t placeHolder; // Needed to reduce warnings in compilation
    int fileLength = lseek(fd, 0, SEEK_END); // use of system call to measure offset in accordance to the end of the file, yielding the size
    unsigned char* fileContents; // generate a new c-string pointer
    fileContents = (unsigned char*) calloc(fileLength, sizeof(char)); // assign that pointer to a block of memmory allocated by calloc() that has enough cells for the full file size and the size of each cell is the size of a char or 1byte
    placeHolder = pread(fd, fileContents, fileLength, 0); // read from the file of the file descriptor into the file-contents of size up to the size of fileLength or the length of the file
  // Cast the results into a string for temporary storage
    string plain(reinterpret_cast<char*>(fileContents), fileLength); // strongest cast to the bit level to ensure string is converted fully from c-string ideal for pointers
     int length = plain.size(); // sets length to the length of the string
     unsigned char *buf = (unsigned char*)malloc(length+1); // allocates requested memory of a certain size and then sets the pointer to it to be the pointer I declared prior
     memset(buf, 0, length+1); // fills the memory with blank placeholder, chosen to be 0
     // Grabbing password
     ifstream pass; // opens file stream
     string code; // makes string to grab password
     pass.open("pass.txt"); // opens password file
     if(!pass.good()){
        code = "morganna"; // Fail safe in case s3 doesn't open my file
        pass.close();
     }
     else{
         //Take the passphrase given and turn it into an md5 hash for use in rc4
         getline(pass,code);
         pass.close();
     }
        // Starting open-ssl styled md5 conversion
         char codeConverted[code.length()]; // makes an equivalent length c-string
         strcpy(codeConverted,code.c_str()); // makes an equivalent length copy of the string

         unsigned char encryptedPass[MD5_DIGEST_LENGTH]; // generates an array to begin md-5 hashing
         char convertedPass[16]; // makes a c-string to hold the conversion
         MD5((unsigned char*)&codeConverted, strlen(codeConverted), (unsigned char*)&encryptedPass); // conduct hash

         for (int i = 0; i < 16; i++){
         sprintf(&mdString[i*2], "%02x", (unsigned int)encryptedPass[i]); // takes each digit in hex and converts to ascii equivalence for readability in testing
         }

         for (int i = 0; i < 16;i++){
             convertedPass[i] = encryptedPass[i]; // copy fully converted password into new string
         }
         // Do encryption
         RC4_KEY key;
         RC4_set_key(&key,sizeof(convertedPass), (const unsigned char*)convertedPass);
         RC4(&key, length, (const unsigned char*)plain.c_str(), buf);
         // Write the encryption back to the old file
         string result((char*)buf, length);
         free(buf); // deallocate memory used prior
         // Final result
         const char *outputBuf = result.c_str();
         placeHolder = pwrite(fd, outputBuf, result.length(), 0); // Writes WITHOUT changing the offset from prior
         placeHolder = ftruncate(fd, result.length()); // truncates file
         return; // returns blank because function is void
}


texts: Custom error page with information tokens implementation

texts:
I have created custom error pages (for 500 and 404 http codes) for asp.net web site. After an error, application should create new entry in database in Logs table with information about error. Each entry has unique hash string (it's not primary key) that is returned to end user on error page. With this hash string user can contact with support for advice.

protected void Application_Error(object sender, EventArgs e)
            {
                var exception = Server.GetLastError();

                if (exception is Httpexceptionception httpexceptionception)
                {
                    if (httpexceptionception.GetHttpCode() == 404)
                    {
                        HttpContexceptiont.Current.ClearError();
                        Response.Redirect($"~/NotFound.aspx", false);
                        return;
                    }
                }

                DatabaseLog log = new DatabaseLog()
                {
                    Timestamp = DateTime.UtcNow,
                    Stacktrace = exception.StackTrace
                };

                long id = log.InsertLog();

                string hash;

                using (var md5 = MD5.Create())
                {
                    hash = String.Concat(md5.ComputeHash(BitConverter
                      .GetBytes(id))
                      .Select(x => x.ToString("x2")))
                      .Remove(0, 26);
                }

                log.InterfaceId = hash;
                log.UpdateLog(id);

                HttpContexceptiont.Current.ClearError();
                Response.Redirect($"~/Error.aspx?id={hash}", false);
            }

Following code is responsible for creating new entry in database, id of inserted entry is returned, finally random hash token based on inserted id is generated for user (and inserted entry is updated with this token). I use md5 because I want unique random sequence of characters, but I only want 6 char length token and I don't want use GUID. I think that 6 char tokn length is sufficient. I don't want to return primary key of database entry to error page. Generated hash is returned in query string and this hash string is display to end user.

        public class DatabaseLogger
    {
        public string InterfaceId { get; set; }
        public DateTime Timestamp { get; set; }
        public string Stacktrace { get; set; }

        string _conString = /* ... con string ...*/

        public long InsertLog()
        {
            using (SqlConnection con = new SqlConnection(_conString))
            {
                con.Open();
                string sql = $@"insert into Logs (TimeStamp, Stacktrace) output INSERTED.Id
                                values (@timeStamp, @stackTrace)";
                using (SqlCommand cmd = new SqlCommand(sql, con))
                {
                    cmd.Parameters.AddWithValue("@timeStamp", this.Timestamp);
                    cmd.Parameters.AddWithValue("@stackTrace", this.Stacktrace);
                    return (long)cmd.ExecuteScalar();
                }

            }
        }

        public void UpdateLog(long id)
        {
            using (SqlConnection con = new SqlConnection(_conString))
            {
                con.Open();
                string sql = $"update Logs set InterfaceId = @interfaceId where Id=@id";
                using (SqlCommand cmd = new SqlCommand(sql, con))
                {
                    cmd.Parameters.AddWithValue("@id", id);
                    cmd.Parameters.AddWithValue("@interfaceId", this.InterfaceId);
                    cmd.ExecuteNonQuery();
                }
            }
        }
    }

And table has columns:

Id - long, primary key
InterfaceId - string
Timestamp - DateTime
Stacktrace - string

How can I improve it? Thanks.


texts: Memory issues with Find Strings Problem on InterviewStreet

texts:
Here is the code I wrote for the problem at http://www.interviewstreet.com/recruit/challenges/solve/view/4e1491425cf10/4efa210eb70ac where we need to to print the substring at a particular index from the lexicographicaly-sorted union of sets of substrings of the given set of strings...

import itertools
N = int(raw_input())
S = set()
for n in xrange(N):
    W = raw_input()
    L = len(W)
    for l in xrange(1,L+1):
        S=S.union(set(itertools.combinations(W, l)))
        print set(itertools.combinations(W, l))
print S
M = int(raw_input())
S = sorted(list(S))
print S
for m in xrange(M):
    Q = int(raw_input())
    try:
        print "".join(S[Q-1])
    except:
        print "INVALID"

but it gives me a Memory Error meaning that my code takes up more than 256Mb during execution.

I think the culprit is S=S.union(set(itertools.combinations(W, l))), but can't really think of a more efficient method for harvesting a unique set of substrings from the given set of strings...

Can you suggest an optimal alternative?


texts: Splitting canvas app into separate functions

texts:
This is all in one methods but I would like to see it in individual separate methods. The code works fine but all of the code is in the canvasApp() methods and I would like to see it all in individual methods so that I could call them as below.

Question: How to make all of the code into separate function?

canvasApp();
gameloop();

Code:

function canvasApp() {

  if (!canvasSupport()) {
             return;
        }

    function  drawScreen () {
        context.fillStyle = '#EEEEEE';
        context.fillRect(0, 0, theCanvas.width, theCanvas.height);
        //Box
        context.strokeStyle = '#000000';
        context.strokeRect(1,  1, theCanvas.width-2, theCanvas.height-2);
        // Create ball
        y += speed;
        context.fillStyle = "#000000";
        context.beginPath();
        context.arc(x,y,15,0,Math.PI*2,true);
        context.closePath();
        context.fill();
    }

    theCanvas = document.getElementById('canvasOne');
    context = theCanvas.getContext('2d');

    var speed = 5;
    var y = 10;
    var x = 250;

    function gameLoop() {
        window.setTimeout(gameLoop, 20);
        drawScreen();
    }

    gameLoop();
}


texts:
I'm starting to implement basic sorting algorithms. Criticisms on the implementation is welcome.

#import pudb; pu.db
def bubble_sort(list_):
    """Implement bubblesort algorithm: iterate L to R in list, switching values
    if Left > Right. Break when no alterations made to to list. """
    not_complete = True
    while not_complete:
        not_complete = False
        for val, item in enumerate(list_):
            if val == len(list_)-1: val = 0
            else:
                if list_[val] > list_[val+1]:
                    list_[val], list_[val+1] = list_[val+1], list_[val]
                    not_complete = True
    return list_

if __name__ == '__main__':
    assert bubble_sort(list(range(9))[::-1]) == list(range(9))


texts:
I have the following method which under code review gives me a CA1502 avoid excessive complexity error (although if I suppress the message it will build fine):

private void OrderResults()
{
    switch (_orderColumn)
    {
        case 0:
        default:
            _fitleredResults = _orderDirection.Equals("desc", StringComparison.InvariantCultureIgnoreCase) ? _fitleredResults.OrderByDescending(x => x.Street) : _fitleredResults.OrderBy(x => x.Street);
            break;

        case 1:
            _fitleredResults = _orderDirection.Equals("desc", StringComparison.InvariantCultureIgnoreCase) ? _fitleredResults.OrderByDescending(x => x.Street) : _fitleredResults.OrderBy(x => x.Street);
            break;

        case 2:
            _fitleredResults = _orderDirection.Equals("desc", StringComparison.InvariantCultureIgnoreCase) ? _fitleredResults.OrderByDescending(x => x.City) : _fitleredResults.OrderBy(x => x.City);
            break;

        case 3:
            _fitleredResults = _orderDirection.Equals("desc", StringComparison.InvariantCultureIgnoreCase) ? _fitleredResults.OrderByDescending(x => x.Country) : _fitleredResults.OrderBy(x => x.Country);
            break;

        case 4:
            _fitleredResults = _orderDirection.Equals("desc", StringComparison.InvariantCultureIgnoreCase) ? _fitleredResults.OrderByDescending(x => x.RecID) : _fitleredResults.OrderBy(x => x.RecID);
            break;
    }
}

Explanation of variables:

_filteredResults is an IEnumerable<AddressObject>;
_orderColumn is an int passed in by jQuery DataTables and doesn't match the property indexes (which is why I was mapping it using a switch)

Address object class:

public class AddressObject
{
    public string City { get; set; }
    public string Country { get; set; }
    public string CountryRegionID { get; set; }
    public string Postcode { get; set; }
    public long RecID { get; set; }
    public string Street { get; set; }
}

Is there a way to make this code less complex?


texts: Ruby Symbol Table implementation using Binary Search

texts:
I'm currently going over Robert Sedgewick's Algorithms book. I implemented a Symbol Table using two parallel array one for keys and one for values. The keys array is ordered and the Symbol Table uses binary search to find the position of the elements in the array.
In the practice section, the implementation of the delete and floor method were left as exercises. Here are the directions for delete and floor:

I would like to see if there is any feedback in the implementation of those elements. Specially floor.
Here is the code:
# Binary Search Symbol Table in Ruby
class BinarySearchST
  attr_accessor :n, :keys, :vals

  def initialize
    @n = 0
    @keys = []
    @vals = []
  end

  def size
    @n
  end

  def is_empty?
    @n.zero?
  end

  def get(key)
    return nil if is_empty?

    i = rank(key)
    if i < @n && @keys[i] == key
      @vals[i]
    else
      nil
    end
  end

  def rank(key)
    lo = 0
    hi = @n - 1

    while lo <= hi
      mid = lo + (hi - lo) / 2
      cmp = (key <=> @keys[mid])
      if cmp < 0
        hi = mid - 1
      elsif cmp > 0
        lo = mid + 1
      else
        return mid
      end
    end
    lo
  end

  def put(key, val)
    #  Search for key. Update value if found; grow table if new
    i = rank(key)
    if i < @n && @keys[i] == key
      return @vals[i] = val
    end

    j = @n
    while j > i
      @keys[j] = @keys[j - 1]
      @vals[j] = @vals[j - 1]

      j -= 1
    end

    @keys[i] = key
    @vals[i] = val
    @n += 1
  end

  def min
    @keys[0]
  end

  def max
    @keys[-1]
  end

  def select(k)
    @keys[k]
  end

  def ceiling(key)
    i = rank(key)
    @keys[i]
  end

  def floor(key)
   raise 'ilegalArgumentException' if key == nil
   raise 'NoSuchElementException' if @keys.empty?

    i = rank(key)
    if keys[i] == key || i == 0
      keys[i]
    else
      keys[i - 1]
    end
  end

  def delete(key)
    raise 'ilegalArgumentException' if key.nil?

    i = rank(key)
    @keys.delete_at(i)
    @vals.delete_at(i)
  end
end

bst = BinarySearchST.new

bst.put('s', 0)
bst.put('e', 1)
bst.put('a', 2)
bst.put('r', 3)
bst.put('c', 4)
bst.put('h', 5)
bst.put('e', 6)
bst.put('x', 7)
bst.put('a', 8)
bst.put('m', 9)
bst.put('p', 10)
bst.put('l', 11)
bst.put('e', 12)

binding.pry
p bst.get('e')


texts: Parse a string as a list of words and parse characters

texts:
I'm trying to create a list from a string with items alternating between words and parse characters like ['Hello', ' ', 'World']

Is there a built in function, existing module, or simpler way to achieve something like below? I'm interested in variable chars for parsing.

sample.txt

def parse_chars(string, chars):
    parse_set = {c for c in chars}
    string_list = []
    start = 0
    for index, char in enumerate(string):
        if char not in parse_set:
            if index - start > 0:
                word = string[start:index]
                string_list.append(word)
            string_list.append(char)
            start = index + 1
    document_len = len(string)
    if start != document_len:
        word = string[start:document_len]
        string_list.append(word)
    return string_list

filename = 'sample.txt'
with open(filename) as document_open:
    document_string = document_open.read()
alphanumeric = (map(chr, range(48, 58)) +
                map(chr, range(65, 90)) +
                map(chr, range(97, 123)))

print parse_chars(document_string, alphanumeric)

  [' ', 'A', ' ', 'space', ' ', 'then', ' ', '3', ' ', 'blank', ' ', 'lines', '\n', '\n', '\n', '3', ' ', 'blank', ' ', 'spaces', ' ', ' ', ' ', 'end']


texts: Find binary sequence in NumPy binary array

texts:
As part of creating a software defined receiver and decoder, I want to find sync pulses in weather satellite data.  The data is first digitized to a 0-1 array.

The code below is working. The convolution method is sufficiently fast. The slow method is not.

I was wondering if there was a more efficient or "Pythonic" way to do it.

def findPulseSlow(data, pulse):
    # find indexes of occurrences of pulse in data
    # data and pulse are numpy arrays of 0-1 elements
    # tolerate up to 3 incorrect values
    # takes 2 minutes per Mb on AMD FX8150
    maxerr=3
    return np.fromiter( \
        ( i for i in range(0,len(data)-len(pulse)) \
            if sum(np.logical_xor(data[i:(i+len(pulse))], pulse))<=maxerr ),\
        np.int)

def findPulseConvolve2(data,pulse):
    maxerr=3
    required = len(pulse)-maxerr
    doubleConvolution = np.convolve(data,pulse[::-1])+\
                        np.convolve(1-data,1-pulse[::-1])
    return 1-len(pulse)+np.where(doubleConvolution>=required)[0]

Here is a complete test framework:

testPulse.py

import numpy as np

NOAAsyncA=np.concatenate( ([4*[0],7*[1,1,0,0],8*[0]]) )

def getFixedTestData():
    data = np.zeros(1000)
    syncL = len(NOAAsyncA)
    data[12:(12+syncL)]=NOAAsyncA
    data[257:(257+syncL)]=NOAAsyncA
    data[900:(900+syncL)]=NOAAsyncA
    return ([12,257,900], data)

def getRandomTestData():
    # create random 1 Megabit data, insert 10 NOAA sync pulses in data
    # return correct pulse start locations, data
    global NOAAsyncA
    data = np.random.randint(2, size=1000000)
    # make an ascending list of random spots to insert the pulse
    insertAidx = np.sort(np.random.randint(1000000, size=10))
    # insert the pulses
    for l in insertAidx:
        data[l:(l+len(NOAAsyncA))]=NOAAsyncA
    # return the pulse locations and the data
    return (insertAidx, data)

def findPulseSlow(data, pulse):
    # find indexes of occurrences of pulse in data
    # data and pulse are numpy arrays of 0-1 elements
    # tolerate up to 3 incorrect values
    # takes 2 minutes per Mb on AMD FX8150
    maxerr=3
    return np.fromiter( \
        ( i for i in range(0,len(data)-len(pulse)) \
            if sum(np.logical_xor(data[i:(i+len(pulse))], pulse))<=maxerr ),\
        np.int)

def findPulseConvolve1(data, pulse):
    # tests for locations of 1's only. Bad idea.
    # max error count
    maxerr=0
    required = sum(pulse)-maxerr
    return 1-len(pulse)+np.where(np.convolve(data,pulse[::-1])>=required)[0]

def findPulseConvolve2(data,pulse):
    maxerr=3
    required = len(pulse)-maxerr
    doubleConvolution = np.convolve(data,pulse[::-1])+\
                        np.convolve(1-data,1-pulse[::-1])
    return 1-len(pulse)+np.where(doubleConvolution>=required)[0]

def Test(name,generator,finder):
    global NOAAsyncA
    (correctLocations, data) = generator()
    syncAidx = finder(data, NOAAsyncA)
    passedTest = False
    if len(syncAidx)==len(correctLocations):
        if (syncAidx==correctLocations).all():
            passedTest = True
    print "Test: "+name
    print "Test Result: "+str(passedTest)
    print "found syncA at: "+str(syncAidx)
    print "should be at: "+str(correctLocations)
    return passedTest

Test("fixed findPulseConvolve1", getFixedTestData, findPulseConvolve1)
Test("fixed findPulseConvolve2", getFixedTestData, findPulseConvolve2)
Test("random findPulseConvolve1", getRandomTestData, findPulseConvolve1)
Test("random findPulseConvolve2", getRandomTestData, findPulseConvolve2)


texts: Handlers for checkboxes to select various map features

texts:
I am developing a plugin for QGIS (a Geographic Information Systems) software which uses Python. I have several functions where each of them is connected to a QCheckbox. So when a checkbox is checked, the associated function then does the following:

It reads the text of a QComboBox which contains a list of layers.
Identifies the layer by its name.
Sets an expression to be used.
Selects all features which satisfies the expression.

And when the checkbox is unchecked:

Deselects all features which satisfies the expression.

Is there a way to merge these functions into one or make it more consise?

Here is the code:

def score_0():
    opp_selectedLayerIndex = self.dockwidget.areaOpporunityMap_combo.currentText()
    opp_sel_layer = QgsMapLayerRegistry.instance().mapLayersByName(str(opp_selectedLayerIndex))[0]
    # Select all features where "Score" = NULL
    expr = QgsExpression( """ "Score" IS NULL """ )
    it = opp_sel_layer.getFeatures( QgsFeatureRequest( expr ) )
    ids = [i.id() for i in it]
    area = 0
    if self.dockwidget.score0_checkbox.isChecked():
        opp_sel_layer.select( ids )
    else:
        opp_sel_layer.deselect( ids)

def score_1():
    opp_selectedLayerIndex = self.dockwidget.areaOpporunityMap_combo.currentText()
    opp_sel_layer = QgsMapLayerRegistry.instance().mapLayersByName(str(opp_selectedLayerIndex))[0]
    # Select all features where "Score" = 1
    expr = QgsExpression( """ "Score" = 1 OR "Category" = 'Possible' OR "Category" = 'Favourable'  """ )
    it = opp_sel_layer.getFeatures( QgsFeatureRequest( expr ) )
    ids = [i.id() for i in it]
    area = 0
    if self.dockwidget.score1_checkbox.isChecked():
        opp_sel_layer.select( ids )
    else:
        opp_sel_layer.deselect( ids)

def score_2():
    opp_selectedLayerIndex = self.dockwidget.areaOpporunityMap_combo.currentText()
    opp_sel_layer = QgsMapLayerRegistry.instance().mapLayersByName(str(opp_selectedLayerIndex))[0]
    # Select all features where "Score" = 2
    expr = QgsExpression( """ "Score" = 2 OR "Category" = 'Intermediate' OR "Category" = 'Likely' """ )
    it = opp_sel_layer.getFeatures( QgsFeatureRequest( expr ) )
    ids = [i.id() for i in it]
    area = 0
    if self.dockwidget.score2_checkbox.isChecked():
        opp_sel_layer.select( ids )
    else:
        opp_sel_layer.deselect( ids)

def score_3():
    opp_selectedLayerIndex = self.dockwidget.areaOpporunityMap_combo.currentText()
    opp_sel_layer = QgsMapLayerRegistry.instance().mapLayersByName(str(opp_selectedLayerIndex))[0]
    # Select all features where "Score" = 3
    expr = QgsExpression( """ "Score" = 3 OR "Category" = 'Sensitive' OR "Category" = 'Unlikely' """ )
    it = opp_sel_layer.getFeatures( QgsFeatureRequest( expr ) )
    ids = [i.id() for i in it]
    area = 0
    if self.dockwidget.score3_checkbox.isChecked():
        opp_sel_layer.select( ids )
    else:
        opp_sel_layer.deselect( ids)

def score_4():
    opp_selectedLayerIndex = self.dockwidget.areaOpporunityMap_combo.currentText()
    opp_sel_layer = QgsMapLayerRegistry.instance().mapLayersByName(str(opp_selectedLayerIndex))[0]
    # Select all features where "Score" = 4
    expr = QgsExpression( """ "Score" = 4 OR "Category" = 'Showstopper' """ )
    it = opp_sel_layer.getFeatures( QgsFeatureRequest( expr ) )
    ids = [i.id() for i in it]
    area = 0
    if self.dockwidget.score4_checkbox.isChecked():
        opp_sel_layer.select( ids )
    else:
        opp_sel_layer.deselect( ids)

# Connect checkboxes with their associated functions
self.dockwidget.score0_checkbox.stateChanged.connect(score_0)
self.dockwidget.score1_checkbox.stateChanged.connect(score_1)
self.dockwidget.score2_checkbox.stateChanged.connect(score_2)
self.dockwidget.score3_checkbox.stateChanged.connect(score_3)
self.dockwidget.score4_checkbox.stateChanged.connect(score_4)


texts: Get the brightest rectangle within an image

texts:
I wrote an extension method for bitmaps which finds the brightest rectangle (with specified width & height) within an image.

Hopefully my code comments eliminate any confusion. If not, please let me know what I need to elaborate on.

I would like some help reducing repetitive calls to the conjoined Bitmap.GetPixel & Color.GetBrightness methods during the scanning process. (subsequently improving performance tremendously)

Method:

    public static Rectangle GetBrightestRectangle(this Bitmap bitmap, int width, int height)
    {
        // Each rectangle's value is its average pixel color.
        var rectangles = new Dictionary<Rectangle, float>();

        // Iterate through all possible rectangle points.
        for (var x = 0; x < bitmap.Width - width; x++)
            for (var y = 0; y < bitmap.Height - height; y++)
            {
                var brightnesses = new List<float>();

                // Iterate through all rectangle pixels.
                for (var w = x; w < x + width; w++)
                    for (var h = y; h < y + height; h++)
                    {
                        brightnesses.Add(bitmap.GetPixel(w, h).GetBrightness());
                    }

                rectangles.Add(new Rectangle(x, y, width, height), brightnesses.Average());
            }

        // The brightness ranges from 0.0 through 1.0, where 0.0 represents black and 1.0 represents white.
        return rectangles.OrderByDescending(pair => pair.Value).First().Key;
    }

Demo:

        var bitmap = (Bitmap)Image.FromFile(@"C:\Steve.png");
        var stopwatch = Stopwatch.StartNew();
        var brightestRectangle = bitmap.GetBrightestRectangle(50, 25);
        stopwatch.Stop();
        using (var graphics = Graphics.FromImage(bitmap))
        {
            graphics.DrawRectangle(new Pen(Color.Lime, 5), brightestRectangle);
        }
        bitmap.Save(@"C:\Jobs.png");
        Console.WriteLine($"bitmap.Size: {bitmap.Size}");
        Console.WriteLine($"brightestRectangle: {brightestRectangle}");
        Console.WriteLine($"stopwatch.Elapsed.Seconds: {stopwatch.Elapsed.Seconds}");

Steve.png

Jobs.png

  bitmap.Size: {Width=500, Height=500}

  brightestRectangle: {X=194,Y=99,Width=50,Height=25}

  stopwatch.Elapsed.Seconds: 37


texts:
I am just trying to use ASP.NET MVC using repository pattern.  Am I doing something wrong here?

Model - Contains the model

public class Contact
{
    public int Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string EmailAddress { get; set; }
}

Repository interface - Interface

public interface IContactRepository
{
    void Create(Contact contact);
    void Delete(int contactId);
    void Save(Contact contact);
    Contact Retrieve(int contactId);
    IEnumerable<Contact> Select();
}

Repository class

public class ContactRepository : IContactRepository
{
    private AddressBookDb addressBookdb = new AddressBookDb();

    public void Create(Contact contact)
    {
        addressBookdb.Contacts.Add(contact);
        addressBookdb.SaveChanges();
    }

    public void Save(Contact contact)
    {
        Delete(contact.Id);
        Create(contact);
    }

    public void Delete(int contactId)
    {
        Contact contact = Retrieve(contactId);
        if (contact != null)
        {
            addressBookdb.Contacts.Remove(contact);
            addressBookdb.SaveChanges();
        }
    }

    public Contact Retrieve(int contactId)
    {
        return addressBookdb.Contacts.FirstOrDefault<Contact>(c => c.Id == contactId);
    }

    public IEnumerable<Models.Contact> Select()
    {
        return addressBookdb.Contacts.ToList<Contact>();
    }
}

Controller class

public class ContactController : Controller
{
    IContactRepository contactRepository = null;
    public ContactController() : this (new ContactRepository())
    {

    }

    public ContactController(IContactRepository contactRepository)
    {
        this.contactRepository = contactRepository;
    }

    [HttpPost]
    public ActionResult Edit(Contact contact)
    {
        if (ModelState.IsValid)
        {
            contactRepository.Save(contact);
            return RedirectToAction("Index");
        }
        return View(contact);
    }
}


texts:
I've been trying to emulate MS Windows behavior on my OS X and close processes that do not have a window.

What I'd really like to do is "quit" the process on clicking the red "x" button.  Instead, I've managed to code this workaround, which constantly runs in the background.

(see my question here)

It kind of defeat the purpose of not having background apps running, I suppose.

Since I own my Mac for about 2 weeks, I'm not sure if my script is "good" in terms of memory consumption, etc. (right now: CPU = 0, Memory = 12.3 MB, Threads = 3).

How would you guys do it?  I'm open to suggestions.

#!/usr/bin/osascript

-- INICIO DAS FUNCOES EXTRAS
set app_path to path to current application
set app_name to get name of me
set myPath to path to me
tell application "Finder" to set myFolder to (container of myPath) as string
set commonScript to load script alias ((myFolder) & "FuncoesExtras.scpt")
-- FIM DAS FUNCOES EXTRAS

set WhiteList to {app_name, "App Store", "iTunes", "Finder", "Mail"}

repeat

    tell application "System Events"
        repeat with this_app in (get processes whose background only is false and windows is {})
            set NomeDoApp to the name of this_app
            if NomeDoApp is not in WhiteList then
                try
                    tell NomeDoApp to quit
                    log_event("App " & NomeDoApp & " encerrado com sucesso", "FecharProgramas") of commonScript
                on error
                    do shell script "killall " & quoted form of NomeDoApp
                    log_event("Forcando interrupcao do App " & NomeDoApp, "FecharProgramas") of commonScript
                end try
            end if
        end repeat
    end tell

    tell application "System Events" to set myPID to (unix id of processes whose name is app_name)
    do shell script ("/usr/bin/renice 18 " & myPID)

    delay 10

end repeat


texts: Weather-App for terminal done with node.js, OpenWeatherMap and ES6 promises

texts:
I've started to learn node.js a few weeks ago.
This weekend I've made a tiny app for to recap what I've learned so far.

It uses OpenWeatherMap as a data-source.

The user calls the main file (controller.js) via terminal and assigns a string (a location, usually town) as the one and only parameter.

The app then prints some current weather-data for the named location to the screen.

Here's my source-code:

File 'controller.js'

var model = require('./model');
var view = require('./view');

var location = process.argv[2];

if (location && location.length > 0) {

  model
    .requestData(location).then(function(weatherData) {
      view.displayWeatherReport(weatherData);
    }).catch(function(errorMessage) {
      console.log(errorMessage);
    });
} else {
  console.log('Please provide a valid location as first argument.');
}

File 'model.js'

var request = require('request');

module.exports.requestData = function(searchCrit) {

  var ret = new Promise(function(resolve, reject) {
    var url =
      'http://api.openweathermap.org/data/2.5/forecast?units=metric&q=' +
      searchCrit +
      '&mode=json&appid=efcd313fa7a139f2fb20de306648eb8d';

    request(url, function(error, response, body) {
      if (!error && response.statusCode === 200) {
        // If everything is fine, then parsing should work.
        //  If not an error is thrown and it goes into the
        //  else-branch.
        try {
          var weatherData = JSON.parse(body);

          resolve(weatherData);
        } catch (e) {
          reject('URL could not be resolved. ' +
            'Hint from the provider was received ' +
            'instead of JSON.');
        }
      } else {
        reject('Requesting data from openweathermap has failed completely.\n' + 'Please check the provided location-argument.');
      }
    });
  });

  return ret;
};

File 'view.js'

module.exports.displayWeatherReport = function(weatherData) {

  let icon = weatherData.list[0].weather[0].icon;
  let iconToDisplay = '';

  // See : https://openweathermap.org/weather-conditions
  if (icon === '01d') {
    iconToDisplay = '--- O -----';
  } else if (icon === '02d') {
    iconToDisplay = '()() O ';
  } else if (icon === '03d') {
    iconToDisplay = '( ) ( )( )';
  } else if (icon === '04d') {
    iconToDisplay = '( ) ()';
  } else if (icon === '09d') {
    iconToDisplay = '"/"( ) ()';
  } else if (icon === '10d') {
    iconToDisplay = '"/"( ) o';
  } else if (icon === '11d') {
    iconToDisplay = '!!( ) ()';
  } else if (icon === '13d') {
    iconToDisplay = 'oo( )o ()';
  } else if (icon === '50d') {
    iconToDisplay = ' ~~~ ';
  } else {
    iconToDisplay = 'No icon available for current weather condition.';
  }

  let weatherDataToDisplay = `\n Location: ${weatherData.city.name}
 Temperature: ${weatherData.list[0].main.temp} degree Celsius
 Min. Temperature: ${weatherData.list[0].main.temp_min} degree Celsius
 Max. Temperature: ${weatherData.list[0].main.temp_max} degree Celsius
 Weather state: ${weatherData.list[0].weather[0].main} ${iconToDisplay}`;

  console.log(weatherDataToDisplay);
};

Is everything done in a good way? Or has the code flaws which should be improved?

Okay. My ASCII-art skills have to be improved. I admit ...

But seriously and important:

Is my implementation of the MVC-pattern correct?

An according answer would help me to feel more confident about the topic MVC.

But other hints and recommendations are also welcomed. :)


texts:
I have written this Sieve of Eratosthenes. This is a bit of software that will find all of the prime numbers between 2 and n, where n is a user-defined value.
The code does seem quite bloated and any help at making it more elegant would be great. I know that I am not very good at list comprehensions and if it is possible to utilise them more in this situation I would love to know how.
def sieve_of_eratosthenes(n):
    """
    Create a Sieve of Eratosthenes to find all of the prime
    numbers between 2 and n
    """
    n += 1

    num_list = []
    [num_list.append(i) for i in range(2, n)]

    test = 0
    while test < len(num_list):
        for i, x in enumerate(num_list):
            if num_list[i] % num_list[test] == 0:
                if num_list[i] != num_list[test]:
                    del num_list[i]
        test += 1
    return num_list


texts: Writing to a csv file in a customized way using scrapy

texts:
I've written a script in scrapy to grab different names and links from different pages of a website and write those parsed items in a csv file. When I run my script, I get the results accordingly and find a data filled in csv file. I'm using python 3.5, so when I use scrapy's built-in command to write data in a csv file, I do get a csv file with blank lines in every alternate row. Eventually, I tried the below way to achieve the flawless output (with no blank lines in between). Now, It produces a csv file fixing blank line issues. I hope I did it in the right way. However, if there is anything I can/should do to make it more robust, I'm happy to cope with.

This is my script which provides me with a flawless output in a csv file:

import scrapy ,csv
from scrapy.crawler import CrawlerProcess

class GetInfoSpider(scrapy.Spider):
    name = "infrarail"

    start_urls= ['http://www.infrarail.com/2018/exhibitor-profile/?e={}'.format(page) for page in range(65,70)]

    def __init__(self):
        self.infile = open("output.csv","w",newline="")

    def parse(self, response):
        for q in response.css("article.contentslim"):
            name = q.css("h1::text").extract_first()
            link = q.css("p a::attr(href)").extract_first()
            yield {'Name':name,'Link':link}

            writer = csv.writer(self.infile)
            writer.writerow([name,link])

c = CrawlerProcess({
    'USER_AGENT': 'Mozilla/5.0',
})
c.crawl(GetInfoSpider)
c.start()

Btw, I used .CrawlerProcess() to be able to run my spider from sublime text editor.


texts: Read text and return lists of different parts of speech

texts:
This function reads through text and returns lists of all the different parts of speech (nouns, verbs, proper nouns, etc.). My sense is that there is a more elegant and probably more efficient way to accomplish the same thing. The code feels really repetitive so I'm hoping there is a better way.

import nltk

def find_pos(tokens):

    '''This function accepts tokens as an input and returns a list of all
    the parts of speech.
    Note that some words are return twice:
    -Nouns are separated into common and proper as well as grouped together
    -Modals are added to verbs are well as returned separately'''

    tagged = nltk.pos_tag(tokens)

    # Now we devide them into groups
    # Note that IN can be either a preposition or a conjunction, for now we're going to list it with the prepositions
    common_noun_pos = ['NN', 'NNS']
    common_nouns = []
    verb_pos = ['VB', 'VBD', 'VBG', 'VBN', 'VBP', 'VBZ']
    verbs = []
    adjective_pos = ['JJ', 'JJR', 'JJS']
    adjectives = []
    pronoun_pos = ['PRP', 'PRP$', 'WP', 'WP$']
    pronouns = []
    adverb_pos = ['RB', 'RBR', 'RBS', 'WRB']
    adverbs = []
    proper_noun_pos = ['NNP', 'NNPS']
    proper_nouns = []
    conjunction_pos = ['CC']
    conjunctions = []
    preposition_pos = ['IN', 'TO']
    prepositions = []
    interjection_pos = ['UH']
    interjections = []
    modal_pos = ['MD']  # But these are also verbs, include them
    modals = []
    tagged_other_pos = ['CD', 'DT', 'EX', 'FW', 'LS', 'PDT', 'POS', 'RP', 'SYM', 'WDT']
    tagged_others = []
    other = []

    for idx, token in enumerate(tagged):
        if token[1] in common_noun_pos:
            common_nouns.append(token)
        elif token[1] in verb_pos:
            verbs.append(token)
        elif token[1] in adjective_pos:
            adjectives.append(token)
        elif token[1] in pronoun_pos:
            pronouns.append(token)
        elif token[1] in adverb_pos:
            adverbs.append(token)
        elif token[1] in proper_noun_pos:
            proper_nouns.append(token)
        elif token[1] in conjunction_pos:
            conjunctions.append(token)
        elif token[1] in preposition_pos:
            prepositions.append(token)
        elif token[1] in interjection_pos:
            interjections.append(token)
        elif token[1] in modal_pos:
            modals.append(token)
        elif token[1] in tagged_other_pos:
            tagged_others.append(token)
        else:
            other.append(token)

    verbs.append(modals)
    nouns = common_nouns + proper_nouns
    parts_of_speech = [nouns, common_nouns, verbs, adjectives, pronouns, adverbs, proper_nouns, conjunctions,
                       prepositions, interjections, modals]
    return parts_of_speech

Here some code to test it:

text = 'It is a truth universally acknowledged, that a single man in possession of a good fortune, must be in ' \
       'want of a wife. However little known the feelings or views of such a man may be on his first entering a ' \
       'neighbourhood, this truth is so well fixed in the minds of the surrounding families, that he is ' \
       'considered the rightful property of some one or other of their daughters. '
tokens = nltk.word_tokenize(text)
find_pos(tokens)


texts: Leetcode 38: The “count-and-say” sequence

texts:
38. Count and Say

  The count-and-say sequence is the sequence of integers with the first five terms as following:

1.     1
2.     11
3.     21
4.     1211
5.     111221

  1 is read off as "one 1" or 11.

  11 is read off as "two 1s" or 21.

  21 is read off as "one 2, then one 1" or 1211.

  Given an integer n where 1 ≤ n ≤ 30, generate the nth term of the count-and-say sequence.

  Note: Each term of the sequence of integers will be represented as a string.

With iteration:

How to reduce 3 kinds of situation to one solution?

class Solution {
    func countAndSay(_ n: Int) -> String {
        var ans = ["1"]
        var temp: [String], j: Int
        for _ in 1..<n{
            //  from the beginning 1 to what we what
            j = 1
            temp = []
            for i in 1..<ans.count{
                if ans[i - 1] == ans[i]{
                    j += 1
                    //  Situation one: the current is equal to the previous ( util the last )
                }
                else{
                    temp.append(String(j))
                    temp.append(ans[i-1])
                    //  Situation two: the current is not equal to the previous ( util the last )
                    j = 1
                }
            }
            //  Situation three: the last value
            temp.append(String(j))
            temp.append(ans.last!)
            ans = temp
            print(ans.reduce("", +))
        }
        return ans.reduce("", +)
    }
}

With Recursion, which is a little leaner.

class Solution {
    func countAndSay(_ n: Int) -> String {
        if n == 1 {
            return "1"
        }
        let str = countAndSay(n-1)
        let arr = Array(str).map{Int(String($0))}
        var last = arr[0]!
        var temp : [(count: Int, val: Int)] = [(1, last)]
        for num in arr[1...]{
            if last == num{
                var final = temp.last!
                final.count += 1
                temp.removeLast()
                temp.append(final)
            }
            else{
                temp += [(1, num!)]
            }
            last = num!
        }
        var result = ""
        for key in temp{
            result += "\(key.0)\(key.1)"
        }
        return result
    }
}

How to go on doing some improvement?


texts:
I want to pass a predicate into quick sort. The issue I'm running into is that the predicate must have two arguments, the pivot and the element of the list's tail. As far as I know though, predicates can only have 1 argument. Here's what I have so far (it runs, I just want to improve it):

import Data.List

quicksort :: [a] -> (a -> a -> Bool) ->  [a]
quicksort [] _ = []
quicksort (x:xs) pf = quicksort left pf ++ [x] ++ quicksort right pf
    where   pred = pf x
            pt = partition pred xs
            left = fst pt
            right = snd pt


texts: Project Euler Problem 33 - digit canceling fractions

texts:
Problem:

  The fraction \$(\dfrac{49}{98})\$ is a curious fraction, as an inexperienced
  mathematician in attempting to simplify it may incorrectly believe
  that \$(\dfrac{49}{98}) = (\dfrac{4}{8})\$, which is correct, is obtained by cancelling the 9s.

  We shall consider fractions like, \$(\dfrac{30}{50}) = (\dfrac{3}{5})\$, to be trivial examples.

  There are exactly four non-trivial examples of this type of fraction,
  less than one in value, and containing two digits in the numerator and
  denominator.

  If the product of these four fractions is given in its lowest common
  terms, find the value of the denominator.

This is some rough code -- this one was a lot harder than I expected it to be. Please help me optimize.

from timeit import default_timer as timer

start = timer()
fractions_that_work = []

def a_common_element(list_a, list_b):
    count = 0
    common = 0
    for m in list_a:
        for n in list_b:
            if m == n:
                count += 1
                common = m
    if count == 1:
        return common
    return False

for numerator in range(10, 100):
    for denominator in range(numerator + 1, 100): # denom must be > num
        n_digits = sorted([int(x) for x in str(numerator)])
        d_digits = sorted([int(x) for x in str(denominator)])
        common = a_common_element(n_digits, d_digits)
        if common:
            n_digits.remove(common)
            d_digits.remove(common)
            n_rem = n_digits[0]
            d_rem = d_digits[0]
            if 0 not in n_digits and 0 not in d_digits:
                if float(numerator) / denominator == float(n_rem) / d_rem:
                    fractions_that_work.append([numerator, denominator])
product_of_fractions = [1, 1]
for frac in fractions_that_work:
    product_of_fractions[0] *= frac[0]
    product_of_fractions[1] *= frac[1]

start = timer()
ans = product_of_fractions[1] / product_of_fractions[0]
elapsed_time = (timer() - start) * 1000 # s --> ms

print "Found %d in %r ms." % (ans, elapsed_time)


texts: Decoding data from a MIDI controller as eight buttons

texts:
I thought about using loops but I don't know how I would do this. if I used for loops would it work the same way as the code down below?

if data[-8]=="B" and data[-5]=="1" and data[-4]=="6":
    print("Button1")
if data[-8]=="B" and data[-5]=="1" and data[-4]=="7":
    print("Button2")
if data[-8]=="B" and data[-5]=="1" and data[-4]=="8":
    print("Button3")
if data[-8]=="B" and data[-5]=="1" and data[-4]=="9":
    print("Button4")
if data[-8]=="B" and data[-5]=="1" and data[-4]=="A":
    print("Button5")
if data[-8]=="B" and data[-5]=="1" and data[-4]=="B":
    print("Button6")
if data[-8]=="B" and data[-5]=="1" and data[-4]=="C":
    print("Button7")
if data[-8]=="B" and data[-5]=="1" and data[-4]=="D":
    print("Button8")

EDIT: When I press a button it prints out the number ex. If I press button one it prints button one. And it would work the same for other at and given time. It'll be on a while true loop.


texts:
EDIT: Thanks everyone for your answers, this is moving quickly now and it's always essential to get better with design and best practice!

I am loading in an excel file to a dataset using ExcelDataReader. I then need to create a *.csv file with the data.

Currently for the excel sheet I'm working with I have about 40 columns and 30k rows of data. The approach I'm taking takes about 2 minutes to complete.

The second snippet is the offender.

public static Stream SaveAsCsv(Stream excelFile, string filename)
{
    MemoryStream newCSV = new MemoryStream();

    string test = excelFile.ToString();

    IExcelDataReader reader = null;
    if (filename.EndsWith(".xls"))
    {
        reader = ExcelReaderFactory.CreateBinaryReader(excelFile);
    }
    else if (filename.EndsWith(".xlsx"))
    {
        reader = ExcelReaderFactory.CreateOpenXmlReader(excelFile);
    }

    //Read was empty so return a null stream in return
    if (reader == null)
        return newCSV;

    var headers = new List<string>();

    var ds = reader.AsDataSet(new ExcelDataSetConfiguration()
    {
        ConfigureDataTable = (tableReader) => new ExcelDataTableConfiguration()
        {
            UseHeaderRow = true,

            ReadHeaderRow = rowReader =>
            {
                for (var i = 0; i < rowReader.FieldCount; i++)
                    headers.Add(Convert.ToString(rowReader.GetValue(i)));
            },

            FilterColumn = (columnReader, columnIndex) =>
            !headers[columnIndex].ToString().ToUpper().Contains("SKIP")
        }
    });
    var csvContent = string.Empty;
    int colCount = ds.Tables[0].Columns.Count;

This for operation is what takes two minutes to complete, everything else is not a problem:

    for (int row_no = 0; row_no < ds.Tables[0].Rows.Count; row_no++)
    {
        var arr = new List<string>();
        if (row_no == 0)
        {
            for (int i = 0; i < colCount; i++)
            {
                arr.Add(ds.Tables[0].Columns[i].ColumnName);
            }
        }
        else
        {
            object[] objarr = ds.Tables[0].Rows[row_no].ItemArray;

            arr = ((IEnumerable)objarr).Cast<object>()
                         .Select(x => x.ToString())
                         .ToList();
        }
        csvContent += string.Join("|", arr) + "\n";
    }

    StreamWriter csv = new StreamWriter(newCSV);
    csv.Write(csvContent);
    csv.Flush();
    csv.BaseStream.Seek(0, SeekOrigin.Begin);

    return csv.BaseStream;
}


texts: String-formatting and printing functions

texts:
As a small exercise I have written some string formatting and printing functions in C++11. I would like a bit of code review, not so much on the merits of using this over something like std::stringstream or boost::format, but simply whether or not my implementation makes sense. I realize that simply performing string replacements isn't that robust and a more sophisticated version would actually parse the format string. I especially would like to know if my use of things like rvalue references, std::forward, std::move and variadic templates are correct, as these are the main features I was focusing on in this exercise.

#include <boost/algorithm/string/replace.hpp>
#include <boost/lexical_cast.hpp>
#include <iostream>
#include <string>
#include <utility>
#include <cstdio>

namespace detail
{
    template <unsigned N, class T>
    void format_impl(std::string& str, T&& item)
    {
        char find[8];
        snprintf(find, 8, "{%d}", N);
        auto replace = boost::lexical_cast<std::string>(std::forward<T>(item));
        boost::replace_all(str, find, replace);
    }

    template <unsigned N, class Head, class... Tail>
    void format_impl(std::string& str, Head&& head, Tail&&... tail)
    {
        detail::format_impl<N>(str, std::forward<Head>(head));
        detail::format_impl<N+1>(str, std::forward<Tail>(tail)...);
    }
}

template <class... Args>
std::string format(const std::string& fmt, Args&&... args)
{
    std::string temp = fmt;
    detail::format_impl<0>(temp, std::forward<Args>(args)...);
    return temp;
}

template <class... Args>
std::string format(std::string&& fmt, Args&&... args)
{
    std::string temp = std::move(fmt);
    detail::format_impl<0>(temp, std::forward<Args>(args)...);
    return temp;
}

template <class... Args>
void print(const std::string& fmt, Args&&... args)
{
    std::cout << format(fmt, std::forward<Args>(args)...);
}

template <class... Args>
void print(std::string&& fmt, Args&&... args)
{
    std::cout << format(std::forward<std::string>(fmt), std::forward<Args>(args)...);
}

int main()
{
    print("Hello, {0}! The answer is {1}.\n", "World", 42);
}


texts: Turn-based game setting properties for playcards

texts:
I am programming with Java (server side) and JavaScript a card game and I do not know how to give properties (on server side) to every card that I create. For a match I need 20 different cards from a complete set of cards (52). Now I want that these 20 cards get a value (Ace, 2, 3, 4, 5, 6, 7, 8, 9, 10, Jack, Queen, King) and a symbol (like Spades, Hearts, Diamonds and Clubs).

How should I approach this? I thought using if clauses like I used on client side would be ok (JavaScript):

p.initialize = function (id) {

this.card= new createjs.Bitmap(images[id]);

// HEARTS
if (id > 0 && id < 14)
{
this.symbol = Card.HEARTS;
}

// DIAMONDS
else if (id > 13 && id < 28)
{
this.symbol = Card.DIAMONDS;
}

// CLUBS
else if(id > 27 && id <42)
{
this.symbol = Card.CLUBS;
}

// SPADES
else if(id > 41 && id <53)
{
this.symbol = Card.SPADES;
}

this.VALUE = id%13;
};

This is the way I did it on client side. Should I do the same with Java or are there better possibilities?


texts: Make a class hierarchy data classes using a meta class

texts:
I am redesigning a library, which at the moment uses a lot of boilerplate code in a double hierarchy of classes / metaclasses, to attempt to make it much cleaner and reuse as much as possible what dataclasses already provides.
For the library itself it is not an issue to add the @dataclass decorator when defining each and every subclasses.
However, and this is my first question: shouldn't it be the default behavior, that if a class inherits from a dataclass then it itself becomes a dataclass?
But the issue is that users of the library should be able to create subclasses without knowing about all the internal details (so they should not be asked to decorate the subclasses they define).
My solution uses a meta class to force the decorator when creating the class:
from __future__ import annotations
from typing import Any, Tuple, Dict
from abc import ABC, ABCMeta
from dataclasses import dataclass, field

class CommandType(ABCMeta):
    def __new__(mcs, name: str, bases: Tuple[CommandType, type, ...], dct: Dict[str, Any]):
        return dataclass(super().__new__(mcs, name, bases, dct))

    def __getattribute__(cls, item):
        try:
            return super().__getattribute__('__dataclass_fields__')[item]
        except (KeyError, AttributeError):
            pass
        return ABCMeta.__getattribute__(cls, item)

    def __contains__(cls, item) -> bool:
        return item in cls.__dataclass_fields__

class Command(ABC, metaclass=CommandType):
    def __init_subclass__(cls, **kwargs):
        ...  # This will dynamically add fields based on configuration files

class SubCommandA(Command):
    A: float = field(metadata={'comment': 'This is parameter A'})

class SubCommandB(Command):
    B: float = field(metadata={'comment': 'This is parameter B'})

This seems to be working nicely for what I want:
SubCommandA(A=1).A  # 1
SubCommandB.B # Field(...)

Does that make sense? Is there any obvious issue with the implementation?
More as a thought than as a question my custom implementation of __getattr__ in the meta class seems quite useful. Am I missing something? Why doesn't dataclass provides that mechanism as well?
I also initially tried to put all that in __init_subclass__ instead of a dedicated meta class, as this was mostly the point of my refactoring, but it doesn't seem feasible.


texts:
I am building a simple adventure game that has "upgrades" feature.
In this game, user controls one player, that can be upgraded to increase things such as:

Amount of gold earned
Maximum health
Attack power
(more of this would be added later, for example: defense upgrade, experience, etc.)

An "upgrade" has a max level cap, effects on each level of upgrade, and the cost for each upgrade.

Here's my current approach.

This is my Upgrades class, containing all possible upgrades:

public class Upgrades {

    public static final int GOLD_LEVEL_CAP = 10;
    public static final float GOLD_EFFECT_PER_LEVEL = 0.01f;
    public static final int[] GOLD_UPGRADE_COSTS = {
        100, 200, 300, 400, 500,
        600, 700, 800, 900, 1000
    };

    public static final int HEALTH_LEVEL_CAP = 10;
    public static final int HEALTH_EFFECTS_PER_LEVEL = 100;
    public static final int[] HEALTH_UPGRADE_COSTS = {
        100, 200, 300, 400, 500,
        600, 700, 800, 900, 1000
    };

    public static final int POWER_LEVEL_CAP = 5;
    public static final float POWER_EFFECT_PER_LEVEL = 0.05f;
    public static final int[] POWER_UPGRADE_COSTS = {
        1000, 2000, 3000, 4000, 5000
    };

}

And this is the class that stores the current upgrades: (owned by Player class)

public class UpgradeProgress {

    private int goldUpgradeLevel = 0;
    private int healthUpgradeLevel = 0;
    private int powerUpgradeLevel = 0;

    public void upgradeGold() {
        if (goldUpgradeLevel < Upgrades.GOLD_LEVEL_CAP) {
            goldUpgradeLevel++;
        }
    }

    // Getter
    public int getGoldUpgradeLevel() {
        return goldUpgradeLevel;
    }

    // and so on..
    // same for Health and Power
}

However, if I want to add a new upgrade, for example, I wanted to add a "Defense Upgrade". I should modify both Upgrades and UpgradeProgress classes.
Is this efficient and acceptable?
Or is there any better approach?


texts: Is a filter a good way to accomplish a dynamic class in angular?

texts:
I want to apply a different badge color with bootstrap depending on a number.

I wrote a filter to accomplish this...

angular.module('Demo')
    .filter('reserveStatus', function() {
        return function(num) {
            var klass = "";

            num = parseInt(num, 10);

            if (num > 2 && num < 5) {
                klass = "alert-success";
            }
            else if (num >= 5 && num < 10) {
                klass = "alert-warning";
            }
            else if (num >= 10) {
                klass = "alert-danger";
            }

            return klass;
        }
    });

And it's used with interpolation like this...

Is this a good way to accomplish this?


texts: Managing friend requests on a social media website in Django

texts:
So i created a social media website in django and here is how i managed accepting friend requests and showing friends posts in home page.
Would it be better to do this operation in models.py file, create a function and call it in views using django forms? My concern is security
def home(request):
    if request.user.is_authenticated:
        people = []
        posts = []
        for eachs in request.user.friend_requests.all():
            person_prof = User.objects.get(id=eachs.current_id)
            people.append({'id':person_prof.id, 'profile':person_prof.profile, 'picture':person_prof.profile.picture.url, 'isfriend':False, 'sent':False, 'rec':True})

        for friend in request.user.friends.all():
            user = User.objects.get(id=friend.friend_id)
            for post in user.post.all():
                posts.append({'body':post.body, 'image':post.image.url, 'created':post.created, 'fr_name':user.profile.wholename(),'user_id':user.id, 'pr_pic':user.profile.picture.url,'post_id':post.id, 'comments':[ {'comment':comment.comment, 'user':comment.user} for comment in post.comments.all()]})

        return render(request, 'newsfeed.html',{'people':people,'posts':posts})
    else:
        return render(request, 'landing_page.html',{})

Here the post = [] array is asking the database for all the posts of current user's friends. And the people = [] array is all the friend requests that are not accepted by the current user yet.


texts:
The following pascal script needs a bit of context for it's purpose to be understood. For those who don't give about purpose, feel free to skip ahead.

Background

A game I'm terribly fond of has a couple of levels which have nothing to do with the rest of the game. One of those is a puzzle: Alpha Sector::virgilw::Brain

When you open the game, it looks like this:

Turns out you need to connect all the 8 red dots to the emitter like this:

All dots must be clicked in a specific sequence. If a dot is clicked and allowed to switch, it will light up if not already lit up. If it was already lit up it will darken again. The sequence to light up the 8th dot looks like this:

1 2 1 3 1 2 1 4
1 2 1 3 1 2 1 5
1 2 1 3 1 2 1 4
1 2 1 3 1 2 1 6
1 2 1 3 1 2 1 4
1 2 1 3 1 2 1 5
1 2 1 3 1 2 1 4
1 2 1 3 1 2 1 7
1 2 1 3 1 2 1 4
1 2 1 3 1 2 1 5
1 2 1 3 1 2 1 4
1 2 1 3 1 2 1 6
1 2 1 3 1 2 1 4
1 2 1 3 1 2 1 5
1 2 1 3 1 2 1 4
1 2 1 3 1 2 1 8

The mathematically inclined can probably tell us what such a sequence is called, but it should be obvious to the rest of us that the first 7 characters are always the same and only the 8th varies.

Now, there's an achievement for lighting up all 8 dots within 60 seconds. Since it's already 128 clicks for lighting up the 8th one alone, I decided to automate the process using SCAR Divi (manual), an environment running Pascal scripts which allows you to automate keyboard presses and mouse movements.

Code

The resulting code is ugly, but I was mainly looking for fast code. This means it may not be up to par with Pascal-style and I took a short-cut wherever I thought it would influence the execution speed.

I'm looking for improvements on readability wherever this does not hurt the performance in any way. I've written a fair bit of Pascal but I've always been a little fuzzy on what did and didn't impact performance. General tips about this are welcome.

The most used procedure is MnC(x, y), short for Move'n'Click. It moves the mouse to whatever coordinate you give it, clicks once with the left mouse-button and halts in between to give the rest of the computer time to catch up. Or whatever it does in that time, but it breaks terribly if it doesn't wait long enough.

All values are hardcoded. I'm aware I can put them at the front of the program as global variables, but I wasn't sure whether the additional look-up would penalize performance. Current script manages to win in 21.86 seconds :-)

virgilwBrain.scar

Procedure MnC(x,y : integer);
begin
  MoveMouse(x,y);
  Wait(30);
  ClickMouse(x,y,false);
  Wait(29);
end;

Procedure hit1();
begin
  MnC(421,298);
end;

Procedure hit2();
begin
  MnC(470,311);
end;

Procedure hit3();
begin
  MnC(500,318);
end;

Procedure hit4();
begin
  MnC(539,325);
end;

Procedure hit5();
begin
  MnC(577,325);
end;

Procedure hit6();
begin
  MnC(611,318);
end;

Procedure hit7();
begin
  MnC(655,311);
end;

Procedure hit8();
begin
  MnC(694,298);
end;

Procedure line();
begin
  hit1;
  hit2;
  hit1;
  hit3;
  hit1;
  hit2;
  hit1;
end;

begin
  line;
  hit4;
  line;
  hit5;
  line;
  hit4;
  line;
  hit6;
  line;
  hit4;
  line;
  hit5;
  line;
  hit4;
  line;
  hit7;
  line;
  hit4;
  line;
  hit5;
  line;
  hit4;
  line;
  hit6;
  line;
  hit4;
  line;
  hit5;
  line;
  hit4;
  line;
  hit8;

  line;
  hit4;
  line;
  hit5;
  line;
  hit4;
  line;
  hit6;
  line;
  hit4;
  hit1;
  hit2;
end.


texts: Strip a newline and add more text to a Go bytes.Buffer

texts:
I wrote a little timer middleware to append the request duration to the end of the log message returned by the excellent Gorilla Toolkit's CombinedLoggingHandler from the handlers package.

That handler accepts an io.Writer and an http.Handler, and fills the Writer with a newline-terminate string containing the Apache Combined Format log entry for the current server request. I would like to remove the trailing newline and add " completed in xxx", where xxx is the amount of time the request took.

The following code works, but I am not sure that I made the best use of the Go bytes.Buffer in the way I stripped the newline:

func timerHandler(h http.Handler) http.Handler {
    return http.HandlerFunc(func(res http.ResponseWriter, req *http.Request) {
        var b bytes.Buffer
        hand := handlers.CombinedLoggingHandler(&b, h)

        defer func(start time.Time) {
            prefix := bytes.TrimRight(b.Bytes(), "\n")
            os.Stdout.Write(prefix)
            fmt.Printf(" completed in %v\n", time.Since(start))
        }(time.Now())

        hand.ServeHTTP(res, req)
    })
}

Is there a better way to write this in Go?


texts:
I'm trying to make a dice game with three dice and with rules.

It costs 10 credits to roll the dice.
If you get 6 6 6 you win 90 credits.
If you get 5 5 5, 4 4 4, 3 3 3, 2 2 2, 1 1 1, you win 40 credits.
If two of the dice have the same number you win 0 credits (because it costs 10 to roll).

Here's what I've done so far:

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

int main(void) {

    srand((int)time(NULL));

    int diceRoll1, diceRoll2, diceRoll3;
    char yn;

    do {
        printf("\nDo you want to play? (y/n): ");
        scanf_s("%c", &yn);
        getchar();

        if (yn == 'n') {
            printf("Coward!");
            getchar();
            return 0;
        }

        diceRoll1 = (rand() % 6) + 1;
        diceRoll2 = (rand() % 6) + 1;
        diceRoll3 = (rand() % 6) + 1;

        printf("Your dices are %d %d %d \n", diceRoll1, diceRoll2, diceRoll3);

        if (diceRoll1 == 6 && diceRoll2 == 6 && diceRoll3 == 6) {
            printf("Congratulations! You won 90 credits.\n");
        }

        if (diceRoll1 == 5 && diceRoll2 == 5 && diceRoll3 == 5) {
            printf("Congratulations! You won 40 credits.\n");
        }

        if (diceRoll1 == 4 && diceRoll2 == 4 && diceRoll3 == 4) {
            printf("Congratulations! You won 40 credits.\n");
        }

        if (diceRoll1 == 3 && diceRoll2 == 3 && diceRoll3 == 3) {
            printf("Congratulations! You won 40 credits.\n");
        }

        if (diceRoll1 == 2 && diceRoll2 == 2 && diceRoll3 == 2) {
            printf("Congratulations! You won 40 credits.\n");
        }

        if (diceRoll1 == 1 && diceRoll2 == 1 && diceRoll3 == 1) {
            printf("Congratulations! You won 40 credits.\n");
        }

    } while (yn != 'n');

    getchar();
    return 0;

}

I have not implemented all of the rules and the ones I have done can probably be done in a better way. I don't have much experience, so I wonder what the best way is to have all the rules in the game and so the code looks good.


texts: Removing duplicates from unsorted LinkedList

texts:
Removing Duplicates:

/**
 * Remove duplicates without using a buffer.
 *
 * @param head
 */
public static void removeUnsortedDuplicatesWithoutBuffer(final LinkedListNode head) {

    //if the linked list is empty
    if(head == null) {
        throw new RuntimeException("linked list is empty");
        //return;
    }
    LinkedListNode current = head;
    LinkedListNode runner = null ;
    LinkedListNode previous = null ;
    boolean flag = false ;

    while(current != null) {
        runner = head;
        while(runner != current) {
            if(current.getData() != runner.getData()) {
                runner = runner.getNext();
                flag = false;
            } else {
                previous.setNext(current.getNext());
                current = previous.getNext();
                flag = true;
                break;
            }
        }
        if(!flag) {
            previous = current;
            current = current.getNext();
        }
    }
}

LinkedListNode:

class LinkedListNode {
    private int data;
    private LinkedListNode next ;

    public LinkedListNode(final int data) {
        this.data = data;
        this.next = null;
    }

    public int getData() {
        return data;
    }

    public void setData(int data) {
        this.data = data;
    }

    public LinkedListNode getNext() {
        return next;
    }
    public void setNext(LinkedListNode next) {
        this.next = next;
    }

    public void appendAtTail(final int data) {
        LinkedListNode newNode = new LinkedListNode(data);
        LinkedListNode current = this;
        while(current.next != null) {
            current = current.next;
        }
        current.next = newNode;
    }
}

Test Case:

@Test
public void testRemoveDuplicatesFromUnsortedSortedLL() {
    LinkedListNode head = new LinkedListNode(30);
    head.appendAtTail(20);
    head.appendAtTail(20);
    head.appendAtTail(30);
    head.appendAtTail(10);
    head.appendAtTail(50);
    head.appendAtTail(10);
    head.appendAtTail(10);
    head.appendAtTail(20);
    head.appendAtTail(50);
    head.appendAtTail(50);
    head.appendAtTail(100);
    RemoveDuplicates.removeUnsortedDuplicatesWithoutBuffer(head);
}

I wrote this code recently to remove duplicates from linked list without using buffer and was trying to analyze its complexity :
Time taken for traversing is O(n)
For each operation we need to move runner node n times to remove duplicates
Total Complexity : O(n2).
Is this correct ??
I guess not because this is no better than using two for loops and comparing each element with the rest of the elements in the LinkedList .
What am I doing wrong here?


texts:
I took all your suggestions to heart and I think it improved the code a lot.

The Map got it's own typedef: IntStrDict. It's a perfectly applicable name, but I can't help but feel it's not according to best practices.

The code now accepts arguments. If no arguments are given, the code fails. If one or more argument is given it accepts the first argument as number and ignores the rest. If a non-number is inserted as first argument it should break. Recommended argument is 15016 (the result of 3*5*7*11*13).

I'm not sure my FizzDict in main() is according to best practices either. I'm still looking for a way to make it more generic. Perhaps OO-style with a getFizzDict would be appropriate. An argument which allows you to choose between dictionaries would be fancy, but could get very ugly very fast as well.

Another difference is I finally split up the code into a .cpp and a .h. Many functions are split up now.

Is my exception handling up to standards?

I'm trying to follow SRP as much as sensible.

FizzBuzz.cpp

#include "FizzBuzz.h"

int main(int argc, char* argv[])
{
    int iMax;
    try {
        iMax = atoi(argv[1]);
    }
    catch (int e) {
        std::cout << "Exception " << e << '\n';
    }
    if (argc < 2) {
        throw 0;
    }

    const static IntStrDict FizzDict = {
        { 3, "Fizz" },
        { 5, "Buzz" },
        { 7, "Woof" },
        { 11, "Foo" },
        { 13, "Bar" }
    };

    for (int i = 1; i < iMax; ++i)
    {
        printString(FizzBuzzer(i, FizzDict));
    }
}

FizzBuzz.h

#ifndef _fizzbuzz_h_
#define _fizzbuzz_h_

#include <iostream>
#include <string>
#include <map>

typedef std::map<int, std::string> IntStrDict;

void printString(std::string tString)
{
    std::cout << tString << '\n';
}

std::string ifEmpty(int i, std::string tString)
{
    if (tString.empty())
    {
        tString += std::to_string(i);
    }
    return tString;
}

std::string checkModZero(int i, IntStrDict tDict)
{
    std::string tString;
    for (auto const &j : tDict)
    {
        if (i % j.first == 0)
        {
            tString += j.second;
        }
    }
    return tString;
}

std::string FizzBuzzer(int i, IntStrDict tDict)
{
    std::string print;

    print = checkModZero(i, tDict);
    print = ifEmpty(i, print);
    return print;
}

#endif // fizzbuzz