texts:
I am writing API in Kotlin - this is my first code in this language. I implemented a very primitive 'player' endpoint. I was wondering if I am doing everything ok (please don't mind the static variables - I will put them in the database later)

import org.springframework.http.ResponseEntity
import org.springframework.web.bind.annotation.*
import pl.domain.Player
import pl.rest.dto.PlayerDto

@RestController
@RequestMapping("/player")
class PlayerController {

    var players: Map<Long, Player> = mapOf(
            1L to Player(1L, "user1", "password1"),
            2L to Player(2L, "user2", "password2"),
            3L to Player(3L, "user3", "password3")
    )

    @GetMapping("/{id}")
    fun fetchPlayer(@PathVariable id : Long): ResponseEntity<Player> =
        players[id]?.let { ResponseEntity.ok(it) } ?: ResponseEntity.notFound().build()

    @PostMapping
    fun createPlayer(@RequestParam username: String, @RequestParam password : String): ResponseEntity<Player> {
        val playerId = (players.size + 1).toLong()
        val player = Player(playerId, username, password)
        players = players.plus(player.id to player)
        return ResponseEntity.ok(player)
    }

    @PutMapping
    fun updatePlayer(@RequestBody playerDto: PlayerDto): ResponseEntity<Player> {
        return players[playerDto.id]
                ?.apply {
                    username = playerDto.username ?: username
                    password = playerDto.password ?: password
                }?.let { ResponseEntity.ok(it) } ?: ResponseEntity.badRequest().build()
    }

    @DeleteMapping("/{id}")
    fun deletePlayer(@PathVariable id: Long): ResponseEntity<Nothing> {
        players = players.minus(id)
        return ResponseEntity.noContent().build()
    }

}

PlayerDto.kt:

class PlayerDto(var id: Long? = null, var username: String? = null, var password: String? = null)

Player.kt:

data class Player(var id: Long, var username: String, var password: String)


texts: Using functional interface arguments in methods of services injected via Spring

texts:
Here is the working code for my Spring service:

@Service
public class UploadService {

    @Inject
    @Qualifier("session")
    Session session;

    @Inject
    AsyncImageConvertService asyncImageConvertService;

    @Value("${aws.bucket-name}")
    String awsBucketName;

    @Inject
    AmazonS3 amazonS3;

    @Inject
    ImageMapper imageMapper;

    @Transactional(isolation = Isolation.READ_COMMITTED, propagation = Propagation.REQUIRED)
    public void uploadImage(Image image, String url, Runnable fnSaveObject) {
        File file = new File(System.getProperty("java.io.tmpdir"), image.getUrl());

        image.setUrl(url);
        image.setCreator(session.getUser());
        PutObjectRequest request = new PutObjectRequest(awsBucketName, image.getUrl(), file);
        request.setCannedAcl(CannedAccessControlList.PublicRead);
        amazonS3.putObject(request);

        TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() {
            public void afterCommit() {
                // Database has a newly inserted (and committed) image data here. asynceImageConvertService will select and update it.
                // fnSaveObject function should run in current transaction.
                asyncImageConvertService.processImage(image.getId(), file);
            }
        });

        imageMapper.insert(image); // image's id will be generated here.
        fnSaveObject.run();  // image's id should exists here.
    }
}

It is called from the following code:

uploadService.uploadImage(
                profileImage,
                "/user/" + user.getId() + "/" + profileImage.getUrl(),
                () -> userMapper.insertImage(user, profileImage) // generated image's id will be applied.
);

The Runnable functional interface will run in transaction and invoke async service method after transaction committed.

*Mapper is injected instance also, via spring-mybatis.

This code looks like it's working well, but I'm afraid it's not safe.

Is it safe to use functional interface arguments in methods of services injected via Spring?


texts:
I'm currently writting piece of logic which copies entities from one user account to another. My current strategy in doing this is like that:
Consider the following code:

 public class MobileOrderSettings:ICloneable
{
    public long Id { get; set; }
    public bool allowCash { get; set; }
    public int deliveryPrice { get; set; }
    public int deliveryTreshold { get; set; }
    public bool orderingEnabled { get; set; }
    public bool paymentsEnabled { get; set; }
    public int shippingType { get; set; }

    public virtual MobileApp MobileApp { get; set; }

    public object Clone()
    {
        var copy = CopyUtils.ShallowCopyEntity(this);
        copy.Id = default(int);
        copy.MobileApp = null;
        return copy;
    }
}

The ShallowCopyEntity method defined like in this way:

 public static TEntity ShallowCopyEntity<TEntity>(TEntity source) where TEntity : class, new()
    {

        // Get properties from EF that are read/write and not marked witht he NotMappedAttribute
        var sourceProperties = typeof(TEntity)
                                .GetProperties()
                                .Where(p => p.CanRead && p.CanWrite &&
                                            p.GetCustomAttributes(typeof(System.ComponentModel.DataAnnotations.Schema.NotMappedAttribute), true).Length == 0);
        var notVirtualProperties = sourceProperties.Where(p => !p.GetGetMethod().IsVirtual);
        var newObj = new TEntity();

        foreach (var property in notVirtualProperties)
        {

            // Copy value
            property.SetValue(newObj, property.GetValue(source, null), null);

        }

        return newObj;

    }

So, as you can see, I firstly copy all fields which is not virtual, reassing Id value and then perform copy of the dependent object(collection)(In this particular situation MobileOrderSettings depends on MobileApp entity, so I make MobileApp null, and in MobileApp Clone menthod I assign MobileOrderSettings virtual field the copy of MobileOrderSettings). Is this approach is good, or you can suggest any better solution?


texts: Holding server response header data after parsing it

texts:
I'm creating a program to retrieve web content in order to learn how these things work. I would like it to be as correct as possible, ideally fully compliant.

But I'm not sure this is the right approach to the problem. Is the following structure an appropriate way to hold server response header data after parsing it?

typedef enum {
    OPTIONS = 1, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT, PATCH
} HTTP_Methods;

typedef enum {
    KEEP_ALIVE = 1, CLOSE
} HTTP_Connection_Field;

typedef enum {
    CHUNKED = 1, COMPRESS, DEFLATE, GZIP, IDENTITY
} HTTP_Transfer_Encoding;

typedef struct {
    uint8_t http_version; //e.g. HTTP/1.1 = 11, HTTP/1.0 = 10, HTTP/0.9 = 9
    uint16_t response_code; //e.g. 200, 404, 500, ...
    char *accept_ranges;
    uint32_t age; //Non-negative, time in seconds, at least 31 bits of range
    HTTP_Methods allow;
    char *cache_control;
    HTTP_Connection_Field connection;
    char *content_encoding;
    char *content_language;
    uint32_t content_length;
    char *content_location;
    char *content_MD5;
    char *content_disposition;
    char *content_range;
    char *content_type;
    time_t date;
    char *etag;
    time_t expires;
    time_t last_modified;
    char *link;
    char *location;
    char *p3p;
    char *pragma;
    char *proxy_authenticate;
    char *refresh;
    time_t retry_after;
    char *server;
    char *set_cookie;
    char *strict_transport_security;
    char *trailer;
    HTTP_Transfer_Encoding transfer_encoding;
    char *vary;
    char *via;
    char *warning;
    char *www_authenticate;
} HTTP_Response_Header;

Maybe grouping the members that are not very commonly used into a different struct that is only allocated when they are in use would be a better idea?


texts: Ricochet Challenge: Robust IO and working with different types of numbers in Haskell

texts:
Background

I've tried to solve /r/DailyProgrammer Challenge #303 [Easy]: Ricochet (summarised below) in Haskell. The code below is now the second Haskell script I've ever written, so I'd consider myself quite the beginner. It works (to a bare minimum), but I'm not particularly happy with it.

My knowledge in Haskell at this point spans as far as the first two chapters of the fantastic Haskell Wikibook. I've not reached functors, monads, or friends, so if the solutions to my queries lie there then it might be wisest for me to settle until I learn more.

My Queries

Whilst I'm sure there are many problems, my main concerns in the code below regard the manner in which I'm dealing with the numerical arguments to ricochet, and the fragile nature of IO.

More particularly, regarding ricochet:

I wanted the 5 arguments (namely h, w, m, n and v) all to be any kind of integer (not minding Int or Integer, etc., so long as it's a whole number, mathematically speaking), barring v which can be any number at all (i.e. 1.05).
Whilst need for integers is important (as modulo (and thus the algorithm) wouldn't make sense without them), I also want to be able to perform arbitrary arithmetic, including any kind of division.
I took me much time and frustration to come up with anything that'd even compile, for what's considerably basic arithmetic, and at the end I still find that function signature and spam fromIntegral nasty. Any advice on dealing with this kind of situation in future?

And regarding IO:

What's there now is the bare minimum to work with the challenge. I'm not happy with it because it's so fragile. If anything at all is wrong with the input, the whole program explodes.
I'd rather just output a blank line if the input is invalid, but I've no idea how to get that done.

However, I'd of course appreciate any advice at all, even around spacing/indentation!

#!/usr/bin/env stack
-- stack --resolver=lts-8.2 --install-ghc runghc

{-
Ricochet
========

- https://redd.it/5vb1wf
-}

module Main
    ( Corner(..)
    , ricochet
    , main
    ) where

data Corner = UL | UR | LR | LL deriving (Show, Eq)

ricochet :: (Integral a, Fractional b) => a -> a -> a -> a -> b -> (Corner, a, b)
ricochet h w m n v
    = (c,b,d / v)

    where
    -- What's a more idiomatic way of doing this?
    h', w', d :: Num a => a
    h' = fromIntegral (h - m)
    w' = fromIntegral (w - n)
    d  = fromIntegral $ lcm w' h'

    b  = (d * (h' + w')) `div` (h' * w') - 2
    c  =
        case (
            ((d `div` h' - 1) `mod` 2),
            ((d `div` w' - 1) `mod` 2)
        ) of
            (0,0) -> LR
            (0,1) -> LL
            (1,0) -> UR
            (1,1) -> UL

main :: IO ()
main = interact ( unlines
                . map (output . input . words)
                . lines
                )

    where
    -- How to make these less fragile and more idiomatic?
    input (h:w:m:n:v:[]) = ricochet (read h) (read w) (read m) (read n) (read v)
    output (c,b,t) = show c ++ " " ++ show b ++ " " ++ show t

Challenge Summary

Each line input describes a bounding box with dimensions h and w, and an inner box with dimensions m and n (for height and width respectively).

The inner box starts in the top-right corner (0,0) and is travelling diagonally, towards (1,1). You're told the inner box is travelling at a velocity of v units per second.

I've interpreted all of the parameters as whole numbers, other than v, which is a real number.

An example line of input: 2 4 1 2 0.5.

The inner box can ricochet off of the bounding walls as it travels.

For each line of input, calculate the first corner that the inner box reaches (UR (upper right), LR (lower right) or LL (lower left)), along with the number of times the box ricocheted off of a wall before it reached that corner, and the time taken to get there.


texts:
/*
 * LinkedList.h
 *
 *  Created on: Mar 9, 2014
 *      Author: steven
 */

#ifndef LINKEDLIST_H_
#define LINKEDLIST_H_
#include <iostream>
using std::cout;
using std::endl;

template<class T>
class LinkedList {

    template<class E>
    struct Node {
        Node<E> *rightNode;
        E data;
        Node() {
            rightNode = NULL;
        }
    };
private:
    Node<T> *startNode;
    int size;
public:
    LinkedList() {
        startNode = NULL;
        size = 0;
    }
    void pushFront(T data) {
        if (size > 0) {
            Node<T> *temp = new Node<T>();
            temp->data = data;
            temp->rightNode = startNode;
            startNode = temp;
            size++;
            return;
        }
        pushBack(data);
    }
    void pushBack(T data) {
        if (size > 0) {
            Node<T> *temp = startNode;
            for (int i = 0; i < size - 1; i++) {
                temp = temp->rightNode;
            }
            temp->rightNode = new Node<T>();
            temp->rightNode->data = data;
            size++;
            return;
        }
        startNode = new Node<T>();
        startNode->data = data;
        size++;

    }

    T get(int num) {
        if (num > 0) {
            Node<T> * temp = startNode; //1
            for (int i = 0; i < num - 1; i++) {
                temp = temp->rightNode;
            }
            T tempData = temp->rightNode->data;
            delete temp;
            return tempData;
        } else {
            return startNode->data;
        }
    }
    void removeBack() {
        if (size > 2) {
            Node<T> *temp = startNode;
            for (int i = 0; i < size - 2; i++) {
                temp = temp->rightNode;
            }
            delete temp->rightNode;
            temp->rightNode = NULL;
        } else if (size == 2) {
            delete startNode->rightNode;
            startNode->rightNode = NULL;
        } else {
            delete startNode;
            startNode = NULL;
        }
        size--;

    }
    void printLinkedList() {
        Node<T> *temp = startNode;
        cout << temp->data << endl;
        for (int i = 0; i < size - 1; i++) {
            temp = temp->rightNode;
            cout << temp->data << endl;
        }
    }
    int getSize() {
        return size;
    }
    virtual ~LinkedList() {
        if (size > 2) {
            Node<T> *temp = startNode;
            while (temp->rightNode->rightNode != NULL) {
                Node<T> *currentTemp = temp;
                temp = temp->rightNode;
                delete currentTemp;
            }
            return;
        }
        if (size == 1) {
            delete startNode;
            return;
        }
        if (size == 2) {
            delete startNode->rightNode;
            delete startNode;
            return;
        }

    }
};

#endif /* LINKEDLIST_H_ */

Please critique the singly linked list, specifically the working aspect of it (making sure deleting correctly, etc.).


texts:
I made a bunch of functions and an enumeration, that together allow me to write something like a switch expression. It's not as powerful as Swift switch statements, since it's lacking pattern matching and I don't intend to use this in real code, it was just an experiment. Here is what I got:

enum Caze<T: ForwardIndexType where T: Equatable> {
    case RangeCaze(Range<T>)
    case ArrayCaze([T])

    func contains(elem: T) -> Bool {
        switch self {
        case let .RangeCaze(r):
            return r.contains(elem)
        case let .ArrayCaze(arr):
            return arr.contains(elem)
        }
    }
}

func caze<T: ForwardIndexType, R where T: Equatable>(vals: T..., @autoclosure(escaping) ret f: () -> R) -> (Caze<T>, () -> R) {
    return (.ArrayCaze(vals), f)
}

func caze<T: ForwardIndexType, R where T: Equatable>(vals: Range<T>, @autoclosure(escaping) ret f: () -> R) -> (Caze<T>, () -> R) {
    return (.RangeCaze(vals), f)
}

func caze<T: Equatable, R>(vals: T..., @autoclosure(escaping) ret f: () throws -> R) -> ([T], () throws -> R) {
    return (vals, f)
}

func schwitch<T: ForwardIndexType, R where T: Equatable>(value: T, _ cases: (Caze<T>, () -> R)..., @autoclosure def: () throws -> R) rethrows -> R {
    for (vals, f) in cases {
        if vals.contains(value) {
            return f()
        }
    }
    return try def()
}

func schwitch<T: Equatable, R>(value: T, _ cases: ([T], () -> R)..., @autoclosure def: () throws -> R) rethrows -> R {
    for (vals, f) in cases {
        if vals.contains(value) {
            return f()
        }
    }
    return try def()
}

This allows me to write code like:

schwitch(5, // results in "lol"
    caze(0, ret: "hello"),
    caze(1, 2, ret: "test"),
    caze(3..<7, ret: "lol"),
    def: "nop")

schwitch("helloo", //results in "nop"
    caze("hello", "Hello", ret: "test"),
    def: "nop")

I think there are a few problems with this though.

There is quite a bit of code duplication due to a few nearly identical functions being needed.
The closure sent to the caze functions are escaping, though they are intended to never actually escape beyond a very defined scope.
If code in a caze function throws, it doesn't get rethrown.
I also considered an alternative implementation for the schwitch functions but am worried that it takes brevity a bit too far:

(cases.filter{$0.contains(value)}.first ?? def)()

Are there any ways to improve on these 4 points and are there any other things that I missed or could have done better?


texts: UIImageView Animation with duration change

texts:
I have an array of UIImages that I animating using UIImageView,
and creates an effect of wave.
the user have plus and minus button and can control the wave
plus will make the wave animate faster.

But, when I change the animation duration of the UIImageView
the animation stopped and I cannot continue with the stopped position.
Only from start and the animation stopped in the middle.
Also I cannot get the current present frame / start the animation from specific frame.

So I tried to find a solution for this problem by animation only one every time.
But I feel that there are to many things happened in many threads.

Is there anything I can do to optimize my code?

class ViewController: UIViewController {

    @IBOutlet weak var imageView: UIImageView!

    var run = true
    var onComplete : (()->Void)?
    var time : Double = 3

    override func viewDidLoad() {
        super.viewDidLoad()

        imageView.animationImages = animationImages
        imageView.animationRepeatCount = 1

    }

    @IBAction func plusAction(_ sender: Any) {
        self.time -= 0.5
        self.onComplete = { [weak self] in
            if self?.run == false {return}
            self?.animate(secs: self?.time ?? 2)
            self?.run = false
        }
    }

    @IBAction func minusAction(_ sender: Any) {
        self.time += 0.5
        self.onComplete = { [weak self] in
            if self?.run == false {return}
            self?.animate(secs: self?.time ?? 2)
            self?.run = false
        }
    }

    @IBAction func stopAction(_ sender: Any) {
        run = false
        onComplete = nil
    }

    @IBAction func startAction(_ sender: Any) {
        animate(secs: self.time ?? 3)
        run = true
    }

    func animate(secs : Double){

        startAnimate(with: secs) { [weak self] in
            self?.onComplete?()
            if self?.run == false{
                self?.run = true
                return
            }
            self?.animate(secs: secs)

        }
    }

    func startAnimate(with duration : Double, onFinish : @escaping ()->Void){
        DispatchQueue.main.async { [weak self] in
            self?.imageView.animationDuration = duration
            self?.imageView.startAnimating()
            DispatchQueue.global().asyncAfter(deadline: .now() + duration) {
                onFinish()
            }
        }
    }
}


texts:
This code belongs to a contest. I tried to apply the range of data to a std::map. The contest system however warns me that the implementation of the assign function is not valid. I don't know which part of the code is written incorrectly, hence the system doesn't reveal any details except that the implementation is erroneous.

Edit: I also added the test class that I used for testing the interval_map class. I tried to test every possible aspect of what could possibly go wrong. The test runs without any problem.

        void assign(unsigned char first, unsigned char last, unsigned char value)
        {
            test();

            interval_map::assign(first, last, value);
                for (int i = first; i < last; ++i)
                    vector_cont[i] = value;

            test();
        }
```


texts: Calculating overlap of segments in chromosome data

texts:
I wrote an R code that basically performs 2 operations:

For each segment in file A, find all segments in file B that lie in that segment.
Find the percentage of overlap for each case in previous point.

The code that I have written works fine but given I have 74 files of type A and the rows in file B are about 200K, the approximate run time for this on my cluster is about ~18 days! I am writing the code and input files below and would really appreciate your comments on how I can improve the run time, with code if possible.

File A

Chromosome    Start       End
1         0           2420037
1         2420037     2522634
1         2522634     10794763
1         10794763    10925915
1         10925915    11280057
...

File B

chr       start   end     variantaccession    variantsubtype
1     10001   127330  nsv7879             Gain+Loss
1     10001   846808  dgv2n71             Gain
1     10377   177417  dgv1e1              Complex
1     10377   177417  nsv428112           Gain
1     10377   1018704 dgv3e1              Complex
1     10499   177368  esv27265            Gain+Loss
...

A lot of rows from file B will map to each row of file A. Once my code finds indices of mapped rows from file B it also extracts certain other values part of additional columns of file B.

setwd("/abc/xyz")

filenames <- basename(list.files(path=getwd())) # reading list of all files of type A

# Reading File B
ref <- read.table("xyz.txt", header=TRUE,sep="\t")

for (i in 1:length(filenames))
{
  # Reading file
  file <- read.table(filenames[i],header=TRUE,sep="\t")
  cat("Working with ",filenames[i], " i.e. ",i,"/",length(filenames),"\n")
  # Start the clock!
  ptm <- proc.time()
  for(j in 1:nrow(file))
  {
    cat(j,"\n")
    ind <- which(file$Chromosome[j] == ref$chr)
    ref2 <- ref[ind,]
    B <- ""
    C <- ""
    D <- ""
    count <- 0
    for(k in 1:length(ind))
    {
      if((ref2$start[k]>=file$Start[j] & ref2$start[k]<=file$End[j]) | (ref2$end[k]>=file$Start[j] & ref2$end[k]<=file$End[j]))
      {
        B[k] <- as.character(ref2$variantaccession[k])
        C <- as.integer(append(C,ref2$start[k]:ref2$end[k]))
        D[k] <- as.character(ref2$variantsubtype[k])
        count <- count+1
      }
    }
    file$CNVcount[j] <- count
    C <- C[2:length(C)]
    E <- file$Start[j]:file$End[j]
    file$PerCNVoverlap[j] <- (length(E)/length(which(C %in% E)))*100
    B2 <- paste(unique(B[complete.cases(B)]),collapse=",")
    B3 <- paste(B2,",",sep="")
    file$CNVs[j] <- B3
    D2 <- paste(unique(D[complete.cases(D)]),collapse=",")
    D3 <- paste(D2,",",sep="")
    file$CNVtypes <- D3
  }
  # Stop the clock
  proc.time() - ptm
  file <- file[,c(1,2,3,4,5,6,8,7)]
  write.table(file,filenames[i],col.names=TRUE,row.names=FALSE,sep="\t")
}

How I am calculating overlap:

  File A, row 01: 1 2 3 4 5 6 7 8 9 10
  File B, seg 01:   2 3 4
  File B, seg 32:         5 6 7
  File B, seg 12:     3 4 5 6 7 8 9
Consensus File B:   2 3 4 5 6 7 8 9
Percentage overlap = 8/10 -> 80%

Required Output (i.e add additional columns to File A)

Chromosome    Start       End    Overlap_Count     Overlap_Percentage     Overlaps_Names     Overlap_subtype
1         0           2420037    800             22.12%            nsv7879,dgv1e1...    Gain+Loss,Complex
1         2420037     2522634    626             35.12%            nsv7879,dgv1e1...    Gain+Loss,Complex
1         2522634     10794763    200             17.12%            nsv7879,dgv1e1...    Gain+Loss,Complex
1         10794763    10925915    75             42.12%            nsv7879,dgv1e1...    Gain+Loss,Complex
1         10925915    11280057    800             22.12%            nsv7879,dgv1e1...    Gain+Loss,Complex


texts:
How efficient is this program? How could I make it more efficient?

package main;

import java.math.BigInteger;

public class Ackermann {

    public static void main(String[] args) {
        System.out.println(ack(BigInteger.valueOf(4),BigInteger.valueOf(2)));

    }

    public static BigInteger ack(BigInteger a, BigInteger b) {
        BigInteger ans;
        if (a.equals(BigInteger.ZERO)) ans = b.add(BigInteger.ONE);
        else if (b.equals(BigInteger.ZERO)) ans = ack(a.subtract(BigInteger.ONE),BigInteger.valueOf(1));
        else ans = ack(a.subtract(BigInteger.ONE), ack(a,b.subtract(BigInteger.ONE)));
        return (ans);
    }

}


texts:
I have a sequence of numbers: 1, 2, 3, 5, 8, 3, 1, 4, 5, 9, 4, 3, 7, 0, 7, 7, 4,... I have to guess the rule which the sequence follow and to:

Compute the sum of all prime numbers smaller than n
Find how many times the digit k appears in the element of the sequence
The number on the position p in the sequence.

Input:
n, k, p

I have written the next code: it serves it's purpose, but I would like you to give me some tips on code style and performance(and I am thinking specifically to speed).

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

int prime(int n)
{
    if(n < 2) return 0;
    if(n == 2) return 1;
    if(n % 2 == 0) return 0;
    int i;
    for(i = 3; i <= sqrt(n); i += 2)
    {
        if(n % i == 0)
            return 0;
    }
    return 1;
}

int main()
{
    int n;
    int p;
    int k;
    scanf( "%d", &n );
    scanf( "%d", &k );
    scanf( "%d", &p );

    int primeSumPerSubSequence = 128;
    int nAux = n;
    int primeSum = 0;
    int subSequences = 0;

    if( n > 60 )
        subSequences = n / 60;
    if( n > 60 )
    {
        nAux = n % 60;
        primeSum = primeSum + primeSumPerSubSequence * subSequences;
    }

    int i = 2;
    int firstNumber = 1;
    int secondNumber = 2;
    if( !nAux ) secondNumber = 0;
    int thirdNumber = 3;
    int kFound = 0;

    switch( k )
    {
        case 0: kFound = 4 * subSequences;break;
        case 1: kFound = 8 * subSequences;break;
        case 2: kFound = 4 * subSequences;break;
        case 3: kFound = 8 * subSequences;break;
        case 4: kFound = 4 * subSequences;break;
        case 5: kFound = 8 * subSequences;break;
        case 6: kFound = 4 * subSequences;break;
        case 7: kFound = 8 * subSequences;break;
        case 8: kFound = 4 * subSequences;break;
        case 9: kFound = 8 * subSequences;break;
    }

    if(( kFound == 1 ) || ( kFound == 2 )) kFound++;
    int pNumber = -1;
    if( !p ) pNumber = 0;
    else if( p % 60 == 0) pNumber = 1;
    else if( p > 60 ) p %= 60;

    while( i <= nAux )
    {
        if( nAux && prime( secondNumber ) )
        {
            primeSum += secondNumber;
        }
        if(( i == p ) && ( pNumber != 1)) pNumber = secondNumber;
        firstNumber = secondNumber;
        secondNumber = thirdNumber;
        thirdNumber = firstNumber + secondNumber;
        if( thirdNumber > 9 )
            thirdNumber %= 10;
        if(( secondNumber == k ) && ( i < n )) kFound++;
        i++;
    }

    firstNumber = 1;
    secondNumber = 2;
    thirdNumber = 3;

    if( pNumber == -1 )
    {
        for( i = 3; i <= p; i++ )
        {
            firstNumber = secondNumber;
            secondNumber = thirdNumber;
            thirdNumber = firstNumber + secondNumber;
            if( thirdNumber > 9 )
                thirdNumber %= 10;
            if( i == p ) pNumber = secondNumber;
        }
    }

    if( pNumber == -1) pNumber = 0;

    printf( "\n%d", primeSum );
    printf( "\n%d", kFound );
    printf( "\n%d", pNumber );

    return 0;
}

Should I edit the question and add how I thought the algorithm?
Thank you and please excuse my bad english.


texts:
The sequence of Fibonacci numbers is defined as F1 = 1, Fn = Fn−2 +
  Fn−1. It has been conjectured that for any Fibonacci number F, F2 + 41
  is composite.

  ... [T]ask is to either prove the conjecture to be true or find a
  counter-example that demonstrates it is false.

(source)

Here is my working code for this problem - although I don't know the conjecture is either true or false in general.

I tested it for first 107 natural numbers, also for first 1000 Fibonacci numbers - and it seems conjecture is true. but I takes a lot of time (80-90 seconds) to spit out a result.

As you see in last three functions, I have 3 method to test conjecture.

First one (fibonacci_conjecture) generates a sequence of Fib2+41s and returns result of primality test.
Second one is similar to first, but it first checks if numbers in a given range are Fibonacci numbers or not.
Third one seems more optimal. As we know from definition, for a given Fibonacci number f, 5f2+4 or 5f2-4 is perfect square. If we add 41 to both of them we'll have 5f2+45 or 5f2+37. The first one is always divisible by 5, so there's no need to check these values.

How can this code be written in an optimal way, for faster results? Or, which techniques should I follow (either within the code or within the math)?

import math

def is_perfect_square(x):
    return int(math.sqrt(x)) == math.sqrt(x)

def is_fibo(x):
    c = 5*x*x
    return is_perfect_square(c+4) or is_perfect_square(c-4)

def is_prime(x):
    c = int(math.sqrt(x))+2
    if (x%2==0 and x!=2) or is_perfect_square(x): return False
    else:
        for i in range(2, c):
            if x%i==0: return False
    return True

def minus_four(fib):
    if is_fibo(fib) and fib>0: return is_perfect_square(5*fib*fib-4)

def fibo(x):
    if x<2: return 1
    else: return fibo(x-1)+fibo(x-2)

def fibonacci_conjecture(end):
    return (True not in map(is_prime, [fibo(i)*fibo(i)+41 for i in range(end+1)]))

def second_way(end):
    return (True not in map(is_prime, [i**2+41 for i in range(end+1) if is_fibo(i)]))

def third_way(end):
    return (True not in map(is_prime, [fibo(i)*fibo(i)+41 for i in range(end+1) if minus_four(i)]))

There is also a brute-force like implementation. that checks if 5x2+37 is prime, then checks if that number is a Fibonacci number.

from fibonacci_conjecture import * # functions above
import time
from sys import argv

script, start, end = argv

_list = []

start_time = time.time()
for i in range(int(start), int(end)):
    if is_prime(5*i*i+37) and is_fibo(5*i*i+37): _list.append(i)
print _list
print time.time() - start_time

Results calling the last one from Terminal:

$ python timings.py 0 1000
[]
0.0163550376892
$ python timings.py 1000 2000
[]
0.0392298698425
$ python timings.py 2000 12000
[]
1.66012907028
$ python timings.py 12000 42000
[]
35.4742548466
$ python timings.py 42000 43000
[]
2.01177597046
$ python timings.py 43000 48000
[]
11.1937119961


texts: Solution to Max Range Sum challenge on CodeEval

texts:
The challenge in CodeEval is to take a number of days and iterate over the gains and losses and determine which lengths will yield the highest possible profit.  I'm wondering if I could write this any better?  It seems like sort of clunky code to me.

file = ARGV[0]

File.open(file).each do |line|

    duration, days = line.chomp.split(";")
    days = days.split(" ").map! { |num| num = num.to_i }
    duration = duration.to_i - 1

    profit = 0
    max_profit = 0

    days[0..(days.length - duration)].each_with_index do |day, index|

        days[index..(index + duration)].inject(0) do |change, total|
            profit = change + total
        end

        max_profit = profit if profit > max_profit
    end

    puts max_profit

end


texts:
I use the following function for opening files in Python:

def file_path(relative_path):
    folder = os.path.dirname(os.path.abspath(__file__))
    path_parts = relative_path.split("/")
    new_path = os.path.join(folder, *path_parts)
    return new_path

I call it with a relative path, like this:

with open(file_path("my_files/zen_of_python.txt")) as f:
    zop = f.read()

I like it because you can use a relative path works no matter where the Python script is executed from:

folder = os.path.dirname(os.path.abspath(__file__)) gets the
absolute path to the folder holding the python script.
os.path.join(folder, *path_parts) gets an os-independent path to the file to open.

To further explain, let's say I have the following folder structure:

- parent_folder
  - example.py
  - my_files
    - zen_of_python.txt

If example.py looks like this:

with open("my_files/zen_of_python.txt") as f:
    zop = f.read()

Then I have to run example.py from the parent_folder directory or else it won't find my_files/zen_of_python.txt.

But if I open my_files/zen_of_python.txt using the file_path() function shown above, I can run example.py from anywhere.

One downside as @infinitezero pointed out is that you can't use an absolute path, but for my purposes, that's okay for my purposes. The script is self-contained. I'm not passing in external files when I run it.

Can anyone see any downside to this? Or does anyone have a more Pythonic way of accomplishing the same thing?


texts: #define or NSString * const - Benefits and drawbacks of string literal constant syntax?

texts:
I'm interested in discussing string literals in Objective-C and would like to know 1. if there's a preferred paradigm / style and 2. what (if any) the performance implications might be.

There are parts of the Cocoa / CocoaTouch frameworks that use strings as identifiers. Some examples in Cocoa / CocoaTouch...

-[NSNotificationCenter addObserver:selector:name:object:]
-[UITableView dequeueReusableCellWithIdentifier:]
-[UIViewController performSegueWithIdentifier:sender:]

I find myself most often declaring a global variable within the class like so...

NSString * const kMySegueIdentifier = @"Awesome Segueueueueue";

For segue identifiers, I will often times expose the variable in the header file extern NSString * const kMySegueIdentifier; so that other modules can reuse it.

The same behaviors can be accomplished with preprocessor macros: #define kMySegueIdentifier @"Awesome Segueueueueue". I believe this would also prevent the app from consuming memory to hold these globals. I cringe a little at this syntax however because it exposes the "implementation details" of my string literal constants.

Both of these lines accomplish an end goal of abstracting the string into being easy to remember, type correctly, and will generate compile warnings / errors, is one actually better then the other? What are the situations that would arise where one would be preferred over the other?


texts:
I have written a binary search algorithm, but it seems to be a bit different than other peoples that I've seen. I was hoping that the community could give me some feedback as to whether or not I'm missing something, or doing something the wrong way.

Binary Search:

import java.util.Arrays;

public class BinarySearch {

    public int[] numbers = new int[] {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20};

    /**
     * @param num
     * @param key
     *
     * Function recursively searches sorted array of integers, finding the specific number (key).
     * Search looks at the midpoint of array, checking to see if midpoint is number being sought,
     * if not, depending of whether the sought number is greater than, or less than, the midpoint
     * the function copies the upper, or lower, half of the array and passes it into a recursive
     * function call.
     *
     */
    public int performSearch(int[] num, int key){
        if(num.length == 0){
            System.out.println("Array empty");
            return 0;
        }else{
            int mid;
            int number=0;
            mid = (num.length)/2;
            if(key == num[mid]){
                number =  num[mid];
                System.out.println("Found the number " + number);
                return number;
            }else if((key < num[mid]) && num.length > 1){
                num = Arrays.copyOfRange(num, 0, mid);
                System.out.println("Low Range: " + Arrays.toString(num));
                return performSearch(num, key);
            }else if((key > num[mid]) && num.length > 1){
                num = Arrays.copyOfRange(num, mid, num.length);
                System.out.println("High Range: " + Arrays.toString(num));
                return performSearch(num, key);
            }else{
                System.out.println("Number does not exist in array.");
                return 0;
            }
            //return number;
        }

    }

    /**
     * @param args
     */
    public static void main(String[] args) {
        int key = 22;
        BinarySearch bs = new BinarySearch();
        int index = bs.performSearch(bs.numbers, key);
        System.out.println("Number " + index);
    }

}


texts: Register inputs (click) - write the inputs

texts:
This app register where you click on the screen, then it writes the inputs on the page. The text is responsive, you can change the dimension or orientation of the webpage and it still will be in the middle with the right size to fill the entire page. With a double click the program will restart.

http://jsfiddle.net/Diquadro/ah1nfxkb/

class Text {
  constructor (element) {
    this.element = element
  }

  write (inputs) {
    for (let i = 0; i < inputs.length - 1; ++i) {
      this.element.appendChild(document.createTextNode(`${i + 1}: ${inputs[i]}`))
      this.element.appendChild(document.createElement('br'))
    }
    this.element.appendChild(document.createTextNode(`${inputs.length}: ${inputs[inputs.length - 1]}`))
  }

  erase () {
    while (this.element.firstChild) {
      this.element.removeChild(this.element.firstChild)
    }
  }

  resize () {
    this.element.style.fontSize = '50vw'
    // fitting the text the whole page
    for (let i = 50; window.innerWidth < this.element.offsetWidth || window.innerHeight < this.element.offsetHeight; --i) {
      this.element.style.fontSize = `${i}vw`
    }
  }
}

async function application () {
  const inputs = await new Promise(resolve => {
    const inputs = []

    function touch (event) {
      // it will be replace with event.touches[event.touches.length - 1].clientX
      if (event.clientX >= window.innerWidth / 2) {
        inputs.push('RIGHT')
      } else {
        inputs.push('LEFT')
      }

      if (inputs.length === 4) {
        // it will be replace with touchstart
        window.removeEventListener('click', touch)
        resolve(inputs)
      }
    }

    // it will be replace with touchstart
    window.addEventListener('click', touch)
  })

  const text = new Text(document.getElementById('text'))
  text.write(inputs)
  text.resize()

  function resize () {
    text.resize()
  }
  window.addEventListener('resize', resize)

  function reset () {
    window.removeEventListener('resize', resize)
    window.removeEventListener('dblclick', reset)
    text.erase()
    application()
  }
  window.addEventListener('dblclick', reset)
}

application()
* {
  margin: 0;
  border: 0;
  padding: 0;

  user-select: none;
  overflow:hidden;
}

body {
  background: black;
}

#text {
  white-space: nowrap;
  color: white;

  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}
<!DOCTYPE html>

  <meta charset="UTF-8">
  <meta name='viewport' content='width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0'>
  <meta name="mobile-web-app-capable" content="yes">
  <link rel="stylesheet" type="text/css" href="style.css">
  <title>Magic</title>


texts:
I have a matrix transpose function that takes arrays with a possibly different number of rows and columns.

How can I improve performance and code quality?

void matrix_transpose(float *matrix, int rows, int columns)
{
    int current_row;
    int current_column;
    float temp;
    float buffer[MATRIX_TRANSPOSE_BUFFER_SIZE];
    int buffer_position = 0;

    if(rows == columns)
    {
        for(current_row = 0; current_row < rows; ++current_row)
        {
            for(current_column = current_row; current_column < columns; ++current_column)
            {
                temp = *(matrix + current_row * columns + current_column);
                *(matrix + current_row * columns + current_column) = *(matrix + current_column * columns + current_row);
                *(matrix + current_column * columns + current_row) = temp;
            }
        }
    }
    else if(rows * columns < MATRIX_TRANSPOSE_BUFFER_SIZE)
    {
        for(current_column = 0; current_column < columns; ++current_column)
        {
            for(current_row = 0; current_row < rows; ++current_row)
            {
                buffer[buffer_position++] = *(matrix + current_row * columns + current_column);
            }
        }
        buffer_position = 0;
        while(buffer_position < rows * columns)
        {
            *matrix++ = buffer[buffer_position++];
        }
    }
}

Here's an example call:

float matrix[] = {
     1,  2,  3,  4,
     5,  6,  7,  8,
     9, 10, 11, 12,
    13, 14, 15, 16,
    17, 18, 19, 20
};

matrix_transpose(matrix, 5, 4);


texts: Selection sort implementation in C++ iterator approach

texts:
I am trying to learn the C++ way of writing code. I was wondering if this code could be improved or if there are any major mistakes. Is it ok how I name the variables?

template<typename Iterator, typename Comparator>
void selection_sort(Iterator begin, Iterator end, Comparator comparator) {
    for (; begin != end; ++begin) {

        auto min = std::min_element(begin, end, comparator);

        if (comparator(*min, *begin)) {
            std::iter_swap(min, begin);
        }
    }
}
template<typename Iterator>
void selection_sort(Iterator begin, Iterator end) {
    typedef typename std::iterator_traits<Iterator>::value_type value_type;

    selection_sort(begin, end, std::less<value_type>());
}


texts: Read value from config and return function

texts:
I’ve the following function which should be run in production
I read some config If valid add the runner otherwise just return,
the function is working!
Is there a cleaner/better way to do it in go? error handling...
https://play.golang.org/p/QcU9YHDXo36
func (z *zmp) Add(val string, runner Runner) {
    vmap := viper.GetStringMap(val)
    if len(vmap) > 0 {
        if val, ok := configs["active"]; ok {
            if !val.(bool) {
                log.info(“not valid”)
                return
            }
        }
    }
    z.Add(runner)
}


texts: REST API returning NotFound (404) if record is not found in the database

texts:
I'm not really sure what the preferred way is to deal with records not found in the database. Is it better to write a Find method which returns null or a Get method which raises a RecordNotFoundException?

[AuthenticateFilter(UsernameAndSecretKey)]
[Route("api/v1/activities/emails/{id}")]
[HttpGet]
public IHttpActionResult GetEmailActivity(int id)
{
  try
  {
    // business logic service, could use only db service but this way we can do unit tests (just fill bl service method with fake objects)
    var service = new EmailActivityBlService();

    // 1. use Find method which returns null in case record with provided id does not exist in db
    var model = service.FindActivity(id);
    if( model != null )
      return Ok(model);
    return NotFound();

   // 2. or is this approach better
   // throws RecordNotFoundException in case row by id is not found in database
   return Ok(service.GetActivity(id));
  }
  catch(RecordNotFoundException e) { return NotFound(); }
  catch(Exception e) { return InternalServerError(e); }
}

EmailActivityBlService has next code in case anyone interested (showing only the important part):

private EmailActivityDbService _dbService;

public EmailActivityModel GetActivity(int id)
{
  var model = this._dbService.GetActivity(id);
  if( model == null )
    throw new RecordNotFoundException(); // I suppose System.Data.ObjectNotFound is also suitable
  return model;
}

public EmailActivityModel FindActivity(int id)
{
  // typical entity framework query
  // using(var context = new ..) { return contect.EmailActivity.Where()..SingleOrDefault().ConvertToModel();
  return this._dbService.GetActivity(id);
}


texts:
I have three lists, and I need to operate on the ith element of each list simultaneously.

private void TripleForEach<T1, T2, T3>(IEnumerable<T1> a1, IEnumerable<T2> a2, IEnumerable<T3> a3, Action<T1, T2, T3> x)
{
    a3.Zip(a2, (t3, t2) => Tuple.Create(t2, t3)).Zip(a1, (t23, t1) => Tuple.Create(t1, t23.Item1, t23.Item2)).ToList().ForEach(z => x(z.Item1, z.Item2, z.Item3));
}

Any better way to do this? Creating and pulling apart those temporary Tuples smells bad to me.


texts:
I come to see you to help me improve an express middleware that allows you to control access resources by checking the rights of the user.
The following code is supposed to be as generic as possible so that it can easily be added to another project.

But I have doubts both on its genericity and the clarity of its prototype, I let you judge :)

acl.ts

export let config: ACLConfig = {
  userField: 'me',
  roleField: 'roles'
};

export function isAllowed(roles: String[], ...cbs: Function[]) {
  return async function (req, res, next) {
    let allowed = false;
    let user = req[config.userField];
    if (!user) throw new APIError('ACL module cannot find req.{{userField}}', APICodes.ACL_INTERNAL_ERROR);

    let userRoles = user[config.roleField] || '';
    userRoles = userRoles.split(',');

    if (roles && roles.length) {
      for (let role of roles) {
        if (userRoles.indexOf(role) !== -1) return next();
      }
    }

    if (cbs && cbs.length) {
      for (let cb of cbs) {
        if (cb(req) === true) return next();
      }
    }

    throw new APIError('You do not have the required privileges', APICodes.AUTH_ACCESS_FORBIDDEN, HttpStatus.UNAUTHORIZED, true);
  }
}

must be used like this

route('/...').all(verifyToken, isAllowed(['staff, admin'], policies.isMyArticle))

maybe this following prototype is better ?

isAllow(...args: String | Function)
isAllow('staff', policies.isMyArticle, 'staff');


texts: Boolean constant for assert in if..else block

texts:
I have the following condition statement in Groovy:

if ( condition_1 ) {
    //some actions
} else if ( condition_2 ) {
    //some another actions
} else {
    assert false, 'Assertion description'
}

Code Narc gives me a warning about using boolean false constant in the assertion. I'm not sure if it is real issue, so please share your thoughts about it.

I thought about using exceptions in this code instead of assert false but it looks too heavy (exception handling is too heavy I think) for my particular case.


texts: Generating all permutations of a sequence

texts:
import itertools

def permutation_lib(iterable):
    return itertools.permutations(iterable)

def permutation(iterable):
    if len(iterable) <= 1:
        yield tuple(iterable)
    else:
        for sequence in permutation(iterable[:-1]):
            for i in range(len(sequence)+1):
                yield insert_at(sequence, i, iterable[-1])

def insert_at(iterable, idx, value):
    if idx == 0:
        return (value,) + iterable[:]
    elif idx == len(iterable):
        return iterable[:] + (value,)
    else:
        return iterable[:idx] + (value,) + iterable[idx:]

import unittest

class TestPermutation(unittest.TestCase):
    def test_permutations(self):
        self.assertEqual(list(permutation([0])), list(permutation_lib([0])))
        self.assertEqual(sorted(list(permutation([0,1]))), list(permutation_lib([0, 1])))

if __name__ == '__main__':
    unittest.main()


texts:
This is a very simple rock paper scissors game implemented in Haskell.

import System.IO (hFlush, stdout)
import System.Random (getStdGen, randomR)

data RPS = Rock | Paper | Scissors deriving (Eq, Show, Read)

instance Ord RPS where
    Rock `compare` Scissors = GT
    Scissors `compare` Rock = LT

    Paper `compare` Rock    = GT
    Rock `compare` Paper    = LT

    Scissors `compare` Paper = GT
    Paper    `compare` Scissors = LT
    _ `compare` _ = EQ

prompt :: String -> IO String
prompt text = do
    putStr text
    hFlush stdout
    getLine

main = do

    gen <- getStdGen

    humanchoice <- prompt "Rock, Paper, or Scissors: "

    let (compchoice, _) = randomR (0,2) gen
        compchoice' = case (compchoice :: Int) of
                          0 -> Rock
                          1 -> Paper
                          2 -> Scissors
        humanchoice' = read humanchoice :: RPS

    case compchoice' `compare` humanchoice' of
        EQ -> putStrLn "Tie."
        GT -> putStrLn "You Lose :("
        LT -> putStrLn "You Win! :)"

All kinds of reviews are welcome, but I am specifically interested in knowing what kind of beginner mistakes I might have done. For example, are there things that I could simplify, or are things that you wouldn't see in a intermediate level haskell code?


texts: Filtering script for products by category

texts:
I built a simple product filtering feature that works at least in the browsers and platforms that I have tried using it on, but I am unsure about a couple of aspects of it.  I built this on a Bigcommerce site but I think my questions could still apply broadly (some):

Is this a solid approach?  Conventional?  If not, why, and how could/should I approach it differently?
Should I expect to have any problems with browser compatibility?  If so, would they be different problems than any problems I might experience if I was using the stock Bigcommerce faceted search option, or even some other random search feature from another site?

Assume an out of the box faceted search option is not an available. jQuery is loaded twice in HTMLhead.html (head template) as 1.7.2 and 2.2.2

The following example is a simplified version of what I created.  In this example there are only 4 products and 2 categories present.  We can also assume that no products belong in more than one category:

HTML - (Two checkboxes, one for each category)

<fieldset>

<input id="example-category-1" type="checkbox" value="first-checkbox" />CHOOSE CATEGORY 1

<input id="example-category-2" type="checkbox" value="second-checkbox" />CHOOSE CATEGORY 2

</fieldset>

HTML - fiddle with expanded li showing the structure of a random example product.

JS:

Page loads, all products present, no checkboxes clicked. When a checkbox is clicked for the first time, all products are hidden (rather, their parent lis are)

    var test = true;
    $(".test-one").change(function() {
        if(test){
            $('div[data-product]').parents("li").hide();
            //hide every product after first click on any checkbox

            if( $('#example-category-1').is(':checked') ) {
            //check for checkbox activation and show products if true
                $('div[data-product="1802"]').parents("li").show();
                $('div[data-product="1781"]').parents("li").show();
            }
            if( $('#category-2').is(':checked') ) {
            //check for checkbox activation and show products if true
                $('div[data-product="1348"]').parents("li").show();
                $('div[data-product="1347"]').parents("li").show();
            }
            test =false;
            //set to false so we don't enter this if statement again
        }
    });

For the rest of the time, this is what is handling the filtering (would like to exclude the following code from the first click, but seems to work okay as is):

$('#example-category-1').click(function() {
        if( $(this).is(':checked') ) {
            $('div[data-product="1802"]').parents("li").show();
            $('div[data-product="1781"]').parents("li").show();
        } else {
            $('div[data-product="1802"]').parents("li").hide();
            $('div[data-product="1781"]').parents("li").hide();
        }
    });
    $('#example-category-2').click(function() {
        if( $(this).is(':checked') ) {
            $('div[data-product="1348"]').parents("li").show();
            $('div[data-product="1347"]').parents("li").show();
        } else {
            $('div[data-product="1348"]').parents("li").hide();
            $('div[data-product="1347"]').parents("li").hide();
        }
    });

Final note: I was told that I can manipulate the product object to achieve goals like this one - I kind of know in theory what the product object is, but I don't know how to access it / act on it - any input, test suggestions, or criticism would be greatly appreciated.


texts: Calculator that can add/subtract/divide/multiply two inputs

texts:
Here I am making a calculator for a robotics assignment. I need the program to be able to take two inputs and convert to float. It also needs to display previous calculations when exiting and also stop when trying to divide by 0. It works I just want to make sure its clean and im not using any bad practices.
operators = ["+", "-", "*", "/"]
answers = []
def run_calculator():
    def instructions():
        try: chosen_operator = int(input("Choose an Operator:\n1) Addition\n2) Subtraction\n3) Multiplication\n4) Division\n\n5) Exit\nInput (1/2/3/4/5):"))
        except:
            print('Invalid Input: Choose A Valid Operation')
            return
        if chosen_operator > 4 or chosen_operator < 1:
            if chosen_operator == 5: return
            print('Invalid Input: Choose a Valid Operation')
            return
        operator = operators[chosen_operator - 1]
        try: firstnum = float(input('First Number:'))
        except:
            print('Invalid Input: Not a valid number')
            return
        try: secondnum = float(input('Second Number:'))
        except:
            print('Invalid Input: Not a valid number')
            return
        return operator, firstnum, secondnum
    while (True):
        try: operator, firstnum, secondnum = instructions()
        except: break
        if operator == "/" and secondnum == 0.0:
            print("Cannot divide by 0")
            break
        calc_function = float.__add__ if operator == "+" else float.__sub__ if operator == "-" else float.__mul__ if operator == "*" else float.__truediv__
        answers.append(f"{firstnum} {operator} {secondnum} = {calc_function(firstnum, secondnum)}")
        restart = input((f"{firstnum} {operator} {secondnum} = {calc_function(firstnum, secondnum)}\nWould you like to do another calculation? (Y/N)"))
        if restart.lower() == 'y':
            continue
        else:
            print("Results:")
            for x in range(len(answers)):
                print(f"{answers[x]}")
            break
run_calculator()


texts: Excerpt from a brute force Rubik's Cube algorithm

texts:
I have a program that brute force searches for a combination of inputted array elements by the user and when the program is searching all the for loops are nested for the brute search then I have this test() which looks is responsible for testing out all the possible combinations of the nested for loop to find the the combination entered by the user of the program, how ever the code is super redundant, here is a sample.

public static boolean test(int a, int b, int c, int d, int e, int f, int g, int h, int i, int j, int k){
    boolean result1 = true;

    if(a == 0){
        cube = turn_U(cube);
    }
    else if(a == 1){
        cube = turn_Ui(cube);
    }
    else if(a == 2){
        cube = turn_U2(cube);
    }
    else if(a == 3){
        cube = turn_L(cube);
    }
    else if(a == 4){
        cube = turn_Li(cube);
    }
    else if(a == 5){
        cube = turn_L2(cube);
    }
    else if(a == 6){
        cube = turn_F(cube);
    }
    else if(a == 7){
        cube = turn_Fi(cube);
    }
    else if(a == 8){
        cube = turn_F2(cube);
    }
    else if(a == 9){
        cube = turn_R(cube);
    }
    else if(a == 10){
        cube = turn_Ri(cube);
    }
    else if(a == 11){
        cube = turn_R2(cube);
    }
    else if(a == 12){
        cube = turn_B(cube);
    }
    else if(a == 13){
        cube = turn_Bi(cube);
    }
    else if(a == 14){
        cube = turn_B2(cube);
    }
    else if(a == 15){
        cube = turn_D(cube);
    }
    else if(a == 16){
        cube = turn_Di(cube);
    }
    else if(a == 17){
        cube = turn_D2(cube);
    }

This is what happens for letters a through k and I was wondering how I could shorten this, I had an idea where I could make a method that selects a turn method based on the letter in the test() , this would reduce so that test has 11 calls to the method instead of the all of this repeated ones.


texts: Merge 2 arrays, when one is larger and can accomodate smaller

texts:
How will you merge two sorted arrays, when The longer array has empty spaces to accomodate the second array. Complexity: O (items in longer  + items in smaller).  Request for making code concise, clean and optimal.

public final class MergeArrays {

    private MergeArrays() {}

    private static void check(Integer[] big, Integer[] small) {
        if (big == null && small == null) {
            throw new NullPointerException("The input arrays are null.");
        }

        if (big.length < small.length) {
            throw new IllegalArgumentException("The arrays is smaller smaller array");
        }
    }

    public static Integer[] mergeSortedArrays(Integer[] big, Integer[] small) {
        check(big, small);
        int limit = 0;
        for (Integer val : big) {
            if (val == null) { break; }
            limit++;
        }
        return mergeSortedArrays(big, limit, small);
    }

    private static Integer[] mergeSortedArrays(Integer[] big, int limit, Integer[] small) {
        assert big != null;
        assert small != null;

        int limitIndex = limit - 1;
        int bigIndex = big.length - 1;
        int smallIndex = small.length - 1;

        while (smallIndex >= 0) {
            if (limitIndex < 0 || big[limitIndex] < small[smallIndex]) {
                big[bigIndex--] = small[smallIndex--];
            } else {
                big[bigIndex--] = big[limitIndex--];
            }
        }

        return big;
    }


texts: Return the largest product of 2 numbers that is a multiple of 9 in O(n)

texts:
Given an array of integers, I have to return the largest product of any 2 numbers, and that product has to be a multiple of 9.

Example input 1:
int[] a = {6, 5, 7, 2, 4, 8, 9};
Example output:
72

Example input 2:
int[] b = {1, 6, 7, 3};
Example output:
18

This is easy with 2 nested loops, calculating all products between every element of the array and checking if the product is a multiple of 9, but that solution is \$O(n^2)\$. I was told I can solve this problem in \$O(n)\$ only, but I'm struggling to cover all the cases.

I have the following code:

    int max_number = -1;
    int max_multiple_9 = -1;

    for(int i = 0; i < input.length; i++) {
        if(input[i] % 9 == 0) {
            if(input[i] > max_multiple_9) max_multiple_9 = input[i];
            else if(input[i] > max_number) max_number = input[i];
        } else {
            if(input[i] > max_number) max_number = input[i];
        }
    }

    return max_multiple_9*max_number;

This only works for cases where there is a multiple of 9 in the array (like the first example), because I'm looking for the greatest multiple of 9 and multiplying it for the greatest any other number. But how would I change the code to also find products that don't involve multiples of 9, such as 6*3 in the second example?


texts: find the maximum occur number in an integer

texts:
Write a function named maxOccurDigit that returns the digit that
  occur the most. If there is no such digit,  it will return -1. For
  example maxOccurDigit(327277) would return 7 because 7 occurs three
  times in the number  and all other digits occur less than three times.

  Other examples:

  maxOccurDigit(33331) returns 3

  maxOccurDigit(3232, 6) returns -1

  maxOccurDigit(5) returns 5

  maxOccurDigit(-9895) returns 9

  The function signature is
  maxOccurDigit(int n)

I have done it this way:

public class checknumbers{
   public static void main(String[] args)  {
   System.out.println(maxOccurDigit(32332));
  }

 public static int maxOccurDigit(int a){
    String str2 = Integer.toString(a); // converts a into String
    char[] ch2 = str2.toCharArray(); //gets str2 into an array of char
    int[] t2 = new int[ch2.length];  //defines t2 for bringing ch2 into it
    for(int i=0;i<ch2.length;i++){ //  ASCII table
      t2[i]= (int) ch2[i]-48;   // ch2[i] is 48 units more than what we want
    }
    int count = 1, tempCount;
    int popular = t2[0];
    int temp = 0;
    for (int i = 0; i < (t2.length - 1); i++){
    temp = t2[i];
    tempCount = 0;
    for (int j = 1; j < t2.length; j++){
      if (temp == t2[j])
        tempCount++;
    }
    if (tempCount > count){
      popular = temp;
      count = tempCount;
    }
  }
    return popular;
  }
 }

How could I return -1 if there are two integers but methods have only one?


texts: Disproving Euler proposition by brute force in C

texts:
I wrote a little bit of code to brute force disprove the Euler proposition that states:

  $$a^4 + b^4 + c^4 = d^4$$

  has no solution when \$a\$, \$b\$, \$c\$, \$d\$ are positive integers.

I'm no mathematician, but reading around this, at least one solution was found by Noam Elkies in 1987 (a = 95800; b = 217519; c = 414560; d = 422481). I wanted to get an idea of how much firepower it would take to solve by brute force, so I wrote the following in C:

#include <stdio.h>
#include <time.h>
#include <math.h>

int prop(long int A, long int B, long int C, long int D) {
    return (pow(A, 4) + pow(B, 4) + pow(C, 4) == pow(D, 4));
}

int main() {
    long int a, b, c, d;
    clock_t t;
    t = clock();

    for (a = 1; a < 100000; a++) {
        for (b = 1; b < 300000; b++) {
            for (c = 1; c < 500000; c++) {
                for (d = 1; d < 500000; d++) {
                    if (prop(a, b, c, d))
                        printf("FOUND IT!\na = %ld\nb = %ld\nc = %ld\nd = %ld\n", a, b, c, d);
                }
                if (!(c%1000))
                    printf("a = %ld, b = %ld, c = %ld, time = %fs\n", a, b, c, ((double)(clock() - t))/CLOCKS_PER_SEC);
            }
            printf("a = %ld, b = %ld, time = %fs\n", a, b, ((double)(clock() - t))/CLOCKS_PER_SEC);
        }
        printf("a = %ld, time = %fs\n", a, ((double)(clock() - t))/CLOCKS_PER_SEC);
    }

}

I ran it for a while, and worked out that it would take roughly \$85 \times 10^6\$ years for it to get to the answer above on my current machine.

I mean, maybe if I waited a few thousand years, I'd have a slightly better machine, but my question is (and I am new to C and computer science in general - so please be gentle); what strategies could I take to make the above code run faster? I thought about threading, and using some sort of bit shifting in place of the pow() calls.

Would there be any way (on my current machine) to get this to run in my lifetime?


texts: Binary search to identify duplicate user names

texts:
I am trying to implement the code described this post about how Reddit identifies duplicate user names (I do believe it is called binary search). Just to clarify, this is mainly for me figuring out how these things work; thanks @Graipher for pointing to bisect). The way I understand it, the steps are:

You have a new user name you are comparing to an alphabetically sorted list of existing names
You compare that new name to the middle item in the list.
If there is no match, you check if the new name is higher or lower in the alphabet than the middle item, and focus on this side of the list, again checking the middle item.
You repeat until there is a match ("User name taken") or none ("User name available").

Below is what I have. It seems to work when I test it on the names in the list and random other names. It'd cool if someone had some feedback re:

Will this work correctly or is there some kind of bug?
Is the while loop the right way to go? Are there better options? I especially don't like the separate loop for a list of length 1.
Performance-wise, are there any real hiccups in here?
Any other comments are much appreciated!

-

def checker(new_name, old_names):
    """
    The checker takes a string new_name and checks if it is contained in the list old_names.
    It prints out the results.
    """
    print "***\n\ninitializing the checker"
    print "searching for ", new_name
    print "old names", old_names
    old_names= sorted(old_names)
    #set the match variable to false
    namematch= False
    #iterate over list while new_name does not match
    while not namematch and len(old_names) > 1:
        middle= len(old_names)/2
        print "middle item is", old_names[middle], "middle index is", middle
        #match
        if old_names[middle] == new_name:
            namematch= True
        #no match
        else:
            if sorted(list((new_name, old_names[middle])))[0] != new_name:
                print "word is to the right"
                old_names = old_names[middle:]
            else:
                print "word is to the left"
                old_names = old_names[:middle]
    #check for list of length 1: is it new_name
    if (len(old_names)) == 1 and (old_names[0] == new_name):
        namematch = True
    if not namematch:
        print "this name is not taken", new_name
    else:
        print "this name is taken:", new_name

Here is my test data:

-

names_list= [u'annie', u'max', u'chris', u'11alpha', u'zotti', u'zatti', u'zutti', u'?andy', u'getr\xfc', u'zilly']

checker('max', names_list)  # True
checker('fail', names_list)  # False


texts: SQLite database for a micro/tumble blog application

texts:
I'm creating a personal website where, among other things, there is a blog, or a "microblog" (I'm still not sure how to define the two), where I will be writing articles and having users, who will create accounts, write comments on the posts. In addition, the blog posts will be tagged to allow for easier searching of specific blog posts. I was also planning on having the users' comments and posts be listed on their profile page, so that it is possible to view all comments or all posts made by a specific user (and reach said comment or post from their profile).

The blog will be built using Python 3, Flask, and SQLAlchemy for the backend.

The structure for the website will be a list of Users, which has a list of Posts that they've created (and are related to in a one-to-many relationship). Each Post will have only one author (one-to-one), but can be tagged a variety of Tags (many-to-many since many posts can be tagged with many tags). Each post will also have a list of comments (multiple comments), but each comment can only be linked to one Post and one User (the author).

Does the models code that I have below accurately describe and implement the design of my database that I'm trying to achieve?

from hashlib import md5
from app import lm, db
from flask.ext.sqlalchemy import SQLAlchemy
from flask.ext.login import LoginManager, UserMixin

class User(UserMixin, db.Model):
    __tablename__ = 'users'
    id            = db.Column(db.Integer, primary_key=True)
    join_date     = db.Column(db.DateTime)
    username      = db.Column(db.String(64), index=True, unique=True, nullable=False)
    realname      = db.Column(db.String(128), index=True)
    email         = db.Column(db.String(128), index=True)
    role          = db.Column(db.String(64))
    about_me      = db.Column(db.String(500))
    last_seen     = db.Column(db.DateTime)

    posts         = db.relationship('Post', backref='author', lazy='dynamic')
    comments      = db.relationship('Comment', backref='author', lazy='dynamic')

    def avatar(self, size):
        gravatar_url = 'http://www.gravatar.com/avatar/%s?d=identicon&s=%d&r=pg'
        return gravatar_url % md5(self.email.encode('utf-8')).hexdigest()

    def __repr__(self):
        _repr = '<models.User instance; ID: {}; username: {}>'
        return _repr.format(self.id, self.username)

@lm.user_loader
def load_user(id):
    return User.query.get(int(id))

class Post(db.Model):
    __tablename__ = 'posts'
    id            = db.Column(db.Integer, primary_key=True)
    author_id     = db.Column(db.Integer, db.ForeignKey('users.id'))
    tag_id        = db.Column(db.Integer, db.ForeignKey('tags.id'))
    title         = db.Column(db.String(128))
    body          = db.Column(db.String(20000))
    create_date   = db.Column(db.DateTime)
    comments      = db.relationship('Comment', backref='tagged_post', lazy='dynamic')

    def __repr__(self):
        _repr = '<models.Post instance; ID: {}; title: {}>'
        return _repr.format(self.id, self.title)

class Tag(db.Model):
    __tablename__ = 'tags'
    id            = db.Column(db.Integer, primary_key=True)
    title         = db.Column(db.String(64))
    tagged        = db.relationship('Post', backref='tag', lazy='dynamic')

    def __repr__(self):
        _repr = '<models.Tag instance; ID: {}; title: {}>'
        return _repr.format(self.id, self.title)

class Comment(db.Model):
    __tablename__ = 'comments'
    id            = db.Column(db.Integer, primary_key=True)
    post_id       = db.Column(db.Integer, db.ForeignKey('posts.id'))
    author_id     = db.Column(db.Integer, db.ForeignKey('users.id'))
    body          = db.Column(db.String(1500))
    create_date   = db.Column(db.DateTime)

    def __repr__(self):
        _repr = '<models.Comment instance; ID: {}; post_title: {}>'
        return _repr.format(self.id, self.post_id.title)

Here is a link to the (current) full source of the website.


texts: The correct place to implode array - MVC and Repositories concept

texts:
I am writing an application with the repositories concept in php with laravel framework.
In my controller I have this method:

/**
 * Update the specified resource in storage.
 * PUT /locais/{id}
 *
 * @param  int  $id
 * @return Response
 */
public function update($id)
{
    $data = Input::all();
    $data['str_categories'] = implode(',', $data['categories']);
    $this->place->update($id, $data);

    return Redirect::route('locais.index');
}

I am concerned about this line in controller:
$data['str_categories'] = implode(',', $data['categories']);

This line can be in controller method? Or this is a responsibility of places repository?


texts: Implementing a singly linked list in C++

texts:
I'm really just looking for some advice on my current code and with moving forward. As you can see, I have a pointer to my student list and data (which just haven't been made yet).

#include<iostream>
#include<cstdio>
#include<cstdlib>

using namespace std;

class List{ //Building the base of the program, being the nodes, and initializing the functions of the list
    private:
        typedef struct node {
            int student_number;
            int class_number;
            struct node* classpointer;
            struct node* studentpointer;
        }* nodePtr; //condensing node structure to simply "nodePtr"

        nodePtr head;
        nodePtr curr;
        nodePtr temp;

    //functions that I will be using
    public:
        List();
        void addNode();
        void PrintList();
};
//initialize the list pointers
List::List() {
    head = NULL;
    curr = NULL;
    temp = NULL;
}
//function to add a node to the linked list
void List::addNode() {
    nodePtr n = new node;
    n->classpointer = NULL;

    cout << "What value would you like to add?" << endl;
        int x;
    cin >> x;
    n->class_number = x;

    if(head != NULL) {
        curr = head;
        while (curr->classpointer != NULL) {
            curr = curr->classpointer;
        }
        curr->classpointer = n;
    }
    else {
        head = n;
    }
}

void List::PrintList() {
    curr = head;
    while(curr != NULL) {
        cout << " " << endl;
        cout << curr->class_number << endl;
        curr = curr->classpointer;
    }
}

int menu() {
    int input;
    List List;
    while (input != 3) {
        cout << " " << endl;
        cout << "Press '1' to input a node" << endl;
        cout << "Press '2' to view the list of nodes" << endl;
        cout << "Press '3' to exit" << endl;
        cout << " " << endl;
        cin >> input;
        if (input == 1) {
        List.addNode();
        }
        else if (input == 2) {
        List.PrintList();
        }
        else if (input == 3) {
            return 0;
        }
        else {
        cout <<"That is an invalid key" << endl;
        }
    }
}

int main() {
    int i;
    for (i=0; i < 500; i++) {
        menu();
    }
}


texts:
I tried to parse command line arguments. The program requires four arguments. I iterate over the arguments. If the argument is an option, I process the option. Otherwise the argument is one of the required arguments. In order to read the required arguments I need some kind of state machine. In the first case the first argument should be read. In the second case the second argument and so on.
I wrote a Proc class with just one method, which returns again a Proc class.
static abstract class Proc {
  abstract Proc exec (String arg);
}

By this I can execute some action and define what should be done next.

save db host and then read name
save db name and then read user
save db user and then read xml file
save xml file and then nothing

But because of all the class overhead it is hard to read.
Proc proc = new Proc () {
    Proc exec (String arg) {
      db_host = arg;
      return new Proc () {
        Proc exec (String arg) {
          db_name = arg;
          return new Proc () {
            Proc exec (String arg) {
              db_user = arg;
              return new Proc () {
                Proc exec (String arg) {
                  xml_file = arg;
                  return null;
                }
              };
            }
          };
        }
      };
    }
  };

Is there a way to simplify the code? I tried Lambdas, but it seems to me that Lambdas can use only final variables, which is a bit useless, when I want to store a value.
Complete example:
public class Import
{
  static String db_host = null;
  static String db_port = "5432";
  static String db_name = null;
  static String db_user = null;
  static String xml_file = null;

  static void usage ()
  {
    System.err.println ("Usage: Import [-p PORT] HOST DATABASE USER FILE");
  }

  static abstract class Proc {
    abstract Proc exec (String arg);
  }

  static void parse_args (String[] args)
  {
    Proc proc = new Proc () {
        Proc exec (String arg) {
          db_host = arg;
          return new Proc () {
            Proc exec (String arg) {
              db_name = arg;
              return new Proc () {
                Proc exec (String arg) {
                  db_user = arg;
                  return new Proc () {
                    Proc exec (String arg) {
                      xml_file = arg;
                      return null;
                    }
                  };
                }
              };
            }
          };
        }
      };

    try {
      for (int i = 0; i < args.length; i++)
        switch (args[i]) {
        case "-p":
          db_port = args[++i];
          break;
        case "-h":
          usage ();
          break;
        default:
          proc = proc.exec (args[i]);
        }
    }
    catch (Exception ex) {
      throw new Error ("Can not parse args!", ex);
    }
  }

  public static void main (String[] args)
  {
    parse_args (args);

    System.err.println ("db_host: " + db_host);
    System.err.println ("db_port: " + db_port);
    System.err.println ("db_name: " + db_name);
    System.err.println ("db_user: " + db_user);
    System.err.println ("xml_file: " + xml_file);
  }
}


texts: Return most recent DateTime C# Entity Framework

texts:
Job -> Many Quotes
Quote -> EmailLogList
EmailLogList -> Many EmailLogs

I want to return a CreatedDate from an EmailLog which has been created most recently - using a Job.Guid.

Is this the best way possible?

public DateTime? GetMostRecentEmailLog(Guid jobGuid)
{
    using (DbContext dbContext = new DbContext())
    {
        IEnumerable<Guid?> logLists = dbContext
            .Jobs
            .Include(j => j.Quotes)
            .First(j => j.Guid == jobGuid)
            .Quotes
            .Where(q => q.EmailLogListGuid != null)
            .Select(q => q.EmailLogListGuid);

        return dbContext
            .EmailLogs
            .OrderByDescending(e => e.CreatedDate)
            .Where(e => logLists.Contains(e.EmailLogListGuid))
            .Select(e => e.CreatedDate)
            .FirstOrDefault();
    }
}


texts: String checking functions in functional JavaScript

texts:
Please review these string checking functions. This is the whole module
which is actually written here. It supports buffer, array, and
string by checking the char code.

const charCode = chr => typeof chr === 'number' ? chr : chr.charCodeAt(0)

const every = (fn) => (list) => {
  for (let i = 0; i < list.length; ++i)
    if (!fn(list[i])) return false
  return true
}

const compose   = (f, g) => a => f(g(a))
const inBetween = (num, min, max) => num >= min && num <= max

const space        = code => code == 9  || code == 10 || code == 12 ||
                             code == 13 || code == 32
const numeric      = code => inBetween(code, 48, 57)
const lowerAlpha   = code => inBetween(code, 97, 122)
const upperAlpha   = code => inBetween(code, 65, 90)
const alpha        = code => lowerAlpha(code) || upperAlpha(code)
const alphaNumeric = code => numeric(code)    || alpha(code)
const printable    = code => space(code)      || inBetween(code, 32, 127)

My thought is is that this style is less readable than the original one. What do you think about its readability? And do these functions satisfy what
said as functional?


texts: Leetcode 3Sum problem using hashmap in Python

texts:
For practice, I solved Leetcode 15. 3Sum question:

  Given an array nums of n integers, are there elements a, b, c in nums such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.

My code pass all testcases from my location but get Time Limit Exceeded from leetcode. Can anyone suggest me how to improve my code?

def threeSum(nums):
    """
    :type nums: List[int]
    :rtype: List[List[int]]
    """
    if len(nums) < 3: return []
    len_n, res, n_map, target = len(nums), set(), dict(), 0
    nums.sort()
    for i, n in enumerate(nums):
        for j, c in enumerate(nums[i + 1:], i + 1):
            s = n + c
            n_map[s] = n_map.get(s, []) + [(i, j)]

    for i, n in enumerate(nums):
        s = target - n
        for k in n_map.get(s, []):
            if i > k[1]:
                res.add((nums[i], nums[k[0]], nums[k[1]]))
    return list(map(list, res))


texts: Speed up Django migration that adds two fields into one

texts:
Currently trying to migrate two fields of information into one field. We have many, many objects to go through and it takes roughly 12 minutes to loop through all the objects. That would mean the website would be down for 12 minutes and we do not want that. Is there any way to speed up this migration? It works, it's just slow.

from __future__ import unicode_literals

from django.db import migrations, models

def set_people(apps, schema_editor):
    ParticipationCount = apps.get_model('partcount', 'ParticipationCount')
    for row in ParticipationCount.objects.all():
        row.people = row.male + row.female
        row.save()

class Migration(migrations.Migration):

    dependencies = [
        ('partcount', '0002_participationcount_people'),
    ]

    operations = [
        migrations.RunPython(set_people),
    ]

No is an acceptable answer in this case, I am just curious if there is a different way to do this, as loops can be slow. I am using Django 1.8 and python 2.


texts: Timed requests and parsing JSON in Python

texts:
I wrote this tiny script to pull the JSON feed from the CitiBike website:

import requests
import time

def executeCiti():
    r = requests.get("http://citibikenyc.com/stations/json")
    print r.json()

    time.sleep(62)

while True:
    executeCiti()

exit()

Then I just run the script in terminal and output it to a .txt file like so: python citi_bike.py > output.txt

The end goal of what I would like by the end of this exercise is well formatted JSON data (with only select few of the pairs from each request), separated by each request.  I want it to be manageable so I can create visualizations from it.

Is this an okay way to start what I'm trying to accomplish?
Is there a better way to begin, so that the data came out like I want it as my end goal? In regards to this question, I feel like I have already started taking a very roundabout way to getting to a cleaned up data set, even though this is only the first step.


texts:
I'm learning to code for about a year and recently I finished my Javascript project. It contains of 11 fairly simple apps involving using APIs and DOM manipulations
https://github.com/matt765/js
it's live here https://www.blackravenstudio.net/javascript/
I would gladly hear any opinions on my code. Next project I plan to do in React, propably some more complex stuff
Code below is first app listed in this project
    const cat_result = document.getElementById('cat');
    const dog_result = document.getElementById('dog');

    const cat_btn = document.getElementById('cat-btn');
    const dog_btn = document.getElementById('dog-btn');

    cat_btn.addEventListener('click', getRandomCat);
    dog_btn.addEventListener('click', getRandomDog);
    getRandomCat();
    getRandomDog();
        function getRandomCat() {
        fetch('https://aws.random.cat/meow')
            .then(res => res.json())
            .then(data => {
                cat_result.innerHTML = `<img src="${data.file}" />`;
            });
        }

        function getRandomDog() {
        fetch('https://random.dog/woof.json')
            .then(res => res.json())
            .then(data => {
                if (data.url.includes('.mp4')) {
                    getRandomDog();
                } else {
                    dog_result.innerHTML = `<img src="${data.url}" />`;
                }
            });
        }

If you are interested in front-end, when you go back to main domain there are few websites that I did just to have them in the portfolio. Code of 2 projects is also available on GitHub


texts: OOP in PHP. Exercising on creating a blog

texts:
I am attempting to do object oriented programming in right way, and appreciate any review to see if my approach is correct.

class_blogpost.php as below:

<?php
class BlogPosts {

function __construct() {
    # code...
}

public function ListAllBlogPosts() {
    $DB = DatabaseFactory::getFactory()->Connect();
    $query = $DB->prepare("SELECT * FROM posts ORDER BY date DESC");
    $query->execute();
    $list_all = $query->fetchAll(PDO::FETCH_ASSOC);
    return $list_all;
}

public function ShowABlogPost($post_id) {

    if (isset((int)$_GET["id"];)) {
        $post_id = (int)$_GET["id"];
        $DB = DatabaseFactory::getFactory()->Connect();
        $query = $DB->prepare("SELECT * FROM posts WHERE id = :post_id");
        $query->bindParam(':post_id', $post_id, PDO::PARAM_INT);
        $query->execute();
        $show_post = $query->fetchAll(PDO::FETCH_ASSOC);
        return $show_post[0];
    } else {
        echo "Post not found.";
    }

}

}

$blogposts = new BlogPosts;

Below is code for home.php which uses ListAllBlogPosts() function:

<?php
include_once 'connect.php';
$title = "Home";
include_once 'header.php';
$list_all = $blogposts->ListAllBlogPosts();
?>

<?php
foreach ($list_all as $r) {
  $id = $r["id"];
  $title = $r["title"];
  $post = $r["post"];
  $date = $r["date"];
?>

<?php echo $title; ?>

<?php echo $post; ?>

        <a href="post.php?id=<?php echo $id; ?>">more

<?php
} #ends foreach loop
?>

And finally post.php below, user reaches as post.php?id=1 like that:

<?php
include_once 'connect.php';
$id = $blogposts->ShowABlogPost($_GET["id"])["id"];
$title = $blogposts->ShowABlogPost($id)["title"];
$date = $blogposts->ShowABlogPost($id)["date"];
$post = $blogposts->ShowABlogPost($id)["post"];
include_once 'header.php';
?>

<?php echo $title; ?>

<?php echo $post; ?>


texts: Dijkstra's implementation in c++ with STL priority_queue

texts:
This is dijkstras shortest path algorithm implementation in c++ using priority_queue STL.

Looking for two things: a) Correctness of algorithm itself and b) Any improvement suggestions.

/*                  3
    ----->  b   ----------->d
 10/ -1--  ^  |     1    ^/ |
  / /      |  |   ------// 1|
 x v      2|11|  / /-1--    |
  \        |  v / v         V
   \----->  c  -----------> e
     1             8
*/
class EdgeNode
{
  public:
  char label;
  int weight;
  EdgeNode(char l = 0, int w = 0) : label(l), weight(w) {}
};

using EdgeNodes = vector<EdgeNode *>;

class Graph
{
  public:
  unordered_map<char, EdgeNodes *> adj;

  void addNode(char node)
  {
    if(adj.find(node) == adj.end()) {
      adj[node] = new EdgeNodes();
    }
  }
  void addEdge(char start, char end, int weight)
  {
    if(adj.find(start) != adj.end()) {
      for(auto node : *adj[start]) {
        if(node->label == end) {
          node->weight = weight;
          return;
        }
      }
    } else {
      adj[start] = new EdgeNodes();
    }
    if(end) {
        adj[start]->push_back(new  EdgeNode(end, weight));
    }
  }

  void get_parent(unordered_map<char, char>& parent, char c)
  {
    cout << "Parent chain of \'" << c << "\' =";
    while((parent.find(c) != parent.end()) && parent[c]) {
      cout << parent[c] << ", ";
      c = parent[c];
   }
    cout << endl;
  }

  void get_distance(unordered_map<char, int>& dist)
  {
    cout << "distances => ";
    for(auto a : dist) {
       cout << "(" << a.first << "=" << a.second << ")  ";
    }
    cout << endl;
  }

  void djikstras()
  {
    unordered_set<char> visited;
    unordered_map<char, int> dist;
    unordered_map<char, char> parent;

    using Pair = pair<char, int>;
    priority_queue<Pair, vector<Pair>, greater<Pair>> pq;
    char snode = 'x';

    visited.insert(snode);
    dist[snode] = 0;
    parent[snode] = 0;
    pq.push(make_pair(snode, 0));

    while(!pq.empty()) {
      Pair front = pq.top(); pq.pop();
      for(EdgeNode *edge : *adj[front.first]) {
        if(visited.find(edge->label) == visited.end()) {
          dist[edge->label] = dist[front.first] + edge->weight;
          visited.insert(edge->label);
          parent[edge->label] = front.first;
          pq.push(make_pair(edge->label, dist[edge->label]));
        } else {
          /* //Parent comparison not needed in directed graph for djikstras
             //Its anyways useless because distance back to parent will always be larger
          if(parent[front.first] == edge->label) {
             cout << "Parent " << front.first << " = " <<  parent[front.first] << endl;
             continue;
          }*/
          if(dist[edge->label] > (dist[front.first] + edge->weight)) {
            dist[edge->label] = dist[front.first] + edge->weight;
            parent[edge->label] = front.first;
            pq.push(make_pair(edge->label, dist[edge->label]));
          }
        }
      }
    }
    get_distance(dist);
    get_parent(parent, 'e');
  }
};

int main(void)
{
  Graph g;
  g.addEdge('x', 'c', 1); g.addEdge('x', 'b', 10);
  g.addEdge('b', 'x', 1);  g.addEdge('b', 'c', 11); g.addEdge('b', 'd', 3);
  g.addEdge('c', 'b', 2);  g.addEdge('c', 'd', 1);  g.addEdge('c', 'e', 8);
  g.addEdge('d', 'c', 1);  g.addEdge('d', 'e', 1);
  g.addNode('e');

  g.djikstras();
}


texts: Sending mail using nodemailer in Clojure

texts:
I'm very new to Clojure/ClojureScript and have a question regarding a "proper" way to express something.

This code sends a mail using nodemailer on nodejs:

(defn send-mail [some-id]
  (try
    (let [clj-props (:mail (config/config-file)) ; get the mail server cofiguration
          mail-address (mail-adress-from-props clj-props) ; get the mail address
          mail (clj->js (create-mail mail-address some-id)) ; create a mail to send
          transporter (.createTransport nodemailer (clj->js clj-props))] ; create a transporter using nodemailer
      (.sendMail transporter mail on-mail-sent)) ; send mail using nodemailer
    (catch js/Error e
      (logging/error (.toString e)))))

It is working, but looks completely out of place in ClojureScript. I woud like for a more idiomatic way to do this, so any feedback is welcome.


texts: Proper way to process the huge amount of data from a sensor using Parallel.For

texts:
I am getting the huge amount of data from a sensor. In order to speed up data processing, I thought of using Parallel.For. Below is the sample code:

object sync = new object();
private Random random = new Random();
private List<byte> container = new List<byte>();
private readonly int FRAME_WIDTH = 1000;
private readonly int DATA_LENGTH = 217088;
private readonly int FRAME_HEIGHT = 800;

private void getPointsFromSensor(out Point2D[] points2d, out Point3D[] points3d)
{
    points2d = new Point2D[DATA_LENGTH];
    points3d = new Point3D[DATA_LENGTH];
    for (var index = 0; index < DATA_LENGTH; index++)
    {
        points2d[index] = new Point2D(random.Next(-index, index), random.Next(-index, index));
        points3d[index] = new Point3D(random.NextDouble(), random.NextDouble(), random.NextDouble());
    }
}

private void OnDataArrived(object sendor, DataArrivedEventArgs e)
{
    getPointsFromSensor(out Point2D[] points2d, out Point3D[] points3d);

    int validDataCount = 0;

    container.Clear(); // Remove old points
    // reserving 4 bytes for storing 'validDataCount' and we are going to modify it later
    container.AddRange(BitConverter.GetBytes(validDataCount));

    Parallel.For(0, DATA_LENGTH, index =>
    {
        int points2dX = points2d[index].X;
        int points2dY = points2d[index].Y;

        if (points2dX >= 0 && points2dX < FRAME_WIDTH && points2dY >= 0 && points2dY < FRAME_HEIGHT)
        {
            lock (sync)
            {
                container.AddRange(BitConverter.GetBytes(points3d[index].X));
                container.AddRange(BitConverter.GetBytes(points3d[index].Y));
                container.AddRange(BitConverter.GetBytes(points3d[index].Z));
            }
            Interlocked.Increment(ref validDataCount);
        }
    });

    var validDataCountBytes = BitConverter.GetBytes(validDataCount);//4 bytes
    container[0] = validDataCountBytes[0]; container[1] = validDataCountBytes[1];
    container[2] = validDataCountBytes[2]; container[3] = validDataCountBytes[3];
}

The Point2D and Point3D are defined as follows:

class Point2D
{
    public int X;
    public int Y;

    public Point2D(int x, int y)
    {
        X = x;
        Y = y;
    }
}

class Point3D
{
    public double X;
    public double Y;
    public double Z;

    public Point3D(double x, double y, double z)
    {
        X = x;
        Y = y;
        Z = z;
    }
}

It turns out that the Parallel.For version is taking much time compared to simple for loop.

I am wondering if there exists is a better way to use Parallel.For inside a callback function in C#.


texts: Determining the number of vowels in each word from a file

texts:
I'm 5 weeks into my first C++ class. I'm curious about how this code could be improved, more streamlined or simply things that I could/should have done better.

The project was:

  Read from a .txt file that has different words on separate lines.
  Determine how many vowels each word has, and print each word AND vowel count to the console. You must write and use a function outside of main().

Here's the code I wrote:

#include <iostream>
#include <string>
#include <fstream>
using namespace std;

//prototypes
void readFile();
void printWords(string);

int main()
{
    readFile();
    return 0;
}//end main

void readFile()
{
    ifstream inFile;
    string words;

    inFile.open("words.txt");

    while(!inFile.eof())
    {
        inFile>>words;
        printWords(words);
    }//end while loop

    inFile.close();
}//end readFile function

void printWords(string str)
{
    char a = 'a', e = 'e', z = 'i', o ='o', u ='u';
    int num_A = 0, num_E = 0, num_I = 0, num_O = 0, num_U = 0;

    cout<< str <<endl;

    for(int i = 0; i < str.length(); ++i)
    {
        if(str.at(i) == a)
        {
            num_A++;
        }
        if(str.at(i) == e)
        {
            num_E++;
        }
        if(str.at(i) == z)
        {
            num_I++;
        }
        if(str.at(i) == o)
        {
            num_O++;
        }
        if(str.at(i) == u)
        {
            num_U++;
        }
    }//end for loop
    cout<< "a: " << num_A <<endl;
    cout<< "e: " << num_E <<endl;
    cout<< "i: " << num_I <<endl;
    cout<< "o: " << num_O <<endl;
    cout<< "u: " << num_U << "\n" <<endl;

}//end printWord function

I feel like there should be a smoother function to extract, count and return the vowels. Then a function to print. Also, I tried to use a switch statement because there were so many if statements, but I couldn't get it to work.


texts:
I implemented a test that reads data from temp file on Windows.
I originally had an issue that I solved with the help of this answer

def test_read(self):
    """Test read from file"""
    import tempfile
    import os
    try:
        with tempfile.NamedTemporaryFile(delete=False) as temp:
            content = 'Some data'
            temp.write(content.encode('utf-8'))
            temp.flush()
            self.assertEqual(content, b.read(Path(temp.name)))
    finally:
        os.remove(temp.name)

How can I do this better? Is it ok to have try...finally in the test?

b is a custom module.
It reads data from temp file.

def read(path):
    """Reads file content from FS"""
    if path in VIRTUAL_FS:
       return VIRTUAL_FS[path]
    with open(path.as_posix(), 'r') as file:
       return file.read()


texts: Is my use of CSS inheritance clean enough for these sprites?

texts:
I have a set of links with background images on this CodePen.

I am seeking feedback to see if I did this the most optimal way. For example, I made a sprite so that I can just load one image. And I leveraged inheritance so that I did not have to assign every containing div a class. Just used a child selector and for the individual buttons, I used :nth-of-type to pass the background image.

Tell me your thoughts if this could use improvement.

HTML

      Dentist

      Patient

      Lab

CSS

.introSelect { text-align:center; }
.introSelect div {
  display:inline-block;
  position: relative;
  text-align: center;
  background: url('https://s3-us-west-2.amazonaws.com/s.cdpn.io/101702/bruxzir-user-sprites_1.png') no-repeat;
  width: 90px;
  height: 90px;
}
.introSelect div:nth-of-type(1) {
  background-position: 0 -180px ;
}
.introSelect div:nth-of-type(2) {
  background-position: -90px -180px;
}
.introSelect div:nth-of-type(3) {
  background-position: -180px -180px;
}

.introSelect a {
  display:block;
  text-decoration: none;
}
.introSelect span {
  background-color: rgba(152, 216, 242, 0.7);
  color: #444;
  font-weight: bold;
  letter-spacing: 1px;
  position: absolute; bottom: 0; left: 0; right: 0;
}


texts: Batch/PowerShell script that toggles the minimized state of a window

texts:
I wrote this script for a user who wants to toggle the minimized state of a window that minimizes to the tray.  The user required a .bat script, so I wrote a bat + PowerShell hybrid script in order to import functions from user32.dll.

<# : minimize.bat
:: toggles minimized state of a window by its filename
:: minimize.bat /? for usage

@echo off & setlocal

if "%~1"=="" goto usage
set "prog=%~n1"
tasklist | findstr /i "\<%prog%\>" >NUL || goto usage

set /P "=Toggling the minimized state of %prog%... " <NUL
powershell -noprofile -noninteractive "iex ((gc \"%~f0\") -join \"`n\")"

goto :EOF

:usage
echo syntax: %~nx0 progname[.exe]
echo;
echo If the program is visible, minimize it.  If minimized, restore it.
goto :EOF

End batch / begin PowerShell hybrid chimera #>

Add-Type user32_dll @'
    [DllImport("user32.dll")]
    public static extern bool ShowWindowAsync(IntPtr hWnd, int nCmdShow);

    [DllImport("user32.dll")]
    public static extern int GetWindowLong(IntPtr hWnd, int nIndex);

    [DllImport("user32.dll")]
    public static extern IntPtr FindWindowEx(IntPtr parentHandle, IntPtr childAfter,
        IntPtr lclassName, string windowTitle);
'@ -namespace System

$hwnd = (ps $env:prog)[0].MainWindowHandle

if ($hwnd -eq 0) {
    tasklist /v /fi "imagename eq $env:prog*" /fo list | %{
        $title = $_ -replace '^[^:]+:\s+'
    }
    $zero = [IntPtr]::Zero
    $hwnd = [user32_dll]::FindWindowEx($zero, $zero, $zero, $title)
}

$state = [user32_dll]::GetWindowLong($hwnd, -16)

# mask of 0x20000000 = minimized; 2 = minimize; 4 = restore
if ($state -band 0x20000000) { $action = 4 } else { $action = 2 }

if ([user32_dll]::ShowWindowAsync($hwnd, $action)) {
    write-host "Success" -f green
} else {
    write-host "Fail" -f red
}

Questions:

Neither the get-process cmdlet nor gwmi win32_process nor [diagnostics.process]::getProcessByName() would show me either the window title or the HWND of a window that's minimized to the tray (uTorrent, for example).  Is there an API method I missed, or is tasklist.exe the correct hack here?
Is there any situation where FindWindowEx() would not be able to find a window that could be found with FindWindow()?  Should I import and use FindWindow() as well?

Suggested improvements and other comments (not including "Why not just write the whole thing in PowerShell?") are welcome, of course!