texts:
I've been working on a a text based game with a very simple battling system. There are way to many questions I can ask to get reviewed about this project, but I'll take small steps at a time (this is my first post).
I'm mostly concerned about how I handle command input and the execution of said commands within the game. Just to give a simple example of what a command might look like:
go north

go - command (called action in the code, as Command is the whole class)
north (and anything after that) - arguments, you most likely know about these

INPUT
Currently, I've made it work using the readline package from Node. The input is being sent to a "commander" where it is parsed, made into a Command which will in the end be passed to an "executor" which will execute the command. Here's the code:
//Player.ts
import readline from 'readline';
//other imports...

class Player extends Entity {
    // fields, constructor and other methods...

    async getInput(questionPrompt?: string): Promise<string> {
        return new Promise((resolve, _) => {
            const prompt = readline.createInterface({
                input: process.stdin,
                output: process.stdout,
            });

            const question = (questionPrompt) ? questionPrompt : ">";

            prompt.question(question, (answer) => {
                prompt.close()

                resolve(answer);
            })
        })
    }
}

export default Player;

//commander.ts (technically it's inside commander/index.ts)
import Command from '../models/Command';
import Player from '../models/Player';

const actions = ['go', 'look', 'take', 'equip', 'inventory', 'help'];

export const parse = (text: string): (Command | null) => {
    const action = text.split(' ')[0];
    const args = text.split(' ').slice(1);

    if (!actions.find((a) => action === a))
        return null;

    return new Command(action, args);
}

export const execute = (command: Command, receiver: Player) => {
    switch (command.action) {
        case 'go':
            const success = receiver.move(command.args[0]);
            if (success) {
                return console.log(`You have entered a new room.\n${receiver.currentRoom.getDescription()}`);
            } else {
                return console.log(`You can't go there. Please try another one.`);
            }
        case 'look':
            const text = `You are in ${receiver.currentRoom.name}.\n` +
                `${receiver.currentRoom.description}`;
            return console.log(text);
        case 'take':
            const item = receiver.currentRoom.takeItem(command.args[0]);
            if (item)
                return receiver.takeItem(item);
            else
                return console.log(`A ${command.args[0]} couldn't be found.`);
        case 'equip':
            return receiver.inventory.map((i) => {
                if (i.name === command.args[0]) {
                    receiver.equip(i.id);
                }
            })
        case 'inventory':
            return console.log(receiver.inventory);
        case 'help':
            return console.log("No help for now... Maybe later?");
        default:
            console.log('Command error.');
            return console.log(command);
    }
}

export default {
    parse,
    execute,
}

I'm not entirely sure if this is an appropriate way to handle this use case, but this is all I could come up with. The other solution I managed to think of was to have the different commands in a separate folder where I could have them as modules and I could try to import them. This way they can maybe be classes and have their own help messages which will also make it easier to document the commands. The reason I decided to stick with this approach is because it seems a bit easier, and having the commands as separate modules kinds seems overkill to me, maybe I'm totally wrong.
I know I've probably missed something very important, so a link to the whole project can be found here.


texts:
I have the following relationship in EF Core 3.1.1 (Many-To-Many):
public partial class Movie
{
    public Movie()
    {
        Directors = new HashSet<MovieDirector>();
    }

    public int Id { get; set; }
    public string Title { get; set; }

    public virtual ICollection<MovieDirector> Directors { get; set; }
}

public partial class Director
{
    public Director()
    {
        MovieDirector = new HashSet<MovieDirector>();
    }

    public string Id { get; set; }
    public string Name { get; set; }

    public virtual ICollection<MovieDirector> MovieDirector { get; set; }
}

public partial class MovieDirector
{
    public int Id { get; set; }
    public int MovieId { get; set; }
    public string DirectorId { get; set; }

    public virtual Movie Movie { get; set; }
    public virtual Director Director { get; set; }
}

And I have the following method to create a Director:
public Director CreateDirector(int movieId, Director director)
{
    var movie = _repository.Movie.FirstOrDefault(w => w.Id == movieId);

    movie.Directors.Add(new MovieDirector{ Director = director });

    _repository.SaveChanges();

    return director;
}

The CreateDirector method can perfectly create a new Director including relationships.
My biggest question is if every time I need to insert in a table that has a relationship I will need:

Find the parent/root entity (Movie)

Create a new MovieDirector object

Associate the new MovieDirector object with the parent/root, like:
movie.Directors.Add(new MovieDirector)

Is this correct or is there some kind of shortcut?


texts:
At the moment I am trying to create a Japanese rehearsal system, and it's working perfectly. However, I am not pleased with the code. Basically I had a .txt file called lesson1.txt. I saved it as UTF-8 so it can contain Japanese characters.

I had the problem that I couldn't directly use the Japanese characters in JavaScript.  I tried bypassing that issue by finding the Unicode code point of each character in PHP, echo that out in as a JavaScript array and use a JavaScript function to convert it back to the Japanese characters.

Now I figured this is not the way to go, because someone on this site told me this is an awful way of coding. My question is, how do I go by improving this? How can I get the Japanese characters into my JavaScript code the most efficient way? Also, have a look at how badly it is coded right now to get a better way of understanding my problem.

In case necessary: I used this PHP loop to get each Unicode point transferred into characters and saved into a JavaScript array:

$x = 0;
//$LineArray is an array in which each element contains a line of  lesson1.txt
    // so for example: $LineArray[0] = "あつい";
foreach($LineArray as $s)
{
    echo "TextCharacters[" . $x . "] = new Array();\n";
    for($i = 0; $i < mb_strlen($s,"utf-8"); $i++)
    {
        $char = mb_substr($s, $i, 1, "utf-8");
                    // REMOVE BOM
        if(strtoupper(bin2hex(iconv('UTF-8', 'UCS-2', $char))) != "FEFF")
        {
            echo "TextCharacters[" . $x . "].push(go(\"" .   strtoupper(bin2hex(iconv('UTF-8', 'UCS-2', $char))) . "\"));\n";
        }
    }
    $x++;
}


texts:
Using the algorithm at the end of this research paper, I've written an extremely fast 1 Ackermann function in Rust. Can the implementation be made faster?

Thoughts:

Using a struct makes a lot of sense, but it's weird to have to Some(Box::new(v2)). Can this be avoided in some way?
Are for loops the best way of doing the v transformations? Would (1..(i + 1)).fold(Record::new(1, 0, None), |v, k| a_use_p(k - 1, 1, v)) be more "Rustic"? It seems slightly faster, but that's hard to tell.
Is there a way to parallelize this? Or any part of it?

Thanks.

extern crate time;

use time::PreciseTime;

fn main() {
    let m = 3;

    for n in 1..20 {
        let s = PreciseTime::now();
        let res = fast_ackermann(m, n);
        let e = PreciseTime::now();
        println!("a_opt(3, {}) -> {} took {}", n, res, s.to(e))
    }
}

#[derive(Clone)]
struct Record {
    result: u64,
    previous_result: u64,
    cache: Option<Box<Record>>,
}

impl Record {
    fn new(result: u64, previous_result: u64, cache: Option<Box<Record>>) -> Record {
        Record { result, previous_result, cache }
    }
}

fn fast_ackermann(m: u64, n: u64) -> u64 {
    let mut cache = Record::new(1, 0, None);
    for m_builder in 0..m {
        cache = ack_with_incrementalization(m_builder, 1, cache)
    }
    for n_builder in 1..(n + 1) {
        cache = ack_with_incrementalization(m, n_builder, cache)
    }
    cache.result
}

fn ack_with_incrementalization(m: u64, n: u64, current_cache: Record) -> Record {
    if m == 0 {
        Record::new(n + 1, 0, None)
    } else if n == 0 {
        let mut new_cache = Record::new(1, 0, None);
        for m_builder in 0..m {
            new_cache = ack_with_incrementalization(m_builder, 1, new_cache);
        }
        new_cache
    } else if n == 1 {
        let cache_result = current_cache.result;
        let mut new_cache = current_cache;
        for n_builder in 2..(cache_result + 1) {
            new_cache = ack_with_incrementalization(m - 1, n_builder, new_cache);
        }
        Record::new(new_cache.result, cache_result, Some(Box::new(new_cache)))
    } else {
        let cache_result = current_cache.result;
        let mut new_cache = *current_cache.cache.unwrap();
        for n_builder in (current_cache.previous_result + 1)..(current_cache.result + 1) {
            new_cache = ack_with_incrementalization(m - 1, n_builder, new_cache);
        }
        Record::new(new_cache.result, cache_result, Some(Box::new(new_cache)))
    }
}

1 With m = 3, n = 20, the code takes 0.95 seconds. With n = 30 it takes 16 minutes. In the paper, n = 20 takes 5.05 seconds and n  =30 takes 87 minutes. A version with an intermediate cache (in Rust), n = 20 took 2.1 seconds and n = 25 (not 30 like the others) took 39 minutes.


texts:
Can someone please review this design I created for deck of cards in Java?

package prep.design;

import java.lang.reflect.Array;
import java.util.*;

/**
 * Created by rohandalvi on 5/14/16.
 */
public class CardDeck {

    private ArrayList<Card> cards;

    CardDeck(){
        cards = new ArrayList<>();
        for(Card.Suit s: Card.Suit.values()){
            for(Card.Rank r: Card.Rank.values()){
                cards.add(new Card(r,s));
            }
        }
    }

    public void print(){
        for(Card card: cards){
            System.out.println("Card: "+card.getRank()+" Suit: "+card.getSuit());
        }
    }

    public void shuffle(ArrayList<Card> c){
        if(c==null){
            Collections.shuffle(cards);
        }else{
            Collections.shuffle(c);
        }

    }

    public static void main(String[] args) {
        CardDeck cd = new CardDeck();
        cd.shuffle(null);
        //cd.print();

        cd.deal(5);
    }

    public void deal(int numberOfPlayers){
        ArrayList<Card> tempDeck = new ArrayList<>(cards);
        Map<Integer,List<Card>> playerDeck = new HashMap<>();
        //List<List<Card>> playerDeck = new ArrayList<>();
        shuffle(tempDeck);
        shuffle(tempDeck);

        int i=0;
        while(i!=52){
            int j = i%numberOfPlayers;
            List<Card> tempList;
            if(playerDeck.containsKey(j)){
                tempList = playerDeck.get(j);
            }else{
                tempList = new ArrayList<>();
            }
            tempList.add(tempDeck.get(i));
            playerDeck.put(j,tempList);

            i++;

        }

        System.out.println("Dealt");

        displayPlayerCards(playerDeck);

    }

    public void displayPlayerCards(Map<Integer,List<Card>> playerDeck){
        int i=0;
        for(Integer player: playerDeck.keySet()){
            List<Card> playerCards = playerDeck.get(player);

            System.out.println("Player "+i);
            for(Card c: playerCards){
                System.out.print("Rank: "+c.getRank()+" Suit: "+c.getSuit()+"\t");
            }
            System.out.println();
            i++;
        }
    }
}

class  Card{
    Suit s;
    Rank r;
    public  enum  Suit{
        Spade , Heart , Diamond , Clubs
    }

    public enum Rank{
        ACE(1) , TWO(2), THREE(3), FOUR(4), FIVE(5) , SIX(6), SEVEN(7), EIGHT(8), NINE(9), TEN (10), JACK(11), QUEEN (12), KING(13);

        int priority;
        Rank(int s) {
            priority = s;
        }

        public int getPriority(){
            return priority;
        }

        public Rank getRankByPriority(int p){
            switch (p){
                case 1: return Rank.ACE;
                case 2: return Rank.TWO;
                case 3: return Rank.THREE;
                case 4: return Rank.FOUR;
                case 5: return Rank.FIVE;
                case 6: return Rank.SIX;
                case 7: return Rank.SEVEN;
                case 8: return Rank.EIGHT;
                case 9: return Rank.NINE;
                case 10: return Rank.TEN;
                case 11: return Rank.JACK;
                case 12: return Rank.QUEEN;
                case 13: return Rank.KING;

                default: return null;
            }

        }
    }

    Rank getRank(){
        return r;
    }

    Suit getSuit(){
        return s;
    }

    Card(Rank r, Suit s){
        this.r = r;
        this.s = s;
    }

}

class cardComparator implements java.util.Comparator<Card.Rank>{

    @Override
    public int compare(Card.Rank o1, Card.Rank o2) {
        if(o1.getPriority() > o2.getPriority()){
            return 1;
        }else if(o1.getPriority() < o2.getPriority()){
            return -1;
        }else{
            return 0;
        }
    }

    @Override
    public Comparator<Card.Rank> reversed() {
        return null;
    }
}


texts:
Here's is the code I'd like reviewed:

module Main where

import Control.Monad ( when )
import System.Exit ( exitSuccess )

import Idris.AbsSyntax
import Idris.Error
import Idris.CmdOptions
import Idris.Info
import Idris.Info.Show
import Idris.Package
import Idris.Main

import Util.System ( setupBundledCC )

processShowOptions :: [Opt] -> Idris ()
processShowOptions opts = runIO $ do
  when (ShowAll `elem` opts)          $ showExitIdrisInfo
  when (ShowLoggingCats `elem` opts)  $ showExitIdrisLoggingCategories
  when (ShowIncs `elem` opts)         $ showExitIdrisFlagsInc
  when (ShowLibs `elem` opts)         $ showExitIdrisFlagsLibs
  when (ShowLibdir `elem` opts)       $ showExitIdrisLibDir
  when (ShowPkgs `elem` opts)         $ showExitIdrisInstalledPackages

check :: [Opt] -> (Opt -> Maybe a) -> ([a] -> Idris ()) -> Idris ()
check opts extractOpts action = do
  case opt extractOpts opts of
    [] -> return ()
    fs -> do action fs
             runIO exitSuccess

processClientOptions :: [Opt] -> Idris ()
processClientOptions opts = check opts getClient $ \fs -> case fs of
  (c:_) -> do
    setVerbose False
    setQuiet True
    case getPort opts of
      Just  DontListen       -> ifail "\"--client\" and \"--port none\" are incompatible"
      Just (ListenPort port) -> runIO $ runClient (Just port) c
      Nothing                -> runIO $ runClient Nothing c

processPackageOptions :: [Opt] -> Idris ()
processPackageOptions opts = do
  check opts getPkgCheck $ \fs -> runIO $ do
    mapM_ (checkPkg opts (WarnOnly `elem` opts) True) fs
  check opts getPkgClean $ \fs -> runIO $ do
    mapM_ (cleanPkg opts) fs
  check opts getPkgMkDoc $ \fs -> runIO $ do
    mapM_ (documentPkg opts) fs
  check opts getPkgTest $ \fs -> runIO $ do
    mapM_ (testPkg opts) fs
  check opts getPkg $ \fs -> runIO $ do
    mapM_ (buildPkg opts (WarnOnly `elem` opts)) fs
  check opts getPkgREPL $ \fs -> case fs of
    [f] -> replPkg opts f
    _   -> ifail "Too many packages"

-- | The main function for the Idris executable.
runIdris :: [Opt] -> Idris ()
runIdris opts = do
  runIO setupBundledCC
  processShowOptions opts    -- Show information then quit.
  processClientOptions opts  -- Be a client to a REPL server.
  processPackageOptions opts -- Work with Idris packages.
  idrisMain opts             -- Launch REPL or compile mode.

-- Main program reads command line options, parses the main program, and gets
-- on with the REPL.
main :: IO ()
main = do
  opts <- runArgParser
  runMain (runIdris opts)

I'd like to improve it. There are two main related problems.

This code uses exitSuccess for early exit. This then leads to a misleading piece of code in runIdris.

I'd prefer runIdris to look something like:

runIdris opts = do
  runIO setupBundledCC
  runIO execute (processShowOptions opts
             <|> processClientOptions opts
             <|> processPackageOptions opts
             <|> idrisMain opts)

I think I've worked out a way forward but would love to hear your thoughts.


texts: Find the no of pairs whose sum divides the product from 0 - 1000000000

texts:
I have designed the code but the problem is it timeouts as the range is 1000000000 but works fine with 1000. Any idea to optimize this or a mathematic logic for it? I just need to find the no of pairs(a,b) such that a < b and a*b % a+b == 0 if a range is given,
eg: 15 - o/p 4 as (3,6)(4,12)(6,12)(10,15).

php code:

$count = 0;
$no = 1000;
for($b = 1; $b <= $no; $b ++) {
    for($a = 1; $a < $b; $a ++) {
        $sum = $a + $b;
        $prod = ($a * $b);

        if (($prod % $sum == 0) {
            ++ $count;
        }
        $arr [$b] = $count;
    }
}

echo '<pre>';
print_r($arr);
echo '<pre>';

I need some math logic to get no of pairs rather performing actual process as above. If I found a relation or expression for this then actual process is not required.


texts: Non-recursively replace all uppercase letters in files within current directory with lowercase letters - without looping

texts:
Let's say that I have a directory that looks like this:

dir
    | File1.txt
    | fILE2.md
    | file3.tex

When I execute my bash script from within the dir directory, I want to receive files with names "file1.txt", "file2.md" and "file3.tex".

I have written this script:

ls | xargs -n1 -I {} sh -c 'fst={}; snd=`echo $fst | tr [:upper:] [:lower:]`; mv $fst $snd'

It works but is complex (uses variables). Is there a nicer way to perform it by piping commands? I don't want to use loops.


texts:
I'm new to Python and GAE, but years of procedural programming. I have this code, but I know that there must be some better solution to avoid retyping code.

The first and last section of code are identical in both GET and POST methods, so I suppose there must be another way to share the identical code.

# This class manage the user account
class MyAccount(webapp2.RequestHandler):
        def get(self):
                """ Shows actual user account """

                # Get actual user
                user = users.get_current_user()

                if user:
                        # Get the actual user data
                        data = Person.gql("WHERE username = :nick",
                                                            nick=user.nickname()).get()

                        # Test if we found the user
                        if data:
                                templateValues['data'] = data
                                template = jinja_environment.get_template('myAccount.htm')
                        else:
                                templateValues['custom_msg'] = "The logged user is not available."
                                template = jinja_environment.get_template('customMessage.htm')

                else:
                        templateValues['custom_msg'] = "You are not logged in. Please, login to access to your account"
                        template = jinja_environment.get_template('customMessage.htm')

                # Render the page
                self.response.out.write(template.render(templateValues))

        def post(self):
                """ Saves user updated data """

                # Get actual user
                user = users.get_current_user()

                if user:
                        # Get the actual user data
                        person = Person.gql("WHERE username = :nick",
                                                            nick=user.nickname()).get()

                        # Test if we found the user
                        if person:
                                person.username = self.request.get('username')
                                person.password = self.request.get('password')
                                if person.email: self.request.get('email')
                                person.name = self.request.get('name')
                                person.lastname = self.request.get('lastname')
                                person.idnumber = self.request.get('idnumber')

                                templateValues['data'] = person
                                template = jinja_environment.get_template('myAccount.htm')

                        else:
                                templateValues['custom_msg'] = "The logged user is not available."
                                template = jinja_environment.get_template('customMessage.htm')

                else:
                        templateValues['custom_msg'] = "You are not logged in. Please, login to access to your account."
                        template = jinja_environment.get_template('customMessage.htm')

                # Render the page
                self.response.out.write(template.render(templateValues))


texts:
I would appreciate some feedback on my design of a few classes to query the Trakt.tv API.

public abstract class TraktQuery
{
    private const string baseUrl = "http://api.trakt.tv/";
    private const string apiKey = "[API key here]";

    protected abstract string QueryUrl { get; }
    protected abstract List<string> QueryParameters { get; }
    protected abstract TraktResponse ParseResponse(string response);

    public TraktResponse PerformQuery()
    {
        //exception handling removed for brevity
        WebClient webClient = new WebClient();
        string url = baseUrl + QueryUrl + "/" + apiKey + "/" + string.Join("/", QueryParameters);
        string response = webClient.DownloadString(url);
        return ParseResponse(response);
    }
}

public class TraktQueryEpisodeSummary : TraktQuery
{
    private string _showName;
    private int _season;
    private int _episodeNumber;

    public TraktQueryEpisodeSummary(string showName, int season, int episodeNumber)
    {
        _showName = showName;
        _season = season;
        _episodeNumber = episodeNumber;
    }

    protected override string QueryUrl
    {
        get { return "show/episode/summary.json"; }
    }

    protected override List<string> QueryParameters
    {
        get
        {
            List<string> paramters = new List<string>();
            paramters.Add(_showName);
            paramters.Add("" + _season);
            paramters.Add("" + _episodeNumber);
            return paramters;
        }
    }

    protected override TraktResponse ParseResponse(string response)
    {
        return JsonConvert.DeserializeObject<TraktResponseEpisodeSummary>(response);
    }

public class TraktResponseEpisodeSummary : TraktResponse
{
    public TraktShowInformation show { get; set; }
    public TraktEpisode episode { get; set; }
}

Currently TraktResponse is an empty abstract class but I'll probably add to it soon.

This code is then used as follows:

class Program
{
    static void Main(string[] args)
    {

        TraktQueryEpisodeSummary query = new TraktQueryEpisodeSummary("House", 1, 1);
        TraktResponseEpisodeSummary summary = (TraktResponseEpisodeSummary)query.PerformQuery();

        Console.WriteLine("Title: " + summary.show.title);
        Console.WriteLine("Poster image: " + summary.show.images.poster);
        Console.WriteLine("Genres: " + string.Join(", ", summary.show.genres));
        Console.WriteLine("Episode name: " + summary.episode.title);
        Console.WriteLine("Overview: " + summary.episode.overview);
    }
}

What makes me think my design isn't quite right is that I have to cast from TraktResponse to the more specific TraktResponseEpisodeSummary in order to access the information I need. What I would like to do is make TraktQueryEpisodeSummary.ParseResponse() return a TraktResponseEpisodeSummary instead of a TraktResponse however I'm aware that C# doesn't support return type covariance which I think is what this is.

Are my concerns well-founded or not? Is there a better design that avoids this casting or is it perfectly normal and acceptable?


texts:
I have this model:

  schema "jobs" do
    field :name, :string
    has_many :shiptos, MosaicApi.ShipTo
  end

I want to update the shiptos associated with a job: there could be new shiptos, some deleted, and changes to existing ones. In the end I decided simply to delete the existing and replace with what is sent by the client. This is what I ended up with:

  def update(conn, %{"id" => id, "shiptos" => ship_tos}, _user) do
    current_job =
      Repo.one from j in Job,
                where: j.id == ^id,
                preload: :shiptos
    current_shiptos =
      Map.get(current_job, :shiptos)
      |> Enum.map(fn st -> st.id end)

    # IO.inspect(current_shiptos)
    new_shipto_ids =
      Enum.map(ship_tos,
        fn ship_to ->
          ShipToController.insert_one %{job_id: id, ship_to: ship_to}
        end)

    # IO.inspect(new_shipto_ids)
    case Enum.all?(new_shipto_ids, fn {res, _} -> res == :ok end) do
      true ->
        Enum.each(current_shiptos,
          fn id -> ShipToController.delete_one id end)

        ids =
          new_shipto_ids
          |> Enum.map(fn {_, shipto} -> shipto.id end)

        render(conn, "new_ids.json", ids: ids)
      false ->
        conn
        |> put_status(:unprocessable_entity)
        |> send_resp(:no_content, "")
    end
  end

It seems to work, but I don't feel it is very robust.


texts: Return error messages for sending emails

texts:
How can I optimize this piece of code and avoid the multiple if/else call for returning error message ?

    if ($cardStatus == true) {

        $cardEmailContent = $this->setCardEmailContent();
        $sendUserEmail    = $this->sendCardToUser($cardEmailContent);

        if ($sendUserEmail) {
            $this->sendAdminEmail();
            $this->updateCardDetails();
        } else {
            return $sendUserEmail;
        }

    } else {
        return $this->cardApiError;
    }


texts:
Idea:
In C++, often a straightforward implementation of comparison operators is needed. In C++11, they can be conveniently implemented using std::tie. The following mixin class automatically enables comparison operators by deriving a class T from Comparable<T>.

Implementation: (please review this part, requires C++14)

// A mixin class that makes derived classes comparable
template<typename T>
struct Comparable {
    // nothing is needed here
};

// Default: Assume the client class offers a tie method
// Alternative: The client class can override this method
template<typename T>
auto tie(const Comparable<T>& a_object)
{
    return static_cast<const T&>(a_object).tie();
}

template<typename T>
bool operator==(const Comparable<T>& a_lhs, const Comparable<T>& a_rhs)
{
    return tie(a_lhs) == tie(a_rhs);
}

template<typename T>
bool operator!=(const Comparable<T>& a_lhs, const Comparable<T>& a_rhs)
{
    return tie(a_lhs) != tie(a_rhs);
}

template<typename T>
bool operator<(const Comparable<T>& a_lhs, const Comparable<T>& a_rhs)
{
    return tie(a_lhs) < tie(a_rhs);
}

template<typename T>
bool operator>(const Comparable<T>& a_lhs, const Comparable<T>& a_rhs)
{
    return tie(a_lhs) > tie(a_rhs);
}

template<typename T>
bool operator<=(const Comparable<T>& a_lhs, const Comparable<T>& a_rhs)
{
    return tie(a_lhs) <= tie(a_rhs);
}

template<typename T>
bool operator>=(const Comparable<T>& a_lhs, const Comparable<T>& a_rhs)
{
    return tie(a_lhs) >= tie(a_rhs);
}

Usage Example: Client code then could look like the following. The implementation of the tie function automatically defines a lexicographical ordering for all supported operations.

struct Client : public Comparable<Client>
{
    auto tie() const
    {
        return std::tie(m_a, m_b);
    }

    int m_a = 1;
    int m_b = 2;
};

Client a, b;
b.m_b = 5;

const bool isEqual = (a == b);
const bool isNotEqual = (a != b);
const bool isSmaller = (a < b);
const bool isGreater = (a > b);
const bool isSmallerOrEqual = (a <= b);
const bool isGreaterOrEqual = (a >= b);

Advantage: There is no need anymore to implement many comparison operators by hand for many classes individually. If there are many different classes requiring comparison operators with straightforward semantics this can save quite some code.


texts: Increasing the coefficients of two numbers to sum to a targeted value

texts:
I've naively tried to gradually increase two values so eventually, they sum to a targeted value.

Since this code runs many times and eventually for very large values, I don't know how to optimize so that it doesn't take more than 0.5 seconds.

def coefTargetSum(R, X, Y):
    coefResult = []
    for x in range(R):
        for y in range(R):
            if x * X + y * Y == R:
                coefResult.extend([x, y])
                return coefResult
    return -1


texts: Printing random lines from a file in Python

texts:
Is this the most efficient solution or can the performance be improved? Just opens a file and prints random words (lines with newlines stripped out).

import random

filename = "20k.txt"

def main(filename):
    words_file = open(filename, 'r')

    words = words_file.read().split("\n")
    temp_words = []
    for word in words:
        temp_words.append(word.strip("\r"))
    words = temp_words

    while True:
        length = int(raw_input("Words:"))
        for i in range(0,length):
            print(words[random.randrange(0,len(words)+1)]),
        print("\n")

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


texts: Testing whether today is the second or fourth Saturday of the month

texts:
This is working. Is it ok?

import calendar
from datetime import datetime

def second_fourth_saturday(year):
    holidays = {}
    for month in range(1, 13):
        cal = calendar.monthcalendar(year, month)
        if cal[0][calendar.SATURDAY]:
            holidays[month] = (
                cal[1][calendar.SATURDAY],
                cal[3][calendar.SATURDAY]
            )
        else:
            holidays[month] = (
                cal[2][calendar.SATURDAY],
                cal[4][calendar.SATURDAY]
            )
    return holidays

if __name__ == "__main__":
    today = datetime.today().day
    tomonth = datetime.today().month
    if today in second_fourth_saturday(2019)[tomonth]:
        print("Enjoy")
    else:
        print("Start Working")


texts: Rendition of Project Euler 26 - reciprocal cycles

texts:
This is my solution for problem 26 from Project Euler:

"""Find the value of d < 1000 for which
1/d contains the longest recurring cycle
in its decimal fraction part."""

from timeit import default_timer as timer
import math
from decimal import *

start = timer()

def longestPeriod(n): # define function
    longest = [0, 0] # length, num

    def isPrime(k): # checks if a # is prime
        for x in range(2, int(math.ceil(math.sqrt(k)))):
            if k % x == 0:
            return False
        return True

    def primeFact(k): # returns prime factorization of # in list
        if k <= 1: return []
        prime = next((x for x in range(2,
            int(math.ceil(math.sqrt(k))+1)) if k%x == 0), k)

        return [prime] + primeFact(k//prime)

    def periodIfPrime(k):
        period = 1
        while (10**period - 1) % k != 0:
            period += 1

        return period # returns period of 1/d if d is prime

    def lcm(numbers): # finds lcm of list of #s
        def __gcd(a, b):
            a = int(a)
            b = int(b)
            while b:
                a,b = b,a%b
            return a
        def __lcm(a, b):
            return ( a * b ) / __gcd(a, b)

        return reduce(__lcm, numbers)

    for x in range(3, n): # check all up to d for 1/d

        if all(p == 2 or p == 5 for p in primeFact(x)) == True: # doesn't repeat
            pass

        elif isPrime(x) is True: # run prime function
            if longest[0] < periodIfPrime(x):
                longest = [periodIfPrime(x), x]

        elif len(primeFact(x)) == 2 and primeFact(x)[0] == primeFact(x)[1]:
            if x == 3 or x == 487 or x == 56598313: # exceptions
                period = int(math.sqrt(x))
            else: # square of prime
                period = periodIfPrime(primeFact(x)[0]) * x
                if period > longest:
                    longest = [period, x]

        else:
            fact = primeFact(x)
            periods = []
            for k in fact:
                if k != 2 and k != 5:
                    if fact.count(k) == 1:
                        periods.append(periodIfPrime(k))
                    else:
                        periods.append((periodIfPrime(k)) * k**(fact.count(k) - 1))

            if lcm(periods) > longest[0]:
                longest = [lcm(periods), x]

            return longest

elapsed_time = timer() - start
elapsed_time /= 100 # milliseconds

print "Found %d in %r ms." % (longestPeriod(1000)[1], elapsed_time)

Can it be written in a better way?


texts:
I am getting Out of Memory errors when I try to parse through a large CSV file (2.5Gb). My computer has 32Gb of Memory but Perl uses all of it up. The CSV has 2 columns.  The first is the time in epoch and the second is a 10000+ line XML file as a single-line. There are around 13k rows. I then use XML::XPath to retrieve the customer name and save the XML to [customername]-[time].xml. If there is an error, it is because the XML is invalid and I skip it.

Is there any way to make my code run more efficiently and look better?

#!/usr/bin/perl

use strict;
use warnings;
use XML::XPath;
use XML::XPath::XMLParser;
use File::Slurp;

my $file = '../FILENAME.csv';
open my $info, $file or die "Could not open $file: $!";
my $count = 0;
$| = 1;

while( my $line = <$info>)  {
    next if ++$count == 1; #Ignore headers
    my ($time, $report) = ($line =~ /(\d+),(.*)$/); # time, XML file
    eval {
        my $xp = XML::XPath->new(xml => $report);
        our $ext = $xp->getNodeText('/report/customer') . "-" . $time . ".xml";
        write_file($ext, $report);
    };
    if ( $@ ) {printf "ERROR ";}
    else {printf "$count ";}
}

close $info;


texts: Converting a DropDownList retrieval service to generics or delegate methods

texts:
mappingService below is actually just Automapper. I have a wrapper around it so that I can inject it.

I want to refactor the following code to be cleaner:

 public class DropDownListService : IDropDownListService
{
    private readonly IMappingService _mappingService;
    private readonly ICompanyRepository _companyRepository;
    private readonly IProjectTypeRepository _projectTypeRepository;
    private readonly IStatusRepository _statusRepository;
    private readonly IProjectManagerRepository _projectManagerRepository;
    private readonly IProjectArchitectRepository _projectArchitectRepository;
    private readonly IFeeTypeRepository _feeTypeRepository;
    private readonly IStateRepository _stateRepository;
    private readonly IPersonTypeRepository _personTypeRepository;

    public DropDownListService(IMappingService mappingService, ICompanyRepository companyRepository, IProjectTypeRepository projectTypeRepository, IStatusRepository statusRepository, IProjectManagerRepository projectManagerRepository, IProjectArchitectRepository projectArchitectRepository, IFeeTypeRepository feeTypeRepository, IStateRepository stateRepository, IPersonTypeRepository personTypeRepository)
    {
        _mappingService = mappingService;
        _companyRepository = companyRepository;
        _projectTypeRepository = projectTypeRepository;
        _statusRepository = statusRepository;
        _projectManagerRepository = projectManagerRepository;
        _projectArchitectRepository = projectArchitectRepository;
        _feeTypeRepository = feeTypeRepository;
        _stateRepository = stateRepository;
        _personTypeRepository = personTypeRepository;
    }

    public IEnumerable<IDropDownList> RetrieveCompanies()
    {
        return _mappingService.Map(_companyRepository.GetAll(), new List<Company>());
    }

    public IEnumerable<IDropDownList> RetrieveJobTypes()
    {
        return _mappingService.Map(_projectTypeRepository.GetAll(), new List<ProjectType>());
    }

    public IEnumerable<IDropDownList> RetrieveStatuses()
    {
        return _mappingService.Map(_statusRepository.GetAll(), new List<Status>());
    }

    public IEnumerable<IDropDownList> RetrieveProjectManagers()
    {
        return _mappingService.Map(_projectManagerRepository.GetAll(), new List<ProjectManager>());
    }

    public IEnumerable<IDropDownList> RetrieveProjectArchitects()
    {
        return _mappingService.Map(_projectArchitectRepository.GetAll(), new List<ProjectArchitect>());
    }

    public IEnumerable<IDropDownList> RetrieveFeeTypes()
    {
        return _mappingService.Map(_feeTypeRepository.GetAll(), new List<FeeType>());
    }

    public IEnumerable<IDropDownList> RetrievePhases()
    {
        return _mappingService.Map(_feeTypeRepository.GetAll(), new List<Phase>());
    }

    public IEnumerable<IDropDownList> RetrieveStates()
    {
        return _mappingService.Map(_stateRepository.GetAll(), new List<State>());
    }

    public IEnumerable<IDropDownList> RetrievePeopleTypes()
    {
        return _mappingService.Map(_personTypeRepository.GetAll(), new List<PersonType>());
    }

    public IEnumerable<IDropDownList> RetrieveMarkets()
    {
        return _mappingService.Map(_marketRepostiory.GetAll(), new List<Market>());
    }
}

As you can see I am injecting way too many things into this controller. I am not currently doing a spa application so I cannot do this separately on the presentation layer. What I would really like to do is use generics. The problem is, the DB value that is returned to me looks like this:

    public int StateID { get; set; }
    public string StateName { get; set; }

Each entity has the ID field and the name field only they are named for the table. I am unable to write one map (as far as I know how) with automapper to map them to the correct type.

How can I clean this class up?


texts:
I have a query which selects a show from anime_series, then selects corresponding information from other tables (such as studio, which is stored as a SMALLINT reference to another table). The below query works as intended, but I really don't believe my code is as efficient as it can or should be.

The real complexity is that shows can and often do have multiple genres and studios. I'm current using GROUP_CONCAT on the multiple genres, studio names, and studio links, though I'm not sure this is the best method. I'm using a sub query for the next episode because I only need the first episode that hasn't aired, again, my method is probably over-complicating it.

SELECT
    anime.*,
    episode.number AS episode,
    episode.air_date AS ep_airdate,
    station.name AS station_name,
    station.link AS station_link,
    GROUP_CONCAT(DISTINCT genre.name ORDER BY LOWER(genre.name)) AS genres,
    GROUP_CONCAT(DISTINCT studio.name) AS studio_names,
    GROUP_CONCAT(DISTINCT studio.link) AS studio_links
FROM
    `anime_series` AS anime
LEFT JOIN (
    SELECT
        `air_date`,
        `series`,
        `number`
    FROM
        `anime_episodes`
    WHERE
        `air_date` > NOW()
    GROUP BY `series`) episode
    ON anime.id = episode.series
LEFT JOIN `anime_stations` station
    ON anime.station = station.id
LEFT JOIN `anime_genre_connections`
    ON anime_genre_connections.series_id = anime.id
    JOIN `anime_genres` AS genre
        ON anime_genre_connections.genre_id = genre.id
LEFT JOIN `anime_studio_connections`
    ON anime_studio_connections.series = anime.id
    JOIN `anime_studios` AS studio
        ON anime_studio_connections.studio = studio.id
WHERE anime.id = 1
GROUP BY anime.id;

Here's some table examples (anime_series missing irrelevant columns):

anime_series
id | station
 1 |    1

anime_stations
id |     name     |        link
 1 | Something TV | http://example.com

anime_episodes
id | series |       air_date      | number
 1 |   1    | 2013-07-09 01:00:00 |   1
 2 |   1    | 2013-07-16 01:00:00 |   2

anime_genre_connections
id | series_id | genre_id
 1 |     1     |    1
 2 |     1     |    2

anime_genres
id |   name
 1 |  Comedy
 2 |  Action

anime_studio_connections
id | series | studio
 1 |    1   |    1
 2 |    1   |    2

anime_studios
id |      name    |       link
 1 |  Example     | http://example.com
 2 |  Some Studio | http://example.com

EDIT: I should also add that I'm splitting the returned columns genres, studio_names, and studio_links into arrays after the query has executed.


texts:
I have been woring on AJAX and JQuery site. Here is my simple implemtation. i am looking forward to getting your reviews for any improvement/replacement for code mentioned below.

  Brief explanation: when someone want to submit the form with specified ID, all form fields are assigned to appropriate variables. After that a new JSON document is generated based on the form field variables. Then AJAX call is performed. It directed to URL which is specified in the action attribute of form tag. The JSON is used as a data which need to be processed. Type of the request is POST (it can vary depending on operation, e.g. for update it will has PUT value).

        <input name="search" type="text" maxlength="100" id="search"/>

        <button onclick="searchID()"> Search ID </button>
        <button onclick="getAll()"> Get All </button>

 Id: <input name="search" type="text" maxlength="100" id="userId"/>

 First name: <input name="search" type="text" maxlength="100" id="fName"/>

 Last name: <input name="search" type="text" maxlength="100" id="lName"/>

        <button onclick="save()"> Save </button>


texts:
Running Office 2007, I have master workbook with data, which I:

Split master sheet data to new sheets for every salesmen
Create new workbook (with 1 sheet)
Put sheets of salesmen to an array according their manager
Copy array of sheets to new workbook
Delete first sheet on newly created workbook, save it as .xlsx and close

My problem is that it takes more time than I expect, around 8 seconds for one group of salesmen (there are 6 at the end) - altogether with formatting before splitting master sheet data around 60 seconds. I think there is problem in my code and with how Excel manages how and how much RAM it uses.

Master data workbook has 21 MB, .xls format
When I open it, it uses 50 MB of RAM
Then when I run code with some formatting etc it grows to 80 MB
Then I start splitting, where it slowly grows to  87, 95, 103, 110, 125, 132 and then finally to 160 MB, where it copies sheets and close new workbook, then again Excel uses 95 MB of RAM. Merging process creates 6 new workbooks with size from 0.6 to 1.8 MB, where these workbooks contain from 6 to 10 sheets.

Dim wb1 As Workbook, group As Variant, new_wb As Workbook

With Application
    .EnableEvents = False
    .ScreenUpdating = False
    .StatusBar = "Merging .."
End With

Set wb1 = ActiveWorkbook
'
'some formatting on master sheet, splitting to sheets
'adding sheets to an array called "group"
'for every manager do ..
'
Set new_wb = Workbooks.Add(xlWBATWorksheet)
With new_wb
    wb1.Sheets(group).Copy After:=.Sheets(1)
Application.DisplayAlerts = False
    .Sheets(1).Delete
Application.DisplayAlerts = True
.SaveAs C:\ & <name of manager from group> & ".xlsx", FileFormat:=51, .Close
End With

With Application
    .EnableEvents = True
    .ScreenUpdating = True
    .StatusBar = False
End With

However, when I prepared my workbook to the step when copying occurs, and run just one line of code:

wb1.Sheets(Array("Sheet1", "Sheet2","Sheet3","Sheet4")).Copy After:=.Sheets(1)

This way it, copies sheets almost instantly to new a workbook.

I'm not sure what I'm doing wrong. What is the proper way how to copy (Excel/RAM friendly) an array of sheets to a new workbook?

When I run this one line of code, it too uses 160 MB of RAM, only this way it takes enough RAM immediately, not slowly growing more and more.


texts:
I'd originally not copied the result vector to vec which I figured and corrected. Iis there a better way to implement the merge sort other than the approach I've taken?

template<typename T> void merge(std::vector<T> &vec, int left, int mid, int right )
{
    int i=left;
    int j=mid+1;
    int k=0;
    int size = (right - left) +1;
    std::vector<T> result(size);

    while(i <= mid && j <= right)  result[k++] = (vec[i] < vec[j])? vec[i++] : vec[j++];
    while(i <= mid)                result[k++] = vec[i++];
    while(j <= right)              result[k++] = vec[j++];

    for(k=0; k < size; k++)
    {
        vec[left+k] = result[k];
    }
}

template<typename T> void mergeSort(std::vector<T> &vec, int left, int right)
{
    // Base Case --- Left is greater than right, then don't execute.

    if (left<right){

        // get mid point.
        int mid = left + (right-left)/2 ;
        // recursive merge sort until array(half) is 1 in length.
        mergeSort(vec, left, mid);
        mergeSort(vec, mid+1, right);
        // merge both arrays.
        merge(vec, left, mid, right);
    }
}

main():

int main()
{
    vector<int> v{14,3,2,5,10};
    //bubbleSort(v);
    //selectionSort(v);
    mergeSort(v, 0, v.size()-1);
    printVec(v);

    return 0;
}

I'm trying to figure out space optimization considerations. Currently, the space is \$O(N)\$ (since I'm creating a resultant array in merge which creates a max size of N? Please correct me if I'm wrong here.)


texts:
In my project, I have this kind of code to test my controllers:

#encoding=utf-8
require 'spec_helper'

describe ProjectsController do
  let!(:project) { build_stubbed(:project, user: user) }
  let(:user) { build_stubbed(:user) }

  before(:each) { sign_in user }

  describe "GET 'index'" do
    it "render index template" do
      get 'index'
      should render_template('index')
    end
  end

  describe "GET 'show'" do
    let!(:comment) { build_stubbed(:comment) }

    before(:each) { Project.stubs(:find).returns(project) }

    it "render show template" do
      get 'show', id: project.id
      should render_template('show')
    end

    it "create a new comment" do
      Comment.expects(:new).returns(comment)
      get 'show', id: project.id
    end
  end

  describe "GET 'new'" do
    it "render new template" do
      get 'new'
      should render_template('new')
    end
  end

  describe "POST 'create'" do
    before(:each) do
      Project.stubs(:new).returns(project)
    end

    context "with valid data" do
      before(:each) { project.stubs(:save).returns(true) }

      it "redirect to project's path" do
        post 'create'
        should redirect_to(project)
      end

      it "save the project" do
        lambda do
          post 'create'
        end.should change(user.projects, :size).by(1)
      end

      it "set a flash message" do
        post 'create'
        should set_the_flash[:notice].to("Votre projet a été ajouté")
      end
    end

    context "with invalid data" do
      before(:each) { project.stubs(:save).returns(false) }

      it "render new template" do
        post 'create'
        should render_template('new')
      end
    end
  end

  describe "GET 'edit'" do
    before(:each) do
      Project.stubs(:find).returns(project)
    end

    it "render edit template" do
      get 'edit', id: project.id
      should render_template('edit')
    end
  end

  describe "POST 'update'" do
    before(:each) do
      Project.stubs(:find).returns(project)
    end

    context "when valid" do
      before(:each) { project.stubs(:update_attributes).returns(true) }

      it "redirect to project's path" do
        post 'update', id: project.id
        should redirect_to(project)
      end

      it "update the project" do
        project.expects(:update_attributes)
        post 'update', id: project.id
      end

      it "set a flash message" do
        post 'update', id: project.id
        should set_the_flash[:notice].to("Votre projet a été modifié")
      end
    end

    context "when invalid" do
      before(:each) { project.stubs(:update_attributes).returns(false) }

      it "render edit template" do
        post 'update', id: project.id
        should render_template('edit')
      end
    end
  end

  describe "DELETE 'destroy'" do
    before(:each) do
      Project.stubs(:find).returns(project)
      project.stubs(:destroy)
    end

    it "redirect to project's path" do
      delete 'destroy', id: project.id
      should redirect_to(root_path)
    end

    it "delete the project" do
      project.expects(:destroy)
      delete 'destroy', id: project.id
    end

    it "set a flash message" do
      delete 'destroy', id: project.id
      should set_the_flash[:notice].to("Votre projet a été supprimé")
    end
  end
end

I do this for:

Isolate my tests: I don't want to retest the model and I don't want to hit the database. It's faster.
Test all actions that should be do by the controller

And I have these questions:

Should I test the assignments or is to long for nothing?
How should I to stub my models? Is it better to place all stubs in a global before(:each) like this?

...
before(:each) do
  sign_in user
  Project.stubs(:find).returns(project)
  Project.stubs(:new).returns(project)
  project.stubs(:destroy)
end
...

It's DRYer and cleaner but less efficient.
Should I really isolate my tests? I tested it without stubs and I lose 10 seconds. What do you think about that?


texts:
Here is an implementation of Conway's Game of Life. My code is working fine but I want you to review and give me your suggestions of how to improve it.

These are the steps of my code:

Initialize the grid cells with zeros (all cells are dead at the start)
Then randomly change some of the grid cells to one (bring some cells to life)
Draw the grid
Update the grid, by checking which cells are going to live or die
Go to step 3

gameOfLife.h

#ifndef GAME_OF_LIFE_H
#define GAME_OF_LIFE_H

#include <vector>
#include <random>

class gameOfLife
{
public:
    typedef std::vector< std::vector<int>> gridVector;

private:
    int gridSize;
    gridVector mainGrid;
    gridVector *gridCopy;

public:
    gameOfLife();

public:
    void run();
    void initGrid();
    void drawGrid();
    void updateGrid();
    void copyGrid ();
    int checkNeighbors(gridVector *grid, int x, int y);
    void nextGeneration(int x, int y, int lod);
    int randGenerate(int start, int end);

private:
    std::random_device randDevice;
    std::mt19937 gen;
};

#endif

implementation.cpp

#include <iostream>
#include "gameOfLife.h";

gameOfLife::gameOfLife() : gridSize(15), gen(randDevice())
{
}

void gameOfLife::initGrid()
{
    for(int i = 0; i < gridSize; i++)
    {
        for(int j = 0; j < gridSize; j++)
        {
            mainGrid[i].push_back(0);
        }
    }

    for(int i = 1; i < gridSize ; i++)
    {
        for(int j = 1; j < gridSize ; j++)
        {
            int randSize     = randGenerate(2 , gridSize);
            int state       = randGenerate(0 , 2);
            int indexRow    = randGenerate(1, randSize );
            int indexColumn = randGenerate(1, randSize );

            mainGrid[indexColumn][indexRow] = state;
        }
    }
}

int gameOfLife::randGenerate(int start, int end)
{
        std::uniform_int_distribution<int> genenNum(start, end - 1);

        return genenNum(gen);
}

void gameOfLife::drawGrid()
{
    char ch = 254;
    for(int i = 1; i < gridSize - 1; i++)
    {
        for(int j = 1; j < gridSize - 1; j++)
        {

                if(mainGrid[i][j])
                {
                    std::cout << " "<<ch;
                }
                else
                {
                    std::cout << "  ";
                }

        }
        std::cout<<std::endl;
    }
}

void gameOfLife::copyGrid ()
{
    gridCopy = &mainGrid;
    (*gridCopy).resize(gridSize);
}

void gameOfLife::updateGrid()
{
    copyGrid();

    for(int i = 1; i < gridSize - 1 ; i++)
    {
        for(int j = 1; j < gridSize - 1; j++)
        {
            int lod = checkNeighbors(gridCopy, i, j);
            nextGeneration( i, j, lod);

        }

    }
}

int gameOfLife::checkNeighbors(gridVector *gridCopy, int x, int y)
{
    int lod = 0;
     for(int i = -1; i < 2; i++)
     {
         for(int j = -1; j < 2; j++)
         {
             if(!(i == 0 && j == 0))
             {
                 if((*gridCopy)[ x + i ][ y + j ])
                 {
                     lod++;
                 }
             }
         }
     }

     return lod;
}

void gameOfLife::nextGeneration(int x, int y, int lod)
{
    if(lod < 2)
    {
        mainGrid[x][y] = 0;
    }
    else if(lod == 3)
    {
        mainGrid[x][y] = 1;
    }
    else if(lod > 3)
    {
        mainGrid[x][y] = 0;
    }
}

void gameOfLife::run()
{
    mainGrid.resize(gridSize);

    initGrid();

    while(true)
    {
        drawGrid();
        updateGrid();
        system("cls");
    }
}

int main()
{
    gameOfLife gol;
    gol.run();

    std::cin.get();

    return 0;
}


texts: Function for setting a streak of strings in a Pandas

texts:
I have a df with artist names in one column, I want to find how many times the artists repeats through the column.

Example:

df = pd.DataFrame({"Artist":["Tim Maia","Jorge Ben","Tim Maia",
                             "Tim Maia","Jorge Ben","Roberto Carlos",
                             "Roberto Carlos","Roberto Carlos",
                             "Roberto Carlos",
                             "Dire Straits"]})

I've already had some success using itertuples(), so that was my starting point for this function:

def artist_streak(df):
    # created to check if artists repeats, not returned
    artists = []
    # this will be returned
    streaks = []
    # since each observation counts, makes sense to start at 1
    count=1

    for row in df.itertuples():
        # artists[-1] in an empty list will raise IndexError:
        try:
            # Checking if current artist is the same as the last appended
            if artists[-1] == row.Artist:
                    count += 1
                    artists.append(row.Artist)
                    streaks.append(count)
            else:
                # The artist does not repeated
                count = 1
                artists.append(row.Artist)
                streaks.append(count)
        # Here we set things right for the first iteration
        except IndexError:
            artists.append(row.Artist)
            streaks.append(count)

    return streaks

Usage:

df["Result"] = artist_streak(df)

My concerns about this code are:

1. The artists list [ ]:

It is the way I could think of checking the current iterator item vs. the previous one, I don't know if it is a good way.

2. The try/except part:

As it addresses the specific case of list artists being empty, I don't know if it hurts performance (i.e. there is a faster way to do it).

Any other suggestions on how to make it faster, cleaner, or even pythonic will be welcome.


texts:
def smoothen(heightProfile, travelTime):
    newHeightProfile = []

    # Berechne einen gleitenden Mittelwert
    smoothingInterval = 30 * travelTime

    for i in xrange(smoothingInterval):
        heightProfile.append(heightProfile[-1])

    for i in xrange(len(heightProfile) - smoothingInterval):
        mean = 0
        for j in xrange(i, i + smoothingInterval):
            mean += heightProfile[j]
        newHeightProfile.append(mean/smoothingInterval)

    return newHeightProfile

Input:

heightProfile: an array of the size travelTime * 60
travelTime: an integer

travelTime can be, for example, 500. heightProfile contains an array of random numbers of the size travelTime * 60. The height profile should describe the height of a random landscape. The function is used to smoothen the values.

However, this code is very slow and expensive, even when using xrange:

Tests for travel time: 500
CPython: 38.3s
Pypy: 0.98s

Questions:

Is there a construct in this code which is very inefficient?
Would this be faster if I were to implement this function in C?

Any other recommendations for improvement are welcome.


texts: Number of Chocolates to Gluttonize in Clojure

texts:
I’ve been dabbling in Clojure by solving programming puzzles. This particular puzzle is from HackerRank, with the objective of figuring out how much chocolate one could eat given three parameters:

The cost of a piece of chocolate
How much money you have
The candy shop owner will give you a free chocolate for x number of wrappers

In the code below, those three numbers are passed to total-chocolates-consumed which returns the answer.

(ns hr.clojure.algorithms.implementation.implementation.chocolate-feast)

(defn int-division
  [numerator denominator]
  (->>
    (/ numerator denominator)
    int))

(defn number-to-purchase
  [totalToSpend costPerChocolate]
  (int-division
    totalToSpend
    costPerChocolate))

(defn number-of-freebies
  [totalWrappers wrappersPerFreebie]
  [(int-division
    totalWrappers
    wrappersPerFreebie)
   (int
     (mod
       totalWrappers
       wrappersPerFreebie))])

(defn total-chocolates-consumed
  [totalToSpend
   costPerChocolate
   wrappersPerFreebie]
   (let [purchasedChocolates (number-to-purchase totalToSpend costPerChocolate)
         freebies (first (number-of-freebies purchasedChocolates wrappersPerFreebie))
         totalChocolates [purchasedChocolates freebies]
         startRemainder (second (number-of-freebies purchasedChocolates wrappersPerFreebie))]
         (loop
           [chocs totalChocolates
            remainder startRemainder]
           (cond
            (> wrappersPerFreebie (+ remainder (last chocs)))
               (reduce + chocs)
             :else
              (recur
                (conj chocs (first (number-of-freebies (+ (last chocs) remainder) wrappersPerFreebie)))
                (second (number-of-freebies (+ (last chocs) remainder) wrappersPerFreebie)))))))

I've written tests for this code here:

(ns hr.clojure.algorithms.implementation.implementation.chocolate-feast.spec)

(load-file "YOUR-PATH-TO-FILE")
(use 'hr.clojure.algorithms.implementation.implementation.chocolate-feast)
(use 'clojure.test)

(deftest chocolate-feast
  (testing "number-to-purchase"
    (is (= 0 (number-to-purchase 2 10)))
    (is (= 2 (number-to-purchase 10 4)))
    (is (= 666 (number-to-purchase 1000 1.5)))
    (is (= 3 (number-to-purchase 6 2)))
    (is (= 5291 (number-to-purchase 10000 1.89))))
  (testing "number-of-freebies"
    (is (= [0 1] (number-of-freebies 1 2)))
    (is (= [100 0] (number-of-freebies 100 1)))
    (is (= [2 0] (number-of-freebies 3 1.5)))
    (is (= [1 1] (number-of-freebies 3 2))))
  (testing "total-chocolates-consumed"
    (is (= 6 (total-chocolates-consumed 10 2 5)))
    (is (= 3 (total-chocolates-consumed 12 4 4)))
    (is (= 5 (total-chocolates-consumed 6 2 2)))
    (is (= 899 (total-chocolates-consumed 43203 60 5)))))

(deftest math-library
  (testing "int-division"
    (is (= 0 (int-division 7 12)))
    (is (= 2 (int-division 12 6)))
    (is (= 2 (int-division 12 5)))))

(run-tests)

General Questions

Is this how tests are written in Clojure?
Is the code readable? Can you tell what I was thinking?

How idiomatic is my code?

Should I use camel case for parameter names?
Should I hyphenate my function names?
Is this “waterfall” sort of formatting typical?

What is a good way to communicate what a function does?

For instance, number-of-freebies returns a vector of [chocolates earned with wrappers, wrappers leftover]. Could I return a type that actually indicates what those values are to the consumer of that function?

How do I refactor total-chocolates-consumed to be less complex?

There is some redundant code in there for figuring the number of freebies, could I pull that out into a local value within the loop?
Should I be using a loop or some higher-order function?


texts: Finding optimal row sequence for a melody on 5-row Bayan Accordion, v2.0

texts:
Another try at this problem in LISP. This time rather than generating every possible row combination for the melody I tried to calculate the best combination directly. Unfortunately there's a problem - the output is a messy list full of vectors and single values. Is there a good way to concatenate vectors together with value between them?

(proclaim '(type (vector (vector symbol 4) 3) *rows*))
(defparameter *rows* #( #(:c :ds :fs :a) #(:cs :e :g :as) #(:d :f :gs :b)))

(defun row-for-note (note)
  (declare (symbol note))
  "Returns the lower row on which a note is played."
  (position-if (lambda (row) (find note row)) *rows*))

(defun equivalent-row (row)
  (declare (fixnum row))
  "Returns the equivalent upper row to a given lower row."
  (case row (1 -2) (2 -1) (0 0)))

(defun rows-for-notelist (notelist)
  (declare ((vector symbol) notelist))
  "Returns the sequence of lower rows on which a sequence of notes are played."
  (map 'vector #'row-for-note notelist))

(defun flip-sequence (rowlist)
  (declare ((vector fixnum) notelist))
  "Returns the sequence of upper rows equivalent to a sequence of lower rows."
  (map 'vector #'equivalent-row rowlist))

(defun vector-last (thevec)
  (declare (vector thevec))
  "Returns the last element of a vector."
  (elt thevec (- (length thevec) 1)))

(defun vector-first (thevec)
  (declare (vector thevec))
  "Returns the first element of a vector."
  (elt thevec 0))

(defun should-flip-block (rowlist)
  (declare ((vector fixnum) rowlist))
  "Determines if a sequence of rows starts and ends on row 2 or not."
  "These sequences are more easily played on upper rows because they will then start and end on row -1."
  (if (= (length rowlist) 0) nil
    (let* ((exithigh (= (vector-last rowlist) 2))
           (enterhigh (= (vector-first rowlist) 2)))
      (and exithigh enterhigh))))

(defun flip-block-if-should (rowlist)
  (declare ((vector number) rowlist))
  (if (should-flip-block rowlist) (flip-sequence rowlist) (eval rowlist)))

(defun optimal-sequence (notelist)
  (declare ((vector symbol) notelist))
  (let* ((baserows (rows-for-notelist notelist))
         (blocks (split-sequence '(0) baserows))
         (flipped (mapcar #'flip-block-if-should blocks)))
    (loop for x in flipped collect x collect 0)))


texts: Print exact value represented by float in [0,1)


texts: A function which translates a sentence to title-case

texts:
The task is to write a JavaScript-function which translates a given blank-separated sentence to title-case.

Means that all words shall start with a capital and then the rest of the word in lower-case. But: A certain, specified set of conjunctions, preposition as well as article shall be all lower-case.

Example: "The second of the four items." becomes "The Second of the Four Items.".

Here's my implementation of such a function:

function translateToTitleCase(str) {
  const translateWord = (sWord) => {
    return sWord.slice(0, 1).toUpperCase() + sWord.slice(1).toLowerCase();
  }

  const words = str.split(" ");

  words[0] = translateWord(words[0]);

  for (let i = 1; i < words.length; i++) {
    if (!["of", "and", "the", "to"].includes(words[i].toLowerCase())) {
      words[i] = translateWord(words[i]);
    } else {
      words[i] = words[i].toLowerCase(); // Make sure is's the correct case, when the sentence (or parts of it) is given in uppercase.
    }
  }

  return words.join(" ");
}

// -- Examples -------------------------------------------------------------------------------
console.log(translateToTitleCase("Into unmerciful the entreating stronger to of word guessing."));
console.log(translateToTitleCase("the OLD MAN aND THE sEa"));

I think my coding is still a bit "noisy" with the usage of all those brackets, chained methods and concatenation.

Any ideas about how to improve my implementation?

Perhaps some cool new ES6-feature I wasn't aware of.

What would you have done differently and why?


texts: Text Snipper WordPress Plugin in JavaScript

texts:
I am making a text snipper plugin for WordPress. Basically, I want it to truncate multiline text that overflows the height of its container and add "...". My code works for direct child elements, too. It is also responsive and keeps working based on window resize.

However, I'm worried that my method might be too much of a resource hog. To snip the text, I continuously set the text equal to itself - 1 character until the overflow stops. Is this an efficient way of doing this?

snipClass is a variable passed from the WordPress plugin. It's just an HTML class to run Text Snipper on. I notice that, especially on window resize, the response is kind of sluggish, but I'm not sure how else I could pull this off. I suppose doing intervals of three characters to snip instead of 1 would lighten the task load, but I want this to be as precise as possible.

(function($) {

    function trimText (el, wrapper) {
        //If there is text in this element, and there is still overflow, trim this element's text
        if ( el.text() != "" && wrapper.clientHeight < wrapper.scrollHeight ) {
            el.text( function (key, string) {
                return string.substring(0, string.length - 1);
            });

            trimText(el, wrapper);
        } else {
            return false;
        }
    }

    function prepareSnipText (first, originalText) {

            $('.' + snipClass).each( function (key) {

                if (first) {
                    originalText.push($(this).html());
                } else {
                    $(this).html(originalText[key]);
                }
                var wrapper = this;

                //Trim text
                if ( wrapper.clientHeight < wrapper.scrollHeight) {
                    //Handle child elements
                    if ($(this).children().length > 0) {
                        $(this).children().reverse().each( function () {
                            trimText($(this), wrapper);
                         });
                    //Handle elements with no children
                    } else {
                        trimText($(this), wrapper);
                    }
                }
                //Add '...'
                if ($(this).children().length > 0) {
                    $(this).children().reverse().each( function () {
                        var isNotEmpty = checkEmpty($(this));
                        if (isNotEmpty) {
                            $(this).text($(this).text().substring(0, $(this).text().length - 3) + '...');
                            return false;
                        }
                     });
                } else {
                    $(this).text($(this).text().substring(0, $(this).text().length - 3) + '...');
                }

        });
    }

    function checkEmpty (el) {
        if (el.text() != "") { return true; } else { return false; }
    }

    //http://www.mail-archive.com/discuss@jquery.com/msg04261.html
    jQuery.fn.reverse = [].reverse;

    $(document).ready( function() {

        if (  $('.' + snipClass).length > 0 ) {

            var originalText = [];

            prepareSnipText(true, originalText);

            // Responsive - trim text again for smaller window, or readd HTML for larger, then snip again
            $(window).resize( function () {
                prepareSnipText(false, originalText);
            });

        }
    });

}(jQuery));


texts: One-way flight trip implementation in Python

texts:
I came across the following problem (found on the SO link below):
https://stackoverflow.com/questions/2991950/one-way-flight-trip-problem

  Given a flight trip that includes a number of transfers: we have a
  ticket for each part of the trip; we do not stop twice in the same
  airport; each ticket contains source and destination airport; all the
  tickets we have are randomly sorted, and we forgot the original
  departure airport and the last destination. We want to design an
  algorithm to reconstruct the trip with minimum big-O complexity.

I tried to solve the problem in python in O(n) time complexity. Here is my solution:

L = [('A', 'B'), ('B', 'C'), ('C', 'D'), ('D', 'E'), ('E', 'F'), ('F', 'G'), ('G', 'H'), ('H', 'I')]
# Note: the input L should normally be shuffled.

def getDepartureArrival(L):
    sources, destinations = zip(*L)
    sources = set(sources)
    destinations = set(destinations)

    for s in sources:
        if s not in destinations:
            depart = s
            break
    for d in destinations:
        if d not in sources:
            arriv = d
            break
    return depart, arriv
#

def getTrip(H):
    trip = [depart]
    k = depart
    while k != arriv:
        k = H[k]
        trip.append(k)
    return trip
#

depart, arriv = getDepartureArrival(L)
H = {s:d for (s,d) in L}
print getTrip(H)

I would like to know if it is possible to have a clearer and more compact Python code than the one I wrote with more than 4 consecutive loops.


texts: jQuery code for displaying server status from XML feed

texts:
I am using the below jQuery and HTML to read in and use an XML server status feed for a server widget. This is the code:

XML Feed:

<status>


texts:
I am just getting a little more comfortable with Bash.
I wanted a super simple log function to write to a file and output to the console for messages and errors. I also wanted the terminal and the file to interpret newline characters rather than printing them out.
Here is what I came up with (it works fine):
#!/bin/bash

log () {
  if [[ "$3" == '-e' || "$3" == '--error' ]]; then
    >&2 echo -e "ERROR: $1" && printf "ERROR: $1\n" >> "$2"
  else
    echo -e "$1" && printf "$1\n" >> "$2"
  fi
}

# Example implementation
log_file=snip/init.log
msg="\nthis is an error message with leading newline character"
log "$msg" $log_file -e
msg="this is success message with no newline characters"
log "$msg" $log_file

I don't need any more functionality however I have some questions:

Is an efficient and readable piece of code that won't break when passed strings with special characters?
Syntactically, could I have done this 'better' such as using pipes instead of &&. tee instead of printf etc.?
How can I refactor this code to allow for the optional -e flag to be passed in first?


texts: JavaScript queue implementation using linked list

texts:
Are there better ways of modularizing the code? Does it contain things JavaScript experts would avoid? Is it idiomatic? Is there a better way of signaling an empty queue than returning null?

function makeQueue () {
  // types
  let Node = {
    next : null,
    data : null
  };

  // data
  let head = null;
  let size = 0;

  // methods
  function enqueue(x) {
    let newNode = {...Node, next : head, data : x};
    head = newNode;
    size++;
  }

  function dequeue() {
    if (size === 0) {
      return null;
    }

    let x = head.data;
    head = head.next;
    size--;

    return x;
  }

  function getSize() {
    return size;
  };

  // public
  return {
    enqueue : enqueue,
    dequeue : dequeue,
    getSize : getSize
  };
};


texts: Scraping IMDB and exporting to JSON or/and CSV

texts:
This code is scraping the data from IMDB and displays it in JSON or CSV format.

I plan to extend it beyond the top rated movies. How can I improve the quality of my code? I am using Python 3.7.3.

from bs4 import BeautifulSoup
import requests
import csv
import json
import codecs

films = []

def getFilms250():
    sourceTop250 = requests.get(
        'https://www.imdb.com/chart/top?ref_=nv_mv_250').text
    soup = BeautifulSoup(sourceTop250, 'lxml')
    counter = 0
    for title_container, rating_container in zip(soup.find_all('td', class_='titleColumn'),soup.findAll('td', class_='ratingColumn imdbRating')):
        title = title_container.a.text
        counter += 1
        year = title_container.span.text
        rating = rating_container.strong.text
        film_data = [counter, title, year.strip('()'), rating]
        films.append(film_data)
    return films

def csvFormat(films, userDelimiter):
    with open('new_film_base.csv', 'w', newline='') as file:
        header = ['Position', 'Title', 'Year', 'imdbRanking']
        film_writer = csv.writer(file, delimiter=userDelimiter)
        film_writer.writerow(header)
        film_writer.writerows(films)
    file.close

def jsonFormat(films):
    with open('new_film_base.json', 'w', encoding='utf8') as file:
        arr = []
        for i in films:
            x = {
                "position": i[0],
                "title": i[1],
                "year": i[2],
                "imbdRanking": i[3]
            }
            arr.append(x)
        movies = {
            "filmsRequested": arr
        }
        json.dump(movies, file, indent=True, ensure_ascii=False)
    file.close

def handleUserFilm(prompt):
    #While user enters a proper input a function will get list of wanted films
    while True:
        try:
            userMessageFilm = input((prompt))
        except ValueError:
            print('Input unkown')
        if userMessageFilm == 'films250':
            getFilms250()
            break
        elif userMessageFilm != 'films250':
            print('No such data')
            continue
    return userMessageFilm

def handleUserFormat(prompt):
    while True:
        try:
            userMessageFormat = input((prompt))
        except ValueError:
            print('Input unkown')
            continue
        if userMessageFormat != 'csv' and userMessageFormat != 'json':
            print('Format unkown')
            continue
        elif userMessageFormat == 'json':
            jsonFormat(films)
            break
        elif userMessageFormat == 'csv':
            while True:
                delimiter = input(
                    'Enter the Delimiter for csv format(";" recommended): ')
                if len(delimiter) > 4:
                    print("delimiter can't be that long")
                    continue
                else:
                    csvFormat(films, delimiter)
                    break

        return userMessageFormat

filmsUser = handleUserFilm('To get Top250 type - films250: ')
formats = handleUserFormat('To get csv format type - csv\nTo get json format type - json ')


texts:
Below is an implementation of a React app printing list. Are there any areas of improvement/suggestions in below code base

  class ListElement extends React.PureComponent {
   render() {
       return
 this.props.handleClick(this.props.index)}>{this.props.item.text}
;
   }
}

class ListComponent extends React.Component {

       handleClick(index) {
           this.props.onClick(index);
       }

       render() {
           const listDetails = this.props.listDetails;
           let height,width;
           if (listDetails.hasOwnProperty("size")) {
               height = listDetails.size.height;
               width = listDetails.size.width;
           }
           return (

                   {this.props.items.map((item, i) => <ListElement item={item} key={i} index={i} handleClick={this.handleClick.bind(this)}/>)}

           );
       }
    }

    ListComponent.propTypes = {
       items: PropTypes.arrayOf(PropTypes.shape({
           text: PropTypes.string.isRequired
       })).isRequired,
       listDetails: PropTypes.object.isRequired
    };


texts: Visitor pattern, Extensible visitor for custom implementation

texts:
I'm writing my own expression tree system, just for fun, but I have a few doubts about my code.
My goal here is to create an abstract layer of expressions, and allow different "languages" to extend it.

For example, those are my base components :
//Base expression class for all expressions in every domain
public abstract class Expression
{
    public void Accept(Visitor visitor)
    {
        visitor.Visit(this);
    }
}

//Base left-right (binary) expression class for all binary expressions in every domain
public abstract class BinaryExpression : Expression
{
    protected BinaryExpression(Expression left,Expression right)
    {
        Left = left;
        Right = right;
    }

    public Expression Left { get; }
    public Expression Right { get; }
}

//Base assignment expression (x <= y) class for all assignment expressions in every domain
public abstract class AssignmentExpression : BinaryExpression
{
    protected AssignmentExpression(Expression destination,Expression source)
        : base(destination,source)
    {
        Destination = destination;
        Source = source;
    }

    public Expression Destination { get; }
    public Expression Source { get; }
}

//The visitor class who can visit expressions
public abstract class Visitor
{
    public abstract void Visit(Expression expression);
}

And I have two languages using the definitions above.
Language A :
//The LangA visitor
public class LangAVisitor : Visitor
{
    public void Visit(LangAMoveExpression expression)
    {
        Debug.WriteLine("LangAMoveExpression");
    }

    public override void Visit(Expression expression)
    {
        Debug.WriteLine("LangAExpression");
        Visit((dynamic)expression);
    }
}

//Language A assignment expression (known for this language as move)
public class LangAMoveExpression : AssignmentExpression
{
    public LangAMoveExpression(Expression destination,Expression source)
        : base(destination,source)
    {

    }
}

//Just an empty expression
public class LangAEmptyExpression : Expression
{

}

And Language B :
//The LangB visitor
public class LangBVisitor : Visitor
{
    public void Visit(LangBStoreExpression expression)
    {
        Debug.WriteLine("LangBStoreExpression");
    }

    public override void Visit(Expression expression)
    {
        Debug.WriteLine("LangBExpression");
        Visit((dynamic)expression);
    }
}

//Language B assignment expression (known for this language as store)
public class LangBStoreExpression : AssignmentExpression
{
    public LangBStoreExpression(Expression destination,Expression source)
        : base(destination,source)
    {

    }
}

//Just an empty expression
public class LangBEmptyExpression : Expression
{

}

Execution Example :
void Main()
{
    Execute(new LangAVisitor(),new LangAMoveExpression(new LangAEmptyExpression(),new LangAEmptyExpression()));
    Execute(new LangBVisitor(),new LangBStoreExpression(new LangBEmptyExpression(),new LangBEmptyExpression()));
}

void Execute(Visitor visitor,params Expression[] expressions)
{
    foreach(var expression in expressions)
    {
        expression.Accept(visitor);
    }
}

I am able to get the desired output I want thanks to the code supplied, but I really don't like the dynamic casting approach, is there any way I can implement this better?
Also, i need to keep the executing as generic as possible.
Many doubts came to me when placing the public void Accept(Visitor visitor) in the base Expression class, should it even be there?
How extensible is this code ?Is it well architecture for any upcoming extensions ?

Thanks in advance !


texts: Euclid's algorithm GCD finder and fraction simplifier

texts:
This program is a practise exercise in using instance methods, and also in recursion which I struggle to get my head around. I want to know how my technique for the recursion could be improved, and if there's anything else which could be made more efficient.

The program creates a Rational object type (a fraction) which has numerator and denominator variables. It runs a method to find the greatest common divisor using Euclid's algorithm, and then prints the simplified form of the fraction.

Any feedback is helpful, but things I'm interested in:

Is there a more efficient way for me to take the two integers of input (which may both be positive or negative and in any size order) and turn them into two positive integers with the largest first? The if/else section I've used feels excessively big for the simplicity of the task but I couldn't think of another way.
Is there a way that I could combine the getGcd and reduce methods into a single method? I couldn't work out how to make a method where a subsection of it is recursive but the rest isn't.
Is there anything that could be improved about my recursive Euclid's algorithm bit? It's pretty simple but I wonder if I missed any tricks to make it extra efficient.

Code:

public class Rational {

public static void main(String[] args) {

    Rational test = new Rational(-462, 1071);
    System.out.println(test.reduce());

}

private int nume;
private int deno;

public Rational(int nume, int deno) {
    this.nume = nume;
    this.deno = deno;
}

public String toString() {
    return this.nume + "/" + this.deno;
}

public Rational reduce() {
    int gcd = this.getGcd();
    return new Rational(this.nume / gcd, this.deno / gcd);
}

public int getGcd() {

    // Set up variables
    int a;
    int b;
    int gcd;
    if (Math.abs(this.nume) > Math.abs(this.deno)) {
        a = Math.abs(this.nume);
        b = Math.abs(this.deno);
    } else {
        a = Math.abs(this.deno);
        b = Math.abs(this.nume);
    }

    // Euclid's algorithm
    if (a%b == 0) {
        gcd =  b;
        return gcd;
    } else {
        gcd = new Rational(b, a%b).getGcd();
        return gcd;
    }

}

}


texts:
I'm starting to learn the object oriented aspect of PHP. In this regard I made a small "exercise" of sorts "translating" one of my PHP functions into OO mode of PHP. I'm asking if there are there any recommendations you can give me concerning my predicament.

Example of non-OO PHP:

<?php
function pristup($servername, $username, $password, $dbname, $sql){

    $conn=new mysqli($servername, $username, $password, $dbname);

    if($conn->connect_error){

        die("Neuspela konekcija: ".$conn->connect_error);

    }

    $result = $conn->query($sql);
    if ($result == TRUE) {
    //echo "Uspela konekcija";
} else {
    echo "Neuspešno izvršavanje upita: " . $conn->error;
}
    return $result;

    $conn->close();

}

?>

Example of this done in an object oriented manner:

<?php

class konekcija{

    private $servername;
    private $username;
    private $password;
    private $dbname;
    private $sql;

    //Setter functions
    public function setVal($par1, $par2, $par3, $par4, $par5){ //Setovanje vrednosti za upit.
    $this->servername = $par1;
    $this->username = $par2;
    $this->password = $par3;
    $this->dbname = $par4;
    $this->sql = $par5;

}

    //Getter functions
    public function getServername() {
        return $this->servername;
    }

    public function getUsername() {
        return $this->username;
    }

    public function getPassword() {
        return $this->password;
    }

    public function getDBname() {
        return $this->dbname;
    }

    public function getSQL() {
        return $this->sql;
    }

    //Function that executes query.
    public function pristup($server_name, $user_name, $pass_word, $db_name, $sql_query){

        $conn=new mysqli($server_name, $user_name, $pass_word, $db_name);

        if($conn->connect_error){

            die("Neuspela konekcija: ".$conn->connect_error);

        }

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

        if ($result == TRUE){

        echo "Uspela konekcija";

        }
        else{

                echo "Neuspešno izvršavanje upita: " . $conn->error;

            }

        return $this->$result;

        $conn->close();

    }

}

$kon = new konekcija(); //Creation of an object.

//Setting values.
$kon -> setVal("localhost", "root", "", "test", "CREATE TABLE example(
            id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
            firstname VARCHAR(30) NOT NULL,
            lastname VARCHAR(30) NOT NULL,
            email VARCHAR(50),
            reg_date TIMESTAMP
            )");

//Getting values and inserting them into class method.
$kon -> pristup($kon->getServername(), $kon->getUsername(), $kon->getPassword(), $kon->getDBname(), $kon->getSQL());

?>

This works, and I'm asking if this code is any good. Is there a better/more established way of doing this?


texts: CreateView set foreign key from URL parameter

texts:
I want to be able to create a lorum, using a ipsum_id (ForeignKey) that has been supplied in the URL. Using Django's class based views.

Given the following URL:

url(r'^lorem/create/ipsum/(?P<ipsum_id>\d+)/$', LoremCreateView.as_view(), name='create'),

I have the following view:

class LoremCreateView(CreateView):
    """ Allow a user to create a Lorem. """
    model = Lorem
    ...

    def get_context_data(self, **kwargs):
        """ Get context variables for rendering the template. """
        ipsum = get_object_or_404(Ipsum, pk=self.kwargs['ipsum_id'])
        kwargs['ipsum'] = ipsum
        return super().get_context_data(**kwargs)

    def form_valid(self, form):
        """ Save the form instance. """
        ipsum = get_object_or_404(Ipsum, pk=self.kwargs['ipsum_id'])
        form.instance.ipsum = ipsum
        return super().form_valid(form)

This works fine, however I don't like the fact I call get_object_or_404 twice.

Is there a better way of doing this?

It might be possible to override an appropriate method and set self.ipsum - not sure I like doing this either.

Also is get_object_or_404 appropriate here?


texts: Load drinks and their ingredients into dictionaries

texts:
I'm working on a web application using Bottle, and it is, at this point, functional.

The gist of it is that I have a database of drinks, with associated IDs, and associated sets of ingredients. the name and ID of the drink are passed to the client, which displays them.

Currently, when the program loads up, all drinks and their associated ingredient amounts are loaded into a list of dictionaries, like so:

SampleDrinkDict = {'name': 'Screwdriver', 'id': 4, 'vodka':2, 'orange juice':6}
DrinkDictList = []
DrinkDictList.append(SampleDrinkDict)

Once the DrinkDictList is fully populated, I pass the names and IDs of every one to the client, which populates those in a list. When a drink is selected, it makes a callback to scan the DrinkDictList and find the matching 'id' field. Once it finds it in the list, the ingredient amounts and details are populated on the page.

Would it be faster/better/more proper for me to only query ingredients from the DB once a drink is selected?

For example, would it be faster/more pythonic/better to do this?

SampleDrinkDict = {'name': 'Screwdriver', 'id': 4,}
DrinkDictList = []
DrinkDictList.append(SampleDrinkDict)

@bottle.route('/drinkSelected/:id'):
def getIng(id,db):
    sqlString = '''SELECT ingredients WHERE Drink_id = ?'''
    argString = (id,)
    ingredientList = db.execute(SqlString, argString).fetchall()

This is all running on a Raspberry Pi, and I'm worried about taxing the RAM once the drink list becomes huge. Is there any reason to go with one approach over the other?


texts:
Following is Objective-C method implementation I did for one of the most simplest sorting algorithms, Bubble Sort to sort an array of integers.

Note:- I have defined it as a static method in the SimpleAlgorithms class.

/**
 * When given jumbled or discending ordered array of integers, following bubble sort method will give you
 * an array ordered in ascending order.
 */
+ (NSArray *) bubbleSort:(NSArray *) arrayToBeSorted {
    // As we can't swap integers in a static array, make a mutable array out of the given static array.
    NSMutableArray *muArrRaw = [[NSMutableArray alloc] initWithArray:arrayToBeSorted];

    // iterate through the array as rounds
    for (int i = 0; i < [muArrRaw count]; i++) {
        // iterate through each element of the array with the given range
        for (int j = 0; j < [muArrRaw count] - i; j++) {
            // comparison
            if (j < ([muArrRaw count] - 1) && [[muArrRaw objectAtIndex:j] intValue] > [[muArrRaw objectAtIndex:(j + 1)] intValue]) {
                int temp = [[muArrRaw objectAtIndex:j] intValue];   // taken the value to be swapped first

                // then do the swapping
                [muArrRaw replaceObjectAtIndex:j withObject:[muArrRaw objectAtIndex:(j + 1)]];
                [muArrRaw replaceObjectAtIndex:(j + 1) withObject:[NSNumber numberWithInt:temp]];
            }
        }
    }

    // return the sorted array
    return [muArrRaw mutableCopy];
}

I call this method as follows:

NSArray *array = [[NSArray alloc] initWithObjects:[NSNumber numberWithInt:5], [NSNumber numberWithInt:3], [NSNumber numberWithInt:4], [NSNumber numberWithInt:1], [NSNumber numberWithInt:2], nil];
NSArray *sortedArray = [SimpleAlgorithms bubbleSort:array];

I know this seems to be silly for asking for improvements for something like this. But I like to find out even smallest improvements that we can made to this kind of things also because sometimes I might have done something stupid in the above implementation also. That's where we can embed power and value to the implementation.

So please give your suggestions and improvements to this Algorithm implementation.

I would be grateful if you can point out the improvements in the following areas:

Objective-C Language oriented improvements, reasoning and suggestions
Algorithm implementation techniques, simplifiable code lines.


texts: Applying EF core in Universal Windows Apps using a large database

texts:
I am building my UWP app and really stuck in the architecture. For the past few days, I have been reading MVVM, Entity Framework, SQLite, Code First, etc and I am confused how I will implement everything.

In this tutorial, it shows the usage of a dbcontext derived class inside a function called Page_Loaded in MainPage.xaml.cs. Is this a bad design?

I made my own implementation below because I don't want to expose SQL queries on my view XAML files. I am completely unsure if this is better or if I can still improve it or replace it with a better one?

MyDbContext.cs

public class MyDbContext : DbContext
{
    internal DbSet<Person> People { get; set; }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        optionsBuilder.UseSqlite("Filename=mydbcontext.db");
    }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Person>().Property(p => p.Id).IsRequired();
        modelBuilder.Entity<Person>().Property(p => p.Name).IsRequired();
    }
}

Repository.cs

public class Repository
{
    public List<Person> People()
    {
        using (var db = new MyDbContext())
        {
            return db.People.ToList();
        }
    }

    public Person GetPersonByName(string name)
    {
        using (var db = new MyDbContext())
        {
            Person person = (from p in db.People
                             where p.Name == name
                             select p).FirstOrDefault();

            return person;
        }
    }
}

MainPage.xaml.cs

private void Page_Loaded(object sender, RoutedEventArgs e)
{
    entriesListView.ItemsSource = _repo.People();
}

Another thing: if I add many tables, my Repository.cs will grow so large that it might reach thousands of lines, how do you break this one? I might add 30 more tables inside so I could imagine how it will look cluttered inside Repository.cs file.


texts:
"Funny String" problem from Hackerrank

  Suppose you have a String, \$S\$ of length \$N\$ indexed from \$0\$ to \$N-1\$. You also have some String, \$R\$, that is the reverse of \$S\$, where \$S\$ is funny if the condition is \$\left|S[i] - S[i-1]\right| = \left|R[i] - R[i-1]\right|\$ is true for all \$i \in [1, N-1]\$.

I code mainly in Java. I'm very new to Python, so I would appreciate feedback on how I can make this code more Pythonic, cleaner and more efficient in general.

import math

def isFunny(word):
    i = 0
    length = len(word)
    arr = []
    revarr = []
    for i in range(0,math.ceil(length/2)):
        sdiff = abs(ord(word[i])-ord(word[i+1]))
        rdiff = abs(ord(word[length-i-1])-ord(word[length-i-2]))
        if sdiff == rdiff:
               continue
        else:
               return False
    return True

if __name__ == "__main__":
    n = int(input())
    for _ in range(n):
        word = input();
        if isFunny(word):
            print("Funny")
        else:
            print("Not Funny")


texts: Get a "train or test" slicing elegantly after splitting

texts:
I am learning numpy, pandas, and sklearn for machine learning now. My teacher gives me code like below, but I guess it is ugly. This code is for splitting the data into training set and testing set, and later we could manipulate the entire data or just training/testing set by the [True, False, True, False ... ] idx_train/idx_test list later.

import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split

m = 10
x1 = np.arange(m)
x2 = x1 * 2
x3 = x1 * 3
x4 = x1 * 4
x = np.c_[x1, x2, x3, x4]
x = pd.DataFrame(x)

x_train, x_test = train_test_split(x, train_size=0.7, random_state=666)
TRAIN, TEST = 'train', 'test'
TRAIN_TEST = TRAIN + TEST
pd.options.mode.chained_assignment = None
x_train[TRAIN_TEST] = TRAIN
x_test[TRAIN_TEST] = TEST
pd.options.mode.chained_assignment = 'warn'
x = pd.concat([x_train, x_test])
idx_train = x[TRAIN_TEST] == TRAIN
idx_test = np.invert(idx_train)
x_train = x[idx_train]  # later
x_test = x[idx_test]

And I get the below code by myself. I feel it is only a little better.
offset_orig = np.arange(m)
rate = 0.7
offset_train, offset_test = train_test_split(offset_orig, train_size=rate, random_state=666)
if rate < 0.5:
    offset_set_train = set(offset_train)
    idx_train = [i in offset_set_train for i in offset_orig]  # This may be slow. Is numpy broadcast or implicit cycling available here?
    idx_test = np.invert(idx_train)
else:
    offset_set_test = set(offset_test)
    idx_test = [i in offset_set_test for i in offset_orig]  # This may be slow. Is numpy broadcast or implicit cycling available here?
    idx_train = np.invert(idx_test)

x_train = x[idx_train]  # later
x_test = x[idx_test]

I want to get the [True, False, True, False ... ] list idx_train and idx_test for slicing usage later.
I believe that in the world of Python, there should be and will be only one appropriate way to achieve an objective. Could someone give me that very approach to get a "train or test" slicing? (Usage of the lib function train_test_split is required.)


texts:
I'm trying to save a webpage as text file, using the following function:

def html_to_txt():
    import urllib.request
    url = str(input('Enter URL: '))
    page = urllib.request.urlopen(url)
    with open(str(input('Enter filename: ')), "w") as f:
        for x in page:
            f.write(str(x).replace('\\n','\n'))
    s= 'Done'
    return s

It gives a correct output, that means I can save a given webpage. But, the final text file contains a b' before the very first line, and a 'b' before each following line.

Here's a sample output of my function (taken from: http://www.uniprot.org/uniprot/P57052.txt)

$ cat P57052.txt
b'ID   RBM11_HUMAN             Reviewed;         281 AA.
'b'AC   P57052; Q6YNC2; Q8NBA1; Q8NFF6;
'b'DT   01-DEC-2000, integrated into UniProtKB/Swiss-Prot.
'b'DT   01-DEC-2000, sequence version 1.
'b'DT   09-JUL-2014, entry version 111.
'b'DE   RecName: Full=Splicing regulator RBM11;
'b'DE   AltName: Full=RNA-binding motif protein 11;
'b'GN   Name=RBM11;

I wonder if it has something to do with binary file "default", I mean, if the webpage is  automatically saved with binary features by my python script.

Thanks in advance for your review.


texts: Finding max amount of integers in list that add up to target

texts:
Introduction
1) Problem description:

Suppose you are managing files. You are given a text file, where in the first line are storage's volume of the server and the amount of users in total that is in the text file. Each line from the second to the end shows volume of individual user's storage. Based on the server's volume limit you need to find the maximum amount of users that can be fit in the database and the maximum volume among them.

2) Sample.txt
100 4
80
30
50
40

3) Sample output: 2 50
4) Sample output's explanation: The maximum amount of users that can be fit in the database is 2 (more than 2 will be more than 100 in total). All possible pairs, which meet volume's requirements, are 30 40 30 50 50 40 (each makes less than 100). The maximum number among these pairs is 50.

Actual problem
1) db.txt
9691 1894
89
24
33
11
...

2) My solution:
fName = open('../root_files/26_7791633.txt')
param = fName.readline().split()
data = [int(el) for el in fName.readlines()]
fName.close()

TARGET = int(param[0])

data.sort()

target_disposable = TARGET
max_num = 0
quantity = 0

# finding maximum amount
while target_disposable - data[quantity] >= 0:
    target_disposable -= data[quantity]
    quantity += 1

new_list = data[0:quantity]

element_in_the_end = new_list.pop()
remainder = TARGET - sum(new_list)

# finding the very maximum number based on quantity
for i in reversed(range(remainder + 1)):
    if i > element_in_the_end:
        max_num = i
        break

print(quantity, max_num)

3) Output:
34 601
Solution accepted
Runtime: 55ms

4) My question: Is there a way to make this code more concise, maybe even improving its runtime? Thank you in advance.