texts:
I would like to know whether I'm going in a correct way or not in building my Poker game. So far, I've implemented card and deck classes and I would like to see your feedback about my work. Feel free to criticize the code of any regard (organization, order, comments ... etc)

card.h

#ifndef CARD_H
#define CARD_H

#include <string>

const int SUIT_MAX(4);
const int RANK_MAX(13);

class Card
{
    friend class Deck; // Deck Class needs to access to Card Class but not vice versa
public:
    explicit Card();
    explicit Card(const int &suit, const int &rank);

    std::string Card2Str() const;

private:
    int generate_suit();
    int generate_rank();
    int get_suit() const;
    int get_rank() const;
    int m_suit;
    int m_rank;
};
#endif

card.cpp

#include <stdlib.h>     /* srand, rand */
#include "card.h"
#include <iostream>

const std::string SUIT[SUIT_MAX]  = {"S", "H", "D", "C"};
const std::string RANK[RANK_MAX]  = {"2","3","4","5","6","7","8","9","10","J","Q","K","A"};

Card::Card()
{
   m_suit = generate_suit();
   m_rank = generate_rank();
}

Card::Card(const int &suit, const int &rank) : m_suit(suit), m_rank(rank)
{

}

int Card::generate_suit()
{
    return rand() % (SUIT_MAX-1) + 0;
}

int Card::generate_rank()
{
    return rand() % (RANK_MAX-1) + 0;
}

std::string Card::Card2Str() const
{
    return SUIT[get_suit()] + RANK[get_rank()];
}

int Card::get_suit() const
{
    return m_suit;
}

int Card::get_rank() const
{
    return m_rank;
}

deck.h

#ifndef DECK_H
#define DECK_H

#include <vector>
#include <iostream>
#include <fstream>
#include "card.h"

using namespace std;

class Deck
{
public:
      explicit Deck();
      void print_Deck() const;
      void getOneCard();
private:
    std::vector<Card> m_deck;

};

#endif

deck.cpp

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

Deck::Deck()
{
    for (unsigned int i(0); i < SUIT_MAX; ++i)
    {
        for (unsigned int j(0); j < RANK_MAX; ++j)
        {
            Card card(i, j);
            m_deck.push_back(card);
        }
    }
}

void Deck::print_Deck() const
{
    unsigned int count(1);

    for (unsigned int i(0); i < m_deck.size(); ++i)
    {
        std::cout << m_deck[i].Card2Str() << " ";
        if ( count == 13 )
        {
          std::cout << std::endl;
          count = 0;
        }
        ++count;
    }
}

void Deck::getOneCard()
{
    Card cd(m_deck.back().get_suit(), m_deck.back().get_rank());
    m_deck.pop_back();
    std::cout << cd.Card2Str() << std::endl;
}

main.cpp

#include <iostream>
#include <vector>
#include <stdlib.h>     /* srand, rand */
#include <time.h>       /* time */
#include <string>

#include "card.h"
#include "deck.h"

int main()
{
    srand (time(NULL));

    Deck _deck;
    _deck.print_Deck();
    _deck.getOneCard();

    std::cout << std::endl;
    _deck.print_Deck();

    std::cout << std::endl;

    return 0;
}


texts: Callback class to callback member (virtual) functions

texts:
After looking at a post on CR I found that pointers to member functions are incredibly hard to use, especially as callbacks. The current solution doesn't solve the problem mentioned in the linked post, but tries to get rid of the type erasure (i.e. std::function<>) by making the target type explicit. I tried to solve lifetime/ownership issue with something else than std::shared_ptr<>, but found that it is impossible without relying on programmer to take care of that. So, I ended up with std::shared_ptr<> as a solution.

So, here is the code:

#pragma once
#include <memory>
#include <utility>

template <typename T, typename Func>
class member_callback;

template <typename T, typename R, typename ... ArgTypes>
class member_callback<T, R(ArgTypes...)>
{
    std::shared_ptr<T> object;
    R(T::* callback)(ArgTypes ...);
public:
    using function_pointer = R(T::*)(ArgTypes ...);

    member_callback(const std::shared_ptr<T>& ptr, R(T::* function)(ArgTypes...)) :
        object(ptr),
        callback(function)
    {}

    member_callback(std::shared_ptr<T>&& ptr, R(T::* function)(ArgTypes...)) :
        object(std::move(ptr)),
        callback(function)
    {}

    R operator()(ArgTypes&& ... args)
    {
        return ((*object).*callback)(std::forward<ArgTypes>(args)...);
    }

    std::shared_ptr<T> get()
    {
        return object;
    }

    function_pointer get_function()
    {
        return callback;
    }
};

It does one tradeoff though, you can't make a vector of them and call member functions of completely unrelated classes. Nevertheless, you'll still be able to invoke virtual functions, and they will work as expected according to this answer.

From the first glance it might look useless. But it is not! It becomes extremely useful when you're making a menu (1. ... 2. ... 3. ...) and want to invoke a function on the single object. So, here is the example:

#include "member_callback.hpp"
#include <iostream>
#include <vector>

class integer
{
    int x;
public:
    integer():
            x(0)
    {}

    integer& operator++()
    {
        ++x;
        return *this;
    }

    integer& operator--()
    {
        --x;
        return *this;
    }

    friend std::ostream& operator<<(std::ostream& os, const integer& i);
};

std::ostream& operator<<(std::ostream& os, const integer& i)
{
    os << "Currently number is: " << i.x << '\n';
}

void print_menu()
{
    static auto message = "Type the specified number to invoke the command.\n";
    static auto menu = "0. Increment\n1. Decrement\nAnything else to exit\n";

    std::cout << message << menu;
}

int main()
{
    auto object = std::make_shared<integer>();

    std::vector<member_callback<integer, integer&()>> actions{{object, &integer::operator++},
                                                              {object, &integer::operator--}};

    std::cout << "Welcome to dummy program!\n";
    std::cout << *object;

    unsigned int response =  -1;
    print_menu();
    std::cin >> response;
    while (response < 2)
    {
        actions[response]();
        std::cout << *object;
        print_menu();
        std::cin >> response;
    }

    std::cout << "Goodbye!\n";
}

If code will ever get changed you can find it here.

I would like a review to focus on the easy of use. Also, does the code provide fine grained control? It will require dealing with std::shared_ptr<>, but I think it is mostly ok. Any other review points are welcome!


texts: Do not select elements that contain data attributes

texts:
I have a selector that pulls in all anchor tags that start with the # symbol. I am trying to add a :not selector of some form for elements that have a data attribute. I know I could do the following...

$('a[href^="#"]:not([data-known])')

But the problem is that I don't know what the data attribute will be called. I have resorted to doing the following.

$('a[href^="#"]').click(function(event){
    if($.isEmptyObject($(this).data())){
        //custom code here
    }
});

Is there a way to avoid the if statement and add the :not to the original selector? Is there a better way of doing this period?

Here is a FIDDLE I have been playing in.


texts:
I have the following method, which can be written in the following two ways: which one would you prefer, and why?

# version with case...when
def choose(value)
  case value
  when value < LOWER_LIMIT
    'a'
  when value > UPPER_LIMIT
    'b'
  else
    'c'
end

# version with Hash#fetch
def choose(value)
  { (value < LOWER_LIMIT) => 'a',
    (value > UPPER_LIMIT) => 'b'
  }.fetch(true, 'c')
end

I personally find the first one more linear and readable.


texts:
I am a beginner in python and I was wondering if the code for this program is nice and clean. The program works I was wondering how could i improve it. So this program asks for your 'username' and checks to see if your 'username' is in the 'banned users' list. If it is then it will 'log out' and won't let you comment. If your 'username' isn't in the 'banned uses' list it will let you comment and ask if you would like to let someone else to comment. If you enter 'yes' the 'while loop' will run again if there isn't then the program will print the username and comments. This is basically what the program does. How can I improve it?

# We define a function here.
def display_comments():
    """Displays User Input (comments)"""
    if user_comments:  # If the dictionary 'user_comments' has at least one key value pair then execute this block of code.
        print("\nTop Comments:")
        for username, comment in user_comments.items(): # Define a for loop for each key value pair in the dictionary 'user_comments'.
            print(f"\n\t{username}: {comment}.")  # Print each key value pair.

username_prompt = "\nUsername: "
comment_prompt = "Comment: "
continue_prompt = "\nWould you like to let another user comment (yes/no)? "

banned_users = ['pete', 'jack', 'ali', 'henry', 'jason', 'emily'] # List of banned users.
user_comments = {} # Empty dictionary that we will store user input later on in the program.

account_active = True  # Set up a flag

while account_active: # Run as long as the 'account_active' flag remains 'True'.
    username = input(username_prompt) # Ask for a username and store it in the variable 'username'.

    if username.lower() in banned_users: # Cross reference the username with the banned_users list. If the username is in the banned_users list then execute the following code.
        print(f"\nI'm sorry {username} but you are banned from using this site.") # Tell the user that they are banned.
        print("Deactivating...") # Simulate logging out.

        account_active = False # Set the flag to 'False'

    else: # Run this code only if the user is not in the 'banned_users' list.
        comment = input(comment_prompt) # Ask the user for their comment and store it in the variable 'comment'.

        user_comments[username] = comment # Add the username and comment (key-value pair) to the 'user_comments' dictionary.

        repeat = input(continue_prompt) # Ask the user if they want to repeat and store it in the variable 'repeat'.

        if repeat == 'no': # If the variable 'repeat' has the value 'no' then execute the following code, otherwise run the while loop again.
            account_active = False # Set the flag to 'False'

display_comments() # Call the 'display_comments()' function to print the key-value pairs in the dictionary.


texts: Conditional merge with Ruby to include a parameter if it hasn't been included

texts:
I have the following function, and I have a hunch it can be written more concisely in Ruby.

def template_params
  filtered_params = params[:template].permit!
  filtered_params[:published] ||= false
  filtered_params
end

The end result is that filtered_params has published: false if the params hash doesn't have published as a key.

I'm wondering if there is some kind of conditional merge w/ Ruby to turn that code into a 1-liner.

Essentially, the params hash includes "what has been changed" and when :published becomes false (it's a checkbox that gets unchecked), it naturally doesn't get included in the params hash. I wanted to pass in the fact that :published became false when it got unchecked.

I do not need to pass in published: false by default, because whatever the default is, is fine. It is the changed state that I need, but from false to true. The alternative works: if the checkbox is checked, it becomes true and gets passed through without issue.

This is more an exercise of how can I turn this bit of code into something more "elegant" and maybe a 1-liner.  As it stands, it does exactly what I need it to do.


texts: Selecting an enum for a payment transaction

texts:
I'm writing a small Android application that deals with payments and, in my function that handles transactions, I need to translate a number of installments (1-12) and whether or not it has interest (0-1) into the de facto objects for those of the SDK I'm using.

Right now I have a switch that looks like the following:

InstalmentTransactionEnum install = InstalmentTransactionEnum.ONE_INSTALMENT;
//TODO: Implement interest
switch (installments) {
    case "1":
        install = InstalmentTransactionEnum.ONE_INSTALMENT;
        break;
    case "2":
        install = InstalmentTransactionEnum.TWO_INSTALMENT_NO_INTEREST;
        break;
    case "3":
        install = InstalmentTransactionEnum.THREE_INSTALMENT_NO_INTEREST;
        break;
    case "4":
        install = InstalmentTransactionEnum.FOUR_INSTALMENT_NO_INTEREST;
        break;
    case "5":
        install = InstalmentTransactionEnum.FIVE_INSTALMENT_NO_INTEREST;
        break;
    case "6":
        install = InstalmentTransactionEnum.SIX_INSTALMENT_NO_INTEREST;
        break;
    case "7":
        install = InstalmentTransactionEnum.SEVEN_INSTALMENT_NO_INTEREST;
        break;
    case "8":
        install = InstalmentTransactionEnum.EIGHT_INSTALMENT_NO_INTEREST;
        break;
    case "9":
        install = InstalmentTransactionEnum.NINE_INSTALMENT_NO_INTEREST;
        break;
    case "10":
        install = InstalmentTransactionEnum.TEN_INSTALMENT_NO_INTEREST;
        break;
    case "11":
        install = InstalmentTransactionEnum.ELEVEN_INSTALMENT_NO_INTEREST;
        break;
    case "12":
        install = InstalmentTransactionEnum.TWELVE_INSTALMENT_NO_INTEREST;
        break;
}
stoneTransaction.setInstalmentTransactionEnum(install);

Now this is without me having implemented interest which in this method would require another massive switch statement where install would be equal to TWO_INSTALLMENT_WITH_INTEREST and so on.

My thinking is that there must be a smarter way of doing this that doesn't involve an if statement to check the interest variable (a boolean) and the massive switch for installments. What is the best way of achieving this?


texts: Append the first half of the first line of /etc/hosts to a conf file

texts:
I have to edit a config automatically before starting a service in a docker container (a storm supervisor), and I want to append something like this in /opt/storm/conf/storm.yaml: storm.local.hostname: 1.1.1.1 (extracted from /etc/hosts)

What I currently do is that:

echo -n "storm.local.hostname: " >> /opt/storm/conf/storm.yaml && head -1 /etc/hosts | awk -F ' ' {'print $1'} | xargs echo >> /opt/storm/conf/storm.yaml

How can I improve on that, on a readability POV? It looks pretty obfuscated to me, but I may just be naive ^^

Disclaimer: this runs inside a docker container, so there's only access to classic bash.


texts: Partitioning an array of objects into four arrays by one attribute

texts:
I have an array of API objects, below is an example of one object:

{
    description: "Get a list of most recent social alerts"
    example_input: ""
    example_output: "status"
    id: 19
    method: "GET"
    resource: "/api/alerts"
}

With my code below, I'm able to loop through the big Array, then filter out items into 1 of 4 arrays (for GET, POST, PUT and DELETE)

RestFactory.getREST().then(function(res) {
    filterArrays(res.data.rest_methods);
});

function filterArrays(data) {
    for (var i=0; i<data.length; i++) {
        if (data[i].method === 'GET') {
            getArray.push(data[i]);
        }
        else if (data[i].method === 'POST') {
            postArray.push(data[i]);
        }
        else if (data[i].method === 'PUT') {
            putArray.push(data[i]);
        }
        else if (data[i].method === 'DELETE') {
            deleteArray.push(data[i]);
        }
    }
}

I feel that this is not the most efficient way to accomplish this, how should this be refactored? Would you recommend lodash in this scenario?


texts: Exposing .NET's internal StorageRoot via Reflection for accessing file/stream-based Structured Storage

texts:
.NET tantalizingly exposes StorageInfo and StreamInfo as public classes, but hides the seminal StorageRoot as an internal class, leaving the user no way of creating or opening a Structured Storage from a file or stream.

Microsoft's Reference Source details the source behind StorageRoot which inherits from StorageInfo, so rather than copy the code, I've chosen to expose the static methods of StorageRoot via reflection, so that I can get a reference to the root storage of a File or Stream. I've also exposed a Close method to close an open root StorageInfo.

using System;
using System.IO;
using System.IO.Packaging;
using System.Reflection;

namespace StructuredStoreageTest
{
    public static class StorageRoot
    {
        public static StorageInfo CreateOnStream(Stream baseStream)
        {
            return (StorageInfo)InvokeStorageRootMethod(null, "CreateOnStream", baseStream);
        }

        public static StorageInfo CreateOnStream(Stream baseStream, FileMode mode)
        {
            return (StorageInfo)InvokeStorageRootMethod(null, "CreateOnStream", baseStream, mode);
        }

        public static StorageInfo Open(string path)
        {
            return (StorageInfo)InvokeStorageRootMethod(null, "Open", path);
        }

        public static StorageInfo Open(string path, FileMode mode)
        {
            return (StorageInfo)InvokeStorageRootMethod(null, "Open", path, mode);
        }

        public static StorageInfo Open(string path, FileMode mode, FileAccess access)
        {
            return (StorageInfo)InvokeStorageRootMethod(null, "Open", path, mode, access);
        }

        public static StorageInfo Open(string path, FileMode mode, FileAccess access, FileShare share)
        {
            return (StorageInfo)InvokeStorageRootMethod(null, "Open", path, mode, access, share);
        }

        public static StorageInfo Open(string path, FileMode mode, FileAccess access, FileShare share, int sectorSize)
        {
            return (StorageInfo)InvokeStorageRootMethod(null, "Open", path, mode, access, share, sectorSize);
        }

        public static void Close(StorageInfo storageRoot)
        {
            InvokeStorageRootMethod(storageRoot, "Close");
        }

        private static object InvokeStorageRootMethod(StorageInfo storageRoot, string methodName, params object[] methodArgs)
        {
            Type storageRootType = typeof(StorageInfo).Assembly.GetType("System.IO.Packaging.StorageRoot", true, false);
            return storageRootType.InvokeMember(methodName,
                BindingFlags.Static | BindingFlags.Instance | BindingFlags.Public |
                BindingFlags.NonPublic | BindingFlags.InvokeMethod,
                null, storageRoot, methodArgs);
        }
    }
}

I can then use StorageRoot as follows:

MemoryStream myStream = new MemoryStream(streamBytes);
StorageInfo myRoot = StorageRoot.CreateOnStream(myStream);

StreamInfo dataStreamInfo = myRoot.GetStreamInfo("data");
Stream dataStream = dataStreamInfo.GetStream();
//read/process the stream
dataStream.Dispose();

StorageRoot.Close(myRoot);

Is relying upon Reflection the best alternative here? I could reproduce the StorageRoot code from Reference Source, and make StorageRoot an instance class, I suppose.


texts: Reorder the Columns in a CSV File in Descending Order

texts:
I wrote a script to reorder the columns in a CSV file in descending order and then write to another CSV file. My script needs to be able to handle several tens of millions of records, and I would like it to be as performant as possible.
This is basically a mockup of a more complex CSV transformation I would be working on for work (I don't yet know the nature of the transformation I would be performing). To clarify, I was directed to write this at work, and it would be tested/scrutinised to see if its performant enough, but it's also not the final script we would eventually run.
CSV-Transform.py
import pandas as pd
import csv

chunksize = 10 ** 6 # Or whatever value the memory permits
source_file = ""
# Change to desired source file
destination_file = ""
# Change to desired destination file

def process(chunk, headers, dest):
   df = pd.DataFrame(chunk, columns=headers)
   df.to_csv(dest, header=False,  index=False)

def transform_csv(source_file, destination_file):
   with open(source_file) as infile:
      reader = csv.DictReader(infile)
      new_headers = reader.fieldnames[::-1]

   with open(destination_file, "w+") as outfile:
      outfile.write(",".join(new_headers))
      outfile.write("\n")

   with open(destination_file, 'a') as outfile:
      for chunk in pd.read_csv(source_file, chunksize=chunksize):
         process(chunk, new_headers, outfile)

transform_csv(source_file, destination_file)


texts:
The code below is meant to build an array with certain properties neccesairy to create column for a table in a database.
Would there be any more effcient way of doing this?

Public fieldName As String
Public fieldType As ADOX.DataTypeEnum
Public fieldProperties As String
Public fieldPropertiesValue
Public fieldIndex As Boolean
Public fieldUnique As Boolean
Public fieldKey As Boolean

Public Sub New(ByVal fieldName As String, ByVal fieldType As ADOX.DataTypeEnum, Optional ByVal fieldProperties As String = Nothing,
               Optional ByVal fieldPropertiesValue As Object = Nothing, Optional ByVal fieldIndex As Boolean = False,
               Optional ByVal fieldUnique As Boolean = False, Optional ByVal fieldKey As Boolean = False)

    Me.fieldName = fieldName
    Me.fieldType = fieldType
    Me.fieldProperties = fieldProperties
    Me.fieldPropertiesValue = fieldPropertiesValue
    Me.fieldIndex = fieldIndex
    Me.fieldUnique = fieldUnique
    Me.fieldKey = fieldKey

End Sub

Public Shared IDOwner As classObjectField = New classObjectField("IDOwner", ADOX.DataTypeEnum.adInteger, "AutoIncrement", True, True, True, True)
Public Shared OwnerAccount As classObjectField = New classObjectField("OwnerAccount", ADOX.DataTypeEnum.adVarWChar, fieldIndex:=True)
Public Shared OwnerName As classObjectField = New classObjectField("OwnerName", ADOX.DataTypeEnum.adVarWChar, fieldIndex:=True)
Public Shared OwnerMail As classObjectField = New classObjectField("OwnerMail", ADOX.DataTypeEnum.adVarWChar, fieldIndex:=True, fieldUnique:=True)

Public Shared ArrayTableOwners = New Object(3) {
    IDOwner, OwnerAccount, OwnerName, OwnerMail
}

Public Shared IDUser As classObjectField = New classObjectField("IDUser", ADOX.DataTypeEnum.adInteger, "AutoIncrement", True, True, True, True)
Public Shared UserName As classObjectField = New classObjectField("OwnerAccount", ADOX.DataTypeEnum.adVarWChar, fieldIndex:=True)
Public Shared UserFunctionCode As classObjectField = New classObjectField("OwnerName", ADOX.DataTypeEnum.adVarWChar, fieldIndex:=True)

Public Shared ArrayTableUser = New Object(2) {
    IDUser, UserName, UserFunctionCode
}

This function below creates the table of an existing Access DB

 Public Shared Function createDBTable(Cat As ADOX.Catalog, tableName As String, objField As Object) As Boolean
    Dim confirm As Boolean = True

    Try
        Dim objTable = New ADOX.Table
        Dim objIndex = New ADOX.Index

        objTable.Name = tableName

        For Each valueField In objField

            objTable.Columns.Append(valueField.fieldName, valueField.fieldType)

            If Not valueField.FieldProperties = Nothing Then

                objTable.Columns.Item(valueField.fieldName).ParentCatalog = Cat
                objTable.Columns.Item(valueField.fieldName).Properties(valueField.fieldProperties).Value = valueField.FieldPropertiesValue

            End If

            If valueField.fieldIndex = True Then

                objIndex = New ADOX.Index
                objIndex.Unique = valueField.fieldUnique
                objIndex.Name = valueField.fieldName
                objIndex.PrimaryKey = valueField.fieldKey
                objIndex.Columns.Append(valueField.fieldName)
                objTable.Indexes.Append(objIndex)

            End If

        Next

        Cat.Tables.Append(objTable)

        objIndex = Nothing
        objTable = Nothing
    Catch ex As Exception

        MsgBox(ex.Message)
        confirm = False

    End Try

    Return confirm
End Function

Usage:

Dim objCn = New ADODB.Connection
Dim objCat = New ADOX.Catalog
objCn.Open(DBSourceLocation)
objCat.ActiveConnection = objCn

createDBTable(objCat, "OWNERLIST", ArrayTableOwners)
createDBTable(objCat, "USERLIST", ArrayTableUser)


texts:
This is a completely functional python script of the Tic-Tac-Toe game. I've used python's set container for almost all data structure and operation. The code is small and somewhat readable. I would very much appreciate your opinion and suggestions to improve it in terms of speed, readability and refactoring wherever necessary. Please post in your answer any modifications needed in the algorithm used.

The grid is marked from 1 to 9 horizontally.
The TTT class handles all the tasks.
self.ploys is a dictionary containing all the solution combinations.

{1: [{1,2,3}, {1,4,7}, {1,5,9}], 2:[{1,2,3}, {2,5,8}], ...}

The Main Loop displays the output, cycles through each player's turn and checks the result.
self.PlayUser and self.PlayCom plays respective turns.

#!/usr/bin/env python3

import os

erase = 'cls' if os.name == 'nt' else 'clear'
# 3x3 grid and 8 solution sets
grid = set(range(1,10))
sols = ({1,2,3}, {4,5,6},
        {7,8,9}, {1,4,7},
        {2,5,8}, {3,6,9},
        {1,5,9}, {3,5,7})

class TTT(object):

    def __init__(self):
        # Valid combinations (shortens during game)
        self.ploys = {k:[s for s in sols if k in s] for k in grid}
        # Holds two sets; user moves and com moves
        self.umoves = set()
        self.cmoves = set()

    def GameOver(self, moves):
        """Returns True if the puzzle is solved, False if it's a tie."""
        if any(s.issubset(moves) for s in sols):
            return True
        elif (self.umoves|self.cmoves) == grid:
            return False

    def PlayUser(self):
        """Plays the user's turn"""
        umove = int(input())
        # Filter invalid moves
        while umove not in grid or (umove in self.umoves or
            umove in self.cmoves):
            umove = int(input("Invalid Move "))
        self.umoves.add(umove)
        # Modify ploys
        del self.ploys[umove]
        for p, s in self.ploys.items():
            for i in [i for i,n in enumerate(s) if umove in n]:
                del self.ploys[p][i]

    def PlayCom(self, cmove=None, best=None):
        """Plays the com's turn"""
        for p, s in self.ploys.items():
            # Check if com can win
            if any(n.issubset({p}|self.cmoves) for n in s):
                cmove = p
                break
            # Check if user can win
            elif any(n.issubset({p}|self.umoves) for n in sols if p in n):
                cmove = p
            # Get the next best move
            elif best is None or len(s) > len(self.ploys[best]):
                best = p
        cmove = cmove or best
        self.cmoves.add(cmove)
        del self.ploys[cmove]

    def Show(self, cols=3, com="X", usr="O", fill=" "):
        """Prints the grid in the command-line."""
        os.system(erase)
        for g in grid:
            if g in self.cmoves:
                print(com, fill, end="") if g % cols else print(com)
            elif g in self.umoves:
                print(usr, fill, end="") if g % cols else print(usr)
            else:
                # Replace g with fill for clean grid
                print(g, fill, end="") if g % cols else print(g)

    def Main(self):
        """Stars the game."""
        from itertools import cycle

        text = ("You Won", "You Lost")
        move = (self.umoves, self.cmoves)
        play = (self.PlayUser, self.PlayCom)

        for t, m, p in cycle(zip(text,move,play)):
            self.Show()
            p()
            self.Show()
            status = self.GameOver(m)
            if status is not None:
                print(t) if status is True else print("Game Over.")
                exit()

if __name__ == "__main__":
    game = TTT()
    game.Main()


texts:
I would like to speed up pandas apply function. I have been using swifter . It currently takes about 5 mins for 200000 records using multiprocessing  as below . Is there any way to speed this up further .

def partial_match(source_words, dest_words):
    matched_words = ''
    if any(word in dest_words for word in source_words) :
        match_words_list = set(source_words)&set(dest_words)
        matched_words = ",".join(match_words_list)
    return matched_words

def exact_match(source_words, dest_words):
    matched_words = ''
    if all(word in dest_words for word in source_words) :
        match_words_list = set(source_words)&set(dest_words)
        matched_words = ",".join(match_words_list)
    return matched_words

series_index = ['match_type', 'matched_words'   ]
def perform_match(x):
    match_series = pd.Series(np.repeat('', len(series_index)), index = series_index)
    if x['remove_bus_ending'] == 'Y':
        x['dest_words'] = x['dest_words_2']
    else:
        x['dest_words'] = x['dest_words_1']
    # exact match
    if (x['partial_match_flag'] == 'Y') :
        match_series['matched_words'] = partial_match(x['source_words'], x['dest_words'])
        if match_series['matched_words'] != '':
            match_series['match_type'] = 'Partial Match'
    elif (x['exact_match_2'] == 'Y'):
        match_series['matched_words'] = exact_match(x['source_words'], x['dest_words'])
        if match_series['matched_words'] != '':
            match_series['match_type'] = 'Exact Match'

    return match_series

from multiprocessing import  Pool
from functools import partial
import numpy as np

def parallelize(data, func, num_of_processes=8):
    data_split = np.array_split(data, num_of_processes)
    pool = Pool(num_of_processes)
    data = pd.concat(pool.map(func, data_split))
    pool.close()
    pool.join()
    return data

def run_on_subset(func, data_subset):
    return data_subset.swifter.apply(func, axis=1)

def parallelize_on_rows(data, func, num_of_processes=8):
    return parallelize(data, partial(run_on_subset, func), num_of_processes)

df[match_series]  = parallelize_on_rows(df, perform_match)

below is some sample data

flag1   partial_match_flag  exact_match_flag    source_words    dest_word_2 dest_words_1
0   N   Y   N   [song, la]  [urban, karamay, credit, city, co, kunlun, com...   [ltd, urban, karamay, credit, city, co, kunlun...
1   N   Y   N   [song, la]  [al, abdulah, nasser]   [al, abdulah, nasser]
2   N   Y   N   [song, la]  [al, abdulah, nasser]   [al, abdulah, nasser]
3   N   Y   N   [song, la]  [abdulamir, mahdi]  [abdulamir, mahdi]
4   N   Y   N   [song, la]  [abdullah, al, nasser]  [abdullah, al, nasser]
5   N   Y   N   [song, la]  [abu, al, jud]  [abu, al, jud]
6   N   Y   N   [song, la]  [al, herz, adam]    [al, herz, adam]


texts: Proper use of tail recursion while forming a list

texts:
As a project to better develop my understanding of functional programming, I am writing a prime number generator in Scheme. I am using a simple brute-force algorithm to detect whether a number is prime and I know there are better algorithms. What I'm interested is whether my attempt at the brute-force algorithm can be better written and whether I am using tail recursion appropriately and forming the list efficiently. The goal is to have a list of numbers at the end I can use for some task or print out. Maybe even write it as a generator where I can continually ask it for the next prime. Here is my current code:

(define is_prime1
 (lambda(num div)
  (if (= num div)
   #t
   (if (= (remainder num div) 0)
    #f
    (is_prime1 num (+ div 1))
   )
  )
 )
)

(define is_prime
 (lambda(num)
  (if (< num 2) #f (is_prime1 num 2))
 )
)

(define list_primes1
 (lambda(idx num)
  (if (<= idx num)
   (if (not (is_prime idx))
    (list_primes1 (+ idx 1) num)
    (cons idx
     (list_primes1 (+ idx 1) num)
    )
   )
   '()
  )
 )
)

(define list_primes
 (lambda(num)
  (list_primes1 0 num)
 )
)

(define print_primes
 (lambda(primes)
  (if (null? primes)
   '()
   (list
    (display (car primes))
    (newline)
    (print_primes (cdr primes))
   )
  )
 )
)

(print_primes (list_primes 4095))


texts:
I've come with a solution super tricky for a simple requirement. I think I could solve the problem using LinQ, but I'm not seeing it so clearly at all.
What's sure, I'm not comfortable with my code.

The requirement is the following:

Given a list of lists of string (IEnumerable>), take the first N elements from each but one by one.
So given this list of list and N=10:

{aaa, bb, ccc, ddd}
{eee, fff}
{ggg, hhhhh, iii, jjj, kkk}
{lll}
{1111, 22, 333, 444, 55555, 66666}

This is the output:

{aaa, eee, ggg, lll, 111, bb, fff, hhhhh, 22, ccc}

And here is the code:

private IEnumerable<string> Extract(
    IEnumerable<IEnumerable<string>> listOfList,
    int N
)
{
    var result = new List<string>();

    for (int i = 0; i < N; i++)
    {
        foreach (IEnumerable<string> list in listOfList)
        {
            if (list.Count() > i)
            {
                result.Add(list.ElementAt(i));

                if (result.Count >= N)
                    return result;
            }
        }
    }

    return result;
}

The code works, but I don't think this is maintainable nor easy to read.
Thanks.


texts: XML Schema File that validates my XML File

texts:
I just want to know if my schema file is correct:

XML File:

  <?xml version="1.0" encoding="UTF-8"?>
  <xs:books xmlns="http://www.w3.com/1999/XML/prjXMLValidation"
   xmlns:xs="http://www.w3.org/2001/XMLSchema/prjXMLValidation"
      xs:noNamespaceSchemaLocation="collection.xsd">
   <xs:book title="A Lesson Before Dying" author="Ernest J. Gaines" version="1">
<xs:stars>
     5
    </xs:stars>
    <xs:description>
  This is a story about a young man that was wrongly
  accused of killing a white man in the south at a time
  when blacks were not given the same rights as whites.
  This is the story of how Jefferson becomes a man.
    </xs:description>
<xs:thoughts>
    Great book!
</xs:thoughts>
  </xs:book>
</xs:books>

Here is my XSD File:

<?xml version="1.0" encoding="utf-8"?>
<xs:schema elementFormDefault="qualified" xmlns:xs="http://www.w3.org/2001/XMLSchema"
       targetNamespace="http://www.w3.org/2001/XMLSchema/prjXMLSchema">
  <xs:element name="books">
    <xs:complexType>
      <xs:element name="book">
        <xs:complexType>
          <xs:sequence minOccurs="1" maxOccurs="unbounded">
            <xs:element name="stars">
              <xs:complexType>
                <xs:choice minOccurs="0" maxOccurs="1">
                  <xs:element ref="1" />
                  <xs:element ref="2" />
                  <xs:element ref="3" />
                  <xs:element ref="4" />
                  <xs:element ref="5" />
                </xs:choice>
              </xs:complexType>
            </xs:element>
            <xs:element name="description" type="xs:string" />
            <xs:element name="thoughts" type="xs:string" />
          </xs:sequence>
          <xs:attribute name="title" type="xs:string" use="required" />
          <xs:attribute name="author" type="xs:string" use="required" />
          <xs:attribute name="version" type="xs:string" />
        </xs:complexType>
      </xs:element>
    </xs:complexType>
  </xs:element>
</xs:schema>


texts:
Just decided to make a quickie Fibonacci Sequence via jQuery and I was wondering if anybody can think of a faster way to interpret it? I can type pretty much any number in and it returns in a fraction of a second.

Can anybody think of a quicker method to calculate a specific Fibonacci number?

http://jsfiddle.net/st9sgrcx/1/

$(function(){
 var counter = 1,
        fibo = [0,1],
        temp = 0,
        whichOne = prompt("Which fibonnaci number do you want?");
    function fib(prev, cur){
        temp = prev + cur;
        fibo.push(temp);
        counter = temp;
        temp = cur;
    }
    for(var i=0; i<whichOne; i++){
        fib(temp, counter);
    }
    alert(temp);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>


texts: Code to send print jobs through Jetdirect port

texts:
I have a program made in Go that lets me send files directly to printers through the Jetdirect port. The program works without issue and I can print in any printer with the port 9100 enabled.

import (
    "io"
    "log"
    "net"
    "os"
)

func main() {

    srcFile := "/path/to/file.pdf"
    serverAddr := "(printerIP):9100"
    uploadFile(srcFile, serverAddr)
}

func uploadFile(srcFile, serverAddr string) {
    // connect to server
    conn, err := net.Dial("tcp", serverAddr)
    if err != nil {
        log.Fatalf("Dial() err: %v", err)
    }
    defer conn.Close()
    // open file to upload
    fi, err := os.Open(srcFile)
    if err != nil {
        log.Fatalf("Open() err: %v", err)
    }
    defer fi.Close()
    // upload
    _, err = io.Copy(conn, fi)
    if err != nil {
        log.Fatalf("Copy() err: %v", err)
    }
}

However, I have no control of the process (files are printed as is). I want to be able to customize the print job (choose to print in color or B/W, how many pages per sheet, etc.) but I'm not sure about how to proceed on that, if it's possible. I thought about sending PJL commands and looking for a way to convert the file to Postscript from Go or to apply the changes manually through OpenCV and/or gopdf, save them in a temporal pdf and send that to the Jetdirect port.

Which would be the more viable approach? Or if there is another option, What better way there is to achieve the level of control over print jobs that I need?


texts:
I have a class with numerous methods, and so I would like to split these up into groups. This would make it easier for the user to find the method they are after. Here is a minimal example of this functionality.

class Greeter():

    def __init__(self, name):
        self.name = name
        self.spanish = Spanish(self)

   def generic(self):
       return f"Hello, {self.name}"

class Spanish():

        def __init__(self, greeter):
            self.grtr = greeter

        def hola(self):
            return f"Hola, {self.grtr.name}"

        def buen_dia(self):
            return f"Buenos días, {self.grtr.name}"

greeter = Greeter("Ann Example")
greeter.generic()
#> "Hello, Ann Example"
greeter.spanish.hola()
#> "Hola, Ann Example"

This feels like a hacky approach. Are there places people could see this failing? Is there a better solution in general?

EDIT

As suggested, here is a reduced example of my actual need for this functionality:

class Matrix():

    def __init__(self, m, n, data):
        # checks on m, n, data
        self.m = m
        self.n = n
        self.data = data
        self.decomposition = Decomposition(self)

    # many generic methods some returning more matrices
    def __add__(self, other):
        # add matrices
        return Matrix(m, n, data)

    # some methods will affect m, n, data
    def transpose(self):
        # set up new attributes
        self.m = m
        self.n = n
        self.data = data

class Decomposition():

    def __init__(self, mtrx):
        self.mtrx = mtrx

    # NB: eventually these might change m, n, data
    def QR(self):
        # do stuff for QR decomposition using self.mtrx
        return Q, R

    def LU(self):
        # do stuff for LU decomposition using self.mtrx
        return L, U


texts:
I implemented the following function using the matrix object from breeze library. Basically it is just a glorified while loop.
The convolution there is extremely slow so I rolled out my own, optimized on a kernel which is just a vector. This is already much faster but I figured there must be something else I can to to make this go faster.
The most expensive operation according to the profiler is the instantiation of the ArrayDeque  (pointed by the arrow) which I don’t really need because all I wanted was a circular buffer, but could not find much in the library.
The second thing is calling until on the Int. I don't think that can be avoided.
Boxing the doubles is also taking quite some time, maybe there is a way to specialize?
Finally the majority of the time is taken by the function call itself (circled in red) which I don’t know what it means. Any insight?
def conv(m: DenseMatrix[Int], k: DenseVector[Double]): DenseMatrix[Double] = {
    val kData = k.data
    val dataIter = m.data.iterator
    val height = m.rows
    val convoluted = Array.newBuilder[Double]
    val prev = mutable.ArrayDeque.empty[Double]
    for (_ <- 1 until k.length) {
      prev.addOne(dataIter.next())
    }
    var count = k.length - 1
    while (dataIter.hasNext) {
      val cur = dataIter.next()
      val slice = prev.append(cur)
      if (count % height >= k.length - 1) {
        var r = 0D
        for (i <- 0 until k.length) {
          r += kData(i) * slice(i)
        }
        convoluted.addOne(r)
      }
      prev.removeHead()
      count += 1
    }
    DenseMatrix.create(m.rows - (k.length - 1), m.cols, convoluted.result())
  }

Following is the annotated flamechart, please note that fut is the above function conv. Everything else is unchanged.


texts: Find the closest enemy in a 2D grid with wrapping allowed

texts:
I'd like feedback on my solution to the outlined programming challenge. Is numpy a good candidate module for this? What might be a more efficient or Pythonic solution?

  Closest Enemy II

  Have the function ClosestEnemyII(strArr) read the matrix of numbers stored
  in strArr which will be a 2D matrix that contains only the integers 1, 0,
  or 2. Then from the position in the matrix where a 1 is, return the number
  of spaces either left, right, down, or up you must move to reach an enemy
  which is represented by a 2. You are able to wrap around one side of the
  matrix to the other as well. For example: if strArr is
  ["0000", "1000", "0002", "0002"] then this looks like the following:

  0 0 0 0
1 0 0 0
0 0 0 2
0 0 0 2

  For this input your program should return 2 because the closest enemy (2)
  is 2 spaces away from the 1 by moving left to wrap to the other side and
  then moving down once. The array will contain any number of 0's and 2's,
  but only a single 1. It may not contain any 2's at all as well, where in
  that case your program should return a 0.

  Examples
Input: ["000", "100", "200"]
Output: 1
Input: ["0000", "2010", "0000", "2002"]
Output: 2

import doctest
import numpy as np

from typing import List

def calc_closest_enemy(matrix: List[str]) -> int:
    """Calculate the minimum number of moves to reach an enemy

    Moves allowed: left, right, up, down. All count as +1
    Wrapping allowed: if current position is on an edge, a move
    can be made to the opposite edge for the cost of 1 move.

    >>> calc_closest_enemy(matrix=["000", "100", "200"])
    1
    >>> calc_closest_enemy(matrix=["0000", "2010", "0000", "2002"])
    2
    >>> calc_closest_enemy(matrix=["0000", "0010", "0000", "0000"])
    0
    >>> calc_closest_enemy(matrix=["0000", "0100", "0000", "0020"])
    3
    >>> calc_closest_enemy(matrix=["0000", "0100", "0000", "0000", "0020"])
    3
    >>> calc_closest_enemy(matrix=["0200", "0100", "0000", "0000", "0020"])
    1
    """
    grid = np.array([list(s) for s in matrix], dtype=np.int32)

    # In case of no enemies
    if 2 not in grid:
        return 0

    # format (y, x)
    friendly_coords = tuple(int(i) for i in np.where(grid == 1))
    assert len(friendly_coords) == 2, "Only one friendly is allowed"

    # Create wrapped grid
    # Wrap the y-axis then take the y-axis wrapped grid, transpose, and wrap the
    # former x-axis (now y-axis after transposition)
    for indx in friendly_coords:
        height, _ = grid.shape

        # These slices are appended to the appropriate grid ends to produce
        # the wrapped grid
        slice_to_friendly = grid[:indx]
        slice_from_friendly = grid[indx+1:]

        grid = np.insert(
            arr=grid, values=slice_to_friendly, obj=height, axis=0)
        grid = np.insert(
            arr=grid, values=slice_from_friendly, obj=0, axis=0)

        # Transpose to reuse code in for loop
        grid = grid.T

    # format (y, x)
    friendly_coords = tuple(int(i) for i in np.where(grid == 1))

    # Gather all enemy coords into a generator
    enemy_locations = np.where(grid == 2)
    enemy_locations = ((x, y) for y, x in zip(
        enemy_locations[0], enemy_locations[1]))

    # Calculate the moves required to travel from friendly to each enemy
    # and return lowest
    moves = [sum((abs(friendly_coords[1] - enemy[0]),
                    abs(friendly_coords[0] - enemy[1])))
                for enemy in enemy_locations]
    min_moves = min(moves)

    return min_moves

if __name__ == "__main__":
    doctest.testmod()


texts: Split Circular linked list into two halves

texts:
I want to improve this code. I want to enter all values in linked list at a time like circular_linked_list<int> cll1(5, 10, 18, 25);

#include <iostream>
#include <utility>

template <class T>
class circular_linked_list
{
  struct Node
  {
    T data;
    Node * next;
    Node(T&& value) : data(std::move(value)), next(nullptr) {}
    /*
    //to enter any number of arguments
    template <typename... Args>
    Node(Args&&... args) : data(std::forward<Args>(args)...), next(nullptr)
                         {}
                         */
  };
  Node *head;

public:
  circular_linked_list() : head(nullptr) {}
  circular_linked_list(const circular_linked_list& cll) = delete; //copy constructor
  circular_linked_list(circular_linked_list&& cll) = delete; //move constructor
  circular_linked_list& operator=(const circular_linked_list& cll) = delete; //copy assignment
  circular_linked_list& operator=(circular_linked_list&& cll) = delete; //move assignment
  ~circular_linked_list();

  void insert_node(T&&);

  /*
  template <typename... Args>
  void insert_node(Args&&... args)
   { ..
     code
     ..
   } */

  Node *split_list()//Returns the mid-node
  {
    Node *slow_ptr = head;
    Node *fast_ptr = head;

    //If odd number of nodes then fast_ptr->next = head
    //If even number of nodes then fast_ptr->next->next = head
    while(fast_ptr->next != head && fast_ptr->next->next != head)
    {
      fast_ptr = fast_ptr->next->next;
      slow_ptr = slow_ptr->next;
    }
    return slow_ptr;
  }

  void print_split_lists();
  void print_list(Node*);
  void print_list()
  {
    print_list(head);
  }
};

template <class T>
void circular_linked_list<T>::insert_node(T&& value)
{
  Node *node = new Node(std::move(value));
  if(head == nullptr)
  {
    node->next = node;
    head = node;
    return;
  }
  Node *tmp = head;
  while(tmp->next != head)
  {
    tmp = tmp->next;
  }
  tmp->next = node;
  node->next = head;
}

template <class T>
void circular_linked_list<T>::print_split_lists()
{
  Node *head1 = nullptr;
  Node *head2 = nullptr;
  Node *mid_node = split_list();
  Node *tail = head;

  while(tail->next != head)
  {
    tail = tail->next;
  }

  if(head->next != head)
  {
  head2 = mid_node->next;
  }

  tail->next = head2;

  head1 = head;
  mid_node->next = head1;
  std::cout << "First half of list \n";
  print_list(head1);
  std::cout << "Second half of list \n";
  print_list(head2);
}

template <class T>
void circular_linked_list<T>::print_list(Node *head)
{
  Node *tmp = head;
  while(tmp->next != head)
  {
    std::cout << tmp->data << ' ';
    tmp = tmp->next;
  }
  std::cout << tmp->data << '\n';
}

template <class T>
circular_linked_list<T>::~circular_linked_list()
{
  Node *tmp = nullptr;
  Node *tail = head;
  while(tail->next != head)
  {
    tail = tail->next;
  }
  tail->next = nullptr;

  while(head != nullptr)
  {
    tmp = head;
    head = head->next;
    delete tmp;
  }
}

int main()
{
  //circular_linked_list<int> cll1(5, 10, 18, 25);
  circular_linked_list<int> cll1;
  cll1.insert_node(2);
  cll1.insert_node(3);
  cll1.insert_node(4);
  cll1.insert_node(1);
  cll1.insert_node(0);
  cll1.print_list();
  cll1.print_split_lists();
}


texts: Use generic to prevent duplicate code in this case

texts:
I have this class hierarchy. I want to apply generics to it but don't know how to do.
AddWikiTask, ScanTask and RescanTask are subclasses of AbstractWorkerTask.
DictionaryScanner has 3 functions to check if all tasks finish. How to prevent duplicate code in 3 those functions?

This is class hierarchy

    public abstract class AbstractWorkerTask<Params, Progress, Result>
    extends AsyncTask<Params, Progress, Result>
    implements Workable {
    ...}

    class AddWikiTask extends AbstractWorkerTask<String, Void, Pair<Integer, Dictionary>> {
    ...}

    class ScanTask extends AbstractWorkerTask<DictionaryBean, Void, Pair<Integer, Dictionary>> {
    ...}

    class RescanTask extends AbstractWorkerTask<DictionaryInformation, Void, Pair<Integer, Dictionary>> {
    ...}

This is DictionaryScanner.

public final class DictionaryScanner {
    private final List<RescanTask> rescanTasks = new ArrayList<RescanTask>();
    private final List<ScanTask> scanTasks = new ArrayList<ScanTask>();
    private final List<AddWikiTask> wikiTasks = new ArrayList<AddWikiTask>();

        public boolean didAllRescanTasksFinish() {
            for (final RescanTask task : rescanTasks) {
                if (task.isWorking()) {
                    return false;
                }
            }
            return true;
        }

        public boolean didAllAddWikiTasksFinish() {
            for (final AddWikiTask task : wikiTasks) {
                if (task.isWorking()) {
                    return false;
                }
            }
            return true;
        }

        public boolean didAllScanTasksFinish() {
            for (final ScanTask task : scanTasks) {
                if (task.isWorking()) {
                    return false;
                }
            }
            return true;
        }
}

Edit: And apply generic for this. It's too long. I really don't know how to refactor it.

private void setOnPreExecuteForAddWikiTask(final AddWikiTask task, final ProgressDialog progressDialog) {
    task.setOnPreExecuteListener(new OnPreExecuteListener() {
        @Override
        public void onPreExecute() {
            if (didAllAddWikiTasksFinish()) {
                progressDialog.show();
            }
        }
    });
}

private void setOnPreExecuteForRescanTask(final RescanTask task, final ProgressDialog progressDialog) {
    task.setOnPreExecuteListener(new OnPreExecuteListener() {
        @Override
        public void onPreExecute() {
            if (didAllRescanTasksFinish()) {
                progressDialog.show();
            }
        }
    });
}

private void setOnPreExecuteForScanTask(final ScanTask task) {
    task.setOnPreExecuteListener(new OnPreExecuteListener() {
        @Override
        public void onPreExecute() {
            if (didAllScanTasksFinish() && progressBar != null) {
                progressBar.setVisibility(ProgressBar.VISIBLE);
            }
        }
    });
}

If the snippet is not elaborate enough, please let me know.


texts: c# Efficient solution: Sequence generator for a pattern

texts:
This is an interview question to generate the below pattern of numbers in a sequence, which is: 12.34, 23.45, 45.67, 78.910, 1112.1314, 1617.1819, 2223.2425, 2930.3132, 3738.3940, 4647.4849, 5657.5859, 6768.6970, 7980.8182, 9293.9495, 106107.108109, 121122.123124 We can use starting seed number as 12 and have to generate all the 16 numbers programmatically without using strings. We can use only arrays but no other built-in collection classes or data structures.
public static void GenerateSequence()
{
    int j = 1;
    ArrayList sequenceList = new ArrayList();

    for (int count = 0; count < 16; count++)
    {
        j = j + count;
        int quotent = getValue(j, j + 1);
        int reminder = getValue(j + 2, j + 3);
        int length = getLength(reminder);
        double result = Convert.ToUInt32(quotent) * getLength(reminder) + reminder;
        sequenceList.Add(result / length);
    }
    Console.WriteLine(sequenceList.ToString());
}

static int getValue(int a, int b)
{
    return a * getLength(b) + b;
}

static int getLength(int value)
{
    int length = (int)(Math.Log10(value) + 1);
    int formattedValue = 10;

    for (int i = 1; i < length; i++)
        formattedValue = formattedValue * 10;

    return formattedValue;
}

I've arrived with above solution but this looks complex and less efficient. Looking for an alternate approach with better time/space complexity.


texts: Calculate number of pairs a,b where a^2 - b^2 = n

texts:
In one site there was one question to make one program where you will be given a positive integer n and we have to calculate the number of such pairs (a, b),
where n = a² - b² and both a and b are positive integers.
for example 15 = 4^2 - 1^2 = 8^2 - 7^2.
Currently this question is closed and in my case I am still not able to do it properly. Still I won't be trying to find solution here but I just want to know that where I am doing wrong with my code.
At first I thought of simply increment a, b by 1 and check every equation.
But time limit is 4 seconds and 1<= n<= 10^13 so it was taking very long time for larger values of n.
Since a^2 - b^2 = (a+b)(a-b) then I took one example 15 and solved for a = n and b = a-1 and observed that I got some special series:
(2n+1): n=1,2,3 ...   (for a = 2 and b = 1)

4n: n=2,3,4 ...       (for a = 3 and b = 1/b = 2)

6n+3: n = 2,3,4 ...   (for a = 4 and b = 1/b = 2/b = 3)

8n: n = 3,4,5 ...

Later I used this concept and made one program. It is working fine with 6 digits numbers(approx).
My program:
n = input()
count = 0
for i in range(1,n):
    first = (n-((2*i)-1))
    second = ((2*i)+2*(i-1))
    if first % second == 0 and first/second >= i:
        count += 1
    elif n%(4*i) == 0 and n/(4*i) >= (i+1):
        count +=1
print count

But for some larger values it is giving some error(16/30). If I make n in range to 100000 then I get few error as compared to previous one (27/30). But still it is taking time for larger input. So does my method is right or do I have to think of something else. If this is wrong then why ?
Explanation
Let us say I want to find for no. 15 then according to formula (a+b)(a-b) = n total no. of possibilities :
(2+1)(2-1) = 3                      # BLOCK 1

(3+1)(3-1) = 8                      #BLOCK 2
(3+2)(3-2) = 5

(4+1)(4-1) = 15
(4+2)(4-2) = 12                     #BLOCK 3
(4+3)(4-3) = 7

And so on ... till
(8+7)(8-7) = 15
So if I go on like this then the last line of each block (in this case it is n = 3,5,7) we found that it is changing as (2n+1) where n = 1,2,3 .... (here we can think n as if from which block we are starting the count)
Now for every last second line (in this case it is 8,12) the equation will be 4n where n = 2,3,4 ....(since first block has only 1 line so there can't be any last second line so we will count from second block)
Repeat this process again and again ....
We get:
2n+1, 4n, 6n+3, 8n, 10n+5, 12n, 14n+7, 16n ... and so on
If we simply try to find these equation every time for different lines then we find out that we can use this concept in program. If any no. 'n' is divisible by this equation it means it has occurred on those lines of block. Means each time it is divisible i will make count + 1.


texts:
I have a pretty straightforward query that I am essentially hard-coding. I have a table with 3 keys and a description field.

The first key has to do with the type of compensation for an employee (Award, Hourly, NonHourly, Staff, Other, and Commission).

The next key has to do with Payment Frequency. O refers to One-Time Payment, M to Multiple Payments.

The third key has to do with the Compensation Rate Code. It's like another frequency. P means Per Project/Assignment, H means Hourly, and M means Monthly.

Certain Employee Compensations types are restricted to different types of compensation. In the below query, I've hard-coded every possibility. Is there a better way to write this query than just hard-coding every combination and unioning them together?

SELECT 'Award'
 , 'O'
 , 'P'
 , 'Per Project or Assignment'
  FROM DUAL
  UNION
 SELECT 'Hourly'
 , 'M'
 , 'H'
 , 'Per Hour'
  FROM DUAL
  UNION
 SELECT 'Hourly'
 , 'M'
 , 'P'
 , 'Per Project or Assignment'
  FROM DUAL
  UNION
 SELECT 'Hourly'
 , 'M'
 , 'M'
 , 'Per Month'
  FROM DUAL
  UNION
 SELECT 'Hourly'
 , 'O'
 , 'H'
 , 'Per Hour'
  FROM DUAL
  UNION
 SELECT 'Hourly'
 , 'O'
 , 'P'
 , 'Per Project/Assignment or Month'
  FROM DUAL
  UNION
 SELECT 'NonHourly'
 , 'M'
 , 'P'
 , 'Per Project or Assignment'
  FROM DUAL
  UNION
 SELECT 'NonHourly'
 , 'M'
 , 'M'
 , 'Per Month'
  FROM DUAL
  UNION
 SELECT 'NonHourly'
 , 'O'
 , 'P'
 , 'Per Project/Assignment or Month'
  FROM DUAL
  UNION
 SELECT 'Staff'
 , 'M'
 , 'H'
 , 'Per Hour'
  FROM DUAL
  UNION
 SELECT 'Staff'
 , 'O'
 , 'H'
 , 'Per Hour'
  FROM DUAL
  UNION
 SELECT 'Other'
 , 'M'
 , 'H'
 , 'Per Hour'
  FROM DUAL
  UNION
 SELECT 'Other'
 , 'M'
 , 'P'
 , 'Per Project or Assignment'
  FROM DUAL
  UNION
 SELECT 'Other'
 , 'M'
 , 'M'
 , 'Per Month'
  FROM DUAL
  UNION
 SELECT 'Other'
 , 'O'
 , 'H'
 , 'Per Hour'
  FROM DUAL
  UNION
 SELECT 'Other'
 , 'O'
 , 'P'
 , 'Per Project or Assignment'
  FROM DUAL
  UNION
 SELECT 'Other'
 , 'O'
 , 'M'
 , 'Per Month'
  FROM DUAL
  UNION
 SELECT 'Commission'
 , 'O'
 , 'P'
 , 'Commission/Tips'
  FROM DUAL

Note that DUAL is just a dummy table. I'm not actually selecting anything from any tables.

EDIT:

This is the SQL behind a View. I wouldn't be opposed to creating new views to "extract" out pieces of the query if that could be used to simplify it. It creates a view that has the following rows in it:

Essentially, my query takes the results of 18 SQL statements and unions them together to get 18 rows in the newly created view. Surely, there's a better way to do it?

The second and third keys are represented in a table that maps their character values to a description (e.g. O -> One-Time Payment). The first key is only used for this view.


texts: Static site generator using JavaScript Promises

texts:
I have created a small static site generator (for learning purposes) in Javascript ES6, using Promises, but I am not certain of how to use them well. The code below works fine, but I wonder if i can't write my promises a better way.

I call my promises in SSG.start();

const yaml = require('js-yaml');
const fs   = require('fs-extra');
const ejs  = require('ejs');
const md   = require('markdown-it')({
    html: true,
    linkify: true,
    typographer: true
});

let SSG = {
    outputFolder: '../output/',

    contentFolder: '../content/',

    assetsFolder: '../assets/',

    contentFiles: async function (dir, filelist) {
        return new Promise((resolve) => {
            files = fs.readdirSync(dir);
            filelist = filelist || [];
            files.forEach((file) => {
                if (fs.statSync(dir + '/' + file).isDirectory()) {
                    return resolve(contentFiles(dir + '/' + file, filelist));
                } else {
                    filelist.push(file);
                    return resolve(filelist);
                }
            });
        })
    },

    generateHTMLFile: async function (file) {
        return new Promise((resolve) => {
            let fstream = fs.readFileSync(file, 'utf8');
            let params = fstream.match(/\+Params\+([\s\S]*?)\+\+\+/g);
            let content = fstream.match(/(\+Content[0-9]*\+|\+Content\+)([\s\S]*?)*(\+\+\+)/g);
            let contents = [];

            params = params[0].replace('+Params+', '').replace('+++', '');
            content = content[0].split('+++');

            try {
                params = yaml.safeLoad(params, 'utf8');
                for (it of content) {
                    it = it.replace('+++', '').replace(/(\+Content[0-9]*\+|\+Content\+)/g, '');
                    contents.push(md.render(it));
                }

                const funs = require('./functions.js');

                ejs.renderFile('../templates/' + params.template + '.ejs', {funs: funs, params: params, content: contents}, {}, (err, html) => {
                    if (err) console.log(err);
                    resolve({html: html, url: params.url});
                });

            } catch (e) {
                console.log(e);
            }
        });
    },

    saveHTML: function (html, url) {
        if (!fs.existsSync(this.outputFolder)) {
            fs.mkdir(this.outputFolder, { recursive: true }, (err) => {
                if (err) throw err;
            });
        }
        fs.writeFile(this.outputFolder + url + '.html', html, (err) => {
            if (err)  return console.log(err);
        });
    },

    saveStaticAssets: function () {
        fs.copySync(this.assetsFolder, this.outputFolder);
    },

    start: async function () {
        try {
            let time = Date.now();
            console.log('Génération des fichiers HTML...');

            let files = await this.contentFiles(this.contentFolder);

            for (file of files) {
                await this.generateHTMLFile(this.contentFolder + file).then(({html, url}) => {
                    this.saveHTML(html, url);
                });
            }

            this.saveStaticAssets();

            console.log('Généré en ' + (Date.now() - time) + 'ms');
        } catch (e) {
            console.error(e.message);
        }
    }
};

(async () => {
    await SSG.start();
})();

What do you think about it ?


texts:
Problem

Adapted from this HackerRank problem.

  A numeric string, \$s\$ is beautiful if it can be split into a sequence of two or more positive integers, \$a_1, a_2,...,a_n\$, satisfying the following conditions:

  \$a_i - a_{a-1} = 1\$ for any \$1 \lt i\le n\$ (i.e., each element in the sequence is 1 more than the previous element).
  No \$a_i\$ contains a leading zero.  For example, we can split \$s = 10203\$ into the sequence {\$1, 02, 03\$}, but it is not beautiful because \$02\$ and \$03\$ have leading zeroes.
  The contents of the sequence cannot be rearranged.  For example, we can split \$s = 312\$ into the sequence {\$3, 1, 2\$}, but it is not beautiful because it breaks our first constraint (i.e., \$1 - 3 \ne 1\$).

Instead of printing YES or NO, I just wanted to return a boolean.

Description

The way I thought about implementing a solution was iterating through all the potential sequences that could be formed.

Because sequences are determined by the value of the first integer, by iterating through all the potential first integer values, you can generate all potential solutions.

For example, take the numeric string 123456. Let's say the first integer is 1. Then the next integer in the sequence would be 2 and so on. However, let's say the first integer is actually 12. Then the next integer in the sequence should then be 13. But it's actually 34. Thus, 12 cannot be the first integer in the sequence. Same if we decided that 123 was the first integer in the sequence.

If we exhaust all possibilities for what the first integer could be, then the numeric string cannot be beautiful.

Implementation Notes

In order to test all possible first integer values, we need to generate all prefixes for the input numeric string that are of length 1 to the length of the input string, rounded down.

For each prefix value, add it to a StringBuilder instance. Then, append the next integer value (so the integer after the prefix value, then the integer after, etc.) until the StringBuilder string length is greater than or equal to the input string or the StringBuilder string, up to that point, does not match the input string.

After exiting this loop, check to see if the StringBuilder string matches the input string. If so, then the string is indeed "beautiful".

If not, move on to the next potential prefix / first integer - if these have all been exhausted, then return false.

Implementation

public class BeautifulNumberValidator {
  public static boolean isValidBeautifulNumber(String s) {
    if (s.length() < 2) {
      return false;
    }

    for (int substringSize = 1; substringSize <= s.length() / 2; substringSize++) {
      long value = Long.parseLong(s.substring(0, substringSize));

      if (value == 0) {
        break;
      }

      StringBuilder sb = new StringBuilder();
      sb.append(value);

      while (sb.length() < s.length() && sb.toString().equals(s.substring(0, sb.length()))) {
        sb.append(++value);
      }

      if (sb.toString().equals(s)) {
        return true;
      }
    }

    return false;
  }
}


texts:
I am currently attempting to understand the fundamentals of factory methods in Java and I found a lot of exampels where a pattern like this has been used.
I got some exercises about sorting algorithms where one task is to write a factory class for all existing algorithms but with the requirement that newly added algorithmes can be integrated via "plug and play". That phrase itched me.By using the switch case solution I would be unable to add Algorithms without rewriting the factory class so I came up with this:

SorterFactory.java

public final class SorterFactory
{

  private SorterFactory()
  {
  }

  public static Sortierer.Sorter getNewSorter( Sorts sorts )
  {
    try
    {
      return (Sortierer.Sorter) Class.forName( sorts.getName() ).getConstructor().newInstance();
    }
    catch ( ClassNotFoundException | InstantiationException | IllegalAccessException
        | IllegalArgumentException | InvocationTargetException | NoSuchMethodException
        | SecurityException e )
    {
      e.printStackTrace();
      // further exception handling
    }
  }
}

Sorts.java

public final class Sorts
{

  private String name;

  // hardcoded for test purpose.
  // will be imported from XML-file
  public static final Sorts HEAPSORT = new Sorts( HeapSort.class.getName() );
  public static final Sorts MERGESORT = new Sorts( MergeSort.class.getName() );
  public static final Sorts BUBBLESORT = new Sorts( BubbleSort.class.getName() );
  public static final Sorts INSERTSORT = new Sorts( InsertSort.class.getName() );
  public static final Sorts QUICKSORT = new Sorts( QuickSort.class.getName() );
  public static final Sorts TRUEHEAPSORT = new Sorts( TrueHeapSort.class.getName() );

  private Sorts( String name )
  {
    this.name = name;
  }

  public String getName()
  {
    return name;
  }
}

So why is the switch case approach much more favored above this kind of solution in terms of safety,security and performance? Also is it useful to box the names in a class to prevent the misusage of the factory method instead of allow Strings as arguments?

Thanks for any advice and criticism.


texts:
I created a multilingual site in MVC and I reached the current results, but I'm not sure it's the right way.

I have created a class named changeLanguage to change the language:

public ActionResult ChangeLanguage(String LanguageAbbrevation)
        {
            if (LanguageAbbrevation != null)
            {
                Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(LanguageAbbrevation);
                Thread.CurrentThread.CurrentUICulture = new CultureInfo(LanguageAbbrevation);

            }
            HttpCookie cookie = new HttpCookie("Language");
            cookie.Value = LanguageAbbrevation;
            Response.Cookies.Add(cookie);
            return RedirectToAction("Index","Home");

        }

Global.asax:

 protected void Application_BeginRequest(object sender, EventArgs e)
        {
            LanguageTB context = new LanguageTB();
            HttpCookie cookie = HttpContext.Current.Request.Cookies["Language"];
            if (cookie != null && cookie.Value != null)
            {
                System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo(cookie.Value);
                System.Threading.Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo(cookie.Value);

            }

            else
            {
                System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("en");
                System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("en");

            }
        }

Controller:

 public ActionResult AboutUs()
 {
        HttpCookie cookie = HttpContext.Request.Cookies["Language"];
        var categoryList = context.SiteContents.Where(x => x.LanguageTB.CultureCode==cookie.Value)).ToList();
        return View(categoryList);
    }

I'm doing this again and again for every view:

 public ActionResult AllAttorney()
{
    HttpCookie cookie = HttpContext.Request.Cookies["Language"];
    var employeelist = context.Employees.Where(x => x.LanguageTB.CultureCode== mainLanguage.lb).ToList();
    return View(employeelist);
}

View:

 en

 az

 ru

         @RHome.MAttorney

         @RHome.MAboutUs

         @RHome.MNews

Language table:

  [Table("LanguageTB")]
public partial class LanguageTB
{
    public LanguageTB()
    {
        Articles = new HashSet
();
        Employees = new HashSet<Employee>();
        SiteContents = new HashSet<SiteContent>();
    }

    [Key]
    public int LanguageId { get; set; }

    [StringLength(50)]
    public string CultureCode { get; set; }

    [StringLength(100)]
    public string CultureName { get; set; }

    public virtual ICollection
 Articles { get; set; }
    public virtual ICollection<Employee> Employees { get; set; }
    public virtual ICollection<SiteContent> SiteContents { get; set; }
}


texts: Less CSS Mixin for positioning with options for corresponding top, left, right, bottom values

texts:
I've created a Mixin in Less CSS. It can do the following things:

Set the position-rule of an element.
Place the element in one of the corners (e.g. top left, bottom right etc.)
Alternatively it can set explicit values for top|right|bottom|left.

Usage example:

.test-1 {
    .position(absolute, top, right);
}

Examples showing the resulting CSS:

.position() { position: static; }
.position(relative) { position: relative; }
.position(absolute, top, right) { position: absolute; top: 0; bottom: auto; left: auto; right: 0; }
.position(absolute, bottom, left) { position: absolute; top: auto; bottom: 0; left: 0; right: auto; }
.position(fixed, 20px, 50%) { position: fixed; top: 20px; right: 50%; }
.position(fixed, 10px, null, null, 10%) { fixed: absolute; top: 10px; left: 10%; }
.position(absolute, 10px, -, -, 10%) { position: absolute; top: 10px; left: 10%; }

The Mixin:

.position(@position: static; @a: null; @b: null; @c: null; @d: null) {
    position: @position;

    & when (top = @a) {
        top: 0;
        bottom: auto;
    }

    & when (bottom = @a) {
        top: auto;
        bottom: 0;
    }

    & when (left = @b) {
        left: 0;
        right: auto;
    }

    & when (right = @b) {
        left: auto;
        right: 0;
    }

    & when not (null = @a) and not (~'-' = @a) and not (top = @a) and not (bottom = @a) {
        top: @a;
    }

    & when not (null = @b) and not (~'-' = @b) and not (top = @b) and not (bottom = @b) {
        right: @b;
    }

    & when not (null = @c) and not (~'-' = @c) {
        bottom: @c;
    }

    & when not (null = @d) and not (~'-' = @d) {
        left: @d;
    }
}

I've also created a shortahand version .p(), which can be called instead of .position():

.p(@position: static; @a: null; @b: null; @c: null; @d: null) {
    .position(@position; @a; @b; @c; @d);
}

My questions are:

Is this a useful Mixin?
Or is it a bad practie to create Mixins like this?
Is it too complicated or too hard to understand?
Can this be optimized or shortend?

Even though most of the time I need to use top and left for positioning, I found it more related to other CSS rules like margin when the values are sorted clockwise like top|right|bottom|left.


texts: Most efficient way to populate a vector of integers with no duplicates

texts:
I am trying to populate a vector of integers with one billion random number.  The only constraint is that there can be no duplicates in the array.

#include <iostream>
#include <algorithm>
#include <vector>
#include <ctime>

using namespace std;

int main()
{
    srand(time(NULL));

    vector<int> container;

    vector<int>::iterator i1;

    for (int i=0;i<1000000000;i++) //a billion numbers
    {
        int number = rand() ;

        i1 = find (container.begin(),container.end() , number );

        if ( i1 != container.end() )
        {
            container.push_back(number);
        }

    }

}

How can my solution be improved on? It can be anything, like time taken or space complexity.


texts: Is it worth to use if-else statement as Java optional pattern?

texts:
I came to a point while refactoring using if {} else {} code with Java optionals. While optimizing code it turned to a result to this:

Optional.of(myBoolean).filter(b -> b).ifPresent(b -> {/*my code if true*/});

I recognized filter(b -> b) is not the way i wanted to use optionals thus i turned it to

If.is(myBoolean).then(b -> {/*my code if true*/}).orElse(b -> {/*my code if false*/});

The code for the If class I wrote to handle this is:

public class If {

    private boolean isTrue;

    public If(final boolean value) {
        isTrue = value;
    }

    public If then(final Consumer s) {
        if (isTrue) {
            s.accept(null);
        }
        return this;
    }

    public void orElse(final Consumer s) {
        if (!isTrue) {
            s.accept(null);
        }
    }

    public static If is(final boolean value) {
        return new If(value);
    }
}

Is this a good (whatever good is or should be) approach using the if {} else {} statement in Java?


texts: A faster way to compute the largest prime factor

texts:
I am self-learning js and came across this problem(#3) from the Euler Project

  The prime factors of 13195 are 5, 7, 13 and 29.

  What is the largest prime factor of the number 600851475143 ?

Logic:

Have an array primes to store all the prime numbers less than number
Loop through the odd numbers only below number to check for primes using i
Check if i is divisible by any of the elements already in primes.

If yes, isPrime = false and break the for loop for j by j=primesLength
If not, isPrime = true

If isPrime == true then add i to the array primes and check if number%i == 0

If number%i == 0% update the value of factor as factor = i

Return factor after looping through all the numbers below number

My code:

function problem3(number){
 let factor = 1;
 let primes = [2]; //array to store prime numbers

 for(let i=3; i<number; i=i+2){  //Increment i by 2 to loop through only odd numbers
  let isPrime = true;
  let primesLength= primes.length;

  for(let j=0; j< primesLength; j++){
   if(i%primes[j]==0){
    isPrime = false;
    j=primesLength; //to break the for loop
   }
  }

  if(isPrime == true){
   primes.push(i);
   if(number%i == 0){
    factor = i;
   }
  }
 }
 return  factor;
}

console.log(problem3(600851475143));

It is working perfectly for small numbers, but is quite very slow for 600851475143. What should I change in this code to make the computation faster?

Edit: Updated code based on feedback


texts: Which is cleaner: a constructor with many parameters or many setters after construction?

texts:
I'm trying to work out which is cleaner, having a large constructor or having to use many setters on a new object before doing some work with it.

Large constructor:

<?php
class PathGeneratorWithBigConstructor {
  //...

  public function __construct($base_directories, $paths, $filename) {
    $this->base_directories = $base_directories;
    $this->paths = $paths;
    $this->filename = $filename;
  }

  //...
}

// Must pass the parameters in the correct order
$path_generator = new PathGeneratorWithBigConstructor($base_directories, $paths, $filename);

Many setters:

<?php
class PathGeneratorWithSetters {
  //...

  public function set_base_directories($base_directories) {
    $this->base_directories = $base_directories;
  }

  public function set_paths($paths) {
    $this->paths = $paths;
  }

  public function set_filename($filename) {
    $this->filename = $filename;
  }

  //...
}

$path_generator = new PathGeneratorWithSetters;

// These can go in any order
$path_generator->set_paths($paths);
$path_generator->set_filename($filename);
$path_generator->set_base_directories($base_directories);

I'm trying to follow Robert "Uncle Bob" Martin's advice in Clean Code where he recommends against having too many parameters in a method. He states on page 40:

  Function Arguments

  The ideal number of arguments for a function is
  zero (niladic). Next comes one (monadic), followed
  closely by two (dyadic). Three arguments (triadic)
  should be avoided where possible. More than three
  (polyadic) requires very special justification—and
  then shouldn’t be used anyway.

  Arguments are hard. They take a lot of conceptual
  power. …

Obviously, I can't quote the whole section here, and if you disagree with his opinion, I'd advise familiarising yourself with the rest of his argument before posting a reply. He goes into greater detail over the next 3-4 pages which I can't summarise here because he has already written the appropriate amount of text on the subject. I do reference his ideas in the following paragraphs which is again why I recommend being familiar with his full opinion before replying.

In the class with the constructor, it's not obvious what order the parameters should go in (no natural ordering - page 42). You can't give a hint to the programmer with the method's name because it's the constructor, which should succinctly describe the object, not the order of its construction parameters (encode the names of the arguments into the function name - page 43).

With the constructor, an error will occur when the object is created if there are too few parameters. With the setters, an error will still occur later if each property is not set correctly, which is also the case for the constructor, so no clear advantage either way. Some IDEs will warn the programmer if the method signature doesn't match, while they can't warn about missing setters.

The parameters in this case can't be combined into an sensible object, because PathGenerator is the sensible object! $base_directories, $paths & $filename don't have a logical grouping (reduce the number of arguments by creating objects out of them - page 43).

The class with the setters seems like a lot of work. It also seems too easy to miss one of the setters before trying to get it to do some work. However, reading the code that uses the setter class, it's obvious what it does, much more so than the large constructor version!

The third option, passing in a $parameters object/array, as I've seen recommended elsewhere, seems to combine the worst of both styles: extra work is needed to construct the object and it's easy to miss a parameter.

My goal is that the code should be easy to maintain (therefore also easy to understand) and easy to use. Which of the two styles is cleaner?


texts:
I have posted a discussion on Math.SE regarding visualizing the complex space and effects of factorization methods on that space.  A quick link to the paper is available here.  I have 3 routines in that paper, the first is the complex space generator.  It works, but it is very slow and would appreciate any suggestions on improvement.

Complex Space Generator:

Complex.Space.Generator <- function(N){
  min.real = ceiling(sqrt(N))
  segtop_x = ceiling(N/6)+1
  segtop_y = floor(N/6)-1
  plot(N,N,xlim=c((0),N/3), ylim =c((0),N/6),xlab="Real",ylab="Imaginary")
  segments(3,0,segtop_x,segtop_y)
  segments(segtop_x,segtop_y,N/3,0, lty = "dotted")

  for (i in 3:N/3){
    for (j in 0:N/3){
      i=as.integer(i)
      j=as.integer(j)
      if((i-j)>=3 && (i+j)<=(N/3) && (i-j)<=min.real)
        points(i,j, pch = 17,col = ifelse((i-j)*(i+j) < N,'blue',ifelse((i-j)*(i+j) == N,'green','red')))
    }
  }
}

The second routine is the simultaneous factorization method involving Fermat and trial division.  It is pretty fast, but I'm sure some improvements can be identified.

 Simultaneous.Complex.Factorization <- function(N){
 min.real = ceiling(sqrt(N))
 max.imaginary = min.real - 3
 divisor = min.real + max.imaginary ### 135degree yellow line
 ### Estimate of where complex space turns red
 min.imaginary = floor(mean(c((N/divisor),max.imaginary)))
 ### Corresponding real to above estimate
 max.real = divisor - min.imaginary
 j = 0L
 while (j>=0L ){
     if(
      sqrt(((min.real + j)^2) - N)%%1==0 |   ### Vertical Fermat

      sqrt(((max.imaginary - j)^2) + N)%%1==0 |    ### Horizontal Fermat

      (N/((min.real+j)-(max.imaginary-j)))%%1==0 |    ### Trial Division

      sqrt(((max.real - j)^2) - N)%%1==0 |    ### Vertical Fermat from estimate

      (N/((max.real-j)-(min.imaginary+j)))%%1==0    ### Trial Division from estimate
      ) {

return(as.matrix(c(iterations=j,
     mapped.real = (min.real+j)-(max.imaginary - j),
     Factor_v = if((sqrt((min.real+j)^2 - N))%%1==0) (min.real+j)-sqrt((min.real+j)^2 - N),
     Factor_h = if((sqrt((max.imaginary - j)^2 + N))%%1==0) (max.imaginary - j) + sqrt((max.imaginary - j)^2 + N),
     Factor_td = if((N/((min.real+j)-(max.imaginary-j)))%%1==0) (N/((min.real+j)-(max.imaginary-j))),
     Factor_v.2 = if((sqrt((max.real-j)^2 - N))%%1==0) (max.real-j)-sqrt((max.real-j)^2 - N),
     Factor_td.2 = if((N/((max.real-j)-(min.imaginary+j)))%%1==0) (N/((max.real-j)-(min.imaginary+j)))
     )))}

 j = j + 1L

  }
}

And finally I have the alternative method presented in the paper.  It is very slow compared to the above method even though it requires noticeably less iterations.

Viole.Factorization <- function(N){
 min.real = ceiling(sqrt(N))
 max.imgainary = (N-9)/6
 iterated.average = 0L

 for (i in 2:log2(max.imgainary)){
      iterated.average[1] = mean(c(min.real,N))
      iterated.average[i] = mean(c(iterated.average[i-1],N))
      }

 descending.iterations = floor(iterated.average)
 ascending.iterations = ceiling(iterated.average)
 print(iterated.average)
 j = 0L

 while(j>=0L){
      for(i in 1:length(iterated.average)){
      if( (descending.iterations[i]-j > descending.iterations[i-1] | ascending.iterations[i]+j < ascending.iterations[i+1]) &&
      GCD(descending.iterations[i]-j,N)>1 && GCD(descending.iterations[i]-j,N)<N |
      GCD(ascending.iterations[i]+j,N)>1 && GCD(ascending.iterations[i]+j,N)<N
      ){

 return(c("Factor"=GCD(descending.iterations[i]-j,N),"Factor"=GCD(ascending.iterations[i]+j,N),"Iterated.Average.Level"=i,"Iterations"=j))}
      }
 j = j + 1L
 }
}

I look forward to any insights regarding the routines.  If you have any suggestions or questions on the content of the paper then please comment on the Math.SE discussion.


texts:
This function is working fine but I'm looking for any better alternative:

function formate(array) {
    var formattedArray = [];
    var count = array.length;

    for (var i = 0; i < count; i++) {
        formattedArray.push({
            all: array[i].all ? array[i].all.split(',') : [],
            any: array[i].any ? array[i].any.split(',') : [],
            not: array[i].not ? array[i].not.split(',') : [],
        });
    }

    return formattedArray;
}

Input:

[{all: "one,two", any: "three,four", not: ""},{all: "five,six", any: "", not: "seven"}]

Output:

[{all: ["one", "two"], any: ["three", "four"], not: []}, {all: ["five", "six"], any: [], not: ["seven"]}]


texts:
I have made a simple gender guesser for an app and thought that this simple bit of code may be useful to other developers. It takes in a string and returns an 'f' for Female and an 'f' Male depending on the name provided. I am not a PHP expert so I was wondering if anyone can give me some feedback on this code.

The full code can be found at the repository here

<?php

Class Gender{
    public $gender;
    protected $maleNames    = [];
    protected $femaleNames  = [];
    public $isMale      = FALSE;
    public $isFemale    = FALSE;
    public function __construct($name, $default, $unknown, $custom){
        $this->maleNames    = $this->getMaleNames($custom);
        $this->femaleNames  = $this->getFemaleNames($custom);
        $this->gender       = $default;
        if(in_array($this->getName($name), $this->maleNames)){
            $this->isMale = TRUE;
        }
        if(in_array($this->getName($name), $this->femaleNames)){
            $this->isFemale = TRUE;
        }
        if($this->isMale && !$this->isFemale){
            $this->gender = 'm';
        }elseif(!$this->isMale && $this->isFemale){
            $this->gender = 'f';
        }elseif($this->isMale && $this->isFemale){
            $this->gender = $default;
        }else{
            $this->gender = $unknown;
        }
    }
    public static function guess($name, $default = 'm', $unknown = 'm', $custom = []){
        $g = new Self($name, $default, $unknown, $custom);
        return $g->gender;
    }
    public static function isMale($name, $default = 'm', $unknown = 'm', $custom = []){
        $g = new Self($name, $default, $unknown, $custom);
        return ($g->gender === 'm')? TRUE : FALSE;
    }
    public static function isFemale($name, $default = 'm', $unknown = 'm', $custom = []){
        $g = new Self($name, $default, $unknown, $custom);
        return ($g->gender === 'f')? TRUE : FALSE;
    }
    protected function getName($name){
        $name = explode(' ', $name);
        $name = $name[0];
        $name = strtolower($name);
        return $name;
    }
    protected function getMaleNames($custom){
        $names = json_decode(file_get_contents(__DIR__ . '/names/male.json'));

        if(is_array($custom['male'])){
            foreach($custom['male'] as $name){
                $names[] = strtolower($name);
            }
        }
        return $names;
    }
    protected function getFemaleNames($custom){
        $names = json_decode(file_get_contents(__DIR__ . '/names/female.json'));

        if(is_array($custom['female'])){
            foreach($custom['female'] as $name){
                $names[] = strtolower($name);
            }
        }
        return $names;
    }
}

echo Gender::guess('anthony');

?>


texts:
In order to get a better grasp of React I decided to create a typeahead component. I'd really love some feedback on this in order to improve, learn or avoid mistakes regarding my code. I'm unsure whether I should split up my components even more than I already did.

import React from 'react';
import ReactDOM from 'react-dom';
import SearchListItem from './search_list_item.jsx';

class SearchList extends React.Component {

  constructor(props) {
    super(props);

    this.state = {
      cursor: 0,
      data: ['Bananas', 'Apples', 'Ape', 'Oranges', 'Ora', 'Cherries', 'Pears', 'Kiwi'],
      searchedList: [],
      searchInput: '',
      showDropdown: true
    }

    this.handleOnchange = this.handleOnchange.bind(this);
    this.handleKeyPress = this.handleKeyPress.bind(this);
    this.handleClickedItem = this.handleClickedItem.bind(this);
  }

  handleOnchange(value) {
    this.setState({ showDropdown: true })
    this.setState({ searchInput: value });
    const dataItem = this.state.data
    let searchedListItems = dataItem.filter(dataItem => dataItem.includes(this.state.searchInput));
    var listToRender = [];
    if (searchedListItems) {
      listToRender.push(searchedListItems);
    } else {
      var itemToRemove = this.state.searchedListItems
      listToRender.remove(listToRender, itemToRemove);
    }
    this.setState({ searchedList: listToRender });
  }

  handleKeyPress(e) {
    const { cursor, searchedList } = this.state;
    const arrowUp = 38;
    const arrowDown = 40;
    const enter = 13;

    if (e.keyCode === arrowUp && cursor > 0) {
      this.setState( prevState => ({
        cursor: prevState.cursor - 1
      }))
    } else if (e.keyCode === arrowDown && cursor < searchedList[0].length - 1) {
      this.setState( prevState => ({
        cursor: prevState.cursor + 1
      }))
    } else if (e.keyCode === enter && cursor >= 0) {
      this.setState({
        searchInput: searchedList[0][this.state.cursor],
        showDropdown: false,
        cursor: 0
       });
    }
  }

  handleClickedItem(data) {
    this.setState({
      searchInput: data,
      showDropdown: false,
      cursor: 0
    })
  }

  submitForm(e) {
    e.preventDefault();
    alert
  }

  renderSearchList() {
    const { cursor } = this.state
    if (this.state.searchedList[0]) {
      const searchList = this.state.searchedList[0].map((data, index) => {
        return (
          <SearchListItem
            key={index}
            id={index}
            handleClickedItem={this.handleClickedItem.bind(null, data)}
            isActive={cursor === index ? 'active dropdown-li' : 'dropdown-li'}
            data={data} />
        );
      });
      return (

            {searchList}

      );
    }
  }

  render() {
    return (

      <form onSubmit={this.submitForm} >
        <input
          className="input"
          type="text"
          value={this.state.searchInput}
          onChange={event => this.handleOnchange(event.target.value)}
          onKeyDown={this.handleKeyPress} />
        </form>
        { this.state.showDropdown ? this.renderSearchList() :
 }

    );
  }
}

ReactDOM.render(<SearchList/>, document.getElementById('main'));


texts:
I came across this SO question on why std::max_element requires a ForwardIterator (as apposed to an InputIterator). Having a max_element-like algorithm for InputIterator would be useful, as it could then be used with objects like std::istream_iterator or boost::transform_iterator.

I came up with the following algorithm for this:

#include <iterator>   // std::iterator_traits, std::advance
#include <stdexcept>  // std::logic_error
#include <algorithm>  // std::for_each
#include <functional> // std::less
#include <utility>    // std::move

template <typename InputIterator, typename Compare>
typename std::iterator_traits<InputIterator>::value_type
max_input(InputIterator first, InputIterator last, Compare comp)
{
    if (first == last) throw std::logic_error {"max_input given empty range"};

    using ValueType = typename std::iterator_traits<InputIterator>::value_type;

    ValueType result {*first};

    std::advance(first, 1);

    std::for_each(first, last, [&result, comp] (ValueType curr) {
        if (comp(result, curr)) result = std::move(curr);
    });

    return result;
}

Example:

#include <sstream>
#include <iostream>

int main()
{
    std::istringstream str("0.1 0.2 0.3 0.4 0.2 0.0 0.1");

    const auto max = max_input(std::istream_iterator<double>(str), std::istream_iterator<double>());

    std::cout << "max is " << max << std::endl;

    return 0;
}

I'm looking for general feedback/improvements, especially on the decision to throw for an empty range. I was also deliberating whether the algorithm should also return the index of the maximum (e.g. in a std::pair).


texts: Reading a collection of strings from the user

texts:
I was trying to write a program that will read a collection of strings from the user, and then end the moment it encounters a ".". So then I write a do-while loop.

I came across a something like this:

string temp;
vector<string> params;
do
{
    cin >> temp;
    if (temp == ".")
        break;

    params.push_back(temp);

} while (temp != ".");

I realized that no matter what, the loop will always end from within its body -- which is the exact result that want.

But there something about piece of code that smells fishy. Are there any better ways?

Another thing to note: I don't want the "." to be pushed onto the vector, hence that's why I added that little if (temp == ".") break; statement.


texts: Python extended Euclidean algortihm + inverse modulo

texts:
I programmed the extended Euclidean algorithm together with the inverse modulo because I am making an RSA system from scratch. Any feedback regarding efficiency etc. is welcome :)

    def ext_gcd(a, b):

        a0, a1 = a, b
        x0, x1 = 1, 0
        y0, y1 = 0, 1

        while a1 != 0:
            q = a0//a1
            r, s, t = a1, x1, y1
            a1 = a0 % a1
            x1 = x0 - q*x1
            y1 = y0 - q*y1
            a0, x0, y0 = r, s, t

        return x0, y0, a0

    def inverse_mod(a, mod):
        va, y0, a0 = Math.ext_gcd(a, mod)
        return va % mod


texts:
I'm a beginner in JavaScript.  I wrote this code so the main image get set on whatever thumbnail image the user clicks.

And if the user didn't click on any image the main photo get changed every 10 seconds.

Here's my code (I feel like I'm doing some unnecessary work here in the timers but I can't figure it out):

HTML:

<!DOCTYPE html>

    <title>Photo Gallery</title>
    <link rel="stylesheet" href="style.css" />

JavaScript:

window.onload = function(){
    var mainImage = document.getElementById("mainImage").getElementsByTagName("img")[0],
        thumbnailImages = document.getElementById("thumbnails").getElementsByTagName("img"),
        j = 0;

    var startTimer = function(){
        stillTimer = setInterval(function(){
                j = (j < 3) ? ++j : 0 ;
                mainImage.src = thumbnailImages[j].src;

            }, 10000);
    }

    startTimer();

    for(i = 0 ; i < thumbnailImages.length ; i++){
        thumbnailImages[i].addEventListener("click", function(evt){
            clearInterval(stillTimer);
            mainImage.src = evt.target.src;
            ++j;
            startTimer();
        });
    };
}

CSS:

body {
    margin: auto;
    width: 800px;
    height: 800px;
}

#mainContainer {
    width: 760px;
    height: 800px;
}

#mainImage {
    margin: auto;
    height: 560px;
}

#mainImage img {
    margin: 10px;
    width: 740px;
    height: 540px;
}

#thumbnails {
    padding-top: 10px;
    height: 205px;
}

.imgThumbnails {
    margin-left: 6px;
    height: 186px;
    width: 180px;
    display: inline;
    hover:
}

.imgThumbnails:hover {
    cursor: pointer;
}


texts: Pythonic attempt at conversion of length

texts:
I'm trying to learn Python, so I started with a program to convert length units, mixing imperial and metric. First I wrote a bunch of small simple functions, but then I wanted to solve the issue of having an intuitive way of calling one function with some easy to remember parameter values in order to convert from any unit to any other unit, as opposed to having to call a bunch of different function names.

Does each instance of Convert remain in memory when I am using __new__ and not actually returning an instance of the class? For example, since only a float is stored in 'x' at the end, is the instance of convert that was created destroyed?

Is this approach valid overall? It feels like I've done something a little strange here.

Note: The code works on both Python 3 and 2.

class Convert(object):
    def __new__(self, val, unit_in, unit_out):
        convertString   = '%s_to_%s' % (unit_in, unit_out)
        try:
            convertFunction = getattr(self, convertString)
        except:
            return None
        return convertFunction(self, val)

    def mm_to_cm(self, millimeters):
        return millimeters / 10.0
    def mm_to_in(self, millimeters):
        return ((millimeters / 1000.0) / 0.9144) * 36.0
    def mm_to_ft(self, millimeters):
        return ((millimeters / 1000.0) / 0.9144) * 3.0
    def mm_to_m(self, millimeters):
        return millimeters / 1000.0

    def cm_to_mm(self, centimeters):
        return centimeters * 10.0
    def cm_to_in(self, centimeters):
        return ((centimeters / 100.0) / 0.9144) * 36.0
    def cm_to_ft(self, centimeters):
        return ((centimeters / 100.0) / 0.9144) * 3.0
    def cm_to_m(self, centimeters):
        return centimeters / 100.0

    def in_to_mm(self, inches):
        return (((inches / 12.0) / 3.0) / (1.0 / 0.9144)) * 1000.0
    def in_to_cm(self, inches):
        return (((inches / 12.0) / 3.0) / (1.0 / 0.9144)) * 100.0
    def in_to_ft(self, inches):
        return inches / 12.0
    def in_to_m(self, inches):
        return (((inches / 12.0) / 3.0) / (1.0 / 0.9144))

    def ft_to_mm(self, feet):
        return (feet / 3.0) / (1.0 / 0.9144) * 1000.0
    def ft_to_cm(self, feet):
        return (feet / 3.0) / (1.0 / 0.9144) * 100.0
    def ft_to_in(self, feet):
        return feet * 12.0
    def ft_to_m(self, feet):
        return (feet / 3.0) / (1.0 / 0.9144)

    def m_to_mm(self, meters):
        return meters * 1000.0
    def m_to_cm(self, meters):
        return meters * 100.0
    def m_to_in(self, meters):
        return (meters / 0.9144) * 36.0
    def m_to_ft(self, meters):
        return (meters / 0.9144) * 3.0

print(Convert( 1.0,   'ft', 'in'))
print(Convert(12.0,   'in', 'ft'))
print(Convert( 0.3048, 'm', 'ft'))
x = Convert(3, 'ft', 'm')
print(x)
exit()
output:
12.0
1.0
1.0
0.9144


texts:
I have a dictionary which I use to lookup my binary and ASCII values (from A - P). It works, but my ascii2bin function just doesn't really feel right (and beautiful). Is there is a better way to write it?

The ascii2bin function splits a 2-letter string (i.e. 'LA') and looks up the keys in the dictionary. Then concatenates the 2 keys to each other to get an 8bit string.

Check the comment for the assignment which was given.

import sdes

"""
Using S-DES, decrypt the string (10100010) using the key (0111111101) by hand.
Then decode the 4 bits of the plaintext string to a letter and the second 4 bits to another letter where
we encode A through P in base 2 (i.e., A = 0000, B = 0001, ..., P = 1111).
"""

KEY = '0111111101'
CIPHERTEXT = '10100010'

ALPHABET = {'0000': 'A',
            '0001': 'B',
            '0010': 'C',
            '0011': 'D',
            '0100': 'E',
            '0101': 'F',
            '0110': 'G',
            '0111': 'H',
            '1000': 'I',
            '1001': 'J',
            '1010': 'K',
            '1011': 'L',
            '1100': 'M',
            '1101': 'N',
            '1110': 'O',
            '1111': 'P'}

def bin2ascii(bin):
    return ALPHABET[bin[:4]] + ALPHABET[bin[4:]]

def ascii2bin(string_of_2_letters):
    bits = []
    for i in range(0, 2):
        bits += ([key for key, val in ALPHABET.items() if val == string_of_2_letters[i]])
    return bits[0] + bits[1]

print bin2ascii(sdes.decrypt(CIPHERTEXT, KEY))