texts:
I am using idenity server 3 authentication.
I have to implement refresh token logic.
AccessTokenLifetime is 1 hour, and after that time I want to update access token with refresh token.

I want do this only once, by using filter in mvc. My idea is to check if token has expired, and if yes that get new token.

This is my code, I want to know if this is best practice or you maybe have better idea?

  public class RefreshTokenActionFilter : FilterAttribute, IActionFilter
        {
            void IActionFilter.OnActionExecuted(ActionExecutedContext filterContext)
            {
                var user = filterContext.HttpContext.User as ClaimsPrincipal;
                var request = filterContext.HttpContext.Request;
                RefreshToken(user, request);
            }

            void IActionFilter.OnActionExecuting(ActionExecutingContext filterContext)
            {
            }

            private  void RefreshToken(ClaimsPrincipal User, HttpRequestBase Request)
            {
                var claims = ClaimsPrincipal.Current.Claims;
                var refreshToken = claims.Where(c => c.Type == AuthenticationValues.RefreshTokenKey).Select(c => c.Value).SingleOrDefault();
                long epoch = Convert.ToInt64((claims.Where(c => c.Type == AuthenticationValues.ExpiresAtEpochKey).Select(c => c.Value).SingleOrDefault()));

                // 60 seconds is tolerance
                if (refreshToken != null && epoch - 60 < DateTime.UtcNow.ToEpochTime())
                {
                    var tokenClient = new TokenClient(ApplicationConfiguration.IdentityServerToken,
                                      AuthenticationController.ClientApplicationId,
                                      AuthenticationController.ClientApplicationSecret);

                    var response = (tokenClient.RequestRefreshTokenAsync(refreshToken)).Result;
                    var user = User as ClaimsPrincipal;
                    var identity = user.Identity as ClaimsIdentity;

                    //Remove old tokens:
                    var oldRefreshToken = user.Claims.Single(c => c.Type == AuthenticationValues.RefreshTokenKey);
                    var oldAccessToken = user.Claims.Single(c => c.Type == AuthenticationValues.AccessTokenKey);
                    var oldExpiresAt = user.Claims.Single(c => c.Type == AuthenticationValues.ExpiresAtKey);
                    var oldEpoch = user.Claims.Single(c => c.Type == AuthenticationValues.ExpiresAtEpochKey);
                    identity.RemoveClaim(oldRefreshToken);
                    identity.RemoveClaim(oldAccessToken);
                    identity.RemoveClaim(oldExpiresAt);
                    identity.RemoveClaim(oldEpoch);

                    //Add new tokens:
                    identity.AddClaim(new Claim(AuthenticationValues.AccessTokenKey, response.AccessToken));
                    identity.AddClaim(new Claim(AuthenticationValues.RefreshTokenKey, response.RefreshToken));
                    identity.AddClaim(new Claim(AuthenticationValues.ExpiresAtKey, (DateTime.UtcNow.ToEpochTime() + response.ExpiresIn).ToDateTimeFromEpoch().ToString()));
                    identity.AddClaim(new Claim(AuthenticationValues.ExpiresAtEpochKey, (DateTime.UtcNow.ToEpochTime() + response.ExpiresIn).ToString()));

                    var authenticationManager = Request.GetOwinContext().Authentication;

                    authenticationManager.AuthenticationResponseGrant = new AuthenticationResponseGrant(
                                                                                new ClaimsPrincipal(identity),
                                                                                new AuthenticationProperties { IsPersistent = true });
                }
            }
        }


texts:
I've created a base structure for my project and found a way to wire classes together, I create an array of previously loaded classes and call them from the cache. I then have a static class that holds the cache and I call the static class when I need a class.

I feel that there is a much better way to do this, and maybe I'm doing something extremely wrong? How do other PHP applications do this? I'm pretty new to it, so I was wondering if anyone could advise me towards a better way to do this? It feels like it could be hugely improved.

Current directory structure:

The static class, I use this to get my classes (providers, I call them):

<?php declare(strict_types = 1);

namespace App;

class App {
    private static $providers = array();

    public static function getProvider($provider) {
        if (!isset(self::$providers[$provider])) {
            $providerName = 'App\Providers\\' . $provider;
            self::$providers[$provider] = new $providerName();
        }

        return self::$providers[$provider];
    }
}

Example of how I use it, I do this in all my controllers to show a view:

<?php declare(strict_types = 1);

use App\App;

namespace App\Controllers\Frontend\Guest;

class LoginController
{
    public function getView()
    {
        \App\App::getProvider('Template')->renderTemplate('index.html');
    }
}

Here is one of my few providers:

<?php declare(strict_types = 1);

namespace App\Providers;

class Template {
    private $twig;

    public function __construct() {
        $this->twig = new \Twig_Environment(new \Twig_Loader_Filesystem(ROOT . '/resources/templates'), array(
            'cache' => ROOT . '/storage/cache/templates',
        ));
    }

    public function renderTemplate($template) {
        echo $this->twig->render($template, array('the' => 'variables', 'go' => 'here'));
    }
}


texts:
How can I improve this window timeout alert code? I need to add it to some third-party master page and don't want to add a separate file for it.

It must be JS only and IE-8 supported.

jsFiddle

(function () {
//    timedRefresh(10); //3600000
    delayedAlert();

    var timeoutID;

    function delayedAlert() {
        clearAlert();
      timeoutID = window.setTimeout(slowAlert, 10000);
    }

    function slowAlert() {
      alert("You may have been logged out due to inactivity. Click OK to refresh the page.");
    }

    function clearAlert() {
      window.clearTimeout(timeoutID);
    }
})();


texts:
The Problem

  Sniffed any good packets lately, dude? Hopefully you haven’t done this illegally, but rest assured that there
  are some who have. If you surf the Internet, you have probably visited companies’ net sites where they sell
  their products online: you give them your credit card number and they ship you the goods. That’s a
  convenient way to shop if you can ensure that your credit card number isn’t being “sniffed” up by wily
  hackers and used illicitly.

  The Internet is an example of a packet-switched network. This means that information is sent in
  discrete groups of bits called packets from computer to computer. For example, when I send email to
  someone in the Philippines, my message (at the binary level) is broken up into packets, and routed packet
  by packet (not all at once) from computer to computer, ultimately to the recipient’s computer.

  “Packet sniffing” refers to writing a program that grabs the individual packets that come your
  computer’s way and reads their contents. Now the term “packet sniffing” has obvious unethical
  connotations: usually it refers to writing a program that reads packets addressed to computers other than
  your own. But the principle is exactly the same when you only intercept those packets that are intended for
  you.

  Let’s suppose that a network packet consists of three parts: a special start-of-packet bit pattern,the packet content, and a special end-of-packet bit pattern. Suppose that the start- and end-of-packet
  pattern are both 1000001 and that the packet content is no more than three consecutive sequences of 7 bits(1’s and 0’s). So, to write a program to “sniff” packets you need only to write a program that scans its
  input and “decodes” everything between pairs of 1000001.

  For this problem assume that the content of each packet is binary representation of no more than
  three ASCII characters, each encoded in 7 “bits” (0’s and 1’s). Your task is to write a program that prints
  out the message (in English) that is being transmitted by a sequence of packets.

  Sample Input

  Take your input from the text file prob4.in. Here’s a sample of its content:

10000011100010110111111011111000001100000101000011000001

  You are guaranteed two things: (1) the encoding is correct, and (2) only lower case letters and punctuation are encoded in the packet.

  Sample Output

  Your program should direct its output to the screen. The correct output for the sample input above is:

boo!

packetsniffer.py

with open('prob4.in') as f:
    for line in f:
        line = line.strip().replace('1000001', '')
        print(''.join([chr(int(c, 2)) for c in [line[i:i+7] for i in range(0, len(line), 7)]]))

Any advice on performance enhancement, solution simplification or that is topical is appreciated!


texts:
I wanted to open Database (Mongo) connection only once when I start application and share the same connection across the application. What am doing as part of app.js is

Creating connection

var dbConnection = mongoose.createConnection(config.database.address, config.database.dbName, config.database.port);

passing dbConnection in every route call

require('./services/MasterServices')(app , dbConnection);

Is it right approach or anything wrong here?


texts: Bank account number validation in IBAN format

texts:
I wrote a JavaScript function for validating bank account numbers in IBAN format for my own joy. Could you have a look if you don't see any obvious mistakes or places for improvement?

function isIbanValid(value) {

    var lengthMap = getLengthMap();

    //cleanup
    value = value.toString().toUpperCase().replace(/\s/g, '').replace(/[-]/g, '');
    //check if alphanumeric
    if (!/^[a-zA-Z0-9]+$/.test(value)) return false;
    //extract countrycode
    var countryCode = value.substring(0, 2);
    //check if letter
    if (!/([a-z]+[\s\-]?)*/i.test(countryCode)) return false;
    //check string length
    if (value.length != lengthMap[countryCode]) return false;

    value = value.concat(value.substring(0, 4)).substring(4);
    value = value.replace(countryCode, countryCodeToStringValue(countryCode));

    return modulo(value, 97) == 1;

    function countryCodeToStringValue(countryCode) {
        return "".concat(((countryCode.charCodeAt(0)) - 55).toString() + (countryCode.charCodeAt(1) - 55).toString());
    }

    function modulo(divident, divisor) {
        var quantization = 12;
        while (quantization < divident.length) {
            var part = divident.substring(0, quantization);
            divident = (part % divisor) + divident.substring(quantization);
        }
        return divident % divisor;
    }

    function getLengthMap() {
        var lengthMap = {};
        lengthMap["AD"] = 24;
        lengthMap["AT"] = 20;
        lengthMap["AZ"] = 28;
        lengthMap["BH"] = 22;
        lengthMap["BE"] = 16;
        lengthMap["BA"] = 20;
        lengthMap["BR"] = 29;
        lengthMap["BG"] = 22;
        lengthMap["CR"] = 21;
        lengthMap["HR"] = 21;
        lengthMap["CY"] = 28;
        lengthMap["CZ"] = 24;
        lengthMap["DK"] = 18;
        lengthMap["DO"] = 28;
        lengthMap["EE"] = 20;
        lengthMap["FO"] = 18;
        lengthMap["FI"] = 18;
        lengthMap["FR"] = 27;
        lengthMap["DE"] = 22;
        lengthMap["GR"] = 27;
        lengthMap["GI"] = 23;
        lengthMap["GL"] = 18;
        lengthMap["GT"] = 28;
        lengthMap["HU"] = 28;
        lengthMap["IS"] = 26;
        lengthMap["IE"] = 22;
        lengthMap["IL"] = 23;
        lengthMap["IT"] = 27;
        lengthMap["JO"] = 30;
        lengthMap["KZ"] = 20;
        lengthMap["KW"] = 30;
        lengthMap["LV"] = 21;
        lengthMap["LB"] = 28;
        lengthMap["LI"] = 21;
        lengthMap["LT"] = 20;
        lengthMap["LU"] = 20;
        lengthMap["MK"] = 19;
        lengthMap["MT"] = 31;
        lengthMap["MR"] = 27;
        lengthMap["MU"] = 30;
        lengthMap["MC"] = 27;
        lengthMap["MD"] = 24;
        lengthMap["ME"] = 22;
        lengthMap["NL"] = 18;
        lengthMap["NO"] = 15;
        lengthMap["PK"] = 24;
        lengthMap["PS"] = 29;
        lengthMap["PL"] = 28;
        lengthMap["PT"] = 25;
        lengthMap["QA"] = 29;
        lengthMap["RO"] = 24;
        lengthMap["SM"] = 27;
        lengthMap["SA"] = 24;
        lengthMap["RS"] = 22;
        lengthMap["SK"] = 24;
        lengthMap["SI"] = 19;
        lengthMap["ES"] = 24;
        lengthMap["SE"] = 24;
        lengthMap["CH"] = 21;
        lengthMap["TN"] = 24;
        lengthMap["TR"] = 26;
        lengthMap["AE"] = 23;
        lengthMap["GB"] = 22;

        return lengthMap;
    }
}


texts: Java Date class- switches and ifs in the constructor

texts:
I'm a beginner i have an assignment to write a Date class (as part of a bigger project). in my question i focus on the constructor. here's some background: the given guidelines are that the date is not expected to be valid and the following instance variables expect this input range: day- integer 1-31 month- integer 1-12 year- integer 4 digits year.

now, if an invalid day/month/year or invalid date (such as 31.2.2010) is entered, the object will be created with the date of 1.1.2000.

this is the code I've come up with and it does compile and seem to work fine.

public class Date
{
    private int _day;
    private int _month;
    private int _year;

    public Date (int day, int month, int year)
    {
        switch (month)
        {
            case 1:
            case 3:
            case 5:
            case 7:
            case 8:
            case 10:
            case 12: if ((day>0 && day<32) && (year>999 && year<10000))
            {
                _day=day;
                _month=month;
                _year=year;
            }
            else
            {
                _day=1;
                _month=1;
                _year=2000;
            }
            break;

            case 4:
            case 6:
            case 9:
            case 11: if ((day>0 && day<31) && (year>999 && year<10000))
            {
                _day=day;
                _month=month;
                _year=year;
            }
            else
            {
                _day=1;
                _month=1;
                _year=2000;
            }
            break;

            case 2: if (leap(year))
            {
                if ((day>0 && day<30) && (year>999 && year<10000))
                {
                    _day=day;
                    _month=month;
                    _year=year;
                }
                else
                {
                    _day=1;
                    _month=1;
                    _year=2000;
                }
                break;
            }

            else
            {
                if ((day>0 && day<29) && (year>999 && year<10000))
                {
                    _day=day;
                    _month=month;
                    _year=year;
                }
                else
                {
                    _day=1;
                    _month=1;
                    _year=2000;
                }
                break;
            }
        }
    }

    /** check if leap year */
    private boolean leap (int y)
    {
        return (y % 4 == 0 && y % 100 != 0) || (y % 400 == 0);
    }
}

here are my questions:

Is it fine to put all that code in the constructor? will it greatly affect the processing time or cause an error? is there an alternative if its a problem?
Is any part of the code could be considered a bad practice? such as the switches and ifs? I'm not feeling to confident with this build despite it working fine...

sorry for indentation inconvenience and such, 1st post :(


texts: Aggregate Pandas Columns on Geospacial Distance

texts:
I have a dataframe that has 3 columns, Latitude, Longitude and Median_Income.  I need to get the average median income for all points within x km of the original point into a 4th column. I need to do this for each observation.

I have tried making 3 functions which I use apply to attempt to do this quickly.  However, the dataframes take forever to process (hours).  I haven't seen an error yet, so it appears to be working okay.

The Haversine formula, I found on here.  I am using it to calculate the distance between 2 points using lat/lon.

from math import radians, cos, sin, asin, sqrt

def haversine(lon1, lat1, lon2, lat2):

    #Calculate the great circle distance between two points
    #on the earth (specified in decimal degrees)

    # convert decimal degrees to radians
    lon1, lat1, lon2, lat2 = map(radians, [lon1, lat1, lon2, lat2])

    # haversine formula
    dlon = lon2 - lon1
    dlat = lat2 - lat1
    a = sin(dlat/2)**2 + cos(lat1) * cos(lat2) * sin(dlon/2)**2
    c = 2 * asin(sqrt(a))
    r = 6371 # Radius of earth in kilometers. Use 3956 for miles
    return c * r

My hav_checker function will check the distance of the current row against all other rows returning a dataframe with the haversine distance in a column.

def hav_checker(row, lon, lat):

    hav = haversine(row['longitude'], row['latitude'], lon, lat)

    return hav

My value grabber fucntion uses the frame returned by hav_checker to return the mean value from my target column (median_income).

For reference, I am using the California housing dataset to build this out.

def value_grabber(row, frame, threshold, target_col):

    frame = frame.copy()

    frame['hav'] = frame.apply(hav_checker, lon = row['longitude'], lat = row['latitude'], axis=1)

    mean_tar = frame.loc[frame.loc[:,'hav'] <= threshold, target_col].mean()

    return mean_tar

I am trying to return these 3 columns to my original dataframe for a feature engineering project within a larger class project.

df['MedianIncomeWithin3KM'] = df.apply(value_grabber, frame=df, threshold=3, target_col='median_income', axis=1)

df['MedianIncomeWithin1KM'] = df.apply(value_grabber, frame=df, threshold=1, target_col='median_income', axis=1)

df['MedianIncomeWithinHalfKM'] = df.apply(value_grabber, frame=df, threshold=.5, target_col='median_income', axis=1)

I have been able to successfully do this with looping but it is extremely time intensive and need a faster solution.


texts: Find the length of the longest Common Subsequence

texts:
I have a DP based implementation for the Longest Common Subsequence(LCS) problem
to find the length of the LCS.

I wanted to know if there is room for improvement in terms of efficiency(space/time).

public int longestCommonSubsequence(char[] firstWord, char[] secondWord) {
        int[][] lcsMatrix = new int[firstWord.length+1][secondWord.length+1];

        for(int i = 0; i < firstWord.length; i++) {
            for(int j = 0; j < secondWord.length ; j++) {

                if (i == 0 || j == 0) {
                    lcsMatrix[i][j] = 0;
                }
                else if(firstWord[i] == secondWord[j]){
                   lcsMatrix[i][j] = lcsMatrix[i-1][j-1]+1;
                }
                else{
                    lcsMatrix[i][j] = Math.max(lcsMatrix[i][j-1],lcsMatrix[i-1][j]);
                }
            }

        }
        return lcsMatrix[firstWord.length-1][secondWord.length-1];
    }


texts:
I have this basic JavaScript that, using a constructor, validates the form where the login fields can't be empty. All this WITHOUT using any JS libraries.

function Validator(txtbox) {
    this.txtbox = txtbox;
}

var validator = new Validator([ "username", "password"]);

Validator.prototype.validate = function(form) {
    for(var i = 0, l=this.txtbox.length; i < l; i++) {
        var status = document.getElementById("status-msg");
        if (form[this.txtbox[i]].value == 0) {
            status.innerHTML="The " + form[this.txtbox[i]].name + " is empty";
            status.style.display = "inline-block"
            status.className = "error";
            return false;
        }
        else {
             status.innerHTML="Login successful";
            status.style.display = "inline-block"
             status.className = "success";
        }
    }
}

function runValidate(form) {
    validator.validate(form);
}

I'm wondering how I can make it more efficient or better.


texts: Java program to detect the Java class File Format magic number, in a given file

texts:
Description:

I wrote a Java program that checks whether the content of the given file begins with the Java class File Format magic number 0xCAFEBABE, in big-endian byte order.

It prints a success message if:

The first 4 bytes match the magic number

It prints an error message if:

The file doesn't exist or cannot be read
The file contains less than 4 bytes
The first 4 bytes don't match the magic number

It prints a usage message if:

A file is not given as input

Code:

import java.io.*;

public class Magic {

    public static void main(String[] args) {
        if (args.length < 1) {
            System.out.println("Usage: java Magic <FILE>");
            return;
        }

        try {
            if (isMagicPresent(args[0])) {
                System.out.println(String.format("'%s' contains the magic number.", args[0]));
            } else {
                System.out.println(String.format("'%s' doesn't contain the magic number.", args[0]));
            }
        } catch (IOException ex) {
            System.err.println(ex.getMessage());
        }
    }

    private static boolean isMagicPresent(String file) throws IOException {
        try (InputStream instream = new FileInputStream(file)) {
            byte[] bytes = new byte[4];
            int readCount = instream.read(bytes);

            if (readCount == 4) {
                return Byte.toUnsignedInt(bytes[0]) == 0xCA &&
                        Byte.toUnsignedInt(bytes[1]) == 0xFE &&
                        Byte.toUnsignedInt(bytes[2]) == 0xBA &&
                        Byte.toUnsignedInt(bytes[3]) == 0xBE;
            }
        }
        return false;
    }

}

Question:

How can I improve the above code in terms of:

Readability
Performance
Boundary case and error handling


texts: Review my "delayed for-loop" in JavaScript

texts:
I have written a small JavaScript class that makes use of setInterval to create a delayed loop for iterating an array. I've used this technique in the past but never utilised a library to do so (and as a result it produced quite messy spaghetti code), and so I wrote up this:

var DelayedLoop = function() { };

DelayedLoop.forEach = function(collection, delay, callback, completedCallback) {
    var index = 0;
    var timerObject;

    var executor = function() {
        // Stop the delayed loop.
        clearInterval(timerObject);

        // Executes the callback, and gets the returned value to indicate what the next delay will be.
        var newInterval = callback(collection[index++]);

        // If they returned false, quit looping.
        if(typeof(newInterval) == "boolean" && newInterval == false) {
            return;
        }

        // If nothing / non-number is provided, re-use initial delay.
        if(typeof(newInterval) != "number") {
            newInterval = delay;
        } else if(newInterval < 0) { // If a negative number is returned, quit looping.
            return;
        }

        // If there are more elements to iterate, re-set delayed loop. Otherwise, call the "completed" callback.
        if(index < collection.length) {
            timerObject = setInterval(executor, newInterval);
        } else {
            completedCallback();
        }
    };

    // Initial loop setup.
    timerObject = setInterval(function() {
        executor();
    }, delay);
};

An example usage can be seen here:

$(document).ready(function() {
    var myArray = [ "aaa", "bbb", "ccc" ];
    DelayedLoop.forEach(myArray, 1000, function(arrayElement) {
        console.log(arrayElement);
    }, function() {
        console.log("Finished all!");
    });
});

How does it look? Are there any browser compatibility issues? Is there any potential flaw I'm not seeing?


texts:
Can you check my code if I wrote like a professional?

connection page.
form sign page.
plan page.
log out page.

First I create the database and tables, then the connection file, then the form sign in page, then the plan page, finally the log out page

Database educate (create table users):

CREATE TABLE users(
id INT AUTO_INCREMENT,
username VARCHAR(50) NOT NULL,
password VARCHAR(100) NOT NULL,
PRIMARY KEY(id)
);

Conection.php:

<?php
$servername = 'localhost';
$username = 'root';
$password = '';
$db = 'educate';
//I added @ to delete error message that comming from  MySQL
$conn = @new mysqli($servername,$username,$password,$db);
if($conn->connect_error) die('Connection faild');
?>

Form signin.php:

<?php
//Check the cookie
if(!empty($_COOKIE['user'])) { header ('location: plan.php'); }
?>

<?php
//Check the inputs
function test_input($data) {
$data = trim($data);
//return a $data with whitespace stripped from the beginning and end of
$data
$data = stripslashes($data); //emoves backslashes
$data = htmlspecialchars($data);
//converts some predefined characters to  HTML entities
return $data;
}
?>

<?php
$username = $password = $password_hash = '';
$usernameErr = $passwordErr = '';

//Connection file
require ('connection.php');

if($_SERVER['REQUEST_METHOD'] == 'POST'){

if(empty($_POST['username'])){
$usernameErr = 'Username cannot be empty';
}else{
$username = test_input($_POST['username']);
}

if(empty($_POST['password'])){
$passwordErr = 'Password cannot be empty';
}else{
$password = test_input($_POST['password']);
$password_hash = md5($password);
}

//Select the data from DB('educate')
$sql = " SELECT username, password FROM users WHERE username='$username'
AND  password='$password_hash' ";

$result = $conn->query($sql);

if($result->num_rows === 0) {
$usernameErr = 'Username is error';
$password = 'Password is error';
} elseif($result->num_rows === 1) {
//Set cookie (one hour) and moved to  another    page
SETCOOKIE('user', $username, time() + (60*60) );
header('location: plan.php');
}

}
?>

<form action="#" method="post">
Username: <input type="text" name="username" placeholder="username">
<?php echo $usernameErr; ?>

Password: <input type="password" name="password" placeholder="password">
<?php echo $passwordErr; ?>

<input type="submit" value="Login">
</form>

Logout.php:

<?php
setcookie('user',"", time() - (30*30) );
header('location: form signin.php');
?>


texts:
How can I improve this code for a dynamic and re-sizable array data structure?

Array.h

#ifndef _ARRAY_H_
#define _ARRAY_H_

class Array
{
private:
    int * m_ArrayContainer;//These two variables
    int m_Size;            //work in pairs.

private:
    void SetSize(int size);
    void AllocateMemoryOfSize(int size);
    void DeallocateMemory();

public:
    Array();
    Array(int size);
    Array(Array & arr);
    void operator = (Array & arr);
    void Resize(int newSize);
    int GetSize();
    void SetItem(int index, int value);
    int GetItem(int index);
    ~Array();
};

#endif

Array.cpp

#include "Array.h"
#include <iostream>

#pragma region Private Methods

void Array :: SetSize(int size)
{
    this->m_Size = size;
}
void Array :: AllocateMemoryOfSize(int size)
{
    this->m_ArrayContainer = new int[size];
    this->SetSize(size);
}
void Array :: DeallocateMemory()
{
    if(this->GetSize() > 0)
    {
        delete [] this->m_ArrayContainer;
        this->SetSize(0);
    }
}
void Array :: SetItem(int index, int value)
{
    this->m_ArrayContainer[index] = value;
}
#pragma endregion

Array :: Array()
{
    //std::cout<<"Array()...\n";

    this->m_ArrayContainer = NULL;

    this->SetSize(0);
}
Array :: Array(int size)
{
    //std::cout<<"Array(int size)...\n";

    this->SetSize(0);

    this->Resize(size);
}
void Array :: Resize(int newSize)
{
    int oldSize = this->GetSize();

    for(int i=0 ; i<oldSize ; i++)
    {
        this->SetItem(i, NULL);
    }
    this->DeallocateMemory();

    this->AllocateMemoryOfSize(newSize);
    this->SetSize(newSize);
}
Array :: Array(Array & arr)
{
    //std::cout<<"Array(Array & arr)...\n";

    this->SetSize(0);

    int size = arr.GetSize();

    this->Resize(size);

    for(int i=0 ; i<size ; i++)
    {
        this->SetItem(i, arr.GetItem(i));
    }
}
void Array :: operator = (Array & arr)
{
    //std::cout<<"operator = (Array & arr)...\n";

    this->SetSize(0);

    int size = arr.GetSize();

    this->Resize(size);

    for(int i=0 ; i<size ; i++)
    {
        this->SetItem(i, arr.GetItem(i));
    }
}
int Array :: GetSize()
{
    return this->m_Size;
}
int Array :: GetItem(int index)
{
    return this->m_ArrayContainer[index];
}
Array :: ~Array()
{
    //std::cout<<"~Array()...\n";
    this->DeallocateMemory();
}


texts:
I made a simple Hearthstone fatigue calculator. For those who don't know, Hearthstone is a card game in which every turn you draw a card from your deck. Once you're out of cards, you start taking fatigue damage, getting 1 more damage each turn. The total damage dealt in X turns is known as the Triangular Number Sequence: 1 (1), 3 (1+2), 6 (1+2+3), 10 (1+2+3+4). For example, at turn 4 the fatigue damage has already dealt 10 dmg (1+2+3+4). This could be used for some decks that make you run out of cards, to calculate how much damage they need to kill the opponent or to just calculate how much damage X fatigue turns will do.

I just wanted to know how my code looks. I know it's a very simple program but I might be doing something wrong and I guess it's better to know as early as possible. Besides, code reviewing a long project is just too boring for everyone. I've been learning by myself and as nobody ever reads my code I might be doing terrible things without knowing it haha

def error():
    print("Whoops, something went wrong. Please try again.")

def calc_mode(t, s):
    d = 0
    for i in range(s, t+s):
        d = d + i
    return d

def lethal_mode(d_input, s):
    d_calc = 0
    i = 1
    t = 0
    while d_calc < d_input:
        d_calc = d_calc + i
        i += 1
        t += 1
    return t

while True:  # Checks if the mode input is valid
    try:
        mode = int(input("\nMODES: "
                         "\n* '1' to get the turns needed for X damage "
                         "\n* '2' to get the damage dealt in X turns "
                         "\nPlease type to select your mode: "))
    except ValueError:
        error()
        continue
    else:
        while True:
            if mode == 1:  # Checks if the input after the mode is valid
                while True:
                    try:
                        damageInput = int(input("\nPlease input the damage needed for lethal: "))
                        startInput = int(input("Starting at how much damage? (default is 1): "))
                    except ValueError:
                        error()
                        continue
                    else:

                        print("\n>> You will need %d fatigue turns for that sweet lethal"
                              % lethal_mode(damageInput, startInput))
                        continue

            if mode == 2:
                while True:
                    try:
                        turnsInput = int(input("\nPlease input how many fatigue turns: "))
                        startInput = int(input("Starting at how much damage? (default is 1): "))
                    except ValueError:
                        error()
                        continue
                    else:
                        print("\n>> It will deal %d damage" % calc_mode(turnsInput, startInput))
                        continue

            else:
                error()
                break

What do you think overall? Thanks!


texts: Angular JS Switcharoo multiple select module

texts:
I have created a script for going a multiple select option in Angular without using a select box that you have to hold control in order to select multiple items.

Demo: http://jsfiddle.net/qwertynl/xfw9f/

Code on GitHub

Here is my code:

Javascript:

var switcharoo = angular.module('switcharoo', []).directive('multiSelect', function(){
    return {
        restrict: 'E',
        scope: {
            items: '=',
            default: '=',
            leftTitle: '@',
            rightTitle: '@'
        },
        templateUrl: "switcharoo.html",
        link: function(scope)   {
            scope.switchItem = function(item)   {
                var index = scope.default.indexOf(item);
                if(index == -1) {
                    //add it in
                    scope.default.push(item);
                }
                else    {
                    //remove it
                    scope.default.splice(index, 1);
                }
            }
        }
    };
})

switcharoo.directive('switchitem', function() {
    return {
        restrict: 'E',
        scope: {
            value: '='
        },
        template: '
{{value}}
'
    };
});

HTML Template:

            {{leftTitle}}
            {{rightTitle}}

                    <switchitem ng-repeat="(key, value) in items" ng-if="default.indexOf(key) == -1" value="value" ng-click="switchItem(key)"></switchitem>

                    <switchitem ng-repeat="(key, value) in items" ng-if="default.indexOf(key) > -1" value="value" ng-click="switchItem(key)"></switchitem>

Is there anything I can do to make my code slicker?


texts: Simplifying similar functions using a hover state with different div content

texts:
I'm trying to hover over over the img then use Greensock Tweenmax on hover to control the speed and opacity of the text within the span.  The opacity will change on mouseover and mouseout.

The problem is that I'm having to repeat the same exact same effect on several div's and it's becoming repetitive.  Each one will be unique to the image being hovered.  I don't want them all to appear at the same time when I hover over one div.  I could give them all the same class then use .hover but then that would activate all of them instead of individually.

They are only to appear respective to that particular div being hovered.  It works just fine, but I would like to simplify it since I will be doing this to about 20 different divs.

I need some help simplifying the code below.  It works just fine, but maybe there is an easier way.

    Here is some text

    Here is some other text

/* tweenmax hover animations */
 $('.test img').hover(
    function(){
     /*mouseover function*/
     TweenLite.to(".test span", 1.5, {opacity:1});
    },
    function(){
    /*mouseout function*/
     TweenLite.to(".test span", 1.5, {opacity:0});
 });

 $('.testx img').hover(
    function(){
     /*mouseover function*/
     TweenLite.to(".testx span", 1.5, {opacity:1});
    },
    function(){
    /*mouseout function*/
     TweenLite.to(".testx span", 1.5, {opacity:0});
 });

 $('.testxy img').hover(
    function(){
     /*mouseover function*/
     TweenLite.to(".testxy span", 1.5, {opacity:1});
    },
    function(){
    /*mouseout function*/
     TweenLite.to(".testxy span", 1.5, {opacity:0});
 });

 $('.testxyz img').hover(
    function(){
     /*mouseover function*/
     TweenLite.to(".testxyz span", 1.5, {opacity:1});
    },
    function(){
    /*mouseout function*/
     TweenLite.to(".testxyz span", 1.5, {opacity:0});
 });


texts:
The question can be found here https://leetcode.com/problems/letter-case-permutation

  Given a string S, we can transform every letter individually to be
  lowercase or uppercase to create another string.  Return a list of all
  possible strings we could create.

My question pertains mostly to the pattern that I am following. I find that with alot of these leetcode question that I want to use recursion for I find myself making two versions of a function. One which acts as the "interface" is this case
letterCasePermutation and one which acts as the worker (letterCasePermutationAux) where the only difference is the arguments (I would usually have something like a counter and a reference to a vector to hold my answers).

I choose this question as an example but really any recursive question could act as a stand in here.

class Solution(object):

    ans = []

    def letterCasePermutationAux(self, S, i=0):

        if i >= len(S):
            self.ans.append(S)
            return

        if S[i].isalpha():
            temp = list(S)
            temp[i] = S[i].upper() if S[i].islower() else S[i].lower()
            self.letterCasePermutationAux("".join(temp), i+1)

        self.letterCasePermutationAux(S,i+1)

    def letterCasePermutation(self, S):
        self.ans=[]
        self.letterCasePermutationAux(S)
        return self.ans

My question is, is there a nicer way I can go about accomplishing this task? One which can perform recursion only using one function?


texts:
I completed Assignment 2 for MIT OpenCourseWare 6.092, titled "Foo Corp". The code I wrote below calculates a an employee's total pay:

package fooCorp;

class Employee{

    private double payPerHour; //regular hourly wage
    private double overTimePayPerHour; //regular hourly wage * 1.5
    private double basePayHours; //hours worked under regular hourly wage
    private double overTimeHours;//hours worked under overtime pay per hour
    private double totalHours; //adds basePayHours and overTimeHours
    private double totalPay;//base pay + overtime pay

    public void setPayPerHour(double x) //takes parameter 'x' a d sets that equal to this objects payPerHour variable
    {
        this.payPerHour = x;
    }
    public double getpayPerHour() //returns this variables payPerHour variable
    {
        return this.payPerHour;
    }

    public void setOverTimePayPerHour() //calculates and sets overtime payPerHour rate
    {
            this.overTimePayPerHour = this.payPerHour * 1.5;
    }
    public double getOverTimePayPerHour() //returns overTimePayPerHour rate
    {
        return this.overTimePayPerHour;
    }

    public void setHours(int x) //sets hours worked into three of this objects variables, basePayHours, overTimeHours and totalHours
    {
        if(x > 40){
            this.basePayHours = 40;
        }
        else{
            this.basePayHours = x;
        }
        if (x > 40){
            this.overTimeHours = x - 40;
        }
        else{
            this.overTimeHours = 0;
        }

        this.totalHours = this.basePayHours + this.overTimeHours;

    }

    public double getBasePayHours()//returns this object's basePayHours value
    {
        return this.basePayHours;
    }
    public double getOverTimeHours()//returns this object's overTimeHours value
    {
        return this.overTimeHours;
    }
    public double getTotalHours()  //returns this object's totalHours value
    {
        return this.totalHours;
    }

    public void calculateTotalPay(){ //calculates this Employee objects total pay and sets it's totalPlay variable to that value
        double basePay = this.getBasePayHours() * this.getpayPerHour();  //calculates basePay
        double overTimePay = this.getOverTimeHours() * this.getOverTimePayPerHour(); //calculates overTimePay
        this.totalPay = basePay + overTimePay;//sets value of this object's totalPay to the sum of basePay and overTimePay
    }
    public double getTotalPay()
    {
        return this.totalPay; //returns this object's totalPay value
    }

}

public class FooCorp {
    public static void main(String[] args)
    {
        Employee employee1 = new Employee();
        employee1.setPayPerHour(8.20);
        employee1.setOverTimePayPerHour();
        employee1.setHours(47);
        employee1.calculateTotalPay();
        System.out.println("You worked  " + employee1.getBasePayHours() + " regular hours."); //should be 40
        System.out.println("Plus "+  employee1.getOverTimeHours() +" hours of overtime."); // should be 7.00
        System.out.println("For a total of " + employee1.getTotalHours() + " hours."); //should be 47
        System.out.println("You get paid $" + employee1.getpayPerHour() + " per hour."); //should be 8.20
        System.out.println("You get paid $" + employee1.getOverTimePayPerHour() + "  per hour for overtime."); // should be 12.3
        System.out.println("Your total pay is: $"+employee1.getTotalPay()); //should be 414.10
    }

}

I feel that this is not proper encapsulation because this seems like a lot of code to do so little? Any advice on something i could do to improve this program would be much appreciated!


texts: Actionscript web service and web method call classes

texts:
I'm trying to isolate a webservice in its own class, and I plan to add separate classes to each webmethod there is in the webservice.  What I have so far works, but I have this feeling tickling that I've missed something (except for the invisible variable declarations down here, I didn't want to clog the page).

Webservice instantiation class and its fault handler:

 public class CfdWS
        {

            [Bindable]
            private var model:ModelLocator = ModelLocator.getInstance();

            public function loadWebService():WebService{
                var webService : WebService = new WebService();
                webService.wsdl = model.configXML.cfdwsWSDL;
                webService.addEventListener(FaultEvent.FAULT, onWebServiceFault);
                webService.loadWSDL();
                return webService;
            }

            private function onWebServiceFault(event:FaultEvent):void{
                var fault: Fault = event.fault;
                var message:String = "\ncodigo: " + fault.faultCode;
                message += "\nDetalle: " + fault.faultDetail;
                Alert.show("Error de webservice:" + message);
            }
        }
    }

The following is my webservice method call class. I have written only what I think is the essential code for the question.

public class GeneratePDF extends CfdWS{

    public function generatePDF():void{
                webService = loadWebService();
                webService.addEventListener(LoadEvent.LOAD, doGeneratePDF);
            }
            private function doGeneratePDF(event:LoadEvent):void{
                webService.generatePDF.addEventListener(ResultEvent.RESULT, generatePDFResultHandler);
                webService.generatePDF(pdfData);
            }
            private function generatePDFResultHandler (event:ResultEvent):void{
                // After getting what I want, I remove the event listeners here.
            }
}

I'm trying to re-write an application that is already in production while on testing phase (testing for the next version I mean).


texts: Forming a dynamic dictionary based on searched key and values pair using RAW logic and not modules of python

texts:
I am trying to create a dictionary with a file containing text based on a matched pattern. Lines containing key_str should become keys and subsequent lines not matching key_str should become values and get associated with keys in the dictionary. so i have below code working: But I need help and getting the

best practices and design pattern in my case
Performance in case my file is in GB
Alternate/different approaches without using any modules but just raw logic. don't want to use collections for example. for using python module I can ask a different question but here I just want to get to raw logic approaches.

File: file2dict.result-soa1
ml1
/var
/home

cpuml2
/var
/home

Output
my_dict: {ml1: ['/var','/home'], cpuml2: ['/var','/home']}

Code:
import os
homedir = os.environ.get('HOME')

key_str = "ml"
my_dict = {}
val_list = []
key = ''
with open(homedir + '/backup/file2dict.result-soa1') as file2dict:
    for line in file2dict:
        words = line.split()
        for aWord in words:
            if key_str in aWord:
                if key:
                    my_dict[key] = val_list
                    val_list = []
                    key = aWord
                else:
                    key = aWord
            else:
                val_list.append(aWord)
    my_dict[key] = val_list
print(my_dict)


texts: IdNumber: a string of fixed length and with character constraints

texts:
In my program, I have special id numbers. They have a fixed length of 10 characters and may only contain digits and lowercase letter. I created my own data type for this. I want to be able to assign string values to it (with the implicit operator). When I do so, there should be automatically a verification if all conditions are met (the length and the constraints at the characters).

public class IdNumber
{
    private string idnumber;

    public static implicit operator IdNumber(string value)
    {
        if (value.Length == 10 && value.All(c => IsDigit(c) || IsLowercaseLetter(c)))
        {
            IdNumber m = new IdNumber();
            m.idnumber = value;
            return m;
        }
        else
        {
            throw new ArgumentException("id numer must have length 10 and must only have digits and lower case-letters");
        }
    }

    public override string ToString()
    {
        return idnumber;
    }

    public override int GetHashCode()
    {
        return idnumber.GetHashCode();
    }

    public override bool Equals(object obj)
    {
        if(obj is IdNumber other)
        {
            return this.idnumber == other.idnumber;
        }
        else
        {
            return false;
        }
    }

    public static bool operator ==(IdNumber m1, IdNumber m2)
    {
        if(m1 is null)
        {
            return m2 is null;
        }
        return m1.Equals(m2);
    }

    public static bool operator !=(IdNumber m1, IdNumber m2)
    {
        return !(m1 == m2);
    }

    private static bool IsDigit(char c)
    {
        return c >= '0' && c <= '9';
    }

    private static bool IsLowercaseLetter(char c)
    {
        return c >= 'a' && c <= 'z';
    }
}

Now I can use it via

IdNumber myId = "ab45jk23zz";
IdNumber otherId = "asfd" // throws exception

I have never used the implicit operator and I am also not sure about overriding the GetHashCode method (I want to use them as a key in a Dictionary, so it is important this works correctly). Hence I want to be sure I did not overlook anything. Of course, any other suggestions for improvement are welcome.


texts: Given time intervals determine if a person could attend all meetings

texts:
The task is taken from LeetCode

  Given an array of meeting time intervals consisting of start and end times [[s1,e1],[s2,e2],...] (si < ei), determine if a person could
  attend all meetings.

  Example 1:

Input: [[0,30],[5,10],[15,20]]
Output: false

  Example 2:

Input: [[7,10],[2,4]]
Output: true

My imperative solution:

/**
 * @param {number[][]} intervals
 * @return {boolean}
 */
var canAttendMeetings = function(intervals) {
  intervals.sort((a,b) => a[0] - b[0]);
  for (let i = 1; i < intervals.length; i++) {
    if (intervals[i][0] < intervals[i - 1][1]) { return false; }
  }
  return true;
};

My functional solution:

/**
 * @param {number[][]} intervals
 * @return {boolean}
 */
var canAttendMeetings = function(intervals) {
  return intervals
    .sort((a,b) => a[0] - b[0])
    .flat()
    .every((x,i, src) => i % 2 === 0 || src[i + 1] === void 0 || src[i] < src[i + 1]);
};


texts:
I wrote a Python module to learn about memoization, and I have some questions on what I did.

How pythonic is this?
Does it make a difference if I used a class attribute instead of a function attribute for my lookup_table?
How can I modify multi_run_chrono to use it like Python's decorators (with @)?
Should I keep the try... except KeyError or rather do if key in dictionary...?
Are there some nice tricks I could do to improve this code's elegance and/or performance?

Here is the code:

from __future__ import print_function
from random import randint
from time import clock

def naive_factorial(n):
    """calculates n! with a simple recursive algorithm"""
    if n == 0:
        return 1
    else:
        return n * naive_factorial(n-1)

def memo_factorial(n):
    """calculates n! using memoization in a recursive algorithm"""
    if not hasattr(memo_factorial, 'lookup_table'):
        memo_factorial.lookup_table = {0: 1}
    try:
        return memo_factorial.lookup_table[n]
    except KeyError:
        val = n * memo_factorial(n - 1)
        memo_factorial.lookup_table[n] = val
        return val

def check_correctness():
    print('Checking both functions do the same things')

    for i in [0, 1, 4, 10, 22, 63]:
        n = naive_factorial(i)
        m = memo_factorial(i)
        print('n = %d -- Naive : %d, Memo : %d' % (i, n, m))
        if n != m:
            print('Error in functions implementation')
            exit()

def multi_run_chrono(func, nb_runs, min_val, max_val):
    print('Running %s %d times, with n from %d to %d'
          % (func.__name__, nb_runs, min_val, max_val))
    tests = [randint(min_val, max_val) for _ in xrange(nb_runs)]
    starting_time = clock()
    for n in tests:
        func(n)
    ending_time = clock()
    print('Duration : %fs' % (ending_time - starting_time))

def main():
    # check_correctness()  # comment/uncomment to check or not
    for func in [naive_factorial, memo_factorial]:
        multi_run_chrono(func, 20000, 10, 200)

if __name__ == '__main__':
    main()

Benchmarking on my computer :

Running naive_factorial 20000 times, with n from 10 to 200
Duration : 0.596933s
Running memo_factorial 20000 times, with n from 10 to 200
Duration : 0.006060s

All remarks are welcome, thank you very much!


texts:
I am trying to optimize my vertex and pixel shader code. Do you have any suggestions what could I possibly do to improve performance? I am using it to draw textured cuboids, and if there are many objects in the screen my framerate drops.

VERTEX SHADER

        float4x4 WorldViewProj                      : register(c0);
        float4x3 WorldInversedMatrix                : register(c4);
        float4x4 World                              : register(c7);
        float3 viewPosition                         : register (c11);
        float3 dirLightDir                          : register(c12);
        float xCoordMultiplication                  : register (c13);
        float yCoordMultiplication                  : register (c14);

        struct VsInput
        {
            float4 position : POSITION;
            float3 normal   : NORMAL;
            float2 texCoord : TEXCOORD;
        };

        struct VsOutput
        {
            float4 position : POSITION;
            float3 dirLightPosition : COLOR;
            float2 texCoord : TEXCOORD0;
            float3 normal   : TEXCOORD1;
            float3 view : TEXCOORD2;
        };

        VsOutput main(VsInput IN)
        {
            VsOutput OUT;

            OUT.position = mul(IN.position, WorldViewProj);

            //if X/YCoordMultiplication != 1, then texture is multiplicated (for example when drawing tiled floor, and my texture is single tile
            OUT.texCoord = float2(IN.texCoord.x * xCoordMultiplication,
                                  IN.texCoord.y * yCoordMultiplication);
            OUT.normal = mul(WorldInversedMatrix, IN.normal);

            float3 worldPosition = mul(IN.position, World).xyz;
            OUT.view = viewPosition - worldPosition;

            OUT.dirLightPosition = mul(dirLightDir, World);
            return OUT;
        }

PIXEL SHADER

float4 filterColor              : register (c1);
float3 specularLightIntensity   : register (c2);

texture texTexture;
sampler textureSampler  : register(s0) = sampler_state {
    Texture = (texTexture);
    Filter = MIN_MAG_MIP_POINT;
    AddressU = Wrap;
    AddressV = Wrap;
};

struct VsOutput
{
    float4 position : POSITION;
    float3 dirLightPosition : COLOR;
    float2 texCoord : TEXCOORD0;
    float3 normal   : TEXCOORD1;
    float3 view : TEXCOORD2;
};

float4 main(VsOutput IN) : COLOR
{

    float4 texColor = tex2D(textureSampler, IN.texCoord);

    float3 specular = specularLightIntensity;
    float materialPower = 9.0f;

    float3 light = normalize(IN.dirLightPosition);
    float3 view = normalize(IN.view);
    float3 normal = normalize(IN.normal);
    float3 halfway = normalize(light + view);

    float3 processedSpecular = pow(saturate(dot(normal, halfway)), materialPower)
                        * specular;

    float alphaChannel = texColor.a + filterColor.a;

    float4 color = 1.2f * (texColor + filterColor.a * filterColor   + float4(processedSpecular, 0.0f));

    return float4(color.r, color.g, color.b, filterColor.a + texColor.a);
}


texts: Filtering ASP.NET membership roles without the default attributes

texts:
I am building an application, and I needed an attribute similar to AuthorizeAttribute, supporting Roles but not using the MembershipProvider roles. (Basically, with the setup I have, I cannot rely on the User.IsInRole method - it's not always accurate, so I manually query the roles in my MasterDbContext instead.)

I have two different parts to it:

public class RequiredRoleAttribute : FilterAttribute, IAuthorizationFilter
{
    public string Roles { get; set; }
    public string Destination { get; set; } = "~/Account/Login";

    public void OnAuthorization(AuthorizationContext filterContext)
    {
        var context = new MasterDbContext();
        var user = context.Users.Find(filterContext.HttpContext.User.Identity.GetUserId());

        var requiredRoles = Roles.Split(',').Select(roleName => context.Roles.First(role => role.Name == roleName).Name).ToList();

        if (!requiredRoles.All(r => user.InRole(r, context)))
        {
            if (Destination == null)
            {
                filterContext.Result = new RedirectToRouteResult("Default", null);
            }
            else
            {
                filterContext.Result = new RedirectResult(Destination);
            }
        }
    }
}

This should be self-explanatory. It does the same thing as [AuthorizeAttribute(Roles = "SomeString")], used in conjunction with that attribute:

[Authorize]
[RequiredRole(Roles = Constants.Roles.Moderators)]
public abstract class BaseController : Controller
{
    public MasterDbContext Context { get; } = new MasterDbContext();
}

So that's easy. As you can see, I can still use [Authorize], I just can't use [Authorize(Roles = ...)].

Then, I wrote User.InRole instead of the User.IsInRole method:

public bool InRole(string roleName, MasterDbContext providedContext = null)
{
    var context = providedContext ?? new MasterDbContext();
    var roleId = context.Roles.First(r => r.Name == roleName).Id;
    return Roles.ToList().Any(r => roleId == r.RoleId);
}

Any/all comments welcome, this is another huge portion of this application and I would love to make it as effective as possible.


texts:
I now processed the suggestions you can find here. I've deleted some duplications and corrected some other minor mistakes.

Here's the code:

import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import java.awt.Dimension;
public class caesar {

    public static void main(String[] args) {
        String field, text;

        field = JOptionPane.showInputDialog("Please enter text:");
        field = field.replaceAll("[^a-zA-Z]+", "");
        field = field.toUpperCase();

        int shift;

        String shift_String = JOptionPane.showInputDialog("Please enter shift to the right:");
        shift = Integer.parseInt(shift_String);

        String d = JOptionPane.showInputDialog("Encrypt (1) or decrypt (2):");
        int decision = Integer.parseInt(d);

        String out = "";

        if(decision == 1) {
            boolean test = true;
            out = operation(field, shift, test);

        }
        else if(decision == 2) {
            boolean test = false;
            out = operation(field, shift, test);

        }
        else if(decision != 1 && decision != 2) {
            out = "Invalid choice!";
        }
        JTextArea msg = new JTextArea(out);
        msg.setLineWrap(true);
        msg.setWrapStyleWord(true);
        JScrollPane scrollPane = new JScrollPane(msg);
        scrollPane.setPreferredSize(new Dimension(300,300));
        JOptionPane.showMessageDialog(null, scrollPane);
    }

    //Encryption
    public static String operation(String text, int n, boolean test) {
        int x = 0;
        int y = 0;
        int z = 1;

        if(!test) {
            z = -1;
        }

        StringBuilder out = new StringBuilder(); //Empty string for result.
        while (x < text.length()) {
            final char currentChar = text.charAt(x);
            if (currentChar > 64 && currentChar < 91) {
                if (currentChar + n > 90) {
                    y = 26;
                }
                out.append((char)(currentChar + (n*z) - (y*z)));
            }
            else {
                out.append(currentChar);
            }
            x++;
            y = 0;
        }
        return out.toString();
    }

}

Are there anymore suggestions to improve the code?


texts:
The following is my sample code:

String month = "09";

String year = "2014";

String monthYear = "092014";

The monthYear format is MMyyyy, I wish to format it to become MMyy. Thus, I am doing it as follows:

Method 1:

final SimpleDateFormat oriMonthYear = new SimpleDateFormat( "MMyyyy" );
final SimpleDateFormat changeMonthYear = new SimpleDateFormat( "MMyy" );

String newMonthYear = changeMonthYear.format( oriMonthYear.parse( month + year) );

This give me correct output, but I am not sure am I doing it by stupid way or not. I believe it should be another best practice and smart to way to do it.


texts: Beginner radian/degree converter program

texts:
I'm a bit of a beginner when it comes to Java, and I created this small code to help me grasp a few small subjects. It allows its user to convert a radical to a degree measure and a degree measure to a radical. This is my final code:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;

public class MainClass {

    public static void dtr (BufferedReader dRead) throws IOException {

        ArrayList<Integer> divisors = new ArrayList<Integer>();
        ArrayList<Integer> gcd = new ArrayList<Integer>();

        int d = Integer.parseInt(dRead.readLine());
        for (int pd = 1; pd <= d; pd++) {
            if (d % pd == 0) {
                divisors.add(pd);
            }
        }

        for (int index = 0; index < divisors.size(); ++index) {
            if (180.0 % divisors.get(index) == 0) {
                gcd.add(divisors.get(index));
            }

        }

        int dem = (180 / gcd.get(gcd.size() - 1));
        if ((d / (gcd.get(gcd.size() - 1))) == 1) {
            System.out.print("Radical: pi / " + dem);
        } else {
            System.out.print("Radical: " + (d / (gcd.get(gcd.size() - 1))) + "pi / " + dem);
        }

    }

    public static void rtd (BufferedReader rnRead, BufferedReader rdRead) throws IOException {

        int rn = Integer.parseInt(rnRead.readLine());
        int rd = Integer.parseInt(rdRead.readLine());

        int dividend = rn * 180;

        System.out.print("Degrees: " + (dividend / rd));

    }

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

        System.out.println("Do you want to convert from radicals to degrees, or degrees to radicals?");
        System.out.print("Use \"R\" for radials to degrees, and \"D\" for degrees to radicals: ");
        BufferedReader userInput = new BufferedReader(new InputStreamReader(System.in));
        String userChoice = userInput.readLine();

        if (userChoice.contains("D") || userChoice.contains("d")) {

            System.out.print("Degrees: ");
            BufferedReader dRead = new BufferedReader(new InputStreamReader(System.in));
            dtr(dRead);

        } else if (userChoice.contains("R") || userChoice.contains("r")) {

            System.out.println("Radical numerator (omit pi): ");
            BufferedReader rnRead = new BufferedReader(new InputStreamReader(System.in));
            System.out.println("Radical denominator: ");
            BufferedReader rdRead = new BufferedReader(new InputStreamReader(System.in));
            rtd(rnRead, rdRead);

        } else {

            System.out.println("Invalid response. Please restart the program.");

        }

    }

}

I know how bad some of this code is, but I just want to know if there is any way I could have optimized what this does, because I'd like to apply those concepts to everything that I'll make in the future.


texts: Style, simplification and modularization for unit converter

texts:
Here is an exercise I completed today from Bjarne Stroustrup's Programming Principles and Practice in C++ book.  Any tips about coding style, simplification, or perhaps modularization by means of using functions for some of the data processing would be sincerely appreciated. FYI I have only been programming for 5 months, apologies in advance for any blatant mistakes.

// This program takes floating-point numbers and select units as input, and displays the sum,
// the amount of measurements entered, and the high and low measurements entered.
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;

// Globals
const double cm_to_m = 0.01;
const double m_to_cm = 100;
const double in_to_m = 2.54 * 0.01;
const double m_to_in = 100 * (1.0/2.54);
const double ft_to_m = 12 * 2.54 * 0.01;
const double m_to_ft = 100 * (1.0/2.54) * (1.0/12.0);

// Main Function
int main()
{
    // Declarations
    int count = 0;
    double num, conv, low, high, sum = 0;
    string unit, low_unit, high_unit;
    vector<double> input_array;

    // Input
    cout << "Enter a measurement in one of the following accepted units (cm, m, in,     ft): " << endl;
    while (cin >> num >> unit) {
        if (unit == "m" || unit == "cm" || unit == "in" || unit == "ft") {
            if (unit == "m") {
                input_array.push_back(num);
                if (count == 0) low = num, low_unit = unit, high = num, high_unit = unit;
                else if (num < low) low = num, low_unit = unit;
                else if (num > high) high = num, high_unit = unit;
                ++count;
            }
            else if (unit == "cm") {
                conv = num * cm_to_m;
                input_array.push_back(conv);
                if (count == 0) low = conv, low_unit = unit, high = conv, high_unit = unit;
                else if (conv < low) low = conv, low_unit = unit;
                else if (conv > high) high = conv, high_unit = unit;
                ++count;
            }
            else if (unit == "in") {
                conv = num * in_to_m;
                input_array.push_back(conv);
                if (count == 0) low = conv, low_unit = unit, high = conv, high_unit = unit;
                else if (conv < low) low = conv, low_unit = unit;
                else if (conv > high) high = conv, high_unit = unit;
                ++count;
            }
            else if (unit == "ft") {
                conv = num * ft_to_m;
                input_array.push_back(conv);
                if (count == 0) low = conv, low_unit = unit, high = conv, high_unit = unit;
                else if (conv < low) low = conv, low_unit = unit;
                else if (conv > high) high = conv, high_unit = unit;
                ++count;
            }
        }
        else
            cout << "Incorrect Unit Entered! Please try again..." << endl;
    }

    // Low/High Unit Re-Conversion
    if (low_unit == "cm")
        low *= m_to_cm;
    else if (low_unit == "in")
       low *= m_to_in;
    else if (low_unit == "ft")
       low *= m_to_ft;

    if (high_unit == "cm")
        high *= m_to_cm;
    else if (high_unit == "in")
        high *= m_to_in;
    else if (high_unit == "ft")
        high *= m_to_ft;

    // Sort
    sort(input_array.begin(), input_array.end());

    // Sum the contents of the array.
    for (int i = 0; i < input_array.size(); ++i)
        sum += input_array[i];

    // Output
    cout << endl;
    cout << count << " measurements were entered" << endl;
    cout << "The sum of measurements entered is " << sum << " m" << endl;
    cout << "The lowest measurement entered was " << low << " " << low_unit << endl;
    cout << "The highest measurement entered was " << high << " " << high_unit << endl;

    // Return
    return 0;
}


texts: Getting a list of all fields in an object

texts:
I've got the following code that I use to output a list of all (public) fields in an object in an easy(ish) to read way. The issue with it is that the code is not easy to look at, and I'm not sure what I could do to improve it.

I'm not too fond of all of the StringBuilders, the append calls are ugly and chaining them does not help the situation however I can't see a better way of doing it.

public abstract class Component {
    private String[] getFields() {
        Class<? extends Component> componentClass = getClass();
        List<String> lines = new ArrayList<>();

        for (Field field: componentClass.getFields()) {
            StringBuilder lineBuilder = new StringBuilder();

            lineBuilder.append(field.getName());

            field.setAccessible(true);

            try {
                Object value = field.get(this);

                lineBuilder.append(" = ");
                lineBuilder.append(value);
            } catch (IllegalAccessException e) {
                lineBuilder.append(" > ");
                lineBuilder.append(e.getClass().getSimpleName());
            }

            lines.add(lineBuilder.toString());
        }

        return lines.toArray(new String[lines.size()]);
    }

    @Override
    public final String toString() {
        StringBuilder builder = new StringBuilder(getClass().getSimpleName());
        boolean firstIteration = true;

        builder.append('(');

        for (String field: getFields()) {
            if (!firstIteration) {
                builder.append(", ");
            } else {
                firstIteration = false;
            }

            builder.append(field);
        }

        builder.append(')');

        return builder.toString();
    }
}

I'm not entirely sure why I separated getFields into it's own method, however it might be better to move it back into toString.


texts:
I'm a beginner to Haskell and functional programming as a whole and as a first project I've written a Brain-Flak implementation in Haskell.

I wanted to get some feedback on this implementation because I've never done anything this big in a functional programming language.  Is my code two iterative?  What could make this better Haskell?  I found pattern matching very useful, am I using it too much?

BrainHack:

Currently I don't have any fancy IO for this program, just a function that can be called with ghci.  The relevant function here is brainflak it takes a String as source and a [Integer] as input to the Brain-Flak.  It is really just a wrapper around the function bf that uses balanced to first check if the Brain-Flak code is syntactically valid.  bf does most of the computation using pattern matching and the Three Stack Model of Brain Flak.

-- pop is a head that defaults to zero
pop :: (Integral a) => [a] -> a
pop [] = 0
pop (x:_) = x

-- rest is a tail for pop
rest :: (Integral a) => [a] -> [a]
rest [] = []
rest (_:x) = x

-- topadd adds an Integer to the top of a [Integer]
topadd :: [Integer] -> Integer -> [Integer]
topadd [] x = [x]
topadd (a:[]) x = [a+x]
topadd (a:b) x = (a+x):b

-- ir is a helper function of interior
ir :: String -> Integer -> String
ir x 0 = ""
ir ('{':x) y = "{" ++ (ir x (y+1))
ir ('}':x) y = "}" ++ (ir x (y-1))
ir (a:x)   y = [a] ++ (ir x   y  )

-- interior finds the inside of a loop {x}... -> x
interior :: String -> String
interior x = init (ir x 1)

-- ex is a helper function for exterior
ex :: String -> Integer -> String
ex x 0 = x
ex ('{':x) y = ex x (y+1)
ex ('}':x) y = ex x (y-1)
ex  (a:x)  y = ex x y

-- exterior finds all the code after a loop {...}x -> x
exterior :: String -> String
exterior x = ex x 1

-- bf is the implementation of brain-flak
bf :: String -> ([Integer],[Integer],[Integer]) -> ([Integer],[Integer],[Integer])
bf []          (x,y,z)= (x,y,z)
bf ('(':')':a) (x,y,z)= bf a (x,y,((pop z+1):rest z))
bf ('<':'>':a) (x,y,z)= bf a (y,x,z)
bf ('{':'}':a) (x,y,z)= bf a ((rest x),y,(topadd z (pop x)))
bf ('[':']':a) (x,y,z)= bf a (x,y,(topadd z (toInteger (length x))))
bf ('(':a)     (x,y,z)= bf a (x,y,(0:z))
bf ('<':a)     (x,y,z)= bf a (x,y,(0:z))
bf ('[':a)     (x,y,z)= bf a (x,y,(0:z))
bf (')':a) (x,y,(h:z))= bf a ((h:x),y,(topadd z h))
bf (']':a) (x,y,(h:z))= bf a (x,y,(topadd z (-h)))
bf ('>':a) (x,y,(_:z))= bf a (x,y,z)
bf ('{':a)      t     = bf (exterior a) (loop (interior a) t)
bf (_:a)        t     = bf a t

-- loop runs the same code until the TOS is zero
loop :: String -> ([Integer],[Integer],[Integer]) -> ([Integer],[Integer],[Integer])
loop s ([],y,z)  = ([],y,z)
loop s (0:x,y,z) = (0:x,y,z)
loop s x         = loop s (bf s x)

-- bl is an helper function of balance
bl :: String -> String -> Bool
bl [] [] = True
bl [] _  = False
bl ('(':x) y   = bl x (')':y)
bl ('[':x) y   = bl x (']':y)
bl ('<':x) y   = bl x ('>':y)
bl ('{':x) y   = bl x ('}':y)
bl  _ [] = False
bl (a:x) (b:y) = (a == b) && (bl x y)

-- balanced checks if a particular String is balanced
balanced :: String -> Bool
balanced x = bl x []

-- Implements Brain-Flak
brainflak :: String -> [Integer] -> [Integer]
brainflak s x
 | balanced source = (\(a,_,_) -> a) (bf source (x,[],[]))
 | otherwise  = error "Unbalanced braces."
 where source = [a|a <- s, elem a "()[]<>{}"]


texts:
Is this a good solution for the Number to Roman Numerals Kata in Javascript?

function toRomans(n) {
    var nString = n.toString();
    var result = "";
    var allLetters = [["I", "V", "X"], ["X", "L", "C"], ["C", "D", "M"], ["M"]];
    var letterSet = nString.length - 1;
    for (var index in nString) {
        result = result + conversor(nString[index], allLetters[letterSet]);
        letterSet --;
    }
    console.log(n + " --> " + result);
}

function conversor(digit, letterSet) {
    switch(digit) {
        case "1":
            return letterSet[0];
            break;

        case "2":
            return letterSet[0] + letterSet[0];
            break;

        case "3":
            return letterSet[0] + letterSet[0] + letterSet[0];
            break;

        case "4":
            return letterSet[0] + letterSet[1];
            break;

        case "5":
            return letterSet[1];
            break;

        case "6":
            return letterSet[1] + letterSet[0];
            break;

        case "7":
            return letterSet[1] + letterSet[0] + letterSet[0];
            break;

        case "8":
            return letterSet[1] + letterSet[0] + letterSet[0] + letterSet[0];
            break;

        case "9":
            return letterSet[0] + letterSet[2];
            break;

        case "0":
            // skip character
            return "";
            break;

        default:
            break;
        }

}

toRomans(2);
toRomans(7);
toRomans(32);
toRomans(456)
toRomans(1243);
toRomans(3500);


texts: Refactor function that returns a comma Operator to pass jsHint

texts:
Some background

This functions does some business logic before submitting a "add to cart" form

HTML

<form class="atcLoginRequired" method="get" action="/somePage">
    <input type="hidden" value="someVal" name="nextpage">
    <input name="ISODSCTX66WA_qty" type="text" value="1">
    <input name="ISODSCTX77WA_qty" type="text" value="1">
    <input type="Image" class="imageSubmit" src="ATCimage.jpg">
</p>

JavaScript

 var atcLoginRequired = $(".atcLoginRequired");
    if (!atcLoginRequired.length) return;
    atcLoginRequired.on("submit", function(){
        var jThis = $(this),
            nextPageInput = jThis.find("[name='nextpage']"),
            nextPageVal = nextPageInput.val(),
            skuValues = jThis.find("[name$='_qty']").map(function(){
                var jThat = $(this);
                return (jThat.remove(), jThat.attr("name") + "=" + jThat.val() + "&");
              // the return statement actually executes the first expression, and "returns" the second one..
            }).get().join("");
        $(".imageSubmit").remove(); // to avoid having the x and y passed
        skuValues = skuValues.substring(0, skuValues.length - 1);
        nextPageInput.val(nextPageVal + "" + skuValues);
    });

The question

What can I do to make this it pass jsHint?
What can I do to make this better in terms of readability, performance and extensibility ?


texts:
I've been going through some 2019 AoC challenges and decided to solve Day 6 in Haskell with the help of Data.Tree.
In summary, the puzzle provides a list of orbits (edges) as input, resembling:
COM)B
B)C
C)D
D)E
E)F
B)G
G)H
D)I
E)J
J)K
K)L
K)YOU
I)SAN

where COM is supposedly the centre of all orbits (i.e. the root). We are tasked with parsing this and...

for Part 1: Find the total number of direct and indirect orbits. In the example,

B directly orbits COM
C directly orbits B (hence, indirectly orbiting COM)
D directly orbits C (hence, indirectly orbiting B and COM)
and so on...

for Part 2: Find the minimum number of orbital transfers. Basically, the number of traversals needed to get from the orbit of YOU to the orbit of SAN. In the example, the traversals are K -> J -> E -> D -> I. Hence, the minimum number of transfers is 4.

Here is my solution to both parts:
import Data.Tree

type Satellite = String
type STree = Tree Satellite
type Orbit = (Satellite, Satellite)

--  Part 1
main :: IO ()
main = interact $ show . countOrbits . fromOrbits . map parseOrbit . lines

--  Part 2
-- main :: IO ()
-- main = interact $ show . findMinimumTransfers "YOU" "SAN" . fromOrbits . map parseOrbit . lines

parseOrbit :: String -> Orbit
parseOrbit s = (takeWhile (/= ')') s, tail $ dropWhile (/= ')') s)

fromOrbits :: [Orbit] -> STree
fromOrbits orbits = construct "COM"
    where construct :: Satellite -> STree
          construct root = Node { rootLabel = root, subForest = map construct $ children root }

          children :: Satellite -> [Satellite]
          children sat = map snd $ filter ((== sat) . fst) orbits

countOrbits :: STree -> Integer
countOrbits = countOrbitsImpl 0
    where countOrbitsImpl :: Integer -> STree -> Integer
          countOrbitsImpl depth (Node rootLabel subForest)
                | length subForest == 0 = depth
                | otherwise = depth + (sum $ map (countOrbitsImpl (depth + 1)) subForest)

-- finds the minimum number of orbital transfers required between two targets
findMinimumTransfers :: Satellite -> Satellite -> STree -> Int
findMinimumTransfers tar tar' = findImpl 0
    where -- find the common node where targets are (possibly indirect) children
          findImpl :: Int -> STree -> Int
          findImpl depth (Node rootLabel subForest)
                | rootLabel == tar || rootLabel == tar' = depth - 1
                | length subForest == 0 = 0
                | otherwise =
                    let childResults = filter (/= 0) $ map (findImpl (depth + 1)) subForest
                    in  if length childResults == 2
                        then sum childResults - (depth * length childResults)   --  found common node
                        else sum childResults   --  propagate results

I'm itching for feedback on the recursion. I use it mainly to keep track of a node's depth and later return it as part of the result... but is there a "better" way to write this? Maybe with folds or applicatives?
I did think about keeping depth as part of a node's data (so that we might have type STree = Tree (Satellite, Int)), then maybe we could fold over that, but I didn't want to "bloat" the structure with redundant information.
Other feedback is also welcome. Thanks!
N.B. this is not a duplicate of AdventOfCode 2019 day 6 in Haskell as the implementation is different.


texts:
private static List<ConstrDirectedEdge> kruskalConstruct(ConstructionDigraph CG) {

    int current = CG.srcVertexIndex();
    boolean visited[] = new boolean[CG.V()];
    visited[current] = true;
    UF uf = new UF(CG.V());
    List<ConstrDirectedEdge> feasibleNeighbours = new ArrayList<ConstrDirectedEdge>();
    List<ConstrDirectedEdge> solution = new ArrayList<ConstrDirectedEdge>();

    do {
        /* clear neighbours from prev iteration */
        feasibleNeighbours.clear();

        /* build feasible neighbour list */
        for (ConstrDirectedEdge directedEdge : CG.adj(current)) {
            int v = CG.getVertex(directedEdge.to()).getSource();
            int w = CG.getVertex(directedEdge.to()).getDestination();

            if (!visited[directedEdge.to()] && !uf.connected(v, w)) {
                feasibleNeighbours.add(directedEdge);
            }
        }

        //TODO: code smell
        if (feasibleNeighbours.isEmpty()) {
            break;
        }

        /* calculate the probability for each neighbour */
        double R = calculateR(feasibleNeighbours);
        System.out.println("R for source is : " + R);
        for (ConstrDirectedEdge feasibleneighbour : feasibleNeighbours) {
            feasibleneighbour.calcProbability(R, alpha, beta);
        }

        /* pick a neighbour */
        ConstrDirectedEdge pickedUp = choiceEdgeAtRandom(feasibleNeighbours);
        visited[pickedUp.to()] = true;
        current = pickedUp.to();
        solution.add(pickedUp);
        uf.union(CG.getVertex(current).getSource(),   CG.getVertex(current).getDestination());
    } while (!feasibleNeighbours.isEmpty());

    return solution;
}

I want to eliminate the code smell that is the break in the middle of the loop. As can be seen I have chosen to use a do {} while() in order to do the initialization with the initial node being CG.srcVertexIndex(). What I was thinking about is make the following code:

        for (ConstrDirectedEdge directedEdge : CG.adj(current)) {
            int v = CG.getVertex(directedEdge.to()).getSource();
            int w = CG.getVertex(directedEdge.to()).getDestination();

            if (!visited[directedEdge.to()] && !uf.connected(v, w)) {
                feasibleNeighbours.add(directedEdge);
            }
        }

into a separate function that will be returning a List<ConstrDirectedEdge> and then the loop can turn into:

while(!(feasibleNeighbours = getFeasibleNeighbours(CG, visited,  uf)).isEmpty()) {
/* calculate the probability for each neighbour */
/* pick a neighbour */
}

But then I will have to pass visited and uf as parameter which in fact are going to be manipulated by getFeasibleNeighbours functions - in essence I will be using input parameters to store output state which is not a good idea.

Finally I could just make visited and uf static private vars and just reinitialize them when needed and use them directly, but again this seems kind of wrong.

The code is working fine, however I'd like to hear opinions on how this can be made more readable.


texts: C# Update account based on user order data. Nested if-else optimization with almost similar values

texts:
The method works, but I would like to know if there is any way to make it more readable, optimized?
I have user data (i want to import/update it).
Accounts is finded by user data.
========
User order data is entered into the system.
userData.Id - user Id; userData.OrderNumber - user order number.
The "UpdateAccount" method below is used by the user.
The user enters their Id and OrderNumber into the system (there are FirstName, LastName, etc., but they are irrelevant here because they are used in the UpdateAllUserDataToAccount method).
Therefore, it is necessary to discover whether an account with the relevant data exists in the system.
You can update account data if the account has userData.OrderNumber or userData.Id.
If no account under userData.OrderNumber or userData.Id is found in the system then create a new account and update its data.
Do not allow anything if userData.OrderNumber, userData.Id is in different account (can not exist in the system in different account).
An account can have userData.OrderNumber in the system and not userData.Id because the employee registered the parcel but did not have a user id.
An account can have userData.Id in the system and not userData.OrderNumber because the user has previously been registered in the system.
The user data userData.OrderNumber and userData.Id are unique and belong to only one user.
bool _isSpecialData - to indicate that the user is special (set before this code).
private void UpdateAccount(UserModel userData)
{
    Account accountById = _accountController.GetAccountById(userData.Id);
    Account accountByNumber = _accountController.GetAccountByNumber(userData.Number);
    bool _isSpecialData = accountByNumber != null ? accountByNumber.Vip : false;

    if (accountById != null)
    {
        if (accountByNumber != null)
        {
            if (accountById.Id == accountByNumber.Id)
            {
                if (_isSpecialData)
                {
                    AddPartUserDataToAccount(userData, accountByNumber);

                    if (userData.Status == Blocked) return;
                }
            }
            else
            {
                _log.Error($"User data can not be in different accounts");
                return;
            }
        }
        else
        {
            AddPartUserDataToAccount(userData, accountById);
        }
    }
    else
    {
        if (accountByNumber != null)
        {
            if (accountByNumber.Id == null)
            {
                accountByNumber.Id = userData.Id;

                if (_isSpecialData)
                {
                    AddPartUserDataToAccount(userData, accountByNumber);
                    if (userData.Status == Blocked) return;
                }
            }
            else
            {
                _log.Error($"accountByNumber.Id can be just with the same value as userData.Id or with null (because it was not set in first place)");
                return;
            }
        }
        else
        {
            CreateNewAccount(userData);
        }
    }

    UpdateAllUserDataToAccount(userData);
}


texts:
I have a .json file with a complex structure: dict in a dict, it has no constant structure and is dynamically changed.

The goal is to make new dict where the keys are numbers of hierarchy and values must be strings that are composed of all previous steps like

2 drinks
2.1 drinks coffee
2.1.1 drinks coffee instant
2.1.2 drinks coffee real
2.2 drinks tea
2.3 drinks water

I wrote a script, and it works. But as I am new to Python and in programming, please check it out and correct me in order to code may look and perform more elegantly and in a pythonic way.

Also I would like to decrease time of execution because the input .json file is going to be quite big.

Sample cat.json file:

{
"communication":
    {"mobile":{
        "vodafone":{"subscr":"","txt":"","mms":"","internet":"","calls":
    {"in":{"home":"","roaming":""},"out":{"home":"","roaming":""}}},
        "verizon":{"subscr":"","txt":"","mms":"","internet":"1Gb","calls":
    {"in":{"home":"","roaming":""},"out":{"home":"500 min","roaming":"Other country"}}}},
    "internet":"SomeProviderName"
    },
"food":{"dairy":{"cheese":"Gauda","milk":{"brand":"name","origin":"place"}}},
"drinks":
        {
        "water":"",
        "tea":"",
        "coffee":
                {
                "instant":"",
                "real":""
                }}}

Script:

#!/usr/bin/env python -tt
# -*- coding: utf-8 -*-
import json
filetoread='cat.json'
def load_existed(filetoread):

try:
    data=json.loads(open(filetoread).read())
    return data

except ValueError:
    print 'data  loading error'

cat_data=load_existed(filetoread)

def walk_dict(d,mess,ln,new_dict,crumbs):
    inter=1
    lc=list(mess)
    last_crumb=crumbs.split( )

    for k,v in sorted(d.items(),key=lambda x: x[0]):
        if mess=='':
            mess=str(inter)
            lc=list(mess)
            last_crumb=crumbs.split( )
        if isinstance(v, dict) :
            ln=len(v)
            lc[len(lc)-1]=str(inter)
            mess="".join(lc)
            crumbs=" ".join(last_crumb)
            if len(crumbs.split( ))>0:
                crumbs=crumbs+" "+k
            else:
                crumbs=k
            #print mess,'-->',k,">"
            new_dict[mess]=crumbs
            mess=mess+'.1'
            walk_dict(v,mess,ln,new_dict,crumbs)
        else:
            if ln>0:
                ln=ln-1
                lc[len(lc)-1]=str(inter)
                mess="".join(lc)
                crumbs=" ".join(last_crumb)
                crumbs=crumbs+" "+k+" "+v
            #print  mess,'-->',"%s -> %s" % (k, v)
            new_dict[mess]=crumbs
        inter=inter+1
    return new_dict

new_data=walk_dict(cat_data,"",0,{},'')
print "-"*30
#print new_data
for v in sorted(new_data):
  print v, new_data[v]


texts: Minimum number of parentheses to be removed to make a string of parentheses balanced

texts:
The task:

  Given a string of parentheses, write a function to compute the minimum
  number of parentheses to be removed to make the string valid (i.e.
  each open parenthesis is eventually closed).

  For example, given the string "()())()", you should return 1. Given
  the string ")(", you should return 2, since we must remove all of
  them.

const brackets = "()())()";

My functional solution:

const numberOfUnbalanced = brackets => Object.values(brackets
  .split("")
  .reduce((brackCounter, b) => {
    b === "(" ? brackCounter.openBrackets++ :
    brackCounter.openBrackets ? brackCounter.openBrackets-- :
    brackCounter.closedBrackets++;

    return brackCounter;
  }, {openBrackets: 0, closedBrackets: 0}))
.reduce((sum, b) => sum + b, 0);

console.log(numberOfUnbalanced(brackets));

My imperative solution:

function numberOfUnbalanced2(brackets) {
  let openBrackets = 0, closedBrackets = 0;
  for (let i in brackets) {
    brackets[i] === "(" ? openBrackets++ :
    openBrackets ? openBrackets-- :
    closedBrackets++;
  }
  return openBrackets + closedBrackets;
}

console.log(numberOfUnbalanced2(brackets));

Usually the functional approach is shorter and tend to be easier to understand in comparison to imperative approaches. However, in this case it doesn't have any advantage to the imperative approach. I guess it is due to the nested  structure in the functional solution.


texts: Compare lines in 2 text files with different numbers of fields

texts:
This is the (hopefully) final version of my script for my file comparison problem mentioned previously in two posts on Stack Overflow  (here and here).

I have come up with the code shown below, which does what I need it to do, but I'm wondering if it can be written in a more pythonic (read elegant) way, especially the clean up of the lists.

#!/usr/bin/python
import sys
import csv

f1 = sys.argv[1]
f2 = sys.argv[2]

with open(f1) as i, open(f2) as j:
    a = csv.reader(i)
    b = csv.reader(j)
    for linea in a:
        lineb = next(b)
        lista = ([x for x in linea if len(x) > 0])
        listastr = map(str.strip, lista)
        listastrne = filter(None, listastr)
        listb = ([x for x in lineb if len(x) > 0])
        listbstr = map(str.strip, listb)
        listbstrne = filter(None, listbstr)
        if len(listastrne) != len(listbstrne):
            print('Line {}: different fields: A: {} B: {}'.format(a.line_num, listastrne, listbstrne))
        elif sorted(map(str.lower, listastrne)) != sorted(map(str.lower, listbstrne)):
            print('Line {}: {} does not match {}'.format(a.line_num, listastrne, listbstrne))

Example input files:

A.csv:

1,2,,
1,2,2,3,4
1,2,3,4
X
AAA,BBB,CCC
DDD,,EEE,
GGG,HHH,III
XXX,YYY   ,ZZZ

 k,

B.csv:

1,2,2,2
1,2,3,4
1,2,3,4
W
AAA,,BBB,CCC
EEE,,DDD,,
,,GGG,III,HHH
XXX,YYY,ZZZ

,


texts: This code looks really repetitive. Any way to shorten it?

texts:
I have something like this in my program:

    private void tspBrush_Click(object sender, EventArgs e)
    {
        currentTool = new Brush(tileLayers);

        UncheckToolstripButtons();

        tspBrush.Checked = true;
    }

    private void tspBucket_Click(object sender, EventArgs e)
    {
        currentTool = new Bucket(tileLayers);

        UncheckToolstripButtons();

        tspBucket.Checked = true;
    }

    private void tspCut_Click(object sender, EventArgs e)
    {
        currentTool = new Cut(tileLayers);

        UncheckToolstripButtons();

        tspCut.Checked = true;
    }

As I increase the amount of tools this list will only get longer. Is there something I could do to shorten it?


texts: Project Euler #3 in C# - largest prime factor

texts:
I just started doing the Project Euler challenges and right now I'm on Challenge #3 - The largest prime factor of 600851475143.

I wrote some code and tried to optimize it based on some other Stack Overflow users' advice.

What I got is this code which does its job, but I think it takes longer than it should - calculating high numbers like 600851475143 takes forever!

Am I in the right way? How could I optimize it?

using System;

namespace ProjectEuler_LargestPrimeFactor
{
    class Program
    {
        static long numberToFactor = 600851475143;

        static void Main(string[] args)
        {
            Console.WriteLine(LargestPrimeFactorOf(numberToFactor) + " is the largest prime factor of " + numberToFactor);
            Console.ReadKey();
        }

        static long LargestPrimeFactorOf(long n)
        {
            long lastPrimeFactor = 0;

            for (long i = 2; i < n; i++)
            {
                if (isPrime(i) && n % i == 0)
                {
                    lastPrimeFactor = i;
                    Console.WriteLine(i + " is a prime factor of " + n);
                }
            }

            return lastPrimeFactor;
        }

        static bool isPrime(long n)
        {
            if (n == 2) return true;
            if ((n > 2 && n % 2 == 0) || n == 1) return false;

            for (long i = 2; i <= Math.Floor(Math.Sqrt(n)); ++i)
            {
                if (n % i == 0) return false;
            }

            return true;
        }
    }
}


texts:
I wrote the following code for printing all the paths to the leaf nodes in a tree (NOT a binary tree ) without using recursion. I have used a stack and performed dfs on the tree. Whenever I reach a leaf node I pop all the elements in the stack right till the root so that the function starts over again from the root and prints a path to another leaf.

The tree that I have assumed in the program is as follows

                              0
                      1            2       3
              4   5      6              7     8

Explanation:

1, 2 and 3 are children of 0;
4, 5, 6 are children of 1;
7 and 8 are children of 3.

My code

//print paths in a tree without recursion
#include<iostream>
#include<vector>
#include<stack>
using namespace std;
struct node
{
       int data;
       vector<node*>children;
};
int visited[100];
stack <node*> st;
int count=0;
int n;
void printpath(node * root)                               //dfs starts here
{
     st.push(root);
     while(visited[0]==0)
     {
         node* v=st.top();
         if(visited[v->data]!=0)                 // leaf nodes or nodes whose all children
            st.pop();                            // are visited are only popped from the stack
         if(visited[v->data])
            continue;
         cout<<v->data<<" ";
         int flag=0;
         for(int i=0;i<v->children.size();i++)      /*check if any of the children have not been visited*/
         {
                 if(visited[v->children[i]->data]==0)
                 {
                      flag=flag||1;
                      st.push(v->children[i]);
                 }
                 else
                       flag=flag||0;
         }

         /*if this is the leaf node then mark it visited and
         along with other intermediate nodes whose all the
         children have been visited.this is continued till we
         reach root which has the value 0 in its data*/

         if(flag==0)
         {
                 visited[v->data]=1;
                  while(v->data!=0)
                  {
                     v=st.top();
                     int flag=0;
                     for(int i=0;i<v->children.size();i++)
                     {
                        if(visited[v->children[i]->data]==0)
                          flag=flag||1;
                       else
                         flag=flag||0;
                     }
                        if(flag==0 && v->children.size()!=0)
                          visited[v->data]=1;
                        if(v->data!=0)
                          st.pop();
                  }
                  cout<<endl;
         }
     }
}
main()
{
   n=8;
   for(int i=0;i<9;i++)
       visited[i]=0;
   node*root = new node();                         //tree construction
   root->data=0;
   node* d = new node();
   d->data=1;
   node* m = new node();
   m->data=2;
   node* n = new node();
   n->data=3;
   root->children.push_back(d);
   root->children.push_back(m);
   root->children.push_back(n);
   node* x = new node();
   x->data=4;
   node* y = new node();
   y->data=5;
   node* z = new node();
   z->data=6;
   d->children.push_back(x);
   d->children.push_back(y);
   d->children.push_back(z);
   node* o = new node();
   o->data=7;
   node* p = new node();
   p->data=8;
   n->children.push_back(o);
   n->children.push_back(p);
   printpath(root);
}

My algorithm seems really inefficient. Can anyone suggest some ways to improve it?

The output is:

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


texts: User Authentication/Permissions for PHP MySQL CRUD

texts:
I took my first stab at a user authentication function. I invented my own way of doing this. Is this a safe and efficient way of giving a user Read/Edit/Delete permission on tables in a MySQL database?

The Class

class Personnel {
//set tables that will need permissions and actions
protected static $actions = array("read", "edit", "delete");
protected static $table_names = array("species", "users", "news");

//this will generate a form with checkbox for each position in the permissions array
public static function set_permissions_form($current_permissions) {

    for($i=0; $i<count(self::$table_names); $i++) {
        $table_name = self::$table_names[$i];
        $form .= $table_name . ":
";
        for($z=0; $z<count(self::$actions); $z++) {
            $action = self::$actions[$z];
            $form .= $action . ": <input type='checkbox' name='permissions[" . $table_name . "][" . $action . "]'";
            if($current_permissions) {
                $form .= ($current_permissions[$table_name][$action] == "1" ? " checked =\"checked\"" : "");
            }
            $form .= " value=1 />";
            $form .= "
";
        }
    }
    return $form;
}
}

The Form

If this is a new user or an existing user with no permissions set then $current_permissions will be NULL. If a permissions array does exist in the database unserialize it and check any checkbox when name = array key.

$current_permissions = unserialize($personnel->permissions);
$form = "<form action='save_personnel.php' method='post'>";
$form .= Personnel::set_permissions_form($current_permissions);
$form .= "<input type='submit' value='Save Changes' />";
$form .= "</form>";
echo $form;

Save

Once the form is submitted each box checked will be a "1" in the permissions array. This next snippet serializes the array and stores it in the database. I did not include code for $personnel->save() but you know what it does. Create user if does not exist, update user if it does.

$personnel = new Personnel();
$personnel->permissions = serialize($_POST['permissions']);
if($personnel->save()) {
    redirect_to("manage_personnel.php");
}

Check for Permission

The next steps I haven't completed yet but basically it will pull $personnel->permissions from database and unserialize it. Then say it is on a page where user is trying to edit species, $permissions["species"]["read"] == '1' ? you shall pass : you shall not pass;.

Am I heading in the right direction with this or am I over complicating?


texts: Print values of an array while stripping out some parts of the string

texts:
Is there a more efficient way to run this? I am especially interested in a way which perhaps does not require a for loop...

shopt -s nullglob

file=
declare -a ARRAY1
ARRAY1=( ~lettus_*.sh )
for file in ${ARRAY1[@]}
do
    ##
    ## Get <name> from /some/path/lettus_name.sh
    ##

    # remove .sh extension
    file=${file%.sh}

    #  remove full path up to and including lettus_
    file=${file//*lettus_}

    echo $file
done

shopt -u nullglob


texts: Generate unique string permutations recursively

texts:
Objective

Write a recursive method for generating all permutations of an input string. Return them as a set.

See: Recursive String Permutations - Interview Cake
 Questions
1: How does the problem change if the string can have duplicate characters?

The solution below works with duplicate characters because the index of the original input is used to generate unique combinations of the original input minus the character at the given index. Therefore, there may be duplicate characters, however, their unique indexes will generate the correct solution.

2: What is the space and time complexity?

Time Complexity: \$O(n^2)\$ because there is one iteration through the input for which index to examine, and a second iteration, placing the character at each position of the input to generate various combinations. Therefore, \$n x n\$. This follows the rule, do X for each time of Y. See: Time complexity of all permutations of a string - GeeksforGeeks

Space Complexity: Is the space complexity also quadratic \$O(n^2)\$ because the unique permutations stored in a Set would grow quickly based on the size of the initial input?

3: How to optimize the time and space complexity?

Time Complexity: I do not see further time complexity optimizations.

Space Complexity: I do not see further space complexity optimizations because the solution syntactically is recursive, but performs iteratively. The recursive part of the code, allPerm performs after each iteration through the input. Therefore, there are no methods saved onto the JVM's call stack.

 Code

Iterate through each char and move the char to each position of the input String.
Add each version to a Set.

fun allPerm(input: String, lookAtIndex: Int, set: HashSet<String>): HashSet<String> {
    if (lookAtIndex <= input.length - 1) {
        for (i in 0 .. input.length - 1) {
            val combo = input.substring(0, lookAtIndex) +
                    input.substring(lookAtIndex + 1)
            set.add(combo.substring(0, i) + input.get(lookAtIndex) +
                    combo.substring(i))
        }
        allPerm(input, lookAtIndex + 1, set)
    }
    return set
}

See: GitHub