texts:
I have been reading today about the Abstract Factory Pattern, and tried to make the following implementation.
I have seen a lot of implementations in the internet, where they use switch statements, but I must say that I didn't like that much, since the more factories you make, it seems to me that it makes very difficult to add new products, if needed.
Anyways, I was hoping you to take a look at it and let me know your opinions. Thanks in advance for taking your time to review it.
Factories
from abc import ABC, abstractmethod

class PlayerFactory(ABC):
    """
    This class is meant to be an interface
    """
    @abstractmethod
    def create_goalkeeper(self):
        pass

    @abstractmethod
    def create_defender(self):
        pass

class FootballPlayerFactory(PlayerFactory):
    def create_goalkeeper(self):
        return FootballGoalkeeper()

    def create_defender(self):
        return FootballDefender()

class HockeyPlayerFactory(PlayerFactory):
    def create_goalkeeper(self):
        return HockeyGoalkeeper()

    def create_defender(self):
        return HockeyDefender()

Football players
class FootballPlayer:
    def __init__(self, uses_hands):
        self.uses_hands = uses_hands

    def play(self):
        print("I'm playing football!")

class FootballGoalkeeper(FootballPlayer):
    def __init__(self):
        super(FootballGoalkeeper, self).__init__(uses_hands=True)

class FootballDefender(FootballPlayer):
    def __init__(self):
        super(FootballDefender, self).__init__(uses_hands=False)

Hockey players (my creativity stopped here, so I didn't include any difference between goalkeepers and defenders)
class HockeyPlayer:
    def play(self):
        print("I'm playing hockey!")

class HockeyGoalkeeper(HockeyPlayer):
    pass

class HockeyDefender(HockeyPlayer):
    pass


texts: Typeahead autocomplete functionality challenge

texts:
I'm working on a Talent Buddy challenge . In this challenge you have to design the autocomplete functionality of Twitter. You are given a list of queries and possible usernames. You have to return the most suited username based on the query. This whole functionality should run under 2 seconds for arrays which do not exceed 100.000 entries. Below you can find my attempt. On my computer it runs the biggest list in 0.517 seconds. But apperently it is not under 2 sec on their system. In the code bellow I did not add the big list, because it will be too much text for a question. Therefore I included the example lists.

My strategy is to divide the usernames into 26 lists (1 list for every letter in the alphabet). So this means that for each query, I do not have to go over all the user names, but only those starting with the same letter. For the rest I optimized my code with best practice rules.

Does anyone know how to make this faster?

usernames= ["james", "jBlank"]
queries= ["j", "jm", "jbl", "JB"]

import cProfile

def do_cprofile(func):
    def profiled_func(*args, **kwargs):
        profile = cProfile.Profile()
        try:
            profile.enable()
            result = func(*args, **kwargs)
            profile.disable()
            return result
        finally:
            profile.print_stats()
    return profiled_func

@do_cprofile
def typeahead(usernames, queries):

    amount_of_queries = len(queries)
    queries_lower = [query.lower() for query in queries]
    username_lower = [item.lower() for item in usernames]
    username_lower = sorted(username_lower)
    querylen = [len(query) for query in queries]

    results = [-1]*amount_of_queries
    alphabet = [[] for x in xrange(26)]
    myDict = {'a':0,'b':1,'c':2,'d':3,'e':4,'f':5,'g':6,'h':7,'i':8,'j':9,'k':10,'l':11,'m':12,'n':13,'o':14,'p':15,'q':16,'r':17,'s':18,'t':19,'u':20,'v':21,'w':22,'x':23,'y':24,'z':25}

    [alphabet[myDict[username[0]]].append(username) for username in username_lower]

    matches=[]
    for q in xrange(amount_of_queries):
        matches[:] = []
        quer = queries_lower[q]

        if querylen[q]==1:
            results[q] = alphabet[myDict[quer[0]]][0]
        else:
            matches = [item  for item in alphabet[myDict[quer[0]]] if quer==item[:querylen[q]]]
            if len(matches)>=1:
                results[q]= matches[0]

    print '\n'.join(map(str, results))

if __name__=="__main__":
    typeahead(usernames, queries);


texts:
I saw in Wikipedia (the first under Optimizing bubble sort) a pseudo-code to bubble sort and I implemented it in Python.

I am posting my implementation here because I'm new to Python, and I'm looking mostly for programming in a more pythonic way.

def bubbleSort(array):
    n = len(array)
    swapped = True
    while swapped:
        swapped = False
        for i in range(n - 1):
            if array[i] > array[i + 1]:
                array[i], array[i + 1] = array[i + 1], array[i]
                swapped = True
        n -= 1
    return array

def main():
    array = [1, 7, 4, 3, 2, 9, 8, 5, 6]
    array = bubbleSort(array)
    print(array)

if __name__ == '__main__':
    main()

I'd love to know if there are any stuff that I can optimize (syntactic-wise), like the fact that I'm writing swapped = True, and afterward changing it again, and again ... which thing annoys me.


texts: Custom CSRF protection in Express / Node

texts:
Please review my code rather than telling me to use a trusted NPM package like csurf.

What are some potential weaknesses with the following implementation?

'use strict'

const   express = require('express'),
        router = express.Router(),
        crypt = require('../services/crypt')

router.use((req, res, next) => {
    if (req.session.csrfToken === undefined) {
        req.session.csrfToken = crypt.randHex(64) // this uses Crypto.randomBytes(); gives a hex of length 64
        // alt: res.locals.csrfToken = crypt.hash('sha256', req.session.csrfToken + req.headers.host) // also using Crypto
    }

    res.locals.csrfToken = req.session.csrfToken
}

module.exports = router

I put the res.locals.csrfToken in all forms with method="post", and this middleware is always used:

'use strict'

const   express = require('express'),
        router = express.Router()

router.post('*', (req, res, next) => {
    if (req.session.csrfToken !== req.body.csrfToken) {
    // alt: if (crypt.hash('sha256', req.session.csrfToken + req.headers.host) !== req.body.csrfToken) {
        let err = new Error('Invalid CSRF Token!')
        err.status = 403

        return next(err)
    }

    return next()
})

module.exports = router

I am using HTTPS, and my express-session options look something like this:

{
    name: 'sessid',
    resave: false,
    saveUninitialized: false,
    secret: 'djt84nq7y4tnvwosufvgsudih3rve783vdk'
}

Will the alternative (alt) implementation help any?


texts: Thread safe algorithm for arrays information manipulation

texts:
I have a program which requires a usage of threads and it must be thread safe. I do not have much experience with threads and critical sections, but as much as I know you must lock code sections where resources are being read and written to. Program is working, but I do not know if I did it correctly.

DataB code was added to answer users Incomputable question. It is just a class which stores information required for program to work.

class DataB {
public:
    DataB() { }
    DataB(double sF, int sC, string n);
    double getField(void);
    void increaseFieldCount(void);
    void decreaseFieldCount(void);
    int getFieldCount(void);
    void setField(double f);
    void setCountField(int fC);
    string getName(void);
private:
    string name;
    double field;
    int fieldCount;
};

    DataB::DataB(double sF, int sC, string n) {
    field = sF;
    fieldCount = sC;
    name = n;
}

double DataB::getField(void) {
    return field;
}

void DataB::increaseFieldCount() {
    fieldCount++;
}

int DataB::getFieldCount(void) {
    return fieldCount;
}

void DataB::decreaseFieldCount(void) {
    fieldCount--;
}

void DataB::setCountField(int cF) {
    fieldCount = cF;
}

void DataB::setField(double f) {
    field = f;
}

string DataB::getName(void) {
    return name;
}

mutex threadLock;

void threadRemove(int dataStart, int dataEnd, int dataCount, DataB B[],  DataB V[], int &sortedCount) {
    bool changed = true;

    while (changed || sortedCount != dataCount ) {
        changed = false;

        for (int i = dataStart; i < dataEnd; i++) {

            threadLock.lock();

            int count = V[i].getFieldCount();

            threadLock.unlock();

            if (count > 0) {

                threadLock.lock();

                double delItem = V[i].getField();

                threadLock.unlock();

                for (int x = 0; x < dataCount; x++) {

                    threadLock.lock();

                    double compare = B[x].getField();

                    threadLock.unlock();

                    if (compare == delItem) {

                        threadLock.lock();

                        B[x].decreaseFieldCount();
                        V[i].decreaseFieldCount();

                        if (B[x].getFieldCount() == 0) {
                            B[x].setCountField(-1);
                            B[x].setField(-1);
                        }

                        changed = true;

                        threadLock.unlock();
                        break;
                    }
                }
            }
        }
    }
}

int main(int argc, char * argv[]) {

/* */

    thread G6(threadRemove, 0, 5, dataCount, B, V, ref(sortedCount));
    thread G7(threadRemove, 5, 10, dataCount, B, V, ref(sortedCount));
    thread G8(threadRemove, 10, 15, dataCount, B, V, ref(sortedCount));
    thread G9(threadRemove, 15, 20, dataCount, B, V, ref(sortedCount));
    thread G10(threadRemove, 20, 25, dataCount, B, V, ref(sortedCount));

    G6.join();
    G7.join();
    G8.join();
    G9.join();
    G10.join();
}


texts: PHP MySQL make insert and update large amount of users faster

texts:
I'am using php on server side to manage data with MySQL. I have to request a API that gives me an list of users. I need to check for each user if he is in the database. If yes, I update his information. If not, I insert him in the data base.

The issue is that there is more than 2000+ users each times and my code in PHP is really slow (sometimes I get 504 Gateway Time-out). We will have even more users very soon.

How can I make my code faster ? Is Php ok if there is more users?

    $userList = getFromAPI();

      foreach ($userList as $userId){

        $db = dbConnect();

  $query = $db->prepare(
      "SELECT openid FROM USERS WHERE openid = :openid"
    );

  $query->execute([
    "openid"=>$openId,
    ]);

    $res = $query->fetch(PDO::FETCH_ASSOC);

  $tagList = implode(",", $user["tagid_list"]);

        if (!empty($res)) {

          $query = $db->prepare(
      "INSERT INTO USERS(id, name, group) VALUES(:id, :name, :group)
       ON DUPLICATE KEY UPDATE name=:name, group=:group"
          );

          $query->execute([
        "id"=>$id,
        "name"=>$name,
        "group"=>$group
          ]);
        }

     }


texts: Extract string list as array from an array of objects

texts:
Having the following array of objects of ingredients used by cooks
images = [{id:1, cook:"jim",   ingredients:"chicken salsa mayo ketchup tomato"},
          {id:2, cook:"steve", ingredients:"pasta mozzarela chicken"},
          {id:3, cook:"jim",   ingredients:"bread lettuce tomato onions"},
          {id:4, cook:"jim",   ingredients:"ketchup sausage bread"},
          {id:5, cook:"jim",   ingredients:"avocado ground_meat chili"},
          {id:6, cook:"jim",   ingredients:"ground_meat guacamole tomato parsley"},
          {id:7, cook:"steve", ingredients:"chicken tomato broccoli"}]

I have to extract an array of ingredients used by a specific cook so that each ingredient appears only once, return only 25 ingredients unless a specific limit is provided.
extractIngredients(array, cook, limit=25)
e.g:
extractIngredients(images, "jim", 10) ==> ["chicken", "salsa", "mayo", "ketchup", "tomato", "bread", "lettuce", "onions", "hotdog", "avocado"]
BONUS POINTS:
Return an ingredient array sorted by the number of occurrences, and then alphabetically, showing the most popular ingredients first.
e.g:
extractIngredients(images, "jim", 10) ==> ["tomato", "bread", "ground_meat", "ketchup", "avocado", "chicken", "chili", "guacamole", "lettuce", "mayo"]
My solution:
extractIngredients(images, username, limit){
  return [...new Set(images.filter(images => images.cook == username)
       .map(a => a.keywords.split(" ")).flat())].slice(0, limit);
}

My solution has an issue with an extremely large input as it would still process all of the objects and then slice the resulting array. It would be better to just process objects until the limit is reached.


texts:
I frequently run a script similar to the one below to analyze an arbitrary number of files in parallel on a computer with 8 cores.

I use Popen to control each thread, but sometimes run into problems when there is much stdout or stderr, as the buffer fills up. I solve this by frequently reading from the streams. I also print the streams from one of the threads to help me follow the progress of the analysis.

I'm curious on alternative methods to thread using Python, and general comments about the implementation, which, as always, has room for improvement. Thanks!

import os, sys
import time
import subprocess

def parallelize(analysis_program_path, filenames, N_CORES):
    '''
    Function that parallelizes an analysis on a list of files on N_CORES number of cores
    '''
    running = []
    sys.stderr.write('Starting analyses\n')
    while filenames or running:
        while filenames and len(running) < N_CORES:
            # Submit new analysis
            filename = filenames.pop(0)
            cmd = '%s %s' % (analysis_program_path, filename)
            p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
            sys.stderr.write('Analyzing %s\n' % filename)
            running.append((cmd, p))
        i = 0
        while i < len(running):
            (cmd, p) = running[i]
            returncode = p.poll()
            st_out = p.stdout.read()
            st_err = p.stderr.read()  # Read the buffer! Otherwise it fills up and blocks the script
            if i == 0:  # Just print one of the processes
                sys.stderr.write(st_err)
            if returncode is not None:
                st_out = p.stdout.read()
                st_err = p.stderr.read()
                sys.stderr.write(st_err)
                running.remove((cmd, p))
            else:
                i += 1
        time.sleep(1)
    sys.stderr.write('Completely done!\n')


texts:
I want to understand if I got this concept correctly.

I should start work from ViewState; a reference type object holding the state of a view. Here it is called PageIndicatorVM. It is bad-to-impossible to have any internal state in a View.
No logic in the View or so they say. Yet here and there in the code samples I see ternary operators and loops.
@Bidindg property wrapper seems quite dangerous for me. It breaks unidirectional data flow and I have doubts if I used it correctly here.

Please point out my mistakes. Will appreciate if you point me to best practices.

This is a dot indicator component. It switches when vm.next() is called or user taps on a dot.
struct DotIndicator: View {
    let pageIndex: Int

    @Binding var isOn: Int

    var body: some View {

        Button(action: {
            self.isOn = self.pageIndex
        }) {
            Circle()
                .scaleEffect( isOn == pageIndex ? 1.3 : 0.9)
                .animation(.spring())
        }

    }
}

class PageIndicatorVM: ObservableObject {
    @Published var currentPage: Int

    let numPages: Int

    init(numPages: Int, currentPage: Int = 0) {
        self.numPages = numPages
        self.currentPage = currentPage
    }

    func next() {
        currentPage = (currentPage + 1) % numPages
    }
}

struct PageIndicator: View {
    @ObservedObject private var vm = PageIndicatorVM(numPages: 5)

    private let spacing: CGFloat = 2
    private let dotSize: CGFloat = 8

    var body: some View {
        VStack {
            HStack(alignment: .center, spacing: spacing) {
                ForEach((0..<vm.numPages ), id: \.self) {
                    DotIndicator(pageIndex: $0, isOn: self.$vm.currentPage)
                    .frame(
                        width: self.dotSize,
                        height: self.dotSize
                    )
                }
            }
        }
    }
}


texts: PDO (MySQL) connection and query class, safety and logic

texts:
For the last few day I tried to figure out how to work with MySQL and PDO. Although I've tried to read a lot about the subject, there are still a lot of things I don't understand.

Because of this lack of knowledge, I can't really judge this code (or other example code on-line) on its safety and logic, and therefore was hoping I could get some feedback on it.

The class makes a connection and returns a query:

class Connection
{
private $username = "xxxx";
private $password = "xxxx";
private $dsn = "mysql:host=host;dbname=name_db";
private $sql;
private $DBH;

function setSQL($sql){
    $this->sql = $sql; //if $sql is not set it troughs an error at PDOException
}

public function query()
{
    //the connection will get established here if it hasn't been already
    if (is_null($this->DBH))
        try {
            $this->DBH = new PDO( $this->dsn, $this->username, $this->password );
            $this->DBH->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );

            //query
            $result = $this->DBH->prepare($this->sql);
            $result->execute();
            return $result->fetch(PDO::FETCH_ASSOC);

        } catch(PDOException $e) {

            echo "I'm afraid I can't do that1.";
            //file_put_contents('PDOErrors.txt', $e->getMessage(), FILE_APPEND);
        }
}

//clear connection and variables
function __destruct(){
        $this->DBH = null;
}

}

Using the class:

$sql = "SELECT * from stock WHERE id = 302";
$test = new Connection();
$test->setSQL($sql);
echo $test->query();


texts:
My in-laws taught me a dice game a couple years ago, and we play every once in a while. A recent excellent answer from @radarbob inspired me to proceed with translating the rules of that dice game into code.

Here's what came out of it:

So it works perfectly, and somehow I'm just as unlucky with this virtual version as in the real-life one (had to click dozens of time to get a freakin' opening roll; by that time my mother-in-law already has thousands of points, every time). At least in this version I can inject some CrookedDie implementation if I want!

I'd like the CalculateRollScore method reviewed, to see what could be improved.

It turns out I thought the code was working as it should. So I wrote a couple unit tests and... well this is where not writing unit tests has bitten me.

Well I had to change the rules anyway, since the rule for 4x 1's was just my wife being mixed-up. My mother-in-law and I agree that 3x 1's is 1000, 4x 1's is 2000 and 5x 1's is 3000.

So before I show any code, I'll show this:

Now here's the working code (view original code here), with only minor changes that don't mootinize any already posted answer:

namespace DiceGame
{
    public interface IRollScoreRules
    {
        int CalculateRollScore(IEnumerable<IRollResult<int>> results);
    }

    public class GameRollScoreRules : IRollScoreRules
    {
        public virtual bool IsOpeningRoll(IEnumerable<IRollResult<int>> results)
        {
            return CalculateRollScore(results) >= 500;
        }

        public virtual int CalculateRollScore(IEnumerable<IRollResult<int>> results)
        {
            var score = 0;

            // if less than 3 1's were rolled, each rolled 1 is 100pts:
            score += results.GroupBy(e => e.Value)
                            .Where(g => g.Key == 1)
                            .Where(g => g.Count() < 3)
                            .Sum(g => g.Count() * 100);

            // if less than 3 5's were rolled, each rolled 5 is 50pts:
            score += results.GroupBy(e => e.Value)
                            .Where(g => g.Key == 5)
                            .Where(g => g.Count() < 3)
                            .Sum(g => g.Count() * 50);

            // if more than 3 of anything other than 1 were rolled, determine number of "extra dice":
            var extras = results.GroupBy(e => e.Value)
                                .Where(g => g.Key != 1 && g.Count() > 3)
                                .ToDictionary(kvp => kvp.Key, kvp => kvp.Count() - 3);

            var extraOnes = results.GroupBy(e => e.Value)
                                   .Where(g => g.Key == 1 && g.Count() > 3)
                                   .ToDictionary(kvp => kvp.Key, kvp => kvp.Count() - 3);

            // any triplet is 100x nominal value; each extra die is another 100x nominal value:
            score += results.GroupBy(e => e.Value)
                            .Where(g => (g.Key != 1 && g.Count() >= 3))
                            .Sum(g => (g.Key * 100) + (extras.ContainsKey(g.Key) ? extras[g.Key] : 0) * (g.Key * 100));

            //score += results.GroupBy(e => e.Value)
            //    .Where(g => (g.Key == 1 && g.Count() >= 3))
            //    .Sum(g => (g.Key * 100) + (extraOnes.ContainsKey(g.Key) ? extraOnes[g.Key] : 0) * (g.Key * 100));

            // 3x 1's is 1000x nominal value; each extra die is another 1000x nominal value:
            score += results.GroupBy(e => e.Value)
                            .Where(g => g.Key == 1 && g.Count() >= 3)
                            .Sum(g => (g.Key * 1000) + (extraOnes.ContainsKey(g.Key) ? extraOnes[g.Key] : 0) * (g.Key * 1000));

            return score;
        }
    }
}


texts: Automated Tweet of new inbound Enquiries in PHP7 (Laravel 5.2)

texts:
Background.

A User can submit an enquiry via a form hosted on a clients website, these are pushed onto a queue, and then taken off the queue for processing, to process several different parts of the enquiry asynchronously a single event is fired, this event is listened for by several different listeners, each one with a unique and distinct set of functionality.

This is the complete listener I've written to post the inbound Enquiry to twitter.

<?php

namespace App\Listeners\Enquiry;

use App\Events\NewEnquiryEvent;
use App\Exceptions\DebuggableException;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use App\Models\Stores\Enquiry;

class Tweet
{
    public function handle(NewEnquiryEvent $event)
    {
        Enquiry::find($event->body->id)->reject(function ($enquiry) {
            return !$enquiry->shouldTweet();
        })->map(function ($enquiry) {
            return $enquiry->sendToTwitter();
        });
    }
}


texts:
I made a simple program that uses OOP methods. Please tell me if I used the 4 methods right. And if not, please show me how.

class Encap{
    private String name;
    public void setName(String newValue){
        name = "Hello, "+newValue+"!";
    }

    public String getName(){
        return name;
    }
}

abstract class Abstraction {
    int fibCount, flag=0, y;
    String inputName;
    String names[] = new String [] {"Anna","Joe","Carl"};
    Scanner x = new Scanner(System.in);
abstract void abscompute();
}

class abs2 extends Abstraction{
    @Override
    void abscompute()
    {
         System.out.print("Enter number of fibonacci: ");
         fibCount = x.nextInt();
         int[] fib = new int[fibCount];
         fib[0] = 0;
         fib[1] = 1;
         for(int i=2; i < fibCount; i++){
             fib[i] = fib[i-1] + fib[i-2];
         }

         for(int i=0; i< fibCount; i++){
                 System.out.print(fib[i] + " ");

                }

    }
}
public class Fibonacci {

    public static void main(String[] args) {
        Abstraction abs = new abs2();
        Encap encap = new Encap();
        System.out.print("Enter your name: ");
        abs.inputName = abs.x.next();
        for (String name : abs.names) {
            if(abs.inputName.equals(name)){
                encap.setName(abs.inputName);
                System.out.println(""+encap.getName());
                abs.flag = 1;
            }
        }
        if(abs.flag!=1){
            System.out.println("Name doesn't exist..");
        }
        else{
            abs.abscompute();
        }
    }
}


texts: Improving a method to guarantee uniqueness

texts:
I have just written something to guarantee a unique URL when creating pages within an old legacy system (sounds odd doing this retrospectively but we've just changed how the routing works). I don't often end up using while and I think this may be why I feel it can be improved.

private string GetUniqueUrl(Page parentPage, Page newPage)
{
    var isNotDuplicatateUrl = false;
    var version = 0;
    var baseUrl = parentPage != null ? parentPage.FullUrl.Trim() + "/" : string.Empty;

    while (isNotDuplicatateUrl == false)
    {
        var friendlyUrl = version > 0 ? (newPage.FriendlyURLName + "-" + version) : newPage.FriendlyURLName;
        var fullUrl = baseUrl + friendlyUrl;

        var duplicateUrlPage =
            Site.Pages.FirstOrDefault(x => x.FullUrl != null && string.Equals(x.FullUrl.Trim(), fullUrl.Trim(), StringComparison.CurrentCultureIgnoreCase));

        if (duplicateUrlPage == null)
        {
            isNotDuplicatateUrl = true;
        }
        else
        {
            version++;
        }
    }

    return newPage.FriendlyURLName + "-" + version;
}

NB: I know Page.FriendlyURLName should be Page.FriendlyUrlName but I'm only looking for improvements within the scope of this method.


texts: Calculating the potential of a matrix of size (424600, 55)

texts:
I have the following working code to calculate the potential of a matrix after normalizing the matrix. But it is too much time consuming. Is there a way to make this code run faster?

import csv
import numpy as np
from normalization import normalized_matrix
n = len(normalized_matrix)
sigma = 1
potential_writer = csv.writer(open('potential.csv', 'w'))
for l in range(n):
    elem = []
    for j in range(len(normalized_matrix[0])):
        GWF = 0
        PotSecPart = 0
        for i in range(n):
            if (i!=l):
                PotSecPart = (PotSecPart + (((normalized_matrix[l][j] - normalized_matrix[i][j])**2)*(np.exp((-(normalized_matrix[l][j] - normalized_matrix[i][j])**2)/(2*(sigma**2))))))
                GWF = GWF + (np.exp((-(normalized_matrix[l][j] - normalized_matrix[i][j])**2)/(2*(sigma**2))))
                PotFirPart = (2*(sigma**2))* GWF
        elem.append(np.round(PotSecPart/PotFirPart, 2))
    potential_writer.writerows([elem])


texts: A version of operator<< that returns ostringstream instead of ostream

texts:
I always thought it would be handy to be able to write:

const std::string s = (std::ostringstream() << "hi" << 0).str();

This doesn't work in C++ by default because operator<< returns the ostringstream as a ostream, which obviously doesn't have the str() member.

I was pleasantly surprised though to discover that this can be done in C++11:

#include <iostream>
#include <sstream>
#include <string>

template <typename CharT, typename traits, typename T>
std::basic_ostringstream<CharT,traits>&& operator<<(std::basic_ostringstream<CharT,traits>&& out, const T& t) {
  static_cast<std::basic_ostream<CharT,traits>&>(out) << t;
  return std::move(out);
}

int main() {
  const std::string s = (std::ostringstream() << "hi" << 0).str();
  std::cout << s << std::endl;
}

It needs rvalue references and move semantics to bind the temporary to a reference here.

Is there a good reason why this isn't provided by the standard library by default? Is it an oversight? Making this idiom legal code seems like it might offer a number of benefits.
In my local C++11 project, I provide some "utility" code. Is there any reason why I shouldn't include this and use it widely?

How about the more generic version:

template <typename S, typename T, class = typename
               std::enable_if<std::is_base_of<std::basic_ostream<typename S::char_type,typename S::traits_type>, S>::value>::type>
S&& operator<<(S&& out, const T& t) {
  static_cast<std::basic_ostream<typename S::char_type,typename S::traits_type>&>(out) << t;
  return std::move(out);
}


texts:
To check out the cssv module i wrote a small programm which takes all xlsx files in a folder and converts them into csv files.

Let me know what you would improve on this program.

xlsx_tp_csv

"""
All xlsx files in the folder of the script get converted into csv files
(One for each sheet).
The names are created as excel filename + sheet name.
"""

import csv
import os
from pathlib import Path
import openpyxl

def make_csv_filename(filename_excel: str, sheet_name: str) -> str:
    """
    Make a filename out of the filename of the excel file and
    the corresponding sheet
    """
    return Path(filename_excel).resolve().stem  + '_' + sheet_name + '.csv'

def xlsx_to_csv():
    """Main loop"""
    target_folder: str = 'csv'
    os.makedirs(target_folder, exist_ok=True)

    for filename in os.listdir('.'):
        if not filename.endswith('.xlsx'):
            continue

        workbook = openpyxl.load_workbook(filename)

        for sheet_name in workbook.sheetnames:
            sheet = workbook[sheet_name]
            csv_filename = make_csv_filename(filename, sheet_name)
            csv_path: Path = Path(target_folder, csv_filename)

            with open(csv_path, 'w', newline='') as csv_file:
                csv_writer = csv.writer(csv_file)

                for row_number in range(1, sheet.max_row + 1):
                    row_data = []
                    for column_number in range(1, sheet.max_column + 1):
                        cell_data = sheet.cell(
                            column=column_number, row=row_number).value
                        row_data.append(cell_data)

                    csv_writer.writerow(row_data)

if __name__ == "__main__":
    xlsx_to_csv()


texts: Complexity Of Determining Tree is balanced?

texts:
boolean isBalance(Node root) {
    if (root == null )
        return true;
    return Math.abs(getHeight(root.left)-getHeight(root.right)) <=1;
}

int getHeight(Node N) {
    int L = 0;
    int R = 0;
    if (N.L!=null) L = getHeight(N.L);
    if (N.R!=null) R = getHeight(N.R);
    return 1 + Max(L,R);
}

I believe that the run time of my algorithm is O(N); But one of my friend told this runs for O(N^2);

My question is whether I am wrong or right since I believe I visit each node once. SO for that its O(N)...


texts: Rust closure to be called on a cache miss

texts:
The official Rust book chapter 13.1 includes an exercise to expand on the example provided in the chapter:

Try modifying Cacher to hold a hash map rather than a single value. The keys of the hash map will be the arg values that are passed in, and the values of the hash map will be the result of calling the closure on that key. Instead of looking at whether self.value directly has a Some or a None value, the value function will look up the arg in the hash map and return the value if it’s present. If it’s not present, the Cacher will call the closure and save the resulting value in the hash map associated with its arg value.
The second problem with the current Cacher implementation is that it only accepts closures that take one parameter of type u32 and return a u32. We might want to cache the results of closures that take a string slice and return usize values, for example. To fix this issue, try introducing more generic parameters to increase the flexibility of the Cacher functionality.

The following is what I have:
use std::thread;
use std::time::Duration;
use std::collections::HashMap;
use std::hash::Hash;

struct Cacher<T, K, J>
    where T: Fn(&K) -> J,
    K: Hash + Eq,
    J: Clone
{
    calculation: T,
    value: HashMap<K, J>,
}

impl<T, K, J> Cacher<T, K, J>
    where T: Fn(&K) -> J,
    K: Hash + Eq,
    J: Clone
{
    fn new(calculation: T) -> Cacher<T, K, J> {
        Cacher {
            calculation,
            value: HashMap::new(),
        }
    }

    fn value(&mut self, arg: K) -> J {
        if let Some(v) = self.value.get(&arg) {
            v.clone()
        } else {
            let v = (self.calculation)(&arg);
            self.value.insert(arg, v.clone());
            v
        }
    }
}

fn generate_workout(intensity: u32, random_number: u32) {
    let mut expensive_result = Cacher::new(|&num| {
        println!("calculating slowly...");
        thread::sleep(Duration::from_secs(2));
        num
    });

    if intensity < 25 {
        println!(
            "Today, do {} pushups!",
            expensive_result.value(&intensity)
        );
        println!(
            "Next, do {} situps!",
            expensive_result.value(&intensity)
        );
    } else {
        if random_number == 3 {
            println!("Take a break today! Remember to stay hydrated!");
        } else {
            println!(
                "Today, run for {} minutes!",
                expensive_result.value(&intensity)
            )
        }
    }
}

fn main() {
    let simulated_user_specified_value = 10;
    let simulated_random_number = 7;

    generate_workout(
        simulated_user_specified_value,
        simulated_random_number
    );
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn call_with_different_values() {
        let mut c = Cacher::new(|&a| a);

        let v1 = c.value(1);
        let v2 = c.value(2);
        assert_eq!(v1, 1);
        assert_eq!(v2, 2);

        let mut d = Cacher::new (|a: &String| a.len());
        let str1 = String::from("abc");
        let v3 = d.value(str1);
        assert_eq!(v3, 3);
    }
}

I don't like the fact that my approach has the generic parameter J bounded by Clone trait. How can I make this work without the bound?
Any other feedback is appreciated.


texts: Iterating worksheets and cells, copying data to summary sheet

texts:
I have been working on this particular sub for a while and it was very very slow from the beginning. Compared to my other subs that go through a lot more data the task of this one is almost minuscule. All it has to do is to go through about ~15 sheets and parse through a couple hundred cells. Since this is a fairly complicated task I need to test it a lot which becomes almost unbearable with how long it takes. I am not sure if there is anything I can do or if there even is a solution. I am open to all kinds of suggestions.

Private Sub CommandButton24_Click()

Dim xSheet As Worksheet
Dim DestSh As Worksheet
Dim Last As Long
Dim copyRng As Range
Dim destRng As Range
Dim cRange As Range
Dim c As Range
Dim uniqueVal() As Variant
Dim x As Long

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

'Delete the summary worksheet if it exists.
Application.DisplayAlerts = False
On Error Resume Next
ActiveWorkbook.Worksheets("Summary").Delete
On Error GoTo 0
Application.DisplayAlerts = True

' Add a worksheet with the name "Summary"
Set DestSh = ActiveWorkbook.Worksheets.Add
DestSh.Name = "Summary"
DestSh.Range("A1").Value = "Account"
DestSh.Range("B1").Value = "Exchange"
DestSh.Range("C1").Value = "Quarter"
DestSh.Range("D1").Value = "Year"
Set destRng = DestSh.Range("E1")

'Define inital array values
uniqueVal = Array("Account by Type", "Total", "lv_nsac_ACCOUNT", "ams_ACCOUNT", "bru_ACCOUNT", "lsem_ACCOUNT", "mse_ACCOUNT", "par_ACCOUNT", "swx_ACCOUNT", "us_ACCOUNT", "wbag_ACCOUNT", "xetra_ACCOUNT", "europe_ACCOUNT", "lv_ACCOUNT", "lv_apac_ACCOUNT")

' This first part subtracts all the relevant column names, just running this
'already took excel about 3-5 minutes
' Loop through all worksheets and copy the data to the
' summary worksheet.
For Each xSheet In ActiveWorkbook.Worksheets

    If InStr(1, xSheet.Name, "ACCOUNT") And xSheet.Range("B1") <> "No Summary Available" Then _

        Set copyRng = xSheet.Range("A:A")

        For Each c In copyRng.SpecialCells(xlCellTypeVisible)

            If Len(c) <> 0 And Not ISIN(c, uniqueVal) Then _

                'Copy to destination Range
                c.Copy destRng
                'move destination Range
                Set destRng = destRng.Offset(0, 1)
                'change / adjust the size of array
                ReDim Preserve uniqueVal(0 To UBound(uniqueVal) + 1) As Variant
                'add value on the end of the array
                uniqueVal(UBound(uniqueVal)) = c.Value

            End If

        Next c

    End If

Next xSheet

'This second part is supposed to capture account names from the sheets and
'and put them in the first column. The command has been running for 20
'minutes with the program being completely non responsive.
'Loop through all worksheets and copy the data to the
'summary worksheet.
For Each xSheet In ActiveWorkbook.Worksheets

    If InStr(1, xSheet.Name, "ACCOUNT") And xSheet.Range("B1") <> "No Summary Available" Then _

        Set copyRng = xSheet.Cells

        For Each c In copyRng.SpecialCells(xlCellTypeVisible)

            If Len(c) <> 0 And Not ISIN(c, uniqueVal) Then _

                If InStr(1, c.Value, "C-") Then _

                'Set destination
                Set destRng = xSheet.Range("A2:A").Find(What:="*", SearchOrder:=xlRows, SearchDirection:=xlPrevious, LookIn:=xlValues)

                'Copy to destination Range
                c.Copy destRng

                End If

            End If

        Next c

    End If

Next xSheet

ExitTheSub:

Application.Goto DestSh.Cells(1)

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

End Sub

Sorry for the massive block of code.


texts:
I am very new to Ruby and building my first game. To be honest I did it this way because I was lazy to type so much. My friend told me that the correct way was to do this with case statement i.e. for scissor we have three cases, for rock we have three cases and similarly for paper.

puts "Rock, paper or scissor"
w = 0 and l =0 and t =0 and j=0
loop{
choice = ["paper" , "rock" , "scissor" ]
i=0

if j ==10
puts "wins : #{w}\nlosses : #{l}\ndraw:    #{t}"
       if w > l
           puts "You won the game"
       elsif w<l
           puts "You lost!"
       else
           puts "The game is a draw"
       end

         gets
      break
      end
while i == 0
human = gets.chomp.downcase
choice.each {
    |x|
    if human == x
        i+=1 and j+=1
        break
    end
    }
    puts "-----------------please enter rock paper or scissor-----------------" if i == 0
end
computer = rand(3)
com = choice[computer]
if (com == "scissor" and human != "rock") or (human == "scissor" and computer !=1)
   v = human <=> com
else
   v = com <=> human
end

puts "You chose #{human}, computer choose #{com}"
case v

    when 1
        puts "---->You win"
        w +=1
    when -1
        puts "---->Computer wins"
        l+=1
    else
        puts "---->draw"
        t+=1
end
}


texts: Java class to compute and get a MD5 hash as a string

texts:
Here is my class file to compute MD5 hashes on a file. I wanted to be able to easily calculate them without having to create a lot of overhead in the code using the class.

Can anyone tell me a list of improvements to make this class acceptable?

package Md5Generator;

/**
 *
 * @author jacob
 */
 import java.io.IOException;
 import java.security.*;
 import java.nio.file.Files;
 import java.nio.file.Paths;
 import java.nio.file.Path;

 /**
  * The point of this class it to compute the MD5 sum of a file
  */
 public class Md5 {
// two instance variables, one to store the file path and one to store the MD5 sum
private String path;
private String md5Sum;

/**
 * Constructor that takes a file path and and calcs the MD5 sum
 *
 * @param filePath the string that contains the full path to the file
 */
public Md5(String filePath) {
    path = filePath;
    calcMd5(path);
}

private void calcMd5(String filePath) {
    //create a messagedigest object to compute an MD5 sum
    try {
        MessageDigest md = MessageDigest.getInstance("MD5");
        //create a input stream to get the bytes of the file
        Path path = Paths.get(filePath);
        //read the bytes from the file and put them in the message digest
        md.update(Files.readAllBytes(path));
        //digest the bytes and generate an MD5 sum thats stored in an array of bytes
        byte[] hash = md.digest();
        //convert the byte array to its hex counter parts and store it as a string
        md5Sum = toHexString(hash);
    } catch (IOException | NoSuchAlgorithmException ex) {
        ex.printStackTrace();
    }

}

private String toHexString(byte[] bytes) {
    char[] hexArray = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
    char[] hexChars = new char[bytes.length * 2];
    int v;
    for (int j = 0; j < bytes.length; j++) {
        v = bytes[j] & 0xFF;
        hexChars[j * 2] = hexArray[v / 16];
        hexChars[j * 2 + 1] = hexArray[v % 16];
    }
    return new String(hexChars);
}

/**
 * Returns the MD5 sum as a String
 *
 * @return the string that contains the MD5 sum
 */
public String getMd5Sum() {
    return md5Sum;
}
}


texts:
I have below Java code to compare two list values with some condition:

 public boolean compareLists(List<SortData> prevList, List<SortData> modelList) {
        if (prevList != null && modelList != null && prevList.size() == modelList.size()) {
            boolean indicator = false;

            for (SortData modelListdata : modelList) {
                if (prevList.size() > 1 && modelList.size() > 1 && prevList.size() == modelList.size()) {
                    for (SortData prevListdata : prevList) {
                        if (modelListdata.getListBoxHeaderName().equals(prevListdata.getListBoxHeaderName())) {
                            indicator = false;
                            break;
                        }
                        else{
                            indicator = true;
                        }
                    }
                }
                for (SortData prevListdata : prevList) {
                    if (prevListdata.getListBoxHeaderName() != null && modelListdata.getListBoxHeaderName() != null) {
                        if (prevList.size() == 1 && modelList.size() == 1
                                && !prevListdata.getListBoxHeaderName().equals(modelListdata.getListBoxHeaderName())) {
                            return true;
                        } else if (prevListdata.getListBoxHeaderName().equals(modelListdata.getListBoxHeaderName())
                                && prevListdata.isSortAscending() != modelListdata.isSortAscending()) {
                            return true;
                        } else if (modelListdata.getListBoxHeaderName().equals(prevListdata.getListBoxHeaderName())
                                && modelListdata.getPosition() != prevListdata.getPosition()) {
                            return true;
                        }
                    }
                }
            }

            if (indicator) {
                return true;
            }
        } else {
            return true;
        }

        return false;

    }

But I do not think this code is optimized.

The condition I am checking:

Both List not null
If both List size 1 & Name not null return true
If header Names equals but sortAcscending boolean variable not same return true.
If header Names equals but position a integer value not same return true
If both List size > 1 and bth list size equals then check same header name exist in both the List if not then return true.

I don't think the above code is optimized and I have to write two for loops which look ugly.  What can I do to optimize this code?


texts:
I have built a delete button in Android, just like in Windows, which removes the string on the right hand side of the cursor (one by one). (Instead of the mainstream Backspace which removes the left side.)

Tell me if you have any better ideas.

package com.example.app;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.text.Editable;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView.BufferType;
import android.widget.Toast;

public class MainActivity extends Activity {
    public Toast t, t1,t2;
    Editable a, b, d, f, a1;
    String e;
    public int c, d1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        final EditText ed;

        Button dlt;

        dlt = (Button) findViewById(R.id.button1);

        ed = (EditText) findViewById(R.id.editText1);
        ed.clearFocus();

        dlt.setOnClickListener(new OnClickListener() {
            @SuppressLint("NewApi")
            public void onClick(View v) {

                InputMethodManager mgr = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                boolean check = mgr.isActive(ed);
                if(check==true){

                    Toast.makeText(getApplicationContext(), "Welcome", t2.LENGTH_SHORT)
                    .show();
                }
                a = ed.getEditableText();

                b = a;
                c = ed.getSelectionStart();

                String a11 = b.toString().substring(c);
                Toast.makeText(getApplicationContext(), a11, t1.LENGTH_SHORT)
                        .show();
                String a22 = b.toString().substring(0, c);

                boolean daj = b.toString().isEmpty();
                if (a11 != null && !a11.trim().equals("")) {

                    int strChar = a11.length();
                    String strcut = a11.substring(1, strChar);
                    e = a22.concat(strcut);

                    ed.setText(e, BufferType.EDITABLE);
                    b = ed.getEditableText();
                    ed.setSelection(c);
                } else {
                    Toast.makeText(getApplicationContext(), "Cool",
                            t.LENGTH_SHORT).show();
                }

            }

        });

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

}


texts:
I've always loved making games and using SFML, and up until a few days ago, I've had to re-write code over and over again. So I decided to write a game engine so I can reuse my code.

I've never done something like this before. I've read about it, and I watched a few videos. I'd love if you could look around, give me some ideas. Keep in mind I've only worked on this for less than a week.

GitHub

So far, I've just re-skinned SFML functions and classes using my own classes, but I've changed some functions around and made things a bit simpler.

Is it, for example, any good creating my own Sprite class that is basically a re-skin of the SFML sprite class, with perhaps some added functionality, or should my resource manager just return an SFML sprite, which the user of the engine can just use all the in-built functionality for the sf::Sprite?

Here is a very simple program that creates a sprite and a text and draws them on the screen. And we can use WASD to move the sprite.

#include <Tengine2D\ResourceManager.hpp>
#include <Tengine2D\Window.hpp>
#include <Tengine2D\Keyboard.hpp>
#include <Tengine2D\Clock.hpp>
#include <Tengine2D\Text.hpp>
#include <Tengine2D\Vector2.hpp>
#include <Tengine2D\GameState.hpp>
#include <Tengine2D\Camera.hpp>

#include <iostream>

int screenWidth = 1600;
int screenHeight = 640;

t2d::Clock _clock;
t2d::GameState gameState;

int main()
{

    t2d::Window _window;
    _window.create(screenWidth, screenHeight, "BELLO!");

    gameState = t2d::GameState::PLAY;

    // Text
    t2d::ResourceManager::createText("Text", "Fonts/times.ttf");
    t2d::ResourceManager::getText("Text").setCharacterSize(50);
    t2d::ResourceManager::getText("Text").setStyle(t2d::TextStyle::Bold);
    t2d::ResourceManager::getText("Text").setColor(t2d::Color::Magenta);
    t2d::ResourceManager::getText("Text").setPosition(screenWidth / 4.0f, screenHeight / 2.0f);
    t2d::ResourceManager::getText("Text").setString("Hello World");

    // Sprite
    t2d::ResourceManager::createSprite("RedPlayer", "Sprites/RedPlayer.png");
    t2d::ResourceManager::getSprite("RedPlayer").setPosition(screenWidth / 4.0f, screenHeight / 2.0f);

    while (gameState != t2d::GameState::QUIT)
    {
        float delta = _clock.restart().asSeconds();

        while (_window.pollEvent())
        {
            if(t2d::Keyboard::keyPressed(t2d::Keyboard::Escape))
            {
                gameState = t2d::GameState::QUIT;
            }
        }

        if (t2d::Keyboard::isKeyPressed(t2d::Keyboard::D))
        {
            t2d::ResourceManager::getSprite("RedPlayer").translate(400 * delta, 0.0f);
        }
        if (t2d::Keyboard::isKeyPressed(t2d::Keyboard::A))
        {
            t2d::ResourceManager::getSprite("RedPlayer").translate(-400 * delta, 0.0f);
        }
        if (t2d::Keyboard::isKeyPressed(t2d::Keyboard::S))
        {
            t2d::ResourceManager::getSprite("RedPlayer").translate(0.0f, 400 * delta);
        }
        if (t2d::Keyboard::isKeyPressed(t2d::Keyboard::W))
        {
            t2d::ResourceManager::getSprite("RedPlayer").translate(0.0f, -400 * delta);
        }

        _window.clear(t2d::Color(150, 150, 5, 255));
        _window.draw(t2d::ResourceManager::getSprite("RedPlayer"));
        _window.draw(t2d::ResourceManager::getText("Text"));
        _window.display();
    }

    return 0;
}


texts:
Given a string, this code

Multiplies odd numbers
Subtracts even numbers, do nothing if only one even number is found
Turns uppercase letters to lowercase and vice versa

I think this code is too long for those operations. There are certainly better ways of doing this. How can I make this shorter, better and faster? And what are better ways of doing this?

#include <string>
#include <cctype>
#include <iostream>

int main() {
    int odd = 0;
    int even = 0;
    std::string letters{};
    bool set = false;
    std::cout << "enter words: ";
    std::string input;
    std::cin >> input;
    for (char c : input) {
        if (isdigit(c)) {
            int number = c-48;
            if (number % 2 == 0) {
                if (!set) {
                    even = number;
                    set = true;
                } else {
                    even -= number;
                }
            } else {
                if (odd == 0) {
                    odd++;
                }
                odd *= number;
            }
        } else if (isalpha(c)) {
            letters += (isupper(c)) ? tolower(c) : toupper(c);
        }
    }
    std::cout << "odd: " << odd << '\n';
    std::cout << "even: " << even << '\n';
    std::cout << "letters: " << letters << '\n';
}


texts:
I'm trying to re-learn some JS fundamentals and wondered if anyone knowledgabe could tell me if I'm doing something very wrong in my approach to this simple word counting class.

I want to create a class that takes arbitrary text and returns information about its wordcount, frequency of words, etc. One of the methods I have so far returns a hash where each key coresponding to a word has an element called count which is its frequency in the text.

One usage is to produce an output that will be printed to a file with WORD COUNT on each line.

function WordCounter(){
   this.text = new String()
}

WordCounter.prototype.addWords = function(words){
    this.text += words
}

WordCounter.prototype.count = function(){
    return this.text.split(" ").length
}
WordCounter.prototype.getFrequenciesAsHash = function(){
    var words = this.text.split(" ")
    var frequencies = {}
    while(words.length > 0){
        var word = words.pop()
    if(typeof frequencies[word] == "undefined"){
        frequencies[word] = {}
        frequencies[word].count = 0
    }
    frequencies[word].count++
    }
    return frequencies
}


texts: Reverse Polish Notation calculator in Scala

texts:
I wrote an RPN solver in Scala. I'd love to get some feedback on approaches to make this feel more idiomatic.

object ReversePolishNotation {
  private object Operator extends Enumeration {
    val Divides = "/"
    val Times = "*"
    val Plus = "+"
    val Minus = "-"
  }

  import Operator._

  private val stringToOperator = Map[String, (Double, Double) => Double] (
    Divides -> {_ / _},
    Minus -> {_ - _},
    Times -> {_ * _},
    Plus -> {_ + _}
  )

  private def foldFunc(acc: List[Double], tok: String) = acc match {
    case Nil | List(_) => tok.toDouble :: acc
    case head::next::rest => tok match {
      case op @ (Divides | Minus | Times | Plus) => stringToOperator(op) (next, head) :: rest
      case s: String => s.toDouble :: acc
    }
  }

  def solve(tokens: Seq[String]) =
  tokens.foldLeft(List[Double]())(foldFunc) match {
    case head::Nil => head
    case Nil => throw new Exception("The stack cannot be empty!")
    case head::next::rest => throw new Exception("The stack should only have one value!")
  }
}


texts: Leetcode: Flatten binary tree to linked list C#

texts:
https://leetcode.com/problems/flatten-binary-tree-to-linked-list/

Please comment on performance

  Given a binary tree, flatten it to a linked list in-place.

  For example, given the following tree:

    1
   / \
  2   5
 / \   \
3   4   6

  The flattened tree should look like:

1
 \
  2
   \
    3
     \
      4
       \
        5
         \
          6

using System;
using System.Collections.Generic;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace LinkedListQuestions
{
    [TestClass]
    public class FlattenBinaryTree2LinkedList
    {
        [TestMethod]
        public void FlattenBinaryTree2LinkedListTest()
        {
            TreeNode root = new TreeNode(1);
            root.left = new TreeNode(2);
            root.right = new TreeNode(5);
            root.left.left = new TreeNode(3);
            root.left.right = new TreeNode(4);
            root.right.right = new TreeNode(6);
            Flatten(root);
            Assert.AreEqual(1, root.data);
            Assert.AreEqual(2, root.right.data);
            Assert.AreEqual(3, root.right.right.data);
            Assert.AreEqual(4, root.right.right.right.data);
            Assert.AreEqual(5, root.right.right.right.right.data);
            Assert.AreEqual(6, root.right.right.right.right.right.data);

        }
        public void Flatten(TreeNode root)
        {
            if (root == null || (root.left == null && root.right == null))
            {
                return;
            }
            Stack<TreeNode> stack = new Stack<TreeNode>();
            var head = root;
            stack.Push(root);
            while (stack.Count > 0)
            {
                var curr = stack.Pop();
                if (curr != root) // in the first iteration, we don't want to move the head to the next item
                {
                    head.right = curr;
                    head = curr;
                }
                if (curr.right != null)
                {
                    stack.Push(curr.right);
                    curr.right = null;
                }
                if (curr.left != null)
                {
                    stack.Push(curr.left);
                    curr.left = null;
                }
            }
        }
    }
}


texts: Optimize function for assigning existing 3D array values to values of keys in array of objects

texts:
I have JSON data from a Google sheet in a 3D array like this:

const values = [
  [
    // useless first array
  ],
  [
    'timestamp_dont_want',
    'bird',
    '',
    '',
    'easy',
    'foot'
  ],
  [
    'timestamp_dont_want',
    'bee',
    'celery'
  ],
  // lots of other arrays
  [
    'timestamp_dont_want',
    'bat',
    'chocolate',
    'droid',
    '',
    'finger',
    '',
    'hella cool',
    'indiana'
  ]
];

The maximum length of any given array is 12. Other than the entire first array and index 0 of every following array, each value (that is present and not empty) in an array corresponds to a desired object key label I have stored as 11 strings in another array:

const labels = [
  'label_b',
  'label_c',
  'label_d',
  'label_e',
  'label_f',
  'label_g',
  'label_h',
  'label_i',
  'label_j',
  'label_k',
  'label_l'
];

Some arrays have all the values I need and many have empty values or stop at a certain index. I would like to create a new array of objects, containing only the useful and present data, that would be organized like this:

const organized = [
  {
    label_b: 'bird',
    label_e: 'easy',
    label_f: 'foot'
  },
  {
    label_b: 'bee',
    label_e: 'celery'
  },
  // lots of other objects
  {
    label_b: 'bat',
    label_c: 'chocolate',
    label_d: 'droid',
    label_f: 'finger',
    label_h: 'hella cool',
    label_i: 'indigo'
  }
];

I wrote a function, but it doesn't feel very elegant:

function sort (arr3d, arrKeys) { // Passing values and labels constants from above
  let organized = []; // Initiate array
  for (var i = 1; i < arr3d.length; i++) { // For each array of values, starts at 1 to ignore first useless array
    organized.push({}); // Create empty objects
  }
  for (var j = 0; j < arrKeys.length; j++) { // Outer loop once for each unique object key
    for (var k = 1; k < arr3d.length; k++) { // Inner loop for each array of values, starts at 1 to ignore first useless array
      if (arr3d[k][j + 1]) { // Testing presence of value before writing in next step, ignoring index 0 of each array
        organized[k - 1][arrKeys[j]] = arr3d[k][j + 1].trim(); // Craete new key in object; trim value from associated array and assign to key
      }
    }
  }
  console.log(organized); // Prove it worked
}

Any ideas about how to refactor or optimize? Maybe you can teach me about using a new JS method.


texts:
Hey guys have a bit of code below I'm looking to optimize, the code is working, just feel it could be shorter as I had to ignore DRY principles sadly - couldn't think of a better way.

Objective: Minimize the if ($isMulti) { } else {} statement

PHPDoc:

/**
 * Syncs an array key => value pair to database column => value
 *
 * Will ignore keys where a column does not exist for which will allow you to enter a dirty array
 * as long as it has the key => value pairs that you wish to update.
 *
 * Cannot override
 *
 * @param array $data
 *
 * @returns void
 */

Code:

final protected function syncToDatabase(array $data)
{
    $isMulti = FALSE;

    $model      = $this->model;
    $identifier = $this->tableIdColumn;

    $sh = (count($data) > 0) ? $data : FALSE;

    if (!$sh) {
        return;
    }

    // determine if the array has multiple result sets
    foreach ($sh as $x) {
        if (is_array($x)) {
            $isMulti = TRUE;
            break;
        }
    }
    /////////////////////

    if ($isMulti) {
        foreach ($sh as $item) {
            $row = $model::get()
                ->filter(
                    array(
                        "{$identifier}" => $item[ $identifier ]
                    )
                )
                ->first();

            if (!is_null($row)) {
                // update existing row
                $row->update($item);
                $row->write();
            }
            else {
                // row not found insert
                $new = $model::create();
                foreach ($item as $res => $val) {
                    $new->$res = $val;
                }
                $new->write();
            }
        }
    }
    else {
        $row = $model::get()
            ->filter(
                array(
                    "{$identifier}" => $sh[ $identifier ]
                )
            )
            ->first();

        if (!is_null($row)) {
            // update existing row
            $row->update($sh);
            $row->write();
        }
        else {
            // row not found insert
            $new = $model::create();
            foreach ($sh as $res => $val) {
                $new->$res = $val;
            }
            $new->write();
        }
    }
}

Example Invocations:

$array1 = array(
    "Column1" => "Foo",
    "Column2" => "Bar",
    "Column3" => "Foobar",
);

$array2 = array(
    array(
        "Column1" => "Foo",
        "Column2" => "Bar",
        "Column3" => "Foobar",
    ),
    array(
        "Column1" => "Some",
        "Column2" => "Random",
        "Column3" => "Values",
    )
);

syncToDatabase($array1);
syncToDatabase($array2);


texts: Wanted to write my own form slider, Jquery/JS

texts:
I would like a fair minded critique of this code to get some feedback. I am not trying to re-invent the mold here, and I know there are plugins galore I could have used to do what I am doing here, but the point was to do it myself so that I can learn more and become better.

I have included comments to try and best explain my train of thought through the process, please don't implicitly critique the comments, they are just to explain my thinking as I made this code.

code below does exactly what I want..functions great in all modern browsers, rip me apart and make it better so I can get better:

$(document).ready(function(){

var sliding = false

    $(function () {
        var pos = new Array(); //certainly a way to automate this more but I didn't mind putting exact numbers in for interval postions...please critique.
         pos[0] = 0;
         pos[1] = 67;
         pos[2] = 133;
         pos[3] = 199;
         pos[4] = 267;
         pos[5] = 333;

        var target = $('span.slider')
        var targetToMove = null;
        var sliderCoordStart = null;
        var mouseMovement = null;

        target.mousedown(function(c) {
              c.preventDefault();//prevent chrome from turning cursor to text when dragging
              sliding = true
              targetToMove = $(this);
              targetToMove.addClass('noselect');//make sure we cant drag  untargeted things all over the screen
              mouseCoordStart =  c.clientX;
              sliderCoordStart=  parseInt(targetToMove.css('marginLeft'));
              oncontextmenu = function() {
              return false
              }

        });
        $(document).mouseup(function(e) {
             oncontextmenu = function() {
             return true
             }
             sliding = false
             document.onselectstart = function(){
             return true;
             }
             if(targetToMove !=null){
             targetToMove.removeClass('noselect');//no need to have the non select class anymore
             }
             var compare = new Array();
             if(mouseMovement !=null ){
             for(c=0;c<=5;c++){//do some math to make sure the slider ends up going to the closest interval postion
                 compare[c] = Math.abs(pos[c] - mouseMovement);
                }
             var goTo = Math.min.apply(Math, compare)
             var finalPos = compare.indexOf(goTo);
             targetToMove.css('marginLeft', pos[finalPos])

             }
        })
        $(document).mousemove(function(e) {
            if(sliding){
            document.onselectstart = function(){ //probably a better/smoother way to chain that right?
            return false;
            }
            sliderPos = targetToMove.css('marginLeft');
            mouseMovement = (e.pageX - mouseCoordStart)+sliderCoordStart;
                if(mouseMovement <= 0){//make sure we never exceed the left boundary
                    mouseMovement = 0;
                }
                if(mouseMovement >= 333){//make sure we never exceed the right boundary
                    mouseMovement = 333;
                }
              targetToMove.css('marginLeft', mouseMovement)
            }
        })
    })

});


texts:
This is a parsing function that will at tildes (~) to end of search terms in certain circumstances.

Example an inputs and outputs:

Input:                        Output:
name:(john doe)               name:(john~ doe~)
name:[andy TO charlie]        name:[andy TO charlie]
john doe                      john~ doe~
james NOT jane                james~ NOT jane
james NOT (james smith)       james~ NOT (james smith)
james NOT jane smith          james~ NOT jane smith~
name:"john doe" australia     name:"john doe" australia~

function addTilde(string) {
    if (!/[\[\[\]~"(NOT)\-\!\d\(\)(OR)(AND)\&\|\: ]/.test(string)) {
        string = string.concat("~");
    }

    return string;
};

function fuzzQuery(rawQuery) {
    /*split the string into spaces, brackets, double quotes and words*/
    re = /(?=[()\[\] "])|(?=[^\W])\b/;
    strSplit = rawQuery.split(re);

    newQuery = "";

    for (var i = 0; i < strSplit.length; i++) {
        var s = strSplit[i];
        var newElement = "";

        /*if it contains a [ or "*/
        if (s.indexOf("\x22") != -1 || s.indexOf("[") != -1) {

            /*determine closing symbol*/
            var closingSymbol;
            if (s == "\x22") {
                closingSymbol = "\x22";
                newElement = newElement.concat(strSplit[i++]); /*need to skip opening one for double quotes*/
            } else closingSymbol = "]";

            /*concat elements together until closing element found)*/
            do {
                newElement = newElement.concat(strSplit[i]);
            }
            while (strSplit[i++] != closingSymbol)
        }

        /*if it contains a NOT*/
        else if (s.indexOf("NOT") != -1) {
            newElement = strSplit[i++]; /*concat the NOT*/

            /*concat any spaces*/
            while (strSplit[i] == " ") {
                newElement = newElement.concat(strSplit[i++]);

            }

            if (strSplit[i] == "(") {
                do {
                    newElement = newElement.concat(strSplit[i]);
                }
                while (strSplit[i++] != ")")

            } else newElement = newElement.concat(strSplit[i++]);

        } else(newElement = strSplit[i]);

        newElement = addTilde(newElement);
        newQuery = newQuery.concat(newElement);
    }

    return newQuery;
};

Now fuzzQuery is quite a long method.
It essentially has five parts.

Split the initial query out into elements.
Loop through each element.

a) Concat square brackets and double quotes.

else b) concat NOTs.

now add tilde to element if appropriate
Return the join the elements back together and return the new query.

What I was thinking is that you could pass off steps two and three to their own methods, so that the whole query looks something like (but not exactly like!):

function fuzzQuery(rawQuery)
{
    strSplit = splitQuery(rawQuery);
    concatSqrAndDblQuotes(strSplit);
    concatNots(strSplit);
    return putBackTogether(strSplit);
}

ie.

function doSquareAndDblQuotes(strSplit, i) {
    if (s.indexOf("\x22") != -1 || s.indexOf("[") != -1) {

        /*determine closing symbol*/
        var closingSymbol;
        if (s == "\x22") {
            closingSymbol = "\x22";
            newElement = newElement.concat(strSplit[i++]); /*need to skip opening one for double quotes*/
        } else closingSymbol = "]";

        /*concat elements together until closing element found)*/
        do {
            newElement = newElement.concat(strSplit[i]);
        }
        while (strSplit[i++] != closingSymbol)
    }

    return newElement;
}

But the problem is here that we'd need to be keeping track of a few variables being changed in this function. ie. the i counter, and whether or not that if statement was executed. So you could start using globals (is that even a thing in javascript?)... and it gets messy.

So possibly another way, would be to create an object that you pass in, and return, which keeps track of these variables.

What do you think?


texts: Implementation of disjoint set in Java with linked-list

texts:
I have just wrote a linked list implementation of disjoint sets in Java for the Rainfall Problem. Can you take a look and tell me if there is something missing and also make a judgement in performance?

public class DisJointSet<E>
{
    int rank;
    DNode<E> head;
    DNode<E> tail;

    public DisJointSet(E data)
    {
        DNode<E> node = new DNode<>(data);
        head = node;
        tail = node;
        rank = 1;
        node.represantive = this;
    }

    public void union(DNode<E> x, DNode<E> y)
    {

        DisJointSet<E> xSet = findSet(x);
        DisJointSet<E> ySet = findSet(y);
        if (xSet.rank>= ySet.rank)
            append(xSet, ySet);
        else
            append(ySet, xSet);
    }

    public void append(DisJointSet<E> first, DisJointSet<E> second)
    {

        if (first.rank == 0 || second.rank == 0)
            throw new IllegalArgumentException();

        // Set the representative of each node in the second set to be
        // the first set.
        DNode<E> curr = second.head;

        while(curr!=null)
        {
            curr.represantive = first;
            curr = curr.next;
        }

        first.tail.next = second.head;
        first.tail = second.tail;
        first.rank += second.rank;

        // Invalidate the second set, just to be sure.
        second.head = null;
        second.tail = null;
        second.rank = 0;
    }

    public DisJointSet<E> findSet (DNode<E> x)
    {
        return x.represantive;
    }
}

class DNode<E>
{
    DNode<E> next;
    DisJointSet<E> represantive;
    E data;

    DNode(E val)
    {
        data = val;
    }
}


texts:
This is my code in C# for performing insertion sort:

static int[] performInsertionSort(int[] inputarray)
{
    for (int i = 0; i < inputarray.Length-1; i++)
    {
        int j = i+1;

        while (j>0)
        {
            if (inputarray[j-1] > inputarray[j])
            {
                int temp = inputarray[j-1];
                inputarray[j - 1] = inputarray[j];
                inputarray[j] = temp;

            }
            j--;
        }
    }
    return inputarray;
}

Is there a way to optimize this code? Can I make further changes to it?


texts: Unit Testing Datalayer written in ADO.net

texts:
I have datalayer code as below which is implementing an interface as:
Note: I have hand written this code on Notepad so it may contain some typo errors, which you can gracefully ignore.  I am searching for an approach here.

public interface ISimpleInterface{
    void DosSomething(long someValue);
}

public class ConcreteImplementation: ISimpleInterface
{
    public void DosSomething(long someValue){
        //add code for creating new command, connection objects here
        using(var connection=new NpgsqlConnection(ConnectionString)){
            connection.Open();
            long ID=GetNextValueFromSeq1(connection);
            using(var command=new NpgsqlCommand()){
                command.Connection=connection;
                command.CommandText="Insert INTO testTable(col1, col2) VALUES (:pcol1, :pcol2)";
                command.Parameters.AddRange(
                    new NpgsqlParameters{ ParameterName="pcol1", ParameterType=NpgsqlDbType.BigInt, Value=ID},
                    new NpgsqlParameters{ ParameterName="pcol1", ParameterType=NpgsqlDbType.BigInt, Value=someValue}
                );
            }
        }
    }

    long GetNextValueFromSeq1(NpgsqlConnection connection){
        //code to get next value from Sequence1 goes here
    }
}

A typical Unit Test class might be:

public class ConcreteImplementationTests{

    public void DoSomething_SimpleInsert_InsertsRecord(long someValue){
        //code for deleting or truncating table  testTable goes here

        var sut=new ConcreteImplementation();

        sut.DoSomething(13);

        //write a select command to check whether a record has been inserted in testTable

        //If there is one record in table then test passes, else it fails.
    }
}

Note: My concerns are that how I can assert that Dosomething method correctly takes value from sequence and inserts in table, because in real life, a developer might even forget to get value from GetNextValueFromSeq1 method.  He/she might not know this thing unless/until at a later stage when running the application they get a run time exception.

I am also open to any suggestions in improving my code so as long as it provides greater testability, test maintainability.

In real life, the DosSomething method might even have a list of long values.


texts: Synchronizer for importing XML files into a database when folder content changes

texts:
I have created a Synchronizer, the purpose of which is to read data from an XML source file and store the result in a DB.

I have different source types, for example Student.XML, School.XML, etc. These files are copied in my source directory, C:\Source.

My Synchronizer watches the Source folder, and every time there is a new file, it should read it, map it to my domain class and write the domain class into the DB.

If C:\Source folder contains Student.XML, it should read the content of the XML file and copy it in Student Table in the DB. If C:\Source contains School.XML, it should read the file and copy the content to School Table.

To solve this, I have defined an ISyncer interface:

public interface ISyncer
{
    // Read input and synchronize destination, return error message if any
    string Sync();
}

Now all my Syncer types (e.g. StudentSyncer, SchoolSyncer, etc) should implement this interface:

public class StudentSyncer : ISyncer
{
    // simple XML reader, reads XML file into a list of List<XMLStudent>
    private XMLStudentReader _reader;

    public StudentSyncer(string file)
    {
        _reader = new XMLStudentReader(file);
    }

    public string Sync()
    {
        // read the input
        List<XMLStudent> source = _reader.ReadAll();

        // using automapper map to domain object
        List<Student> dbStudent = Mapper.Map<List<XMLStudent>, List<Student>>(source);
        dbStudent.ForEach(s => s.IsCurrent = true);                // set IsCurrent

        // write records to Student table, using Unit of Work patterns
        using (var context = new DbContext())
        {
            UnitOfWork uow = new UnitOfWork(context);

            // set the existing records to not current
            var curSet = uow.Student.FindByTrackingChanges(s => s.IsCurrent == true).ToList();
            curSet.ForEach(s => s.IsCurrent = false);
            uow.Student.AddRange(dbStudent);
            uow.SaveChanges();
        }

        return "";  // no error
    }
}

I have a Windows service, which calls the DoSync() method every 30 seconds:

public void DoSync()
{
    foreach (string file in Directory.EnumerateFiles(@"C:\Source", "*.xml"))
    {
        // use syncer factory to initialize the correct instance of syncer based on input file name
        ISyncer syncer = _syncerFactory.CreateInstance(file);

        // do the synchronization task
        syncer.Sync();

        // Move file to processed folder
        MoveFile(@"C:\Destination");
    }
}

The Factory is a simple factory. It reads the source file name, e.g. Student.XML, School.XML and based on the file name. It initializes the correct Syncer, e.g. StudentSyncer, SchoolSyncer.

I am happy with the code, but it is bothering me because I feel it is not following the Single Responsibility Principle. My Syncer class is not doing 1 task, but it is doing 3 tasks: read input, map to domain class, write to DB.


texts: regular expression for telephone/mobile per country and variable naming

texts:
would like to know if there is a better approach in doing a telephone/mobile number regular expression for specific country. this includes naming variables like how to know if format is international format (is it with + sign?), a national format (is it the area code enclosed in parenthesis) or a local format (no + sign, and no area code), currently they are labelled as country_name_telephone/country_name_mobile or country_name_telephone_N_digit, etc...

below are the regular expression for some country.

/** matches the following pattern:
 * - 01-111-11-11
 * - 01 111 11 11
 * - 011-11-11-11
 * - 011 11 11 11
 * - 011111111
 */
public final static String CTRY_BELGIUM_TELEPHONE = "^0(\\d{8}|\\d\\s\\d{3}\\s\\d\\d\\s\\d\\d|\\d-\\d{3}-\\d\\d-\\d\\d|\\d\\d\\s\\d\\d\\s\\d\\d\\s\\d\\d|\\d\\d-\\d\\d-\\d\\d-\\d\\d)$";

/** matches the following pattern:
 * - 0412-34-56-78
 * - 0412 34 56 78
 * - 0412-345-678
 * - 0412 345 678
 * - 0412345678
 */
public final static String CTRY_BELGIUM_MOBILE = "^04\\d\\d(\\d{6}|\\s\\d\\d\\s\\d\\d\\s\\d\\d|\\s\\d{3}\\s\\d{3}|-\\d\\d-\\d\\d-\\d\\d|-\\d{3}-\\d{3})$";

/** matches the following pattern:
 * - 0000-0000
 * - 0000 0000
 * - 00000000
 */
public final static String CTRY_HONG_KONG_TELEPHONE = "^(\\d{4}[-\\s]?\\d{4})$";

/** matches the following pattern:
 * - +852-0000-0000
 * - +852 0000 0000
 * - +85200000000
 */
public final static String CTRY_HONG_KONG_MOBILE = "^\\+852(\\d{8}|-\\d{4}-\\d{4}|\\s\\d{4}\\s\\d{4})$";

/** matches the following pattern:
 * - 212-0000
 * - 212 0000
 * - 2120000
 */
public final static String CTRY_UNITED_STATES_TELEPHONE_7_DIGIT = "^[2-9]((?!11)\\d{2})[-\\s]*\\d{4}$";

/** matches the following pattern:
 * - 200 212 0000
 * - 200-212-0000
 * - 2002120000
 */
public final static String CTRY_UNITED_STATES_TELEPHONE_10_DIGIT = "^[2-9]\\d{2}((-[2-9]((?!11)\\d{2})-)|(\\s[2-9]((?!11)\\d{2})\\s)|([2-9]((?!11)\\d{2})))\\d{4}$";

/** matches the following pattern:
 * - all matches in CTRY_UNITED_STATES_TELEPHONE_7_DIGIT and CTRY_UNITED_STATES_TELEPHONE_10_DIGIT
 */
public final static String CTRY_UNITED_STATES_TELEPHONE = "("+CTRY_UNITED_STATES_TELEPHONE_7_DIGIT+")|("+CTRY_UNITED_STATES_TELEPHONE_10_DIGIT+")";

/** matches the following pattern:
 * - +1 200 212 0000
 * - +1-200-212-0000
 * - +12002120000
 */
public final static String CTRY_UNITED_STATES_MOBILE = "^\\+1((-[2-9]\\d{2}-[2-9]((?!11)\\d{2})-)|(\\s[2-9]\\d{2}\\s[2-9]((?!11)\\d{2})\\s)|([2-9]\\d{2}[2-9]((?!11)\\d{2})))\\d{4}$";


texts: Changes quantities that are displayed in a shopping cart page

texts:
I'm fairly new to PHP and am following e-commerce tutorials. When exploring a way to resolve a problem I had with a PHP code block, I came upon a post another person had with the same code block. The post suggested a way to simplify the code.

Original code block:

<?php
if (isset($_POST ['pid'])) {
    $pid = $_POST ['pid'];
    $wasFound = false;
    $i = 0;
    if (!isset ($_SESSION["cart_array"]) || count($_SESSION ["cart_array"])<1){
        $_SESSION["cart_array"] = array (0=> array("item_id"=> $pid, "quantity" => 1));
    }  else {
        foreach ($_SESSION["cart_array"] as $each_item) {
            $i++;
            while(list($key,$value)=each($each_item)){
            if ($key== "item_id" && $value == $pid) {
                array_splice ($_SESSION["cart_array"], $i-1,1, array(array("item_id"=>$pid,"quantity"=> $each_item['quantity']+1)));
                $wasFound = true;
            }
        }
    }
    if($wasFound==false) {
        array_push ($_SESSION["cart_array"], array("item_id"=> $pid, "quantity" => 1));
        }
    }
    header("Location: cart.php");
    exit();
}
?>

This was the suggested simplified code block and an explanation of what to do after changing code. I am unsure how to implement the the part suggested after the code block.

if (isset($_POST['pid'])) {
    // add (+1) item to cart
    $pid = (int)$_POST['pid']; // cast as integer
    // valid pids are > 0
    if($pid > 0){
    if(!isset($_SESSION['cart_array'][$pid])){
    // item is not in the cart, add it with quantity = 1
    $_SESSION['cart_array'][$pid] = array("item_id" => $pid, "quantity" => 1); // I left the array in the cart the same, but it
could also be simplified so that it is only the quantity, since the
item_id is now the cart array index
    } else {
    // item is in the cart, increment quantity
    $_SESSION['cart_array'][$pid]['quantity']++;
    }
    }
    header("location: cart.php");
    exit();
    }

  To get the details for the cart items, you need to run ONE query that
  gets all of them at the same time (putting a query inside of a loop is
  a resource killer). For the definition of the cart that I have
  suggested, you can use array_keys to get all the item id's. You
  would then implode those into a comma separated list and put them into
  an IN() comparison in the WHERE clause in a query to get all the
  matching rows at once.

This is what I am considering adding to the code block:

if  ($result = print_r(array_keys('cart_array',$pid))) {
$comma_seperated = implode("," $result);
// then use use $comma_seperated in query where needed later in annother code block?
}

Am I on the right path?


texts:
I solved this problem in C++. I was having trouble though understanding what return headA; and return headB; returns after going back down the recursion tree. A code review is also appreciated!

  You’re given the pointer to the head nodes of two sorted linked lists.
  The data in both lists will be sorted in ascending order. Change the
  next pointers to obtain a single, merged linked list which also has
  data in ascending order. Either head pointer given may be null meaning
  that the corresponding list is empty.

/*
  Merge two sorted lists A and B as one linked list
  Node is defined as
  struct Node
  {
     int data;
     struct Node *next;
  }
*/
#include <iomanip>

Node* MergeLists(Node *headA, Node* headB)
{
    // check if either linked list is empty, then return the other one. when doing recursive, a new headA and headB will be passed in, so it will add the entire list correctly
  if (headA == NULL) {
      return headB;
  } else if (headB == NULL) {
      return headA;
  } else { // if neither empty go into this block
      if (headA->data <= headB->data) {
          headA->next = MergeLists(headA->next, headB);
          // returns the entire linked list after the recursion parses it in the correct order
          // not too sure what is returned going down the recursion tree
          // headA = 1 -> 3 -> 5 -> 6 -> NULL
          // headB = 2 -> 4 -> 7 -> NULL
          // would it return 6, 5, 3, 1, 1->2->3->4->5->6->7 after recursion tree?
          return headA;
      } else {
          headB->next = MergeLists(headA, headB->next);
          // return 7, 4, 2 after recursion tree?
          return headB;
      }
  }
}


texts:
Here's my test question for C++ programmer job:

Servers only static content, no cgi
Single process, multithreaded
1000 concurrent request at least
Valid http status codes and headers
No external libraries, just STL, POSIX and glibc

Here's my code:

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

#include <sstream>
#include <vector>

#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <pthread.h>

using namespace std;

    const char *response_200 = "HTTP/1.1 200 OK\nContent-Type: text/html; charset=utf-8\n\nHello!";
    const char *response_400 = "HTTP/1.1 400 Bad Request\nContent-Type: text/html; charset=utf-8\n\nBad Request!";
    const char *response_404 = "HTTP/1.1 404 Not Found\nContent-Type: text/html; charset=utf-8\n\nNot Found!";

void *handle_request(void *pcliefd)
{
    int cliefd = *(int*)pcliefd;
    delete (int *)pcliefd;

    ssize_t n;
    char buffer[255];
    const char *response;

    n = recv(cliefd, buffer, sizeof(buffer), 0);
    if(n < 0) {
        perror("recv()");
        return 0;
    }

    buffer[n] = 0;
    //printf("recv() %s\n", buffer);

    response = response_400;

    string s(buffer), token;
    istringstream ss(s);
    vector<string> token_list;
    for(int i = 0; i < 3 && ss; i++) {
        ss >> token;
        //printf("token %d %s\n", i, token.c_str());
        token_list.push_back(token);
    }

    if(token_list.size() == 3
            && token_list[0] == "GET"
            && token_list[2].substr(0, 4) == "HTTP") {
        if(token_list[1] == "/index.html") {
            response = response_200;
        } else {
            response = response_404;
        }
    }

    n = write(cliefd, response, strlen(response));
    if(n < 0) {
        perror("write()");
        return 0;
    }

    close(cliefd);
    return 0;
}

int main(int argc, const char *argv[])
{
    int sockfd = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
    struct sockaddr_in servaddr;
    pthread_t thread;

    if(sockfd < 0) {
        perror("socket() error");
        exit(EXIT_FAILURE);
    }

    servaddr.sin_family = AF_INET;
    servaddr.sin_port = htons(8080);
    servaddr.sin_addr.s_addr = htonl(INADDR_ANY);

    if(bind(sockfd, (struct sockaddr *)&servaddr, sizeof(servaddr)) < 0) {
        perror("bind()");
        exit(EXIT_FAILURE);
    }

    if(listen(sockfd, 1000) < 0) {
        perror("listen()");
        exit(EXIT_FAILURE);
    }

    struct sockaddr_storage clieaddr;
    int cliefd;
    char s[INET_ADDRSTRLEN];
    socklen_t cliesize;

    while(true) {

        cliesize = sizeof(clieaddr);
        cliefd = accept(sockfd, (struct sockaddr *)&clieaddr, &cliesize);
        if(cliefd < 0) {
            perror("accept()");
            continue;
        }

        inet_ntop(clieaddr.ss_family, (void *)&((struct sockaddr_in *)&clieaddr)->sin_addr, s, sizeof(s));
        printf("accept() %s\n", s);

        int *pcliefd = new int;
        *pcliefd = cliefd;
        if(true) {
            if(pthread_create(&thread, 0, handle_request, pcliefd) < 0) {
                perror("pthread_create()");
            }
        } else {
            handle_request(pcliefd);
        }
    }

    return 0;
}


texts:
I like to overcomplicate things, this is fairly simple though but I would like to keep it simpler without lowering readability. Not just to improve my code but also my self.

private String checkTrailingSlash(String website) {
    if(!website.endsWith("/")){
        website = website + "/";
    }
    return website;
}


texts:
How would one do the following in Haskell:

  Return all permutations of a list where one element comes before the
  another element (cannot assume that elements of the list can be
  ordered)?

My solution was to do:

sLeftOf l r lss =
    [ ls
    | ls <- lss
    , DL.findIndex (l==) ls <= DL.findIndex (r==) ls
    ]

for somewhere to the left of and

sDirectLeftOf l r lss =
  [ls
  | ls <- lss
  , DL.findIndex (l==) ls  == fmap (\x-> x - 1) (DL.findIndex (r==) ls)
  ]

for directly to the left of which works,

*Main Lib> sLeftOf 2 3 (permutations [1..3])
[[1,2,3],[2,1,3],[2,3,1]]

*Main Lib> sDirectLeftOf 2 3 (permutations [1..4])
[[1,2,3,4],[2,3,1,4],[4,2,3,1],[2,3,4,1],[4,1,2,3],[1,4,2,3]]

But I don't like these. The findIndex seems un-Haskelly and the fmap on the result of findIndex feels just wrong. Anyone has better ways to do this? For two lists there is a nice method using guard/zip and elem.

mylist = do
  x <- permutations ["a","b","c"]
  y <- permutations ["1","2","3"]

  leftOf "b" x "3" y
  return $ zip x y
  where
    leftOf x xs y ys = guard $ (x,y) `elem` zip xs (tail ys)
    leftOf' x xs y ys = guard $ (x,y) `elem` (aux xs (tail ys))
    aux a b@(_:ys) = (zip a b) ++ aux a ys
    aux _ []       = []

reqA = (map (map fst )) mylist
reqB = (map (map snd )) mylist
required = zip reqA reqB

The first leftOf is immediately to left of and the second is somewhere to the left of; but this won't work for a single list.


texts:
I have written the following code for returning the list of prime factors.  Any speed-enhancing suggestions?

import math
def is_prime(num):
    for n in range(2,math.floor(math.sqrt(num)+1)):
        if num%n==0:
            return False
    return True

def find_prime_factors(num):
    primes=[]
    for n in range(2,math.floor(num/2)+2):#The maximum value of the factor could only be half of the number
        if is_prime(num):
            primes.append(math.floor(num))
            break
        if is_prime(n) and num %n==0:
            num=num/n
            primes.append(n)
            while num%n ==0:
                num=num/n
                primes.append(n)

    return(primes)


texts:
I wrote a simple generic intercalate function (that should be semantically equivalent to the Haskell intercalate).

template <typename Fwd_It, typename Out_It>
    auto intercalate(Fwd_It first, Fwd_It last, Out_It destFirst,
                     Fwd_It whatFirst, Fwd_It whatLast) {
        if (first == last) return destFirst;
        *destFirst = *first;
        ++first;
        ++destFirst;

        while (first != last) {
            std::copy(whatFirst, whatLast, destFirst);
            *destFirst = *first;
            ++first;
        }
        return destFirst;
    }

It appears to be working with what I've tested with (empty ranges, different iterator-supporting ranges, different types, etc.).

However, is this:

generic enough?
clean enough?
fast enough?


texts:
I'm currently reviewing some different ways to have reusable components enforcing both most of the style & logic. The use case is a generic MainList with children components (eg. MainListToolbar, MainListContent, etc.) that can all be used together to create multiple mostly agnostic lists for business objects (eg. UserList, DeviceList, etc.).

For instance, I want to abstract away a multi-selectable logic and design in MainListContent while still being able to access the related internal state in the parent UserList (eg. this.state.selectedItems). Ideally, the multi-selectable logic (eg. onListItemClick, onListItemDoubleClick, etc.) should not leak at all into UserList.

I first thought about extending some MainListComponent (instead of Component), but I've never seen it in the React world and looks like a bad pattern to me.

I got something working with a state delegation pattern that enables to have an UserList that implements generic children elements and inherits the abstracted logic (eg. listItem selection) in it's own state to use it any way it wants.

Is there something flawed in this pattern/code? Is there a more elegant/safe way to achieve that?

const {Component} = React;

class MainList extends Component {
 render() {
    const {children} = this.props;
   return (

{children}

    );
  }
}

class MainListContent extends Component {
  constructor(props) {
   super(props);
    this.state = {
     selectedItems: []
    };
   this.handleListItemClick = (ev) => {
     const {selectedItems} = this.state;
     const value = ev.target.innerHTML;
      this.setState({
       selectedItems: !selectedItems.includes(value) ? selectedItems.concat(value) : selectedItems.filter(item => item !== value)
      });
    }
  }
  setState(nextState) {
    super.setState(nextState);
    const {onSetState} = this.props;
    if (onSetState) {
      onSetState(nextState);
    }
  }
  render() {
    const {title, items} = this.props;
    const {selectedItems} = this.state;
   return (

{title}

          {items.map((item, index) => (
{item}
))}

    );
  }
}

class UserList extends Component {
  constructor(props) {
   super(props);
    this.state = {};
    this.delegateSetState = this.setState.bind(this);
  }
  render() {
    const {items} = this.props;
    const {selectedItems} = this.state;
   return (
      <MainList>
        <MainListContent ref={ref => { this.mainListContent = ref; }} onSetState={this.delegateSetState} title="Users" items={items} />

count: {selectedItems ? selectedItems.length : 0}

      </MainList>
    )
  }
}

const Root = props => (
  <UserList items={['foo', 'bar', 'baz']}></UserList>
);

ReactDOM.render(
  <Root />,
  document.getElementById('root')
);


texts:
I've been reading more on PHP JSON and APIs I wanted to play around and pull a user's tweets so I wrote a function that requires the TwitterAPIExchange wrapper.

The code:

ini_set('display_errors', 1);
require_once('TwitterAPIExchange.php');
get_twitter_json();

function get_twitter_json() {
    $username       = 'foobar';
    $count          =   5;
    $json_folder    = 'json';
    $pull_time      =   1;

    $settings = array(
        'oauth_access_token'        => "",
        'oauth_access_token_secret' => "",
        'consumer_key'              => "",
        'consumer_secret'           => ""
    );

    if (is_dir($json_folder)) :
        echo "Directory $json_folder exists
";
    else :
        echo "Did NOT find directory $json_folder
";
        exit();
    endif;

    $file_loc   = "json/twitter.json";
    $cachetime  = @filemtime($file_loc);
    $diff       = time() - $cachetime;

    if ($diff <= 60 * $pull_time) :
        $results    = json_decode(file_get_contents($file_loc));
    else :
        $url = 'https://api.twitter.com/1.1/statuses/user_timeline.json';
        $getfield = '?screen_name=' . $username . '&count=' . $count;
        $requestMethod = 'GET';
        $twitter = new TwitterAPIExchange($settings);
        $results = json_decode(
            $twitter->setGetfield($getfield)
                    ->buildOauth($url, $requestMethod)
                    ->performRequest(), true
        );

        $i = 0;
        if (isset( $results['error'])) :
            echo 'Issue found in request';
            exit();
        else :
            foreach($results as $tweet) :
                $tweets[$i]['created']      = $tweet['created_at'];
                $tweets[$i]['text']         = $tweet['text'];
                $tweets[$i]['username']     = $tweet['user']['name'];
                $tweets[$i]['screenname']   = $tweet['user']['screen_name'];
                $tweets[$i]['url']          = $tweet['user']['url'];
                $i++;
            endforeach;
        endif;

        $jsonified = json_encode($tweets);
        $jsoncache = $file_loc;
        $fp = fopen($jsoncache, "w");
        fwrite($fp, $jsonified);
        fclose($fp);
    endif;

}

Are there any improvements I can make to my code?  Eventually I will implement this into a WordPress Plugin.  I am curious about any better approaches than fwrite and fclose so if there is a better way to write to a JSON file that would be helpful.


texts: Project Euler #12 (Highly divisible triangular numbers) in Python 3.x

texts:
I'm a beginner to programming and just started python, I've been trying to work through Project Euler challenges.

I wrote a program to solve Project Euler #12, which asks for the smallest number of the form 1+ 2 + 3 + … + n which has over 500 divisors.  It works perfectly with smaller numbers like 100, but takes too long trying to find up to 500 factors. I gave up waiting after about 20 minutes. I'd like some help with optimizing my code to make it faster.

I basically made a function that finds the triangular number of a given number and another function that counts the number of factors/divisors of a number. I made a while loop where a number keeps increasing till the triangular number of itself has more than 500 factors.

And here is my code:

#Starts the timer to measure time taken for code to run:
import time
start_time = time.time()

#Returns the triangular number of 'num':
def triangular(num):
    return int((num*(num+1))/2)

#Returns the number of factors(divisors) of 'num':
def facCount(num):
    summ = 0
    for i in range(1, num+1):
        if num % i == 0:
            summ += 1
    return summ

#Declares x (starting value):
x = 0

#main:

while True:
    #Checks if number of factors for the triangular of x is above 500
    if facCount(triangular(x)) > 500:
        #Sets the value of 'ans' to the triangular of 'x':
        ans = triangular(x)
        #Exits the loop since answer is found
        break
    x += 1

#Prints answer (the first triangular number that has more than 500 factors):
print(ans)

#Prints the time taken for code to execute:
print("--- %s seconds ---" % (time.time() - start_time))


texts:
I would like to do these actions step by step:

first DB update
copy file
unlink file
second DB update

It is working, but I don't know if my code is correct/valid:

$update1 = $DB->query("UPDATE...");

  if ($update1)
  {
    if (copy("..."))
    {
      if (unlink("..."))
      {
        $update2 = $DB->query("UPDATE ...");
      }
    }
  }

Is it possible to use if statement this way?

I found that it is usually used with PHP operators and PHP MySQL select, for example:

$select = $DB->row("SELECT number...");
  if ($select->number == 2) {
  ...
  }


texts:
Currently building my personal site using Jekyll, inuitcss and GitHub Pages. I'd like to hear your thoughts on the markup of my blog page and its post pages.

What do you think about handling logo's like this? Also I'm not sure about the headings. The page-title probably should be part of the main section.

blog markup:

            BlogPortfolioProfilImpressum

Freundliche Artikel

                    26. Januar 2014

We can't stop here

This is a post excerpt from the actual article. Usually the first paragraph.

                    15. Januar 2014

Introduction anyone?

This is a post excerpt from the actual article. Usually the first paragraph.

Author. Hosting. Used tools.

post markup:

            BlogPortfolioProfilImpressum

            26. Januar 2014

We can't stop here&hellip;

How're you doing? Eveything alright?

Another paragraph. Might be a conclusion.

Author. Hosting. Used tools.


texts: Add variable columns to INSERT statement

texts:
I'm learning SQL using python library pymysql.

I wanted to make an INSERT statement that will update 3, 5 or 10 columns using the same code by just passing the Database name, the Columns name and the Values.

Thus I made this:

def insert_statement(db,cols,values):
    separator = ","
    separator.join(cols)
    statement = "INSERT INTO " + db + " (" + separator.join(cols) + ") VALUES ("
    aux = []
    for i in range(0,len(values)):
        aux.append("%s")

    statement = statement + separator.join(aux) + ")"
    print (statement)
    return statement

Passing the values, the function produces:

>>>INSERT INTO Publicaciones (item_id,title,price) VALUES (%s,%s,%s)

Which works but, is it there a more pythonic way?