texts:
This is the program function code for clustering using k-medoids

def kMedoids(D, k, tmax=100):
    # determine dimensions of distance matrix D
    m, n = D.shape
    # randomly initialize an array of k medoid indices
    M = np.sort(np.random.choice(n, k)
    # create a copy of the array of medoid indices
    Mnew = np.copy(M)
    # initialize a dictionary to represent clusters
    C = {}
    for t in range(tmax):
    # determine clusters, i.e. arrays of data indices
        J = np.argmin(D[:,M], axis=1)
        for kappa in range(k):
            C[kappa] = np.where(J==kappa)[0]
        # update cluster medoids
        for kappa in range(k):
            J = np.mean(D[np.ix_(C[kappa],C[kappa])],axis=1)
            j = np.argmin(J)
            Mnew[kappa] = C[kappa][j]
            np.sort(Mnew)
            # check for convergence
            if np.array_equal(M, Mnew):
                break
                M = np.copy(Mnew)
            else:
                # final update of cluster memberships
                J = np.argmin(D[:,M], axis=1)
                for kappa in range(k):
                    C[kappa] = np.where(J==kappa)[0]
                    # return results
            return M, C

and the I will call The function KMedoids with this program, I think my program run slowly in line D = Pairwise_distances(arraydata, metric='euclidean')

D = pairwise_distances(arraydata,metric='euclidean')

# split into 2 clusters
M, C = kMedoids(D, 2)

print('medoids:')
for point_idx in M:
    print(arraydata[point_idx] )

print('')
# array for get label
temp = []
indeks = []
print('clustering result:')
for label in C:
    for point_idx in C[label]:
        print('label {0}:　{1}'.format(label, arraydata[point_idx]))
        temp.append(label)
        indeks.append(point_idx)

This is the result from this program

clustering result:
label 0:　[0.00000000e+00 0.00000000e+00 1.00000000e+00 1.00000000e+00
1.00000000e+00 1.00000000e+00 1.00000000e+00 1.00000000e+00
1.00000000e+00 1.00000000e+00 1.00000000e+00 1.00000000e+00
1.00000000e+00 1.00000000e+00 1.00000000e+00 1.00000000e+00
1.00000000e+00 1.00000000e+00 1.00000000e+00 1.00000000e+00
1.00000000e+00 1.00000000e+00 1.00000000e+00 1.00000000e+00
1.00000000e+00 0.00000000e+00 1.00000000e+00 1.00000000e+00

Why my result of my program is slow for large data and almost have a result "Memory Error"?  I hope someone can help me to review this code to improve its performance to get the result and process large amounts of data.


texts: C# API Wrapper with Static Function Calls

texts:
I'm creating a wrapper library for an API, and I hit a block on how to redesign it. The entire library is static, and I'd like to change it to make it more testable.

The library's goal is to make rest api requests and return C# objects. There is a networking class, which makes the requests. And there is a class for each endpoint which abstracts the parameters for the request and supplies the relative url.

Networking class: build url, create headers, and return results from request

public class APIClient{

private static string url = null;
private static string apiKey = null;

public static void Initialize(string key,string url)
    {
        APIClient.url = url;
        APIClient.apiKey = key;
    }

public static async Task<T> GetAsync<T>(string path, Dictionary<string, string> parameters)
    {
        var client = CreateHttpClientFromApiCredentials();

        //build url with parameters from the dictionary
        var builder = new UriBuilder("", path);
        builder.Port = -1;

        if (parameters != null)
        {
            var query = HttpUtility.ParseQueryString("");
            foreach (var key in parameters.Keys)
                query[key] = parameters[key];

            builder.Query = query.ToString();
        }

        var response = await client.GetAsync(builder.ToString());

        if (!response.IsSuccessStatusCode)
            throw new HttpException((int)response.StatusCode, response.ReasonPhrase);

        //evaluate API specific data
        return await EvaluateResponseContent<T>(response);
    }
}

Sample endpoint class: provide relative url and arguments to networking class

public class APIObject
{
    public static async Task<List<APIObject>> Get()
    {
        return await APIClient.GetAsync<List<APIObject>>("objectendpoint",null);
    }

}

This design allows for very simple use, with calls like APIObject.Get().

With that said, I have a redesign in mind that will maintain the simplicity of the static functions while also allowing for easy testing. The APIClient will be refactored to be an object, and each of the API object classes will be a nested class inside the APIClient.

A brief example (untested):

public class APIClient
{
    public ApiObjectSender ApiObjectEndpoint;

    public APIClient() {
        ApiObjectEndpoint = new ApiObjectSender(this);
    }

    public class ApiObjectSender
    {
        APIClient apiClient;

        public ApiObjectSender(APIClient cl)
        {
            apiClient = cl;
        }

        public List<APIObject> Get()
        {
            return apiClient.Get("apiobjectendpoint");
        }
    }
}

This allows for similar function calls, like clientVar.ApiObjectEndpoint.Get(). However, I can't help but feel like this approach is... janky.


texts:
My last question had a lot of views (over a 1000) so I decided to apply what I learned from the previous question and revamp the program. I learnt a lot from posting that question (functions, how to do a menu without using using a lot of printf and learning to not repeat code etc). So here's the updated program:

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

//Function prototype
void getData(int *,int *);
int addition(int,int);
int subtraction(int,int);
int multiplication(int,int);
int division(int,int);

//Main function
int main()
{
    do//Infinite do - While loop
    {
        int num1,num2,choice;

        printf("\nEnter a number from the list below\n\n"
               "\t1. Addition\n"
               "\t2. Subtraction\n"
               "\t3. Multiplication\n"
               "\t4. Division\n"
               "\t0. Quit program\n");

        printf("\nEnter number: ");
        scanf("%d",&choice);

        if (choice == 0)
        {
            puts("\nExiting program...");
            exit(0);
        }
        else
        {
            getData(&num1,&num2);//Get values for user input

            if(choice == 1)
            {
                printf("\n%d + %d = %d\n",num1,num2,addition(num1,num2));//Output addition
            }
            else if(choice == 2)
            {
                printf("\n%d - %d = %d\n",num1,num2,subtraction(num1,num2));//Output subtraction
            }
            else if(choice == 3)
            {
                printf("\n%d * %d = %d\n",num1,num2,multiplication(num1,num2));//Output multiplication
            }
            else if(choice == 4)
            {
                if(num2 == 0)
                {
                    printf("\nError! Division by zero! Exiting program\n");
                    exit(1);
                }
                else
                {
                    printf("\n%d / %d = %d\n",num1,num2,division(num1,num2));//Output division
                }
            }
            else
            {
                printf("Enter correct number! Exiting program");
                exit(1);
            }
        }
    }while(1);
}

//Get memory address of num1, num2 and store values in this location
void getData(int *num1_ptr,int *num2_ptr)
{
  printf("\nEnter first number: ");
  scanf("%d",num1_ptr);

  printf("\nEnter second number: ");
  scanf("%d",num2_ptr);
}

//Addition
int addition(num1,num2)
{
    return num1 + num2;
}

//Subtraction
int subtraction(int num1,int num2)
{
    return num1 - num2;
}

//Multiplication
int multiplication(int num1,int num2)
{
    return num1 * num2;
}

//Division
int division(int num1,int num2)
{
    return num1 / num2;
}
//End of code


texts:
std::stoi may throw exceptions so it needs to be surrounded by try/catch.

In applications where std::stoi may be used frequently, it could be useful to have a wrapper.

Is this good practice?

int _stoi(std::string str, int* p_value) {
    // wrapping std::stoi because it may throw an exception

    try {
        *p_value = std::stoi(str);
        return 0;
    }

    catch (const std::invalid_argument& ia) {
        //std::cerr << "Invalid argument: " << ia.what() << std::endl;
        return -1;
    }

    catch (const std::out_of_range& oor) {
        //std::cerr << "Out of Range error: " << oor.what() << std::endl;
        return -2;
    }

    catch (const std::exception& e)
    {
        //std::cerr << "Undefined error: " << e.what() << std::endl;
        return -3;
    }
}


texts: Unity3D script for controlling a character

texts:
This is a Unity3D script I wrote for my game to control a character. I don't consider myself a highly-skilled coder, so I come here to ask for suggestions. Is my code clean enough? How can I improve my coding style and pattern?

using UnityEngine;

public enum OnWallStatus
{
    None = 0,
    OnLeft = 1,
    OnRight = 2
}

public enum OnGroundStatus
{
    OnGround = 0,
    InAir = 1
}

public class MoveControl : MonoBehaviour {

    private const float minSpeed = 1f;
    private const float maxSpeed = 5f;
    private const float minJump = 1f;
    private const float maxJump = 10f;

    [SerializeField]
    private float speedModifier;
    [SerializeField]
    private float jumpModifier;

    private new Rigidbody2D rigidbody2D;
    private new Transform transform;

    private OnGroundStatus _onGroundStatus;
    private OnWallStatus _onWallStatus;

    public OnGroundStatus onGroundStatus
    {
        get { return _onGroundStatus; }
    }

    public OnWallStatus onWallStatus
    {
        get { return _onWallStatus; }
    }

    private bool isHorizontalStill
    {
        get { return (rigidbody2D.velocity.x == 0); }
    }

    private bool isVerticalStill
    {
        get { return (rigidbody2D.velocity.y == 0); }
    }

    void Awake ()
    {
        speedModifier = Mathf.Clamp(speedModifier, minSpeed, maxSpeed);
        jumpModifier = Mathf.Clamp(jumpModifier, minJump, maxJump);

        rigidbody2D = GetComponent<Rigidbody2D>();
        transform = GetComponent<Transform>();

        _onGroundStatus = OnGroundStatus.OnGround;
        _onWallStatus = OnWallStatus.None;
    }

    public void MoveHorizontal(float speed)
    {
        speed = Mathf.Clamp(speed, -1f, 1f);
        rigidbody2D.AddForce(new Vector2(speed * speedModifier * 10f, 0f));

        Vector2 velocity = rigidbody2D.velocity;
        velocity.x = Mathf.Clamp(velocity.x, -1f * speedModifier, 1f * speedModifier);
        rigidbody2D.velocity = velocity;
    }

    public void MoveJump(float speed)
    {
        if (_onWallStatus == OnWallStatus.None && _onGroundStatus == OnGroundStatus.InAir)
            return;

        speed = Mathf.Clamp(speed, 0f, 1f);

        if (_onGroundStatus == OnGroundStatus.OnGround)
        {
            rigidbody2D.velocity = new Vector2(rigidbody2D.velocity.x, speed * jumpModifier);
        }
        else if(_onWallStatus == OnWallStatus.OnLeft)
        {
            rigidbody2D.velocity = new Vector2(1f * speedModifier, speed * jumpModifier);
        }
        else if (_onWallStatus == OnWallStatus.OnRight)
        {
            rigidbody2D.velocity = new Vector2(-1f * speedModifier, speed * jumpModifier);
        }
    }

    public void MoveLand(float speed)
    {
        if (_onWallStatus != OnWallStatus.None || _onGroundStatus != OnGroundStatus.InAir)
            return;

        speed = Mathf.Clamp(speed, -1f, 0f);
        rigidbody2D.velocity = new Vector2(rigidbody2D.velocity.x, speed * jumpModifier);
    }

    void OnCollisionEnter2D(Collision2D collision)
    {
        if (collision.gameObject.tag != "Platform")
            return;

        if (collision.contacts[0].normal.y > 0)
        {
            _onGroundStatus = OnGroundStatus.OnGround;
        }
        else
        {
            if(collision.contacts[0].normal.x < 0)
            {
                _onWallStatus = OnWallStatus.OnRight;
            }
            else
            {
                _onWallStatus = OnWallStatus.OnLeft;
            }
        }
    }

    void OnCollisionExit2D(Collision2D collision)
    {
        if (collision.gameObject.tag != "Platform")
            return;

        if (collision.contacts[0].normal.y > 0)
        {
            _onGroundStatus = OnGroundStatus.InAir;
        }
        else
        {
            _onWallStatus = OnWallStatus.None;
        }
    }

}


texts: Rewrite apply function to use recursion instead

texts:
Probably the hardest part of learning lisp has been to think in the "lisp way" which is elegant and impressive, but not always easy. I know that recursion is used to solve a lot of problems, and I am working through a book that instead uses apply to solve a lot of problems, which I understand is not as lispy, and also not as portable.

An experienced lisper should be able to help with this logic without knowing specifically what describe-path, location, and edges refer to. Here is an example in a book I am working through:

(defun describe-paths (location edges)
  (apply (function append) (mapcar #'describe-path
               (cdr (assoc location edges)))))

I have successfully rewritten this to avoid apply and use recursion instead. It seems to be working:

(defun describe-paths-recursive (location edges)
  (labels ((processx-edge (edge)
         (if (null edge)
         nil
         (append (describe-path (first edge))
             (processx-edge (rest edge))))))
    (processx-edge (cdr (assoc location edges)))))

I would like some more seasoned pairs of eyes on this to advise if there is a more elegant way to translate the apply to recursion, or if I have done something unwise. This code seems decent, but would there been something even more "lispy" ?


texts: The beginnings of a bootloader using GNU-based tools

texts:
This is a personal project of mine.  I am currently in the research phase of developing my own bootloader that will be used to load a single task operating system. I am far away from the final goal, but have been trying to document my process as a reference. The content of my code documentation and code can be found at Bootloader 101.

If possible I would appreciate feedback. The wiki page is open to be edited, and if you feel like you can contribute please feel free to do so. I apologize beforehand for referencing you to another page.  The format of the content is important.

First piece of code:

   # Author: Matthew Hoggan
   # Date Created: Tuesday, Mar 6, 2012
   .code16                        # Tell assembler to work in 16 bit mode (directive)
   .section .text
   .globl _start                  # Help linker find start of program
   _start:
       movb $0x0e,     %ah        # Function to print a character to the screen
       movb $0x00,     %bh        # Indicate the page number
       movb $0x07,     %bl        # Text attribute
       mov  $'A',      %al        # Move data into low nibble
       int  $0x10                 # Video Service Request to Bios
   _hang:
       jmp  _hang
       .end

   /* linker.ld */
   SECTIONS
   {
       /* Set location counter to 0x7c00 */
       . = 0x7c00;
       .text : { *(.text) }
       .data : { *(.data) }
       .other :
       {
            FILL(0x000000)
            . = 0x1F2;
            BYTE(0x55)
            BYTE(0xAA)
       }
   }

Second piece of code:

   # Author: Susam Pal <http://susam.in/>
   .code16                        # Tell the assembler to use 16 bit instructions
   .section .text
   .globl _start
   _start:                        # Tell linker where entry point into program is
       mov $0xb800, %ax           # 0xb800 is the start address of character buffer
       mov %ax, %ds               # Move that address into the data segment
       movb $'B', %ds:0x00        # Write data directly to that buffer at 0
       movb $0x1e, %ds:0x01       # Write text attributes for the text right after
   idle:
       jmp idle

   /* linker.ld */
   SECTIONS
   {
       /* Set location counter to 0x7c00 */
       . = 0x7c00;
       .text : { *(.text) }
       .data : { *(.data) }
       .other :
       {
            FILL(0x000000)
            . = 0x1ED;
            BYTE(0x55)
            BYTE(0xAA)
       }
   }


texts: Beginner's attempt for Project Euler problem 12 (highly divisible triangle number)

texts:
I'm a couple weeks into learning Python and I'm working through the Project Euler problems. Problem 12 asks:

  What is the value of the first triangle number to have over five hundred divisors?

My problem is that my code takes far too long.

I had a list in there to store the factors but I replaced it with a counter variable to count the number of factors. It resets after looping through the divisors.

I'm not entirely sure but I feel like there is a much better way to cycle through the divisors?

How could I optimise this piece of code?

target = 100000000

counter = 0

for value in xrange(1, target + 1):
    x = (value * (value + 1))/2
    for divisor in xrange(1, x+1):
        product = x % divisor
        if product == 0:
            counter += 1

    if counter >= 500:
        print x
        sys.exit()

    else:
        counter = 0

I appreciate that similar questions have already been asked but I am hoping to gain useful 'personalised' advice from this community

Please excuse the vague variable names and the code in general...


texts:
I know there is probably a better way to have coded this. Can anyone be of help? I am not an expert JavaScript coder.

$(function() {
    $('#clientLoginText').hover(function() {
        $('#clientLoginBox').stop().animate({ "height" : '80px'}, 700);
    }, function() {
        //$('#clientLoginBox').stop().delay(500).animate({ "height" : '0px'}, 700);
    });
});

$(function() {
    $('#clientLoginBox').hover(function() {
    }, function() {
        $('#clientLoginBox').stop().delay(500).animate({ "height" : '0px'}, 700);
    });
});


texts: Using Concurrent Dictionary and Lazy to cache expensive query results and only run query once in a threadsafe manner

texts:
Ok, so I'm querying a webservice. This webservice is slow with multiple o's. I want to cache the results of the query, because I only want to query on a given set of parameters once during my transaction (In addition to the query being slow, it's also rate limited, so I don't want to perform unnecessary queries). Finally, to speed things up, I want to be able to run queries in parallel, as latency is my biggest problem here.

With all of that, I think I need a thread safe way to cache data and only run the queries I actually need to run. I think I've managed to cobble that together with Concurrent Dictionary and Lazy

private static ConcurrentDictionary<KeyObject, Lazy<IEnumerable<ValueObject>>> DataCache =
new ConcurrentDictionary<KeyObject, Lazy<IEnumerable<ValueObject>>>();

    public static IEnumerable<ValueObject> GetData(KeyObject key, QueryObject query)
    {
        var value = new Lazy<IEnumerable<ValueObject>>(() =>
        {
            return query.Run();
        });
        DataCache.TryAdd(key, value);
        return DataCache[key].Value;
    }
}

If I'm correct in understanding how all the moving parts work, it should go something like this.

Generate dictionary key and Lazy intializer for value
Try and add lazy initializer to dictionary with key. If another thread has already added key, fail and continue.
Try and get value of lazy intializer on record in the dictionary. If another thread is already getting value, block until other thread has retrieved value.

Does this sound correct?


texts: Python program to take in two strings and print the larger string

texts:
I have written a Python program to take in two strings and print the larger of the two strings.

Here is my code -

string1 = input("Enter first string: ")
string2 = input("Enter second string: ")
count1 = 0
count2 = 0
for i in string1:
      count1 = count1 + 1

for j in string2:
      count2 = count2 + 1

if (count1 < count2):
      print ("Larger string is:")
      print (string2)

elif (count1 == count2):
      print ("Both strings are equal.")
else:
      print ("Larger string is:")
      print (string1)

Here are some example outputs -

Enter first string: everything
Enter second string: nothing
Larger string is:
everything

Enter first string: cat
Enter second string: apple
Larger string is:
apple

I feel that my code is unnecessarily long. Therefore, I would like to know whether I could make this program shorter and more efficient.

Any help would be highly appreciated.


texts: Hash table using open addressing with double hashing probing

texts:
Looking for a general review:

#ifndef HASH_TABLE_HASH_TABLE_H
#define HASH_TABLE_HASH_TABLE_H

#include <utility>
#include <stdexcept>

namespace mds {
    template<typename K, typename V >
    class hash_table {

        std::size_t     M;
        std::pair<K, V> *table;
        bool            *mark;
        std::size_t     N;

        std::size_t hash(std::size_t h, std::size_t i) const {
            auto hash2 = (std::hash<std::size_t>()(h) % (M - 1));
            return ((h % M) + i * (hash2 | 0x1)) % M;
        }

        std::size_t power_of_2_ceiling(std::size_t x) const {
            auto bits = sizeof(std::size_t) << 3;
            --x;
            for (auto i = 1u; i != bits; i <<= 1) {
                x |= x >> i;
            }
            return x + 1;
        }

    public:

        hash_table() : hash_table(0) { }
        hash_table(std::size_t m)
            : M(power_of_2_ceiling(m)),
            table(new std::pair<K, V>[M]),
            mark(new bool[M]), N(0)
        {
            for (std::size_t i = 0; i < M; ++i) {
                mark[i] = false;
            }
        }

        hash_table(hash_table<K, V>&& map)
            : M(map.M), table(map.table),
              mark(map.mark), N(map.N)  {

            map.M = map.N = 0;
            map.mark  = nullptr;
            map.table = nullptr;
        }

        hash_table(const hash_table<K, V>& map)
            : M(map.M), table(new std::pair<K, V>[map.M]),
            mark(new bool[map.M]), N(map.N) {

            for (std::size_t i = 0; i < M; ++i) {
                mark[i] = map.mark[i];
                table[i] = map.table[i];
            }
        }

        hash_table(std::unordered_map<K, V>&& map)
            : M(power_of_2_ceiling(map.size())),
            table(new std::pair<K, V>[M]),
            mark(new bool[M]), N(0)
        {
            for (std::size_t i = 0; i < M; ++i) {
                mark[i] = false;
            }
            for (auto &p : map) {
                insert(std::move(p));
            }
        }

        hash_table<K, V>&  operator=(hash_table<K, V> other) {
            swap(*this, other);
            return *this;
        }

        friend void swap(hash_table<K, V>& first, hash_table<K, V>& second) noexcept {
            using std::swap;

            swap(first.M, second.M);
            swap(first.N, second.N);
            swap(first.table, second.table);
            swap(first.mark, second.mark);
        }

        ~hash_table() {
            delete[] table;
            delete[] mark;
        }

        const std::pair<K, V>* find(const K& key) const {
            auto hash_code = std::hash<K>()(key);
            auto i = 0u;
            auto h = hash(hash_code, i);
            while (i < M && mark[h]) {
                if (table[h].first == key ) {
                    return &table[h];
                }
                h = hash(hash_code, ++i);
            }
            return nullptr;
        }

        bool insert(std::pair<K, V>&& p) {
            auto hash_code = std::hash<K>()(p.first);
            for (std::size_t i = 0; i < M; ++i) {
                auto h = hash(hash_code, i);
                if (!mark[h]) {
                    table[h] = std::move(p);
                    ++N;
                    return mark[h] = true;
                }
                else if (table[h].first == p.first) {
                    return false;
                }
            }
            throw std::overflow_error("overflow");
        }

        bool constains(const K& key) const {
            return find(key) != nullptr;
        }

        std::size_t size() {
            return N;
        }
    };
}

#endif // !HASH_TABLE_HASH_TABLE_H


texts: Movement function for a Sokoban game using Python

texts:
I've been working on the functions that handle when a player's sprite interacts with either a wall (0) or say the crate to push (£)
I'm just wondering how this looks and if there alternative methods, as I've been told I can make things more complicated than they really need to be.

def MOVE_UP():
    x = MapGrid.getCharLocation(PlayerMan.getRow() - 1, PlayerMan.getCol())
    y = MapGrid.getCharLocation(Boxes.getRow() - 1, Boxes.getCol())
    if x == '0':
        pass
    elif x == '£':
        if y == '0':
            pass
        else:
            MapGrid.despawn(Boxes.getRow(), Boxes.getCol())
            Boxes.pushUp()
            MapGrid.spawnBoxes(Boxes.getChar(), Boxes.getRow(), Boxes.getCol())

            MapGrid.despawn(PlayerMan.getRow(), PlayerMan.getCol())
            PlayerMan.MOVE_UP()
            MapGrid.spawnMan(PlayerMan.getChar(), PlayerMan.getRow(), PlayerMan.getCol())
            print(Boxes.displayOnScreen())

    else:
        MapGrid.despawn(PlayerMan.getRow(), PlayerMan.getCol())
        PlayerMan.MOVE_UP()
        MapGrid.spawnMan(PlayerMan.getChar(), PlayerMan.getRow(), PlayerMan.getCol())
        print(MapGrid.displayOnScreen())
        print(PlayerMan.displayOnScreen())

This code, in Python 3.6, is repeated for the other three directions.


texts: Checking whether any anagram of a string appears within another string

texts:
I have the following code that takes a string t and checks to see if any anagram of t is a substring of s:

### Question 1 main function and helper functions.
"""Given two strings s and t, determine whether some anagram of t is a
substring of s. For example: if s = "udacity" and t = "ad", then the
function returns True. Your function definition should look like:
question1(s, t) and return a boolean True or False."""
# Define an anagram.
def anagram(s1, s2):

    # anagram is true if sorted values of s1 and s2 are equal.
    s1 = list(s1)
    s2 = list(s2)
    s1.sort()
    s2.sort()
    return s1 == s2

# Main function.
def Question1(t, s):

    # Defining local variables.
    t_len = len(t)
    s_len = len(s)
    t_sort = sorted(t)

    # Setting the range to be that of t.
    for i in range(s_len - t_len + 1):

        # Call helper function which checks for t in s.
        if anagram(s[i: i+t_len], t):
            return True
    return False

# Simple test case.
print Question1("app", "paple")
# True

# Test case with a space character.
print Question1("", "a space")
# True

# Test case with numbers.
print Question1("15", "4732890793878894351")
# True

# Test case with punctuation.
print Question1("$ %", "100% $Expensive")
# True

# Test case that returns false.
print Question1("music", "muscle")
# False

# End question 1.
print """---End Question 1---
"""

Is this code Industry standard, and if not what can I do that would simplify this code and increase it's efficiency?


texts: Change View visibility programmatically or through XML?

texts:
I have an XML layout used by 2 activities. Within this layout, there's a view that is visible for Activity1 and gone for Activity2. Activity1 is used more times compared to Activity2. I would like to know which of the following methods is a better practice, if there's a better one.

Method 1: The view is gone and it's turned visible with every instance of the Activity1.

XML:

<View android:id="@+id/myView" android:visibility="gone" />

Java:

class Activity1 extends Activity {
    ((View) findViewById(R.id.myView)).setVisibility(0);
}

class Activity2 extends Activity {
}

Method 2: The view is visible and it's turned gone only when Activity2 is being used.

XML:

<View android:id="@+id/myView" android:visibility="visible" />

Java:

class Activity1 extends Activity {
}

class Activity2 extends Activity {
    ((View) findViewById(R.id.myView)).setVisibility(8);
}

So, is it better to change the visibility programmatically multiple times or fewer times?


texts: Run one Python script from another on Windows, Linux and Unix machines that use the same code

texts:
I have a series of rather complicated codes that I developed on a Linux machine, run on a Unix cluster and from time to time need to run on a Windows machine to gain access to a private network. They are all running Python 3.6 and I have not had a lot of success moving the subprocess.call or similar command between platforms.

The codes do not take any inputs and I want to be able to run them on their own, therefore, I do not want to make them function that I call from another script.  Currently, the only way that I have found to run the codes is to import the code on the first time it is called and then recall it using  importlib.reload(Code_2_NLLS_capacity) the next time.

Here is an example (Added for simplicity as it is easier to read) of what I am doing:

import importlib as iml

for i in range(10):
    if i == 0:
        import Code_1
        import Code_2
        import Code_3
        import Code_4

    else:
        iml.reload(Code_1)
        iml.reload(Code_2)
        iml.reload(Code_3)
        iml.reload(Code_4)

This works well enough for a loop, but it gets rather complicated when I try to run the codes out of order.  Lastly, the code takes a fairly long time to run (5+ hours per code) so I do not want to simply pre import the code and then reload the code as needed.

The following code is my actual code. It is run on a cluster machine that provides a .out file of the terminal. This is why errors are ignored and I print large dividing headers.

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
This code runs all the other codes in the system.
@author: downey
"""
#ignore warings to prevent large file sizes on .out files
import warnings
warnings.filterwarnings('ignore')

import matplotlib.pyplot as plt
import numpy as np
import pickle as pickle
import os as os
import importlib as iml

plt.close('all')

#%% Build the dynamic bounds data set

#set the bound limits
bound_limits = np.arange(0.05,.8,0.05)

# for each bound limit, build the linear bound, and cycle though all the code
for bound_i in range(bound_limits.shape[0]):

    # set the battery life in cycles, so the dynamic bound reaches its target
    mass_pos = np.zeros((250,8))

    dynamic_bounds = np.zeros(mass_pos.shape[0])
    dynamic_start = 0
    dynamic_end = bound_limits[bound_i]
    x_bounds = np.arange(0,mass_pos.shape[0])
    dynamic_bounds = np.interp(x_bounds, [0,mass_pos.shape[0]], [dynamic_start,dynamic_end])

    plt.figure()
    plt.plot(x_bounds,dynamic_bounds)
    plt.xlabel('number of charge cycles')
    plt.ylabel('enforced bounds on the NLLS')
    plt.title('dynamic bounds on the NLLS')

    os.chdir('data')
    pickle.dump(dynamic_bounds,open('dynamic_bounds_temp.pickle','wb'))
    os.chdir('..')

    #%% run the codes
    # buid the data sets
    if bound_i == 0:
        import Code_1_build_data_sets
        # run the NLSS on a parameter basis
        import Code_2_NLLS_capacity
        import Code_2_NLLS_slip_pos
        import Code_2_NLLS_mass_neg
        import Code_2_NLLS_mass_pos
        # solve the half cell model on a model basis
        print('***********************************************************************\n Code_3_cell_prognostics_model_1\n***********************************************************************')
        import Code_3_cell_prognostics_dynamic_bounds
        import Code_4_RUL_dynamic_bounds

    else:
        iml.reload(Code_1_build_data_sets)
        # run the NLSS on a parameter basis
        iml.reload(Code_2_NLLS_capacity)
        iml.reload(Code_2_NLLS_slip_pos)
        iml.reload(Code_2_NLLS_mass_neg)
        iml.reload(Code_2_NLLS_mass_pos)
        # solve the half cell model on a model basis
        print('***********************************************************************\n Code_3_cell_prognostics_model_1\n***********************************************************************')
        iml.reload(Code_3_cell_prognostics_dynamic_bounds)
        iml.reload(Code_4_RUL_dynamic_bounds)


texts:
QuickSort is a Divide and Conquer algorithm, which picks an element as "pivot" and partitions a given list around the pivot. There are many different versions of Quick Sort, as to how to pick a pivot in different ways:

Always pick first element as pivot (implemented below)
Always pick last element as pivot
Pick a random element as pivot
Pick median as pivot

Just for practicing, I've implemented the quick sort algorithm, and if you'd like to review it and provide any change/improvement recommendations, please do so, and I appreciate that.

Code

import random
from typing import TypeVar, List
from scipy import stats

T = TypeVar('T')

def quick_sort(input_list: List[T]) -> List[T]:
    """"
    Returns an ascendingly sorted list;
    Input variable is an integer or float array;
    Theoretical Complexity: O(N*Log N) Time and O(N) Memory
    """

    sort(input_list, 0, len(input_list) - 1)
    return input_list

def sort(input_list: List[T], start_index: int, end_index: int) -> None:
    """Recursively sorts the two pivot-divided sublists;"""
    if start_index >= end_index:
        return
    pivot_index = partition(input_list, start_index, end_index)
    sort(input_list, start_index, pivot_index - 1)
    sort(input_list, pivot_index + 1, end_index)

def partition(input_list: List[T], start_index: int, end_index: int) -> int:
    """
    Returns the end index; Partitions a list into two sublists;
    """
    pivot = input_list[start_index]

    i, j = start_index + 1, end_index

    while i <= j:
        while input_list[i] < pivot and i < end_index:
            i += 1
        while input_list[j] > pivot:
            j -= 1

        if i < j:
            temp = input_list[i]
            input_list[i] = input_list[j]
            input_list[j] = temp
            i += 1
            j -= 1
        else:
            break

    input_list[start_index] = input_list[j]
    input_list[j] = pivot

    return j

if __name__ == "__main__":

    # Creates a dash line string and a new line for in between the tests.
    delimiter = "-" * 70 + "\n"

    # Generates a random integer list.
    test_list_integer = random.sample(range(-100, 100), 15) * 3
    print(f"""The unsorted integer array is:
        {test_list_integer}""")
    print(delimiter)

    # Generates a random float list.
    test_list_float = stats.uniform(0, 100).rvs(45)
    print(f"""The unsorted float array is:
        {test_list_float}""")
    print(delimiter)

    # Sample float/integer test list for input.
    integer_float_input = list(test_list_integer + test_list_float)

    # Sample float/integer test list for output.
    integer_float_output = sorted(integer_float_input)

    sorting_algorithms = [
        ("Quick Sort", quick_sort)
    ]

    # Testing
    for description, func in sorting_algorithms:
        if (func(integer_float_input.copy()) == integer_float_output):
            print(f"{description} Test was Successful.")
        else:
            print(f"{description} Test was not Successful.")
        print(f"""{description} (Integer):
            {func(test_list_integer.copy())}""")
        print(f"""{description} (Float):
            {func(test_list_float.copy())}""")
        print(delimiter)

Reference

Quick Sort - Geeks for Geeks
Quick Sort - Wiki


texts: What is the "proper" way to write this in Java?

texts:
I have a class that has 5 similar methods, they just relay input parameters and return a result - best practice would be to skip the class, but that's not what I'm asking about :) This is a method from the class:

public String deleteItem(Integer itemId,String username, String kpNumber) {
        try {
            return getItemServiceFacade().deleteItem(itemId, username, kpNumber);
        } catch (RemoteException re) {
            String message = "5:unexpected error:" + re.toString();
            logger.error(message);
            return message;
        } catch (CoreException ce) {
            String message = "5:unexpected error:" + ce.toString();
            logger.error(message);
            return message;
        }
    }

Now, since all the methods are similar, each has the same catch block, each does the same things... so I'd like to rewrite this but I'm unsure how far should I go in "atomizing" the methods. One way is what I consider the "pure" way, so the new code looks like this:

public String deleteItem(Integer itemId,String username, String kpNumber) {
        try {
            return getItemServiceFacade().deleteItem(itemId, username, kpNumber);
        } catch (RemoteException re) {
            logException(re);
            return getMessage(re);
        } catch (CoreException ce) {
            logException(ce);
            return getMessage(re);
        }
    }

private String getMessage(Exception exception){
    return "5:unexpected error:" + exception.toString();
}

private void logException(Exception exception){
    logger.error(getMessage(exception));
}

but I'm also left wondering if I should combine these two methods into one method, like this

public String handleException (Exception e){
    String message = "5:unexpected error:" + exception.toString();
    logger.error(message);
    return message;
}

so what I guess I'm trying to ask is how far should you go in separation of concerns when you have clear and simple cases like this one.

Edit: It seems I have not managed to make myself clear, so I'll try again :) In this case simple case, is it considered better to write one method:

public String handleException (Exception e){
    String message = "5:unexpected error:" + exception.toString();
    logger.error(message);
    return message;
}

or should I have two:

private String getMessage(Exception exception){
    return "5:unexpected error:" + exception.toString();
}

private void logException(Exception exception){
    logger.error(getMessage(exception));
}


texts: Compare two ArrayList in a two way comparison?

texts:
I have a class called Task which I cannot touch because it's a legacy code and I have two ArrayList made up of Task class which I need to compare. Items can be in any order or there can be duplicates as well in the ArrayList.

What is the best way to compare two ArrayList which has object in it and print out the missing elements as well which are not present in either of the list. Is below code is the right and efficient way to do it? I cannot use any external library for this.

I need to compare my two array list in a two way comparison.

If data is in source but not in actual, then return false and print out missing elements.
If data is in actual but not in source, then return false as well and print out missing elements.

Below is my code:

public boolean compare(List<Task> source, List<Task> actual) {
    Set<Task> intersection = new HashSet<>(source);
    Set<Task> sourceDifference = new HashSet<>(source);
    Set<Task> actualDifference = new HashSet<>(actual);

    intersection.retainAll(actualDifference);

    sourceDifference.removeAll(intersection);
    for (Task t: sourceDifference) {
        System.out.println(String.format("Task %s not present in actual", t));
    }

    actualDifference.removeAll(intersection);
    for (Task t: actualDifference) {
        System.out.println(String.format("Task %s not present in source", t));
    }

    return sourceDifference.isEmpty() && actualDifference.isEmpty();
}

Is there any better and efficient way to do this? I am using Java 7.


texts: Longest common subsequence length and backtracking the string

texts:
Problem: Given two sequences, print the longest subsequence present in both of them. A subsequence is a sequence that appears in the same relative order, but not necessarily contiguous. For example, “abc”, “abg”, “bdf”, “aeg”, ‘”acefg”, .. etc are subsequences of “abcdefg”. So a string of length n has 2^n different possible subsequences.

Examples:
LCS for input Sequences “ABCDGH” and “AEDFHR” is “ADH” of length 3.
LCS for input Sequences “AGGTAB” and “GXTXAYB” is “GTAB” of length 4.

Python 3 code:

def calculate_lcs_length(a,b):
    a_len = len(a)
    b_len = len(b)
    dp = []
    for i in range(a_len + 1):
        dp.append([0 for j in range(b_len + 1)])
    for i in range(1, a_len + 1):
        for j in range(1, b_len + 1):
            if a[i - 1] == b[j - 1]:
                dp[i][j] = dp[i - 1][j - 1] + 1
            else:
                dp[i][j] = max(dp[i-1][j], dp[i][j - 1])
    max_length = dp[a_len][b_len]
    return dp, max_length

def get_path(a, b, dp, i, j):
    if i == 0 or j == 0:
        return ""
    if a[i-1] == b[j-1]:
        return get_path(a, b, dp, i-1, j-1) + a[i-1]
    else:
        if dp[i-1][j] > dp[i][j-1]:
            return get_path(a, b, dp, i-1, j)
        else:
            return get_path(a, b, dp, i, j-1)

if __name__ == "__main__":
    a = "ABCDGH"
    b = "AEDFHR"
    dp, max_length = calculate_lcs_length(a,b)
    lcs_str = get_path(a, b, dp, len(a), len(b))
    print(lcs_str)

Output: ADH

I wonder if I could use one single method (without using recursion) to get the length and string both.

Is this code can be more reader friendly. I am not asking for one liner or complex optimization improve.

Reference: Longest common subsequence problem, From Wikipedia


texts:
Consider the following segment of code:

# Fetch my orders
orders = repo.get_orders_for(self._customer[0])

if len(orders) > 0:
    current_order_no = -1
    for (order_number, quantity, pid) in orders:

        # Print new heading if needed
        if order_number is not current_order_no:
            print("Order #{}".format(order_number))
            current_order_no = order_number

        print("    Product #{}, ordered x{}".format(pid, quantity))

I feel like there's just a lot going on. I basically do a JOIN on two tables, and return some orders and their order_items. The JOIN obviously duplicates the order_number on several rows, so I need a way of telling them apart. Is there a better way of doing this in Python (actually, I'll accept any language answer for curiosity!) Or is it my way of joining that's evil?

For the curious, the SQL statement is:

SELECT OrderNumber, Quantity, Product_ProductId FROM `order` JOIN `orderitem` ON `order`.OrderNumber = Order_OrderNumber WHERE CustomerAccount_CustomerId=%s ORDER BY OrderNumber


texts:
In order to read a whole file as a string using standard libraries you have to allocate memory, terminate the string, determine size of the file and size of each element.
This could happen with fread until I decided to automatize it using this:

char *readFile (FILE* fp, char *source)
{
    unsigned long long int size;
    unsigned long long int i = 0;
    int chr;

    fseek(fp, 0L, SEEK_END);
    size = ftell(fp);

    source = calloc(size + 1, sizeof(char));

    fseek(fp, 0, SEEK_SET); // rewind

    while(chr != EOF)
        source[i++] = (chr = fgetc(fp));

    source[size] = '\0';    // Terminate string

    return(source);
}


texts:
I'm looking for a review paying special attention as to whether the code can be optimized in the form of number of variables used, especially for the delete() method.

public class circularLL {

    Node start;
    Node last;

    circularLL()
    {
        start=null;
        last=null;
    }

    class Node
    {
        int data;
        Node next;

        Node(int datanew)
        {
            data=datanew;
        }
        public void setNext(Node n)
        {
            next=n;
        }
        public Node getNext()
        {
            return next;
        }
        public void setData(int datanew)
        {
            data=datanew;
        }
        public int getData()
        {
            return data;
        }
    }

    public void insert(int datanew)
    {
        Node p=new Node(datanew);
        if(start==null)
        {
            start=p;
            last=p;
            p.setNext(p);
        }
        else
        {
            last.setNext(p);
            last=last.getNext();
            last.setNext(start);
        }
    }
    public void delete(int datanew)
    {
        Node temp=start;
        Node temp1=start;
        Node previous=null;
        Node previous1=null;
        if(last.getData()==datanew)
        {
            while(temp1.getData()!=datanew)
            {
                previous1=temp1;
                temp1=temp1.getNext();
            }
            previous1.setNext(temp.getNext());
            last=previous1;
        }
        while(temp.getData()!=datanew)
        {
            previous=temp;
            temp=temp.getNext();
        }
        previous.setNext(temp.getNext());
    }

    public void display() {
        int count = 0;

        if(start == null) {
            System.out.println("\n List is empty !!");
        } else {
            Node temp = start;

            while(temp.getNext() != last) {
                System.out.println("count("+count+") , node value="+temp.getData());
                count++;
                temp = temp.getNext();
            }
            System.out.println("count("+count+") , node value="+temp.getData());
        }
    }

    public static void main(String args[])
    {
        circularLL ll=new circularLL();
        ll.insert(40);
        ll.insert(20);
        ll.insert(22);
        ll.insert(15);
        ll.insert(16);
        ll.insert(35);
        ll.insert(40);
        ll.insert(38);
        ll.delete(22);
        ll.display();
    }
}


texts:
I wrote the following x86 program to make sure I'm following the correct practices in calling a function and then exiting to the OS:
.globl _start

_start:

    # Calculate 2*3 + 7*9 = 6 + 63 = 69
    # The multiplication will be done with a separate function call

    # Parameters passed in System V ABI
    # The first 6 integer/pointer arguments are passed in:
    #   %rdi, %rsi, %rdx, %rcx, %r8, and %r9
    # The return value is passed in %rax

    # multiply(2, 3)
    # Part 1 --> Call the parameters
    mov $2, %rdi
    mov $3, %rsi
    # Part 2 --> Call the function (`push` return address onto stack and `jmp` to function label)
    call multiply
    # Part 3 --> Handle the return value from %rax (here we'll just push it to the stack as a test)
    push %rax

    # multiply(7, 9)
    mov $7, %rdi
    mov $9, %rsi
    call multiply

    # Add the two together
    # Restore from stack onto rdi for the first function
    pop %rdi
    # The previous value from multiply(7,9) is already in rax, so just add to rbx
    add %rax, %rdi

    # for the 64-bit calling convention, do syscall instead of int 0x80
    # use %rdi instead of %rbx for the exit arg
    # use $60 instead of 1 for the exit code

    movq $60, %rax    # use the `_exit` [fast] syscall
                      # rdi contains out exit code
    syscall           # make syscall

multiply:
    mov %rdi, %rax
    imul %rsi, %rax
    ret

Does the above follow the x86-64 conventions properly? I know it is probably as basic as it comes, but what can be improved here?


texts:
I wrote this implementation of quicksort as a bit of practice and review for myself.  I did not base my algorithm on anything more than my own understanding of quicksort and working through a couple of examples myself on paper, so please let me know of any improvements or optimizations that I could make!

import java.util.ArrayList;
import java.util.Collections;
import java.util.concurrent.ThreadLocalRandom;

/**
 * A simple, generic, in-place implementation of quicksort
 * @implNote The pivot used during the partitioning step is selected at random
 */
public class Quicksort {

    /**
     * Sort the given array using quicksort
     * @param arr Array to sort
     * @param <E> Type of the elements contained by arr
     */
    public static <E extends Comparable> void sort(ArrayList<E> arr) {
        sort(0, arr.size() - 1, arr);
    }

    /**
     * Sorts a designated section of the given array using quicksort
     * @param left  Lower-bound index of section (inclusive)
     * @param right Upper-bound index of section (inclusive)
     * @param arr   Array to perform sort within
     * @param <E>   Type of the elements contained by arr
     */
    private static <E extends Comparable> void sort(int left, int right, ArrayList<E> arr) {
        // Exit if section contains only a single element, or is invalid
        if (right - left < 1) {
            return;
        }

        // Select a pivot at random
        int pivot = ThreadLocalRandom.current().nextInt(left, right + 1);

        // Partition this section of the array
        int pivotFinalIndex = partition(left, right, pivot, arr);

        // Sort the two new partitions
        sort(left, pivotFinalIndex - 1, arr);
        sort(pivotFinalIndex + 1, right, arr);
    }

    /**
     * Partition a section of an array around a pivot value
     * @param left  Lower-bound index of section (inclusive)
     * @param right Upper-bound index of section (inclusive)
     * @param pivot Index of the value to partition around
     * @param arr   Array to perform partitioning within
     * @param <E>   Type of the elements contained by arr
     * @return      The final index of the partition value
     */
    private static <E extends Comparable> int partition(int left, int right, int pivot, ArrayList<E> arr) {
        // Move pivot to left-most position (get out of the way)
        Collections.swap(arr, left, pivot);
        pivot = left;

        // Perform partitioning
        int rightPartitionStart = left + 1;
        for (int i = left + 1; i <= right; i++) {
            // If our current value is less than our pivot, move it into the left partition
            if (arr.get(i).compareTo(arr.get(pivot)) < 0) {
                Collections.swap(arr, i, rightPartitionStart);
                rightPartitionStart++;
            }
        }

        // Put pivot back where it belongs (in between partitions)
        Collections.swap(arr, pivot, rightPartitionStart - 1);
        pivot = rightPartitionStart - 1;

        return pivot;
    }
}


texts: CtCi 2.6: Implement a function to check if a linked list is a palindrome

texts:
I would appreciate feedback on the linked list implementation and usage below for question 2.6 from Cracking the coding interview book.

struct Node {
    char value;
    shared_ptr<Node> next;
    Node(char v) : value(v) {};
};

shared_ptr<Node> head;

void createSampleList(string str)
{
    auto ptr = head;
    for (const char ch : str)
    {
        if(!head) {
            head = make_shared<Node>(ch);
            ptr = head;
        }
        else {
            ptr->next = make_shared<Node>(ch);
            ptr = ptr->next;
        }
    }
}

bool isPalindrome() {

    auto slow = head;
    auto fast = head;
    stack<char> tempStack;

    while (fast != nullptr && fast->next != nullptr)
    {
        tempStack.push(slow->value);
        slow = slow->next;
        fast = fast->next->next;
    }

    if(fast != nullptr)
        slow = slow->next;

    while (slow != nullptr)
    {
       char reverseVal = tempStack.top();
        tempStack.pop();
        if(reverseVal != slow->value)
            return false;
        slow = slow->next;
    }

    return true;
}


texts:
I am developing a multilingual site, so i needed some sort of a function to detect user locale, as well as not to scare away search engines, so I wrote this kind of a method to detect locale.
The priority is as following:

We look if user has active language in $_SESSION;
If not, we look in the database to detect user preference;
If nothing in the database, we look on the domain name and try to detect locale from domain name and superglobal $_SERVER;
If we failed, we look at user's browser locale ($_SERVER again) and try to detect from it.
If we are totally a failure, we fallback to English.

This method is called on every page of a website.

public static function detect_locale() {
    if(isset($_SESSION["lang"])){
        $lang = $_SESSION["lang"];
        return $lang;
    }
    if(isset($_SESSION["id"])){
        $user = new User($_SESSION["id"]);
        $lang = $user->get_locale();
        return $lang;
    }
    if($_SERVER["HTTP_HOST"] == "ru.mysupersite.com" || $_SERVER["HTTP_HOST"] == "www.mysupersite.ru"){
        $lang = "ru";
        return $lang;
    }
    if(isset($_SERVER["HTTP_ACCEPT_LANGUAGE"])){
        $lang = substr($_SERVER["HTTP_ACCEPT_LANGUAGE"], 0, 2);
        return $lang;
    }
    $lang = "en";
    return $lang;
}

I see it as a pretty straightforward solution, but something in the back of my mind says that there might be some flaws. Are there any or am I just paranoid?

Thank you!


texts: Appending a group name to each committee member

texts:
I wrote this script to get text, if it equals, append the name of the group to a person's information. I know using .each() is gpu intensive and this feels like a poor way of writing the code.

var committee = $('.committee');
var committeeName = $('.committee-name');

var detailNames = $('.text_center');

committee.each(function() {
    var members = $(this).find('.com-member ul li');

    members.each(function() {
        member = $(this).text();
        memberCommittee = $(this).closest(committee).find(committeeName).text();

        detailNames.each(function() {
            var detailName = $(this).text();
            var detailCom = $(this).closest('.detail-info').find('.detail-comm');
            if(member == detailName) {
                detailCom.append(memberCommittee + ", ");
            };
        });
    });
});


texts: Simple download manager based on Youtube-dl

texts:
There is a personal program of mine which logs in, scrape links and then download them. The downloader part is based on Youtube-dl and I think it's a smell code. Is there any way to improve this code?
import requests
import subprocess
import getpass
import time
from bs4 import BeautifulSoup as bs
import argparse

def Login(url, login_route, username, password):

    URL = url
    LOGIN_ROUTE = login_route

    headers = {
        'User-Agent': '',
        'origin': URL,
        'referer': URL + LOGIN_ROUTE,
    }

    request_session = requests.session()

    csrf_token = request_session.get(URL).cookies['csrftoken']

    login_payload = {
        'hidden_username': username,
        'password': password,
        'csrfmiddlewaretoken': csrf_token
    }

    login_request = request_session.post(
        URL + LOGIN_ROUTE, headers=headers, data=login_payload)

    # !
    msg = (
        f'You have logged in successfully {login_request.status_code}' if login_request.status_code == 200 else
        f'Error {login_request.status_code}'
    )

    print(msg)

def get_user_input():

    url = 'https://maktabkhooneh.org/signin/?next=/dashboard/'
    username = getpass.getpass('Username: ')
    password = getpass.getpass('Password: ')
    login_route = '/auth/login-authentication'

    return(Login(url, login_route, username, password))

def Scraper(page_url):

    Page_URL = page_url

    headers = {
        'User-Agent': ''
    }

    page = requests.get(
        Page_URL,
        headers=headers,
    )
    soup = bs(page.text, "html.parser")

    URL_List = []
    link_count = 0
    for a_tag in soup.select('a[href^="/course/"]'):

        links = "https://maktabkhooneh.org" + a_tag["href"]

        URL_List.append(links)
        link_count += 1

    return URL_List

def Downloader(url_list):

    URL_List = Scraper(url_list)
    download_count = 0
    for links in URL_List:
        command = f"youtube-dl {links}"
        result = subprocess.call(command, shell=True)

        # !
        if result == 0:
             download_count += 1
             return('\nReturned Value', result)

    return(f'\n{download_count} file(s) have been downloaded')

page_url = 'https://maktabkhooneh.org/course/%D8%A2%D9%85%D9%88%D8%B2%D8%B4-%D8%B1%D8%A7%DB%8C%DA%AF%D8%A7%D9%86-%DB%8C%D8%A7%D8%AF%DA%AF%DB%8C%D8%B1%DB%8C-%D9%85%D8%A7%D8%B4%DB%8C%D9%86-Andrew-NG-mk1085/%D9%81%D8%B5%D9%84-%D8%A7%D9%88%D9%84-%D9%85%D9%82%D8%AF%D9%85%D9%87-ch3364/%D9%88%DB%8C%D8%AF%DB%8C%D9%88-%D8%AE%D9%88%D8%B4%D8%A2%D9%85%D8%AF%DB%8C%D8%AF-%DB%8C%D8%A7%D8%AF%DA%AF%DB%8C%D8%B1%DB%8C-%D9%85%D8%A7%D8%B4%DB%8C%D9%86/'

Login_ = input('Login required Website [Y], [N]? ')
# !
if Login_ == 'y' or 'Y':
    get_user_input()

list_len = len(Scraper(page_url))
# !
Download_Permission = input(
    f'\n{list_len} link(s) have been extracted. Do you want to DOWNLOAD them [Y], [N]? ')
# !
if Download_Permission == 'y' or 'Y':
    Downloader(page_url)

Any help would be highly appreciated.


texts: Stock picker that tells when to buy and when to sell

texts:
The task of this project was to create a method that takes in an array of stock prices, one for each hypothetical day. From there, the method should return the best day to buy and the best day to sell the stock to maximize return.

A few ground rules:

Stocks need to be bought before they can be sold
It is possible that the lowest priced day can be the last day, and the highest price day could be the first day.

With that, and a relatively new working knowledge of Ruby, here's what I came up with. It works, but I'm sure there could be improvements. Be gentle!

def stock_prices (array)
    $largest_difference = 0
    array.each_with_index {|value, index|
        array.each {|i|
            $difference = value -  i
            if ($difference <= $largest_difference) && (index < array.rindex(i))
                $negative_array = [] << $difference
                $negatives = [index, array.rindex(i)]
                $largest_difference = $difference
            end
        }
    }
    if $negative_array.nil?
        puts "The stock should be bought and sold at [0, 1], respectively"
    else
        puts "The stock should be bought and sold at #{$negatives}, respectively"
    end
end

stock_prices([17,3,6,9,15,8,6,1,10])
#stock_prices([25,2,10,9])
#stock_prices([10,12,5,3,20,1,9,20])
#stock_prices([10,9,8,7,6])
#stock_prices([18,17,17,16,15])


texts:
I was happy with my shell script that needed to generate alphanumeric combinations of length N (in this case, 3)

for i in {a..z}{a..z}{a..z}; do ...

Now I became less happy when I needed alphanumeric combinations (specially if I choose a larger value for N)

for i in {0..9}{a..z}{a..z} \
         {a..z}{0..9}{a..z} \
         {a..z}{a..z}{0..9} \
         {a..z}{a..z}{a..z} \
         {0..9}{0..9}{a..z} \
         {0..9}{a..z}{0..9} \
         {a..z}{0..9}{0..9} \
         {0..9}{0..9}{0..9}; do ...

So I decided to write it in Haskell:

import Data.List
c 0 _ = [[]]
c n xs = [ y:ys | y:xs' <- Data.List.tails xs, ys <- c (n-1) xs']
main = sequence_ . map putStrLn . c 3 $ ['a' .. 'z'] ++ ['0' .. '9']

Now, I couldn't find a way to incorporate the above code in my shell script, so I had to reduce it to a one-liner to run with ghc -e, finally giving me the code I have right now:

for i in $(ghc -e "
  let c n l = if n == 0 then [[]] else \
    [y:s | y:q <- Data.List.tails l, s <- c (n-1) q] in
      sequence_. map putStrLn . c 3 $ ['a'..'z'] ++ ['0'..'9']"); do ...

Now, I actually like this style (elsewhere I have inline calls to awk too, etc). But I think this code is too big and too ugly; for example, I'm using if n == 0 instead of guards, etc. Haskell is supposed to be a lot more concise than that.

My only requirement is that I may want to change the length to be larger than 3, but also ['a'..'z'] ++ ['0'..'9'] to another set (perhaps to include - or _).


texts:
I recently started learning Java, and I decided to implement a basic vector system for another particle system I was building.

import java.util.*;

class Vector {
    int x;
    int y;

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

    public void add(Vector vector) {
        this.x += vector.x;
        this.y += vector.y;
    }

    public void sub(Vector vector) {
        this.x -= vector.x;
        this.y -= vector.y;
    }

    public void mul(Vector vector) {
        this.x *= vector.x;
        this.y *= vector.y;
    }

    public void div(Vector vector) {
        this.x /= vector.x;
        this.y /= vector.y;
    }
}

What can be improved? I'm new to Java, so constructive criticism on anything would be nice.


texts: Converting int value to String without using toString and parseInt method

texts:
I am studying about the converting int to string and string to int without using toString and parseInt method. I already made methods. However, I don't believe that my way of doing was the best. I would like to improve these function.

For example, the first converts from String to int:

public static int StringToint(String number)
        int eachnumber = 0;
    int intConvert = 48;
    int reVal = 0;
    int index;
    int maxlen =number.length() - 1;
        for(index = 0 ; index <= maxlen ; index++)
    {
        eachnumber = number.charAt(index);

        eachnumber = eachnumber  - intConvert;

        reVal = reVal + (eachnumber * (int) Math.pow(10, maxlen - index));
    }
    return reVal;
}

Second, for converting int to String:

public static String IntToString(int number)
{
    int StringConvet = 48;

    int eachDigit = number;
    int afterDivide = number;
    String reVal = "";

    while(afterDivide >0)
    {
        eachDigit = afterDivide % 10;
        afterDivide = afterDivide / 10;
        if(eachDigit == 0)
        {
            reVal += "0";
        }
        else if(eachDigit == 1)
        {
            reVal += "1";
        }
        else if(eachDigit == 2)
        {
            reVal += "2";
        }
        else if(eachDigit == 3)
        {
            reVal += "3";
        }
        else if(eachDigit == 4)
        {
            reVal += "4";
        }
        else if(eachDigit == 5)
        {
            reVal += "5";
        }
        else if(eachDigit == 6)
        {
            reVal += "6";
        }
        else if(eachDigit == 7)
        {
            reVal += "7";
        }
        else if(eachDigit == 8)
        {
            reVal += "8";
        }
        else if(eachDigit == 9)
        {
            reVal += "9";
        }
    }
    String reVal2 = "";
    for(int index =  reVal.length() -1 ; index >= 0 ; index--)
    {
        reVal2 += reVal.charAt(index);
    }
    return reVal2;
}

I am sure that the StringToint method is \$O(n)\$ and intToString method will be \$O(n^2)\$. However, I am really sure that there are ways to improve these two methods. Is there any way to improve these two functions?


texts: Django Unified Method for Deleting Instances of Any Model

texts:
This code works, but I don't know if there are better and especially safer ways to do this.

For context: this is a Django view (Python) and I wanted to unify the deletion methods because there were many of them.

def delete(request, class_name, object_ID):
    obj = get_object_or_404(eval(class_name), id=object_ID)
    obj.delete()
    return redirect(dashboard)

Now I know that the eval() method should be used with caution, but would it be enough to wrap a try-catch-method around it or should I do something like a switch-case, or is it even ok to use the code as is?

It will be called from this url route (urls.py):

path('delete/<str:className>/<int:object_ID>', views.delete)

  Note: This route will only be accessible to employees and there will be a permission check, so my question is about best practice and potential problems.


texts: Python function to fill a list based on index number

texts:
I wrote this function to fill a list with object based on the desired index they should have.

Here the func:

def fill(lst, index, add, fillvalue=None):
    '''Fills a list with the add value based on desired index'''
    '''Let the value in place if present'''
    for n in range(index):
        try:
            if lst[n]:
                pass
        except Exception:
            lst.append(fillvalue)
    try:
        if lst[index]:
            pass
        else:
            lst[index]=add
    except Exception:
        if index==len(lst):
            #This if check probably not mandatory
            lst.append(add)
    return lst

edit: here's an usage example that would for example happen in a for loop

>>> my_list = [1, 7, 14]
>>> fill(my_list, 5, 6)
[1, 7, 14, None, None, 6]
>>> fill(my_list, 6, 12)
[1, 7, 14, None, None, 6, 12]
>>> fill(my_list, 3, 25)
[1, 7, 14, 25, None, 6, 12]
>>> fill(my_list, 4, 18)
[1, 7, 14, 25, 18, 6, 12]

Note:

>>> my_list = [1, 7, 14]
>>> fill(my_list, 1, 6)
#returns the list not modified, my_list[1] is already taken
[1, 7, 14]

It works good for my purpose (matrix generating). My matrixes are generated with many "for loops" passes, because the data I convert to is unordered. This is why the "None" elements are important in order to fill them out on a subsequent loop pass.

My questions are:

I'm wondering if I made everything as simple as possible? Or if there
were a lib, that would do the same job?
For now the matrixes aren't so long but I guess, if I go further
in my development, they will become big (1000+ lines). Should
I somehow better use itertools?
I also somehow thought of first using a dict {index: value} and
convert it to a list when filled up. Would it be better practice?

Edit: Now that I pasted the code in here I notice the arg name "add" is blued. My Vim-editor didn't told me that... Is it a name already taken by the python core?


texts: Moving a div to a different parent, which also moves, using matchMedia

texts:
I'm very new to JavaScript so I thought I'd ask for someone to have a quick look over this to make sure it isn't brittle, buggy, or completely unnecessary. It may be all three. I also thought it might help someone in the future (if correct), as I found lots of different suggestions I don't think I needed including looping through all the child nodes and using enquire.js.

It moves a div from one parent container to another depending on whether a media query is relevant. The target div also moves with a normal css media query.

codepen (make the container height a fair bit taller than the width)

1

2

3

4

css

.wrapper{
  display:flex;
  flex-direction: column;
  width: 100%;
  background: #eaeaea;
}

@media (min-aspect-ratio: 4/5){
  .wrapper{
    flex-direction: row;
  }
}

.container{
  display: flex;
  justify-content: space-around;
}

.container1{
  flex-basis: 66.6%;
  background: red;
}

.container2{
  flex-basis: 33.3%;
  background: blue;
}

.item{
  background: white;
  padding: 50px;
  margin: 20px;
  border: 1px solid #333;
}

js

var container1 = document.getElementById('c1');
var container2 = document.getElementById('c2');
var item = document.getElementById('toMove');

matchMedia("screen and (min-aspect-ratio:4/5)").addListener(function(mql) {
   if(mql.matches) {
       moveElement(item, container1);
   }
   else {
       moveElement(item, container2);
   }
});

function moveElement(source, target){
    target.appendChild(source);
}

Appreciate the feedback as I don't really know what I'm doing with JS!

*fixed the problem in the example RE moving the item back to its original location. I just call the method container1.insertBefore(toMove, item3); in the 'else' block, instead of calling moveElement(). (where item3 is a variable pointing to #item3)

In case that helps anyone.


texts: Unit testing with dependency injection and MOQ

texts:
I'm just learning how dependency injection and mocking work, but I'd like some feedback on how I'm setting up a couple of tests.  I can get them to pass, but I'm not sure this is all I need.

This is an MVC application that makes Web API calls to return data.  For this example I'm running queries in the Web APIs that populate dropdowns.

Please give me any and all suggestions about what I'm doing right or wrong here or anything I should be doing differently.

Setup file for Dependency Injection - Unity.WebAPI (NuGet Package)

UnityConfig.cs

public static class UnityConfig
{
    public static void RegisterComponents()
    {
        var container = new UnityContainer();

        // register all your components with the container here
        // it is NOT necessary to register your controllers

        // e.g. container.RegisterType<ITestService, TestService>();

        container.RegisterType<IDropDownDataRepository, DropDownDataRepository>();

        GlobalConfiguration.Configuration.DependencyResolver = new UnityDependencyResolver(container);
    }
}

Controller

public class DropDownDataController : ApiController
{
    private IDropDownDataRepository _dropDownDataRepository;

    //Dependency Injection (I'm using Unity.WebAPI)
    public DropDownDataController(IDropDownDataRepository dropDownDataRepository)
    {
        _dropDownDataRepository = dropDownDataRepository;
    }

    [HttpGet]
    public HttpResponseMessage DateList()
    {
        try
        {
            return _dropDownDataRepository.DateList();
        }
        catch
        {
            throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.NotFound));
        }
    }
}

Repository

public class DropDownDataRepository : IDropDownDataRepository
{
    //Is this fine in here, or should it be injected somehow too?
    private MyDatabaseEntities db = new MyDatabaseEntities();

    public HttpResponseMessage DateList()
    {
        var sourceQuery = (from p in db.MyProcedure()
                           select p).ToList();

        string result = JsonConvert.SerializeObject(sourceQuery);
        var response = new HttpResponseMessage();
        response.Content = new StringContent(result, System.Text.Encoding.Unicode, "application/json");

        return response;
    }
}

INTERFACE

public interface IDropDownDataRepository
{
    HttpResponseMessage DateList();
}

Unit tests

/// <summary>
/// Tests the DateList method is run
/// I pieced this kind of test together from examples online
/// I'm assuming this is good for a simple test
/// </summary>
[TestMethod]
public void DateListTest1()
{
    //Arrange
    var mockRepository = new Mock<IDropDownDataRepository>();
    mockRepository.Setup(x => x.DateList());
    var controller = new DropDownDataController(mockRepository.Object);

    //Act
    controller.DateList();

    //Assert
    mockRepository.VerifyAll();
}

/// <summary>
/// Tests the DateList method returns correct status code.
/// This will run with success, but I'm not sure if that's just
/// because I'm telling it to return what I'm expecting.
/// I welcome suggestions for improvement.
/// </summary>
[TestMethod]
public void DateListTest2()
{
    //Arrange
    var mockRepository = new Mock<IDropDownDataRepository>();
    mockRepository
        .Setup(x => x.DateList())
        //This will only succeed if I have the Returns property here,
        //but isn't that just bypassing the actual "test" of whether or
        //not this works?
        .Returns(new HttpResponseMessage(HttpStatusCode.OK));

    DropDownDataController controller = new DropDownDataController(mockRepository.Object);
    controller.Request = new HttpRequestMessage();
    controller.Configuration = new HttpConfiguration();

    //Act
    var response = controller.DateList();

    //Assert
    Assert.AreEqual(HttpStatusCode.OK, response.StatusCode);
}


texts:
I created a method that does division without the / operator. I believe this code is a bit slow and can be improved, but I am not sure how to do so. I'm not so good with shift operators (>> and >>>), but I believe that this will help a bit. How can I change my code to increase the speed of the division. I am open the changing my logic as well.

public class DivisionReplace {
    public static void divide(int N, int D) {
        int result = 0;

        if (D == 0) {
            System.out.println("Cannot divide by 0");
        }
        else if (N == 0) {
            System.out.println(0);
        }
        else if (N == D) {
            System.out.println(1);
        }
        else if (N > 0 && D > 0 && N < D) {
            System.out.println(0);
        }
        else {
            // both negative
            if (N < 0 && D < 0) {
                while (N <= D) {
                    N += -1 * D;
                    result++;
                }
                System.out.println(result);
            }
            // either N or D negative
            else if (N < 0 || D < 0) {
                if (N < 0) {
                    N = -1 * N;
                }
                else {
                    D = -1 * D;
                }
                while (N >= D) {
                    N -= D;
                    result--;
                }
                System.out.println(result);
            }
            // both positive
            else {
                while (N >= D) {
                    N -= D;
                    result++;
                }
                System.out.println(result);
            }
        }
    }

    public static void main(String[] args) {
        divide(-4,-10);
    }
}


texts:
I'm attempting to speed up my genetic algorithm that modifies images. After searching, I've found that my fitness function is the bottleneck, taking sometimes up to 11 seconds to complete.

The fitness function accepts two images and returns a float representing the total difference between the images' corresponding pixels, measured as distance in Cartesian RGB space.

To test, I used some large images of the same size (1254 x 834). What can I do to speed this process up?

def fitness(original, new):
    fitness = 0

    for x in range(0, width):
        for y in range(0, height):
            r1, g1, b1 = original.getpixel((x, y))
            r2, g2, b2 = new.getpixel((x, y))

            deltaRed = abs(r1 - r2)
            deltaGreen = abs(g1 - g2)
            deltaBlue = abs(b1 - b2)

            pixelFitness = pixelFitness = math.sqrt(deltaRed ** 2 + deltaGreen ** 2 + deltaBlue ** 2)

            fitness += pixelFitness

    return fitness


texts: Counting Characters from an HTML File with Python

texts:
I just completed level 2 of The Python Challenge on pythonchallenge.com and I am in the process of learning python so please bear with me and any silly mistakes I may have made.
I am looking for some feedback about what I could have done better in my code. Two areas specifically:

How could I have more easily identified the comment section of the HTML file? I used a beat-around-the-bush method that kind of found the end of the comment (or the beginning technically but it is counting from the end) and gave me some extra characters that I was able to recognize and anticipated (the extra "-->" and "-"). What condition would have better found this comment so I could put it in a new string to be counted?

This is what I wrote:
from collections import Counter
import requests

page = requests.get('http://www.pythonchallenge.com/pc/def/ocr.html')

pagetext = ""
pagetext = (page.text)
#find out what number we are going back to

i = 1
x = 4
testchar = ""
testcharstring = ""

while x == 4:
    testcharstring = pagetext[-i:]
    testchar = testcharstring[0]
    if testchar == "-":
        testcharstring = pagetext[-(i+1)]
        testchar = testcharstring[0]
        if testchar == "-":
            testcharstring = pagetext[-(i+2)]
            testchar = testcharstring[0]
            if testchar == "!":
                testcharstring = pagetext[-(i+3)]
                testchar = testcharstring[0]
                if testchar == "<":
                    x = 3
            else:
                i += 1
                x = 4
        else:
            i += 1
            x = 4
    else:
        i += 1
print(i)

newstring = pagetext[-i:]

charcount = Counter(newstring)

print(charcount)

And this is the source HTML:

  <title>ocr</title>
  <link rel="stylesheet" type="text/css" href="../style.css">

recognize the characters. maybe they are in the book,
but MAYBE they
are in the page source.

General tips:

Use the hints. They are helpful, most of the times.

Investigate the data given to you.

Avoid looking for spoilers.

Forums: Python Challenge Forums,
read before you post.

IRC: irc.freenode.net #pythonchallenge

To see the solutions to the previous level, replace pc with pcc, i.e. go
to: http://www.pythonchallenge.com/pcc/def/ocr.html

'


texts:
I was given this problem in a mock interview. I would appreciate a review of my implementation.

  Shortest Cell Path In a given grid of 0s and 1s, we have some starting
  row and column sr, sc and a target row and column tr, tc. Return the
  length of the shortest path from sr, sc to tr, tc that walks along 1
  values only.

  Each location in the path, including the start and the end, must be a
  1. Each subsequent location in the path must be 4-directionally adjacent to the previous location.

  It is guaranteed that grid[sr][sc] = grid[tr][tc] = 1, and the
  starting and target positions are different.

  If the task is impossible, return -1.

  Examples:

  input: grid = [[1, 1, 1, 1], [0, 0, 0, 1], [1, 1, 1, 1]] sr = 0, sc =
  0, tr = 2, tc = 0 output: 8 (The lines below represent this grid:)
  1111 0001 1111

  grid = [[1, 1, 1, 1], [0, 0, 0, 1], [1, 0, 1, 1]] sr = 0, sc = 0, tr =
  2, tc = 0 output: -1 (The lines below represent this grid:) 1111 0001
  1011

def shortestCellPath(grid, sr, sc, tr, tc):
    """
    @param grid: int[][]
    @param sr: int
    @param sc: int
    @param tr: int
    @param tc: int
    @return: int
    """
  path_lengths = []
  shortestCellPathHelper(grid, sr, sc, tr, tc, 0, path_lengths)

  return -1 if len(path_lengths) == 0 else min(path_lengths)

def shortestCellPathHelper(grid, r, c, tr, tc, path_len, path_lengths):
  if r < 0 or r >= len(grid) or c < 0 or c >= len(grid[0]):
    return

  if grid[r][c] != 1:
    return

  if r == tr and c == tc:
    path_lengths.append(path_len)
    return

  grid[r][c] = -1

  #4 directions
  shortestCellPathHelper(grid, r, c - 1, tr, tc, path_len + 1, path_lengths)
  shortestCellPathHelper(grid, r, c + 1, tr, tc, path_len + 1, path_lengths)
  shortestCellPathHelper(grid, r - 1, c, tr, tc, path_len + 1, path_lengths)
  shortestCellPathHelper(grid, r + 1, c, tr, tc, path_len + 1, path_lengths)


texts: Code that checks input for calculator app

texts:
I made an Android app, a calculator, that uses buttons for input, Android keyboard is turned off. I have a block of code, that handles the input to string and checks for some things at the same time. The code is completely working, but I think it may feel a little slow on older devices. The code gets strings, such as "8", "Sin", "Log" and so on and puts them at the end of existing EditText string. How can I improve this code? Here is the code:

private void setText(Button button) {
    EditText textView = (EditText) findViewById(R.id.textView);
    int cursor = textView.getSelectionStart();
    String string = textView.getText().toString();
    if (currency) {       //if string is in currency format, formats it back to normal number using formatBack method
        int stringLength = string.length();
        string = formatBack(string);
        cursor = cursor - (stringLength - string.length());
        currency = false;
    }
    String num = button.getText().toString();
    if (!string.equals("")) {      //if string is not empty
        char c = string.charAt(cursor - 1);
        if (((num.equals("÷") || num.equals("×") || num.equals("+") || num.equals("%")) && (c == '(' || c == '.' || c == '√' || c == '^' || c == '%' || c == '÷' ||
                c == '×' || c == '+' || c == '-'))) { // if input is operator and last character is any of those, return
            return;
        }
        if ((num.equals("-") && (c == '.' || c == '√' || c == '^' || c == '%' || c == '÷' ||
                c == '×' || c == '+' || c == '-'))) { // same as last if, but - can be written in front of '(', other operators can't
            return;
        }
    }
    if (string.equals("")) {
        if (num.equals("÷") || num.equals("×") || num.equals("+") || num.equals("%")) { //you cannot input operator into empty string (to forbid things like "×2"
            return;
        }
    }
    if (num.equals("Sin") || num.equals("Cos") || num.equals("Tan") || num.equals("Log") || num.equals("Ln") || num.equals("Rad") || num.equals("(") || num.equals(")") ||
            num.equals("^") || num.equals("√") || num.equals("÷") || num.equals("×") || num.equals("+") || num.equals("-")) { // allows you to input dot after one of these
        dot = false;  //inputting dot uses another method, which only allows one dot per number and sets dot = true; flag (to prevent "2..3")
    }
    if (num.equals("Sin") || num.equals("Cos") || num.equals("Tan") || num.equals("Log") || num.equals("Ln") ||num.equals("Rad") || num.equals("√")) {
        num = num + "("; //puts '(' after any of these, self-explaining I think
    }
    string = string.substring(0, cursor) + num + string.substring(cursor, string.length()); // puts input at the place of cursor
    textView.setText(string); //updates EditText with the new string
    textView.setSelection(cursor + num.length()); //moves cursor according to length of input
    if (string.length() > 10) { //changes text size if string is too long
        textView.setTextSize(40);
    }
}

That is it, if you have any questions, feel free to ask and ty for helping.


texts: Check if two strings are permutation of each other

texts:
private String sort(String word) {
    char[] content = word.toCharArray();
    Arrays.sort(content);
    return new String(content);
  }

  private boolean isPermutation(String s1, String s2) {
    s2 = s2.toLowerCase();
    if (s1.length() != s2.length()) {
      return false;
    }
    if (s1.equals(s2)) {
      return true;
    }
    return sort(s1).equals(sort(s2));
  }

Could the above solution can be optimized(in space and time)?
I think the worst case running time would be: \$O(nlog)\$


texts: Python vs. Java Runtime on Euler 22 - Name Scores

texts:
I want to know why Java is accepted over Python when it comes to runtime. On performing the following Euler problem, Python takes up less lines and runs faster (Python ~0.05s, Java ~0.3s on my machine).

Could I optimize this Java code in any way? The problem is here (http://projecteuler.net/problem=22)

Python:

def main():
    names = open("names.txt", "r").read().replace("\"", "").split(",")
    names.sort()
    print sum((i + 1) * sum(ord(c) - ord('A') + 1 for c in n) for i, n in enumerate(names))

if __name__ == "__main__":
    main()

Java:

import java.util.Arrays;
import java.lang.StringBuilder;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class euler22
{
    public static String readFileAsString(String path) throws IOException
    {
        StringBuilder builder = new StringBuilder();
        BufferedReader reader = new BufferedReader(
                new FileReader(path));
        String buffer = null;

        while((buffer = reader.readLine()) != null)
        {
            builder.append(buffer);
        }

        reader.close();

        return builder.toString();
    }

    public static void main(String[] args) throws IOException
    {
        String[] names = fileAsString("names.txt").replace("\"", "").split(",");
        int total = 0;

        Arrays.sort(names);

        for(int i = 0; i < names.length; ++i)
        {
            int sum = 0;

            for(char c : names[i].toCharArray())
            {
                sum += c - 'A' + 1;
            }

            total += (i + 1) * sum;
        }

        System.out.println(total);
    }
}


texts:
I have a task to print all zero subsets of 5 numbers, input from the console.
I have succeeded in implementing a working code, but it seems it is quite complex (it is like inception) and if the count of the numbers is to be greater, it would be rather pointless to use such a method.

using System;
using System.Collections.Generic;
using System.Linq;

class ZeroSubset
{
    static void Main()
    {
        int number;
        int[] Numbers = new int[5];
        bool result = false;
        for (int i = 0;i <=4; i++)
        {
            here: ;
            Console.WriteLine("Input number {0}", i + 1);
            if (int.TryParse(Console.ReadLine(), out number))
            {
                Numbers[i] = number;
            }
            else
            {
                goto here;
            }
        }

        if (Numbers[0] == 0 && Numbers[1] == 0 && Numbers[2] == 0 && Numbers[3] == 0 && Numbers[4] == 0)
        {
            result = true;
            Console.WriteLine(String.Join("+", Numbers) + " = 0");
            return;
        }

        for (int firstNum = 0; firstNum <= 3; firstNum++)
        {
            for (int secondNum = firstNum + 1; secondNum <= 4; secondNum++)
            {
                if (Numbers[firstNum] + Numbers[secondNum] == 0)
                {
                    result = true;
                    Console.WriteLine("{0} + {1} = 0", Numbers[firstNum], Numbers[secondNum]);
                }
            }
        }

         for (int firstNum = 0; firstNum <= 2; firstNum++)
         {
            for (int secondNum = firstNum + 1; secondNum <= 3; secondNum++)
            {
                for (int thirdNum = secondNum + 1; thirdNum <= 4; thirdNum++)
                {
                    if (Numbers[firstNum] + Numbers[secondNum] + Numbers[thirdNum]== 0)
                    {
                        result = true;
                        Console.WriteLine("{0} + {1} + {2} = 0", Numbers[firstNum], Numbers[secondNum], Numbers[thirdNum]);
                    }
                }
            }
        }

        for (int firstNum = 0; firstNum <= 1; firstNum++)
        {
            for (int secondNum = firstNum + 1; secondNum <= 2; secondNum++)
            {
                for (int thirdNum = secondNum + 1; thirdNum <= 3; thirdNum++)
                {
                    for (int fourthNum = thirdNum + 1; fourthNum <= 4; fourthNum++)
                    {
                        if (Numbers[firstNum] + Numbers[secondNum] + Numbers[thirdNum] + Numbers[fourthNum]== 0)
                        {
                            result = true;
                            Console.WriteLine("{0} + {1} + {2} + {3} = 0", Numbers[firstNum], Numbers[secondNum]
                                    , Numbers[thirdNum], Numbers[fourthNum]);
                        }
                    }
                }
            }
        }

        if (Numbers.Sum() == 0)
        {
            result = true;
            Console.WriteLine(String.Join("+", Numbers) + " = 0");
        }

        if (result == false)
        {
            Console.WriteLine("no zero subsets");
        }
    }
}

I am asking for a more simple approach to this matter.


texts:
I was wondering if I am doing any useless conversions byte←→int, for example:

byte((int(ch-'A')+shift)%26 + 'A')

Converting ch-'A' to an int is because the shift argument can be negative (to implement the decode function). I couldn't figure out a simpler way to negate the operation using bytes.

package main

import (
    "bufio"
    "flag"
    "fmt"
    "os"
)

func main() {
    shift := flag.Int("shift", 13, "Cipher shift")
    decode := flag.Bool("decode", false, "Decode input")

    flag.Parse()

    scanner := bufio.NewScanner(os.Stdin)
    for scanner.Scan() {
        if *decode {
            fmt.Println(Decode(scanner.Text(), *shift))
        } else {
            fmt.Println(Encode(scanner.Text(), *shift))
        }
    }
}

func Encode(s string, shift int) string {
    return cipher(s, shift)
}

func Decode(s string, shift int) string {
    return cipher(s, -shift+26)
}

func cipher(s string, shift int) string {
    var line string
    for _, ch := range []byte(s) {
        if ch >= 'A' && ch <= 'Z' {
            ch = byte((int(ch-'A')+shift)%26 + 'A')
        } else if ch >= 'a' && ch <= 'z' {
            ch = byte((int(ch-'a')+shift)%26 + 'a')
        }
        line += string(ch)
    }
    return line
}


texts:
Question:
You're in a hotel and you forgot what room number you were in but remember that the sum of it's divisors is greater than the number, yet there is no subset of those divisors that add up to the number itself. There are 100 rooms in the Hotel, what's your room number?

My Answer in CoffeeScript:
Looking for constructive criticism of my solution, as well as styling suggestions specific to CoffeeScript.

# hotelRoom.coffee
# splashinn

findRoom = (totalRooms) ->
  findDivisors = (number) ->
    divisors = []
    iterator = number
    divisors.push iterator  if number % iterator is 0  while iterator--
    divisors

  # Returns true or false based on whether the number is found in the sum of array subsets
  isSubsetSum = (number, array) ->
    hasSubset = false
    (findSubset = (total, numbers) ->
      not hasSubset and (hasSubset = total is number)
      return  if hasSubset or total > number
      numbers.forEach (num, index) ->
        findSubset total + num, numbers.slice(0, index).concat(numbers.slice(index + 1))
    ) 0, array
    hasSubset

  # Need a simple helper method that returns the sum of an array
  sumArray = (array) ->
    array.reduce ((memo, num) ->
      memo + num
    ), 0

  # Find the room using the provided functions
  divisors = undefined
  room = 0

  while room <= totalRooms
    divisors = findDivisors(room)

    # The sum of all the divisors must be greater than the number
    return room  if sumArray(divisors) > room and not isSubsetSum(room, divisors)
    room++
  0 # No room number found


texts:
I am just getting started with python. I wanted to make a folder transfer tool to get familiar with python sockets.

import socket, os, sys
print"[*]Enter the IP[*]"
ip = sys.stdin.readline().rstrip()
port = 9999

# A file sender first
def file_sender(location, client_socket):
    f = open(location, 'r')
    data = f.read()
    print("[*]Sending %s[*]" % location)
    client_socket.sendall(data)
    print("[*]Sent %s[*]" % location)
    f.close()
    client_socket.send("STOP")
    client_socket.recv(4096)

# A file reciver for the reciver
def file_reciver(sv, client):
    f = open(sv, 'a')
    data = client.recv(1024)
    while data:
        f.write(data)
        data = client.recv(1024)
        if "STOP" in data:
            break
    f.write(data[:-4])
    client.send("recived")
    f.close()
    print("[*]Saved %s[*]" % sv)

# A folder sender
def folder_sender(location, client_socket):
    os.chdir(location)
    location = os.getcwd()
    no = len(list(os.listdir(location)))
    client_socket.send(str(no))
    print"[*]Preparing to send %d objects[*]" % no
    res = client_socket.recv(1024)
    print res
    for x in os.listdir(location):
        client_socket.send(x)
        print("[*]Sending %s[*]" % x)
        client_socket.recv(1024)
        # Call the server manager
        server_manager(x, client_socket)
        os.chdir(location)
        print(location)

# A folder reciver
def folder_reciver(sv, client):
    try:
        os.mkdir(sv)
    except:
        print "[*]File %s already exists can't overwrite[*]" % sv
        sys.exit(0)
    os.chdir(sv)
    location = os.getcwd()
    print location
    no = client.recv(1024)
    print ("[*]Preparing to recive %s objects[*]" % no)
    client.send("[*]Ready to recive[*]")
    for x in range(int(no)):
        sv = client.recv(4096)
        print ("Reciving %s" % sv)
        client.send("Recived new object")
    # call the client manager
        client_manager(sv, client)
        os.chdir(location)  # Go to the previous diectory
        print("Saved to %s" % location)

   # Server manager, just seperates files from directories
def server_manager(location, client_socket):
    if os.path.isdir(location):
        client_socket.send("DIR")
        folder_sender(location, client_socket)
    else:
        client_socket.send("not dir")
        file_sender(location, client_socket)

def client_manager(sv, client):
    c = client.recv(4096)
    print c
    if c == "DIR":
        folder_reciver(sv, client)
    else:
        file_reciver(sv, client)

# A sender
def sender():
    server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    try:
        server.bind((ip, port))
    except:
        print "[*]Couldn't bind the requested IP[*]"
        sys.exit(0)
    server.listen(1)
    print "[*]Listening to %s : %d[*]" % (ip,port)

    def seer(client_socket):
        re = client_socket.recv(1024)
        print re
        print "[*]The path of the file to send[*]"
        location = sys.stdin.readline().rstrip()
        server_manager(location, client_socket)
        print("[*]sent all[*]")
    client, addr = server.accept()
    print "[*]Accepted connection form %s : %d[*]" % (addr[0], addr[1])
    seer(client)

# A reciver
def reciver():
    client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    try:
        client.connect((ip, port))
    except:
        print "[*]Coudn't connect to the requested server [*]"
        sys.exit(0)
    client.send("[*]Client is ready to recive[*]")
    print "[*]Where to save the file[*]"
    v = sys.stdin.readline().rstrip()
    try:
        os.chdir(v)
    except:
        print "[*]No such path/location [*]"
        sys.exit(0)
    print "[*]Save as[*]"
    b = sys.stdin.readline().rstrip()
    sv = os.path.join(v, b)
    client_manager(sv, client)

while True:
    print "[*]Type s to send or r to recive[*]"
    command = (sys.stdin.readline()).rstrip()
    if command.lower() == "s":
        sender()
    elif command.lower() == "r":
        reciver()
    else:
        print "[*]Invalid Argument: %s" % command


texts: Pattern that adds a different value to the same attribute for many classes

texts:
The purpose of this question is to get some advice for improving the following code in order to make it less repetitive.

.parent-div a {
  border-bottom: 10px solid;
  .blue & {
    border-color: $blue;
  }
  .red & {
    border-color: $red;
  }
  .green & {
    border-color: $green;
  }
  .pink & {
    border-color: $pink;
  }
  .yellow & {
    border-color: $yellow;
  }
  .purple & {
    border-color: $purple;
  }
  // here comes again all the styles but for each hovered anchor
 .blue &:hover {
    border-color: darken($blue, 10%);
  }
 .red &:hover {
     border-color: darken($red, 10%);
  }
}


texts: Does my Linklist implementation have memory leaks?

texts:
Are there any memory leaks in this linklist implementation.Also is the implementation correct?Can the time complexity be optimized?

#include <iostream>
#include <cstdlib>
#include <cstdio>
using namespace std;

struct node
{
int n;
node* point;
};

node* first=NULL;

void search(int n);
void insert(int n);
void del(int n);
void print();

void menu()
{
int s,n;
cout<<"Enter 1 to Search"<<endl;
cout<<"Enter 2 to Insert"<<endl;
cout<<"Enter 3 to Delete"<<endl;
cout<<"Enter 4 to Print"<<endl;
cout<<"Enter 5 to Exit"<<endl;

cin>>s;

switch(s)
{
    case 1: cout<<"Enter number to Search: ";
            cin>>n;
            search(n);
            break;

    case 2: cout<<"Enter number to Insert: ";
            cin>>n;
            insert(n);
            break;

    case 3: cout<<"Enter number to Delete: ";
            cin>>n;
            del(n);
            break;

    case 4: print();
            break;

    case 5: exit(0);

    default: cout<<"Wrong Input"<<endl<<endl<<endl;
}
}

int main()
{
cout<<"Welcome to Linked List"<<endl;
while(1)
    menu();
}

void search(int n)
{
node* ptr=first;

while(ptr!=NULL)
{
    if(ptr->n==n)
    {
        cout<<endl<<n<<" Found!"<<endl<<endl<<endl;
        return;
    }
    else
        ptr=ptr->point;

}

cout<<endl<<n<<" Not Found!"<<endl<<endl<<endl;
return;
}

void insert(int n)
{
node* prev=NULL;
node* next=first;

if(first!=NULL and first->n>n)
{
    first=new node;
    first->n=n;
    first->point=next;
    cout<<endl<<endl;
    return;
}

while(next!=NULL)
{
    if(next->n>n)
    {
        prev->point=new node;
        (prev->point)->n=n;
        (prev->point)->point=next;
        cout<<endl<<endl;
        return;
    }
    else
    {
        prev=next;
        next=next->point;
    }
}
    if(prev==NULL)
    {
        first=new node;
        first->n=n;
        first->point=NULL;
    }
    else
    {
        prev->point=new node;
        (prev->point)->n=n;
        (prev->point)->point=NULL;

    }
    cout<<endl<<endl;
    return;

}

void print()
{
node* next=first;

while(next!=NULL)
{
    cout<<next->n<<" ";
    next=next->point;
}
cout<<endl<<endl<<endl;
return;
}

void del(int n)
{
node* prev=NULL;
node* next=first;

while(next!=NULL)
{
    if(next->n==n)
    {
        if(prev!=NULL)
        {
            prev->point=next->point;
            delete next;
        }
        else
        {
            first=next->point;
            delete next;
        }
        cout<<n<<" Deleted!";
        cout<<endl<<endl;
        return;
    }
    else
    {
        prev=next;
        next=next->point;
    }
}

cout<<"Number not in list"<<endl<<endl<<endl;
return;
}


texts:
I'm a programming newbie. In fact, this is my second code ever (after Hello World). I did a lot of reading actually, here on Stack Overflow, and other websites. I would like to know if there's a way to further improve this code.

#include <iostream>
#include <string>
using std::cout; using std::cin;

int main()
{
cout << "Calculator..... \n";
cout << "Type '3a3'to exit... \n";

double a=0 ,b=0;
char op = 'a'; //operator // 'a' is the exit operator, the value of the integers doesn't matter

int ch = 0; //while loop checker

do
{
    cin >> a >> op >> b;
    if (op == '/' && b == 0)
    {
        cout << "Division By Zero, Please Retry \n" ;
        goto retry;
    }
    switch (op)
    {
        case '+':
        cout << a << " + "<< b << " = " << a+b << "\n";
        ch = 0 ;
        break;

        case '-':
        cout << a << " - "<< b << " = " << a-b << "\n";
        ch = 0 ;
        break;

        case 'x':
        case '*':
        cout << a << " * "<< b << " = " << a*b << "\n";
        ch = 0 ;
        break;

        case '/':
        cout << a << " / "<< b << " = " << a/b << "\n";
        ch = 0;
        break;

        case 'a':
        ch = 1;
        break;

        default:
        ch = 0;
        cout << "Invalid operator, Please retry \n";
    }

    retry: ;

}while (ch != 1);

}