texts: Clean way of passing parameters in swift

texts:
I am creating a user request model to pass-params for web service call

toRegisterParams() is used call register web service request
toLoginParams() is used call register web service request
so my question is this correct way or I need to Optimise my code
or I should make different models for the same. As most-of parameters are the same.
for example, if I need add param in login service there are more probability to add the same in register service param.

 struct UserResquest
{
    var phone: String = ""
    var countryPhoneCode: String = ""
    var referralCode: String = ""
    var firstName : String = ""
    var lastName : String = ""
    var email: String = ""
    var country: String = ""
    var loginBy: String = CONSTANT.MANUAL
    var socialUniqueID: String = ""
    var password: String = ""

    /**
     * Instantiate the instance using the passed dictionary values to set the properties values
     */
    func toRegisterParams() -> [String:Any] {
        var dictParam: [String:Any] = [:]
        dictParam[PARAMS.PHONE] = phone
        dictParam[PARAMS.COUNTRY_PHONE_CODE] = countryPhoneCode
        dictParam[PARAMS.APP_VERSION] = (Bundle.main.infoDictionary?["CFBundleShortVersionString"] as! String)
        dictParam[PARAMS.EMAIL] = email
        dictParam[PARAMS.LAST_NAME] = firstName
        dictParam[PARAMS.FIRST_NAME] = lastName
        dictParam[PARAMS.DEVICE_TOKEN] = preferenceHelper.getDeviceToken()
        dictParam[PARAMS.DEVICE_TYPE] = CONSTANT.IOS
        dictParam[PARAMS.DEVICE_TIMEZONE] = TimeZone.current.identifier
        dictParam[PARAMS.COUNTRY] = country
        dictParam[PARAMS.LOGIN_BY] = loginBy
        if loginBy != CONSTANT.MANUAL {
            dictParam[PARAMS.SOCIAL_UNIQUE_ID] = socialUniqueID
            dictParam[PARAMS.PASSWORD] = ""
        } else {
            dictParam[PARAMS.SOCIAL_UNIQUE_ID] = ""
            dictParam[PARAMS.PASSWORD] = password
        }
        return dictParam
    }

    func toLoginParams() {
        var dictParam: [String:Any] = [:]
        dictParam[PARAMS.APP_VERSION] = (Bundle.main.infoDictionary?["CFBundleShortVersionString"] as! String)
        dictParam[PARAMS.EMAIL] = phone
        dictParam[PARAMS.COUNTRY_PHONE_CODE] = countryPhoneCode
        dictParam[PARAMS.DEVICE_TIMEZONE] = TimeZone.current.identifier
        dictParam[PARAMS.DEVICE_TYPE] = CONSTANT.IOS
        dictParam[PARAMS.SOCIAL_UNIQUE_ID] = ""
        dictParam[PARAMS.DEVICE_TOKEN] = preferenceHelper.getDeviceToken()
        dictParam[PARAMS.LOGIN_BY] = CONSTANT.MANUAL
        dictParam[PARAMS.PASSWORD] = password
        dictParam[PARAMS.PHONE] = phone
        return dictParam
    }
}

let me explain the scenario

in my app user can login throught phone number
 - in first screen user inputs the mobile number and place submit button (which call api and check number exist or not)

if yes then password screen will display when user enter password login api call with above params
If number is not registered register screen will display with entered mobile number and then user can't edit number as it verified by otp. after fill form register api call with above param.


texts: Converting images to greyscale using JuicyPixel

texts:
I would like to use Haskell to do some image processing so I have been writing small programs to test performance. I wrote a program to batch convert PNG images from color to greyscale. I compared the performance of the program below with a Python script using PIL. I found when compiled with -threaded -O2, the Haskell code takes four times longer than the python script (this comparison was done on a folder of 50 images).

Is there a way to speed this process up?

Haskell Code

import Codec.Picture
import System.Environment
import System.Directory
import System.FilePath
import Control.Monad

dynToImg :: DynamicImage -> Image PixelRGB8
dynToImg (ImageRGB8 img) = img

procAvg :: FilePath -> FilePath -> IO ()
procAvg inpath outpath = do
  Right inImage <- readPng inpath
  let image = avgImage . dynToImg $ inImage
  writePng outpath image

main :: IO ()
main = do
  args <- getArgs
  let [infolder,outfolder,tstr] = args
      t = read tstr :: Int
  files <- getDirectoryContents infolder
  let baseNames = filter ((==) ".png" . takeExtension) files
      infiles = map (infolder </>) baseNames
      outfiles  = map (outfolder </>) baseNames

  zipWithM_ procAvg infiles outfiles

avgImage :: Image PixelRGB8 -> Image Pixel8
avgImage = pixelMap pixelAvg

pixelAvg :: PixelRGB8 -> Pixel8
pixelAvg (PixelRGB8 r g b) =
  (r `div` 3 + g `div` 3 + b `div` 3 +
          (r `mod` 3 + g `mod` 3 + b `mod` 3) `div` 3)

Python Code

from PIL import Image
import sys
import os

if __name__ == "__main__":
    infolder = sys.argv[1]
    outfolder = sys.argv[2]

    fnames = os.listdir(infolder)

    for f in fnames:
        infile = os.path.join(infolder,f)
        outfile = os.path.join(outfolder,f)

        inimg = Image.open(infile)
        gray = inimg.convert('L')
        gray.save(outfile)
        inimg.close()


texts: Collect the values of a Map into a MapSet

texts:
# Collect the values of a map into a mapset
def values(map) do
    Enum.reduce(map, MapSet.new(),
        fn ({_, value}, acc) ->
            MapSet.put(acc, value)
        end
    )
end

values.(%{"a"=>1, "b"=>1, "c"=>2}) |>
IO.inspect

Is there a cleaner way to write this values function?


texts: Can someone help me optimize my DFS implementation in Python?

texts:
def dfs(graph, node):
"""Run DFS through the graph from the starting
node and return the nodes in order of finishing time.
"""
stack = [[node, True]]
while True in [x[1] for x in stack]:
    i = 0
    for x in xrange(len(stack)):
        if stack[x][1] == True:
            i = x
            break
    stack[i][1] = False
    stack = [[x, True] for x in graph[stack[i][0]] \
                 if (([x, True] not in stack) and ([x, False] not in stack))] + stack
return [x[0] for x in stack]

Input: Graph as adjacency list Eg: {1:[2, 3], 2:[1], 3:[]}
       Node is an integer value from where depth first search begins Eg: 1
Output: The list of nodes in order of their finishing times.
        Eg: [3, 2, 1]

For large graphs, the above code is taking too long to execute. Is there a better way to do this?
Edit: I could do better time by implementing the following code. Is it possible to do even better?

def dfs(graph, node):
"""Run DFS through the graph from the starting
node and return the nodes in order of finishing time.
"""
seen = defaultdict(bool)
stack = [node]

while True:
    flag = True
    for x in stack:
        if not seen[x]:
            stack = [a for a in graph[x] if not seen[a]] + stack
            seen[x] = True
            flag = False
            break
     if flag:
        break
return stack

Edit: I've changed seen and stack variables to sets. But I'm not getting the required performance boost. What am I doing wrong?

def dfs(graph, node):
    """Run DFS through the graph from the starting
    node and return the nodes in order of finishing time.
    """
    seen = set()
    stack = {node}
    while True:
       flag = True
       for x in stack:
           if x not in seen:
                stack = stack.union(set(graph[x]))
                seen = seen.union({x})
                flag = False
                break
        if flag:
            break
    return list(stack)


texts:
I have a need to do some conversions in a loop to display the results using C++98 on Linux, which doesn't have any itoa() to complement atoi(). I opted for this instead of snprintf(). This is for an embedded device and the conversions will be done in a few loops, so speed is important.

It's based on some code I found on GitHub.  I modified it to write to a user-supplied buffer, so that it's reentrant.

Please let me know if anyone has a better method for small numeric conversions to ascii using base-10 only, or any recommended changes. Thanks.

/*
  Modified from:
  https://gist.github.com/madex/c5cd5c6a23965a845d6e

  This only works for up to 9 digits and only converts to base 10 ascii,
  but no division is used and this method is very fast.
*/

void itoaBase10(int32_t num, char *string, int lengthOfString)
{
    if (!string || num > 9999999999)
    return;
    memset(string, 0, lengthOfString);
    static uint32_t subtractors[10] =
     { 1000000000, 100000000, 10000000, 1000000, 100000, 10000,
       1000, 100, 10, 1 };
    char n, *str = string, sign = num < 0 ? '-' : ' ';
    uint32_t *sub = subtractors;
    uint32_t u = num < 0 ? (uint32_t)-num : (uint32_t)num;
    uint8_t  i = 10;
    while (i > 1 && u < *sub)
    {
        i--;
        sub++;
    }
    str++;
    *(str - 1) = sign;
    while (i--)
    {
        n = '0';
        while (u >= *sub)
        {
            u -= *sub;
            n++;
        }
        *str++ = n;
        sub++;
    }
}


texts:
A basic shell function to create a directory and change to it goes like this:

mkcd () { mkdir "$1" && cd "$1"; }

This works well in many cases but breaks in unusual cases (e.g. if the argument begins with -).

I'm writing a more sophisticated version. This version calls mkdir -p to create parent directories if needed and just change to the directory if it already exists. It has these design goals:

Work in any POSIX compliant shell.
Cope with any file name.
If the shell has logical directory tracking, where foo/.. is the current directory even if foo is a symbolic link to a directory, then the function must follow that logical tracking: it must act as if the cd builtin was called and magically created the target directory.
If a directory is created, it is guaranteed that the function changes into it, as long as there is no race condition (another process moving a parent directory, changing relevant permissions, …).

Here is my best current effort. Does it meet the goals above? Are there situations where the behavior is surprising?

mkcd () {
  case "$1" in
    */..|*/../) cd -- "$1";; # that doesn't make any sense unless the directory already exists
    /*/../*) (cd "${1%/../*}/.." && mkdir -p "./${1##*/../}") && cd -- "$1";;
    /*) mkdir -p "$1" && cd "$1";;
    */../*) (cd "./${1%/../*}/.." && mkdir -p "./${1##*/../}") && cd "./$1";;
    ../*) (cd .. && mkdir -p "${1#.}") && cd "$1";;
    *) mkdir -p "./$1" && cd "./$1";;
  esac
}


texts:
I am looking for better ways to write this code. At the moment it grabs a list of all navigation items and places them into an array (using PDO).

However, as you can see, it is using two foreach loops to grab the subnavigation items under each parent. Is there a better way that this code can be written?

    <?php
    if($grabNav = $db->prepare("SELECT caption,url,visibility,id,class,parent_id FROM navigation ORDER BY parent_id ASC, order_id ASC"))
    {
        $grabNav->execute();
        $grabNav = $grabNav->fetchAll();
        foreach($grabNav as $nav)
        {
            $visibility = true;
            switch($nav['visibility'])
            {
                default:
                case 0: $visibility = false; break;
                case 1: $visibility = true; break;
                case 2: if(LOGGED_IN && isset($cUser)) { $visibility = true; } else { $visibility = false; } break;
                case 3: if(LOGGED_IN && isset($cUser)) { $visibility = false; } else { $visibility = true; } break;
            }
            if(!$visibility) { continue; }
            if($nav['parent_id'] != -1) { continue; }

            $class = $core->output($nav['class']);
            if($nav['id'] == PAGE_ID) { $class .= ' selected'; }
            echo '
output($nav['url']).'">'.$core->output($nav['caption'],true).'
';
            foreach($grabNav as $sub)
            {
                if($sub['parent_id'] == $nav['id'])
                {
                    $visibility = true;
                    switch($sub['visibility'])
                    {
                        default:
                        case 0: $visibility = false; break;
                        case 1: $visibility = true; break;
                        case 2: if(LOGGED_IN && isset($cUser)) { $visibility = true; } else { $visibility = false; } break;
                        case 3: if(LOGGED_IN && isset($cUser)) { $visibility = false; } else { $visibility = true; } break;
                    }
                    if(!$visibility) { continue; }
                    $subClass = $core->output($sub['class']);
                    echo'
output($sub['url']).'">'.$core->output($sub['caption'],true).'
';
                }
            }
            echo'

';
        }
    }
    ?>


texts:
Is there any way of improving this code? (Here's a JSFiddle with an example and comments)

Example: A hotel greeter can greet guests and accepts tips, but it's impossible to see the total of tips a greeter has received.

<!DOCTYPE html>

            []___
           /    /\     O
          /____/__\   /|\
          |[][]||||   / \
                     ALFRED

        <button onclick="javascript:alfred('greet')">Arrive at Hotel</button>
        <button onclick="javascript:alfred('acceptTip', 10)">Tip Alfred $10</button>

Goals:

Keep it DRY
Keep it MVC
Make sure anyone with access to a "greeter" can never manipulate the view or model directly.

Limitations:

To avoid clutter, avoid type checking to avoid simple errors unless it is necessary to guarantee integrity.

Some specific thoughts:

Is there a better way of passing model and view into the controller?
Is there a better way of communicating with the controller?
Is there a good way of making a more general view?
Any other improvements?


texts: Number of unique substrings of particular length of a binary string

texts:
Question: A binary string is given with only 0's and 1's. A number n is also given as the length of a sub string to be considered. It is to find the number of unique substrings. Here, n=3.

My algorithm: The ways I followed:
(i) First, I extracted out the sub string of length 3 and converted it into a number.
(ii) Then, I stored the number in a new integer type array. In this way, I had an integer array full of numbers representing the substrings.
(iii) Lastly, I traversed down the array, keeping track of the occurrence of the unique numbers only. The amount of unique numbers therefore correspond to the number of unique substring.

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

int main(void)
{
    char arr[50];
    int o[50],check[10000];
    int i,j,count=1,l,k=0,sum,p;

    l=strlen(arr);

    for(i=0;i<l-2;i++){
        p=4;sum=0;
        for(j=0;j<3;j++){
            sum+=(arr[i+j]-'0')*p;
            p/=2;
        }
        o[k++]=sum;
    }

    memset(check,0,sizeof(check));

    for(i=0;i<k-1;i++){
        for(j=i+1;j<k;j++){
            if(o[i]!=o[j] && check[o[i]]!=1 && check[o[j]]!=1){
                count++;
                check[o[j]]=1;
            }
        }
        check[o[i]]=1;
    }

    printf("\n%d",count);

    return 0;
}

I think that my code is quite long and it could be shortened with a good optimization. But I can't think of a way.


texts:
I hacked together a way to make a small graph using Braille unicode codepoints by abusing unicodedata:

def plot(timeline):
  ret = []
  for r1, r2 in zip(timeline[::2], timeline[1::2]):
    character_name = "BRAILLE PATTERN DOTS-"
    dots  = [x for x, y in zip("7321", range(r1))]
    dots += [x for x, y in zip("8654", range(r2))]
    character_name += "".join(sorted(dots))
    ret.append(unicodedata.lookup(character_name) if dots else " ")
  return "".join(ret)

>>> print plot([random.randrange(0,4) for _ in range(100)])
 ⣆⣆⣶⣤⢠⡀⣦⡆⢀⡄⣰⣠⣦⣆⣰⢰⢠⢰⣄⡄ ⣀⣦⡆⣄⣶⣤⣠⡆⣠⣦⣆  ⣰⣴⡄⣤⣀ ⡀⣄⡀⣦⣶⣰⣶⣄⣴

Barring low-hanging incremental improvements such as memoizing the call to unicodedata.lookup, what would be a more proper way to perform this lookup?


texts: Find the first common ancestor of 2 nodes in a binary tree

texts:
TreeNode* firstCommonAncestor(TreeNode* root, TreeNode* q, TreeNode* p){

if(root == p || root == q){
    return p;
}

if(root == NULL){
    return NULL;
}
TreeNode* temp = firstCommonAncestor(root->left,q,p);
TreeNode* temp1 = firstCommonAncestor(root->right,q,p);

if(temp1 != NULL && temp1 != p){
    return temp1;
}
if(temp != NULL && temp != p){
    return temp;
}

if((temp == NULL && temp1 != NULL)||(temp1 == NULL && temp != NULL)){
    return p;
}

if(temp != NULL && temp1 != NULL){
    return root;
}

return NULL;

}

I tested this quite thoroughly and it seems to work but looks quite messy. Can anyone give me input on how to improve the style and the performance?


texts: Multiple anonymous IIFEs inside outer function

texts:
I have a scrollHandler function which contains all of my scroll event-listener logic.
I've used multiple IIFE's inside to separate the logic:
import skills from './json/skills.json';

let capToggle = false;
let triggerCalculateHeight = false;
let scrollEnd = false;

function headingFadeIn(heading) {
    if (!heading) return;
    const parent = heading.parentNode.parentNode;
    const triggerHeight = parent.offsetTop - window.innerHeight / 1.5;

    if (window.scrollY > triggerHeight) {
        heading.style.opacity = '1';
    } else heading.style.opacity = '0';
}

export default function scrollHandler() {
    // Headings
    (() => {
        headingFadeIn(document.getElementById('portfolio-heading'));
        headingFadeIn(document.getElementById('skills-heading'));
        headingFadeIn(document.getElementById('bio-heading'));
        headingFadeIn(document.getElementById('contact-heading'));
    })();
    // Skills
    (() => {
        const bars = document.querySelectorAll('.skill-bar');
        if (!bars) return;

        bars.forEach((i, index) => {
            const bottom = i.getBoundingClientRect().bottom;

            if (window.scrollY > bottom && !i.dataset.heightCalculated) {
                i.style.transform = `scale3d(1, ${skills[index].height / 10}, 1)`;
                i.setAttribute('data-height-calculated', true);

                capToggle = true;
                triggerCalculateHeight = true;
            }
        });
    })();
    // Reviews
    (() => {
        const el = document.getElementById('reviews-inner');
        if (!el) return;

        const mainBackground = document.getElementById('ul-bg');
        const backgrounds = document.querySelectorAll('.blockquote-bg');
        const texts = document.querySelectorAll('.reviews-toggle');
        const bound = el.getBoundingClientRect().top * 10;

        if (window.scrollY > bound) {
            mainBackground.style.opacity = '1';
            mainBackground.style.transform = 'scale(1) rotate(45deg)';
            backgrounds.forEach(i => (i.style.opacity = '1'));
            backgrounds[0].style.transform = 'translate(-4%, -9%) skew(45deg)';
            backgrounds[1].style.transform = 'translate(-6%, -2%) skew(45deg)';
            backgrounds[2].style.transform = 'translate(-5%, 1%) skew(45deg)';
            texts.forEach(i => (i.style.opacity = '1'));
        }
    })();
    // Bio
    (() => {
        const container = document.getElementById('bio-container');
        const tabSelected = document.getElementById('tab-selected');
        const tabBackground = document.getElementById('tab-background');
        const height = document.getElementById('bio').offsetTop;
        if (!tabBackground || !container || !tabSelected || !height) return;

        if (window.scrollY > height / 1.1) {
            // Background tab styling
            tabBackground.style.left = `${tabSelected.offsetLeft}px`;
            tabBackground.style.maxWidth = `${tabSelected.offsetWidth + 20}px`;

            // Container transition
            container.style.opacity = '1';
            container.style.transform = 'skew(-25deg)';
            container.childNodes[0].style.transform = 'skew(25deg)';
        }
    })();
    // Contact
    (() => {
        const groups = document.querySelectorAll('.form-group');
        if (!groups) return;

        groups.forEach((i, index) => {
            i.childNodes[1].blur();

            if (window.scrollY > (i.getBoundingClientRect().top * 10) / 1.5) {
                i.style.opacity = '1';

                if (index >= groups.length - 1) scrollEnd = true;
            }
        });
    })();

    return { capToggle, triggerCalculateHeight, scrollEnd };
}

Is this considered good practice? Are there any pitfalls that could come from this?


texts: Calculating relay operating times, according to IEC 60255

texts:
The script below is used to determine relay operating times, as defined in the standard IEC 60255. The equation and relevant information can be found here.

curve_equation takes three input values, and outputs a list of values representing the trip times for currents in the fixed range np.logspace(np.log10(Is), 5, 1e2).

The part in the bottom plots the trip times for the different curves. The function curve_equation will be used to much more than that, so I'm mostly interested in improvements to that one.

# -*- coding: utf-8 -*-
"""
Created on Sun Apr 29 13:28:26 2018

@author: Stewie
"""
import numpy as np
import matplotlib.pyplot as plt

def curve_equation(curve_name, T, Is):
    """
    This function calculates and returns the inverse curves for
    the selected curve type.
    Input:
        curve_name: one of the strings: "SIT", "VIT", "LTI", "EIT", "UIT"
        T: The time dial setting. Typically in the range 0.1 ... 1
        Is: The current setting. Typically in the range 100-10000

    The appropriate k, alpha and theta values are selected based on the
    curve type.
    """

    # Define constants to be used in the curve equation
    k = (0.14, 13.5, 120, 80, 315.2)
    alpha = (0.02, 1, 2, 2, 2.5)
    beta = (2.97, 1.5, 13.33, 0.808, 1)
    curve_types = ("SIT", "VIT", "LTI", "EIT", "UIT")

    # idx is the index of the values we want
    try:
        idx = curve_types.index(curve_name)
    except:
        print("Non-existing curve-type")
        return

    I = np.logspace(np.log10(Is), 5, 1e2)

    def td_equation():
        td = k[idx]/((I/Is)**alpha[idx]-1) * (T / beta[idx])
        return(td)

    return(td_equation())

# For testing / plotting purposes:
curve_types = ("SIT", "VIT", "LTI", "EIT", "UIT")
I = np.logspace(1, 5, 1e2)
for curve_type in curve_types:
    plt.loglog(I, curve_equation(curve_type, 1, 1e2), label=curve_type)

plt.xlabel("Current [A]")
plt.ylabel("Time [s]")
plt.title("IEC Time/current curves")
plt.grid()
plt.legend()


texts: Validation for Model Object using Fluent Validation

texts:
I am using fluentvalidation to validate my object model. I have to make sure that the first two characters of an ISIN must be letters / non numeric. The way I did it is to convert the string to a char array and then perform regex on the first two characters. I was wondering if anyone has a nicer way of doing the validation using a custom fluent validation. Thanks
    public class Create
    {
        public class Command : IRequest
        {
            public string Name { get; set; }

            public string Exchange { get; set; }

            public string Ticker { get; set; }

            public string Isin { get; set; }

            public string Website { get; set; }
        }

        public class CommandValidator : AbstractValidator<Command>
        {
            public CommandValidator()
            {
                RuleFor(x => x.Name).NotEmpty();
                RuleFor(x => x.Isin).SetValidator(new MyValidator());
            }
        }

        public class MyValidator : PropertyValidator
        {
            public MyValidator(
                string errorMessage = "Isin. The first two characters of an ISIN must be letters / non numeric.") : base(errorMessage)
            {
            }

            protected override bool IsValid(PropertyValidatorContext context)
            {
                var stringToValidate = context.PropertyValue as String;
                return IsValid(stringToValidate);
            }

            public bool IsValid(string stringToValidate)
            {
                var charString = stringToValidate.ToCharArray();
                if (Regex.IsMatch(charString[0].ToString(), "[0-9]") || Regex.IsMatch(charString[1].ToString(), "[0-9]"))
                {
                    return false;
                }

                return true;
            }

            public class Handler : IRequestHandler<Command>
            {
                private readonly DataContext _context;

                public Handler(DataContext context)
                {
                    _context = context;
                }
                public async Task<Unit> Handle(Command request,
                    CancellationToken cancellationToken)
                {
                    var company = new Company
                    {
                        Name = request.Name,
                        Exchange = request.Exchange,
                        Ticker = request.Ticker,
                        Isin = request.Isin,
                        Website = request.Website
                    };

                    await _context.Companies.AddAsync(company);

                    var success = await _context.SaveChangesAsync() > 0;

                    if (success) return Unit.Value;

                    throw new Exception("Problem saving changes");
                }
            }
        }
    }
}


texts:
Here's my implementation of Game of Life. I'm quite new to Python and would like to know how could I improve that code, especially in terms of performance, compactness and readability.

import copy
import pygame
from pygame import *
import random

#constants
red = (255, 0, 0)
black = (0, 0, 0)
white = (255, 255, 255)
#neighbour coordinates
neighbours = [[-1,-1],[-1,0],[-1,+1],
              [0,-1],        [0,+1],
              [+1,-1],[+1,0],[+1,+1],]

class cell(object):
        def __init__(self, ngb, state):
                self.state = state
                self.ngb = 0

#2d array for storing cells
cells = [[i for i in range(50)] for i in range(50)]

#random field generation
def generate():
        print "Generating"
        for y in xrange(50):
                for x in xrange(50):
                        cells[x][y] = cell(0, random.randint(0, 1))
        print "DoneGen"

#neighbour processing
def update():
        global cells2
        #saving this turn's state
        cells2=copy.deepcopy(cells)
        for y in xrange(50):
                for x in xrange(50):
                        cellv2=cells2[x][y]
                        cellv2.ngb=0
                        cellv = cells[x][y]
                        #processing
                        for i in neighbours:
                                #offsetting neighbour coordinates
                                dy=i[0]+y
                                dx=i[1]+x
                                if dy < 0:
                                        dy = 49
                                if dy > 49:
                                        dy = 0
                                if dx < 0:
                                        dx = 49
                                if dx > 49:
                                        dx = 0
                                if cells2[dx][dy].state==1:
                                        cellv2.ngb+=1
                        #updating field
                        if cellv2.state==1 and 2<=cellv2.ngb<=3:
                                cellv.state=1
                        else:
                                cellv.state=0
                        if cellv2.state==0 and cellv2.ngb==3:
                                cellv.state=1

#main game function
def play():
        #initialization
        pygame.init()
        scrn = pygame.display.set_mode((500, 500))
        mainsrf = pygame.Surface((500, 500))
        mainsrf.fill(white)
        generate()
        #game cycle
        while 1:
                #tracking quitting
                for event in pygame.event.get():
                        if event.type == QUIT:
                                pygame.quit()
                                sys.exit()
                #drawing
                for y in xrange(50):
                        for x in xrange(50):
                                if cells[x][y].state==1:
                                        pygame.draw.rect(mainsrf, black, (x*10, y*10, 10, 10))
                                else:
                                        pygame.draw.rect(mainsrf, white, (x*10, y*10, 10, 10))
                                if cells[x][y].ngb==3:
                                        pygame.draw.rect(mainsrf, red, (x*10, y*10, 10, 10))
                update()
                scrn.blit(mainsrf, (0, 0))
                pygame.display.update()

#running the game
if __name__ == "__main__":
                                play()


texts: Add To Query Based Off Date Picker Or Drop Down List

texts:
I have a page where the user can either input a start date and an end date into two date fields, OR the user can select 10 days, 20 days, 30 days from a drop down list on the page.  My php/html knowledge is very basic and I have the syntax set-up like such which works, but there is probably a more efficient way to code this syntax.  Speed is my #1 priority here (and this current syntax will have the page load in roughly 3 seconds, sweet!) - but is there optimization/better logic flow that can be used for htis?

Start Date:<input type="date" name="bgin" value="<?= $_POST['bgin'] ?>">
End Date:<input type="date" name="end" value="<?= $_POST['end'] ?>">

    Show last 10 - 20 - 30 Days
    <select name="daterange">
        <option value="">Select...</option>
        <option value="10">10 Days</option>
        <option value="20">20 Days</option>
        <option value="30">30 Days</option>
    </select>

<input type="submit" name="submit" value="Show Me">
<?php
    $bgin = $_POST['bgin'];
    $end   = $_POST['end'];
    if (isset($_POST['daterange'])) {
        $datecriteria = $_POST['daterange'];
    }
    //The user input a begin and end date so process based off those values
    if (isset($bgin) && isset($end)) {
        //Connect to mssql here
        $db                 = JDatabase::getInstance($option);
        $query              = $db->getquery(true);
        $query              = "Select statement blah blah where datefield >= '$bgin' and datefield <= '$end'";
    }
    if (isset($datecriteria)) {
        //Connect to mssql here
        $db                 = JDatabase::getInstance($option);
        $query              = $db->getquery(true);
        $query              = "Select statement blah blah
        if ($datecriteria = '10') {
            $query              = " where datefield >= DateAdd(day, -10, getdate()) And datefield <= getdate())";
        }
        if ($datecriteria = '20') {
            $query              = " where datefield >= DateAdd(day, -20, getdate()) And datefield <= getdate())";
        }
        if ($datecriteria = '30') {
            $query              = " where datefield >= DateAdd(day, -30, getdate()) And datefield <= getdate())";
        }
    }
    else {
        echo "Please check the selection criteria and process again."
    }
?>


texts:
I’m learning a lot of from Combine thanks to an amazing book in raywenderlich.
Currently i’m writing an app and following the clean MVVM architecture.
Then I have the following layers:

Domain(UseCases and RepositoryProtocols)
Data(RepositoryImplementations)
Presentation(ViewController and ViewModels)

So this is what I have by now:
LoginUseCase.swift
import Foundation
import Combine
public enum LoginState {
    case idle
    case inProgress
    case success
    case emailValidationPending
    case wrongPassword
    case invalidEmail
    case invalidPassword
    case error
}
public protocol LoginUseCase {
    func login(email: String, password: String) -> AnyPublisher<LoginState, Never>
}
public class LoginUseCaseImp: LoginUseCase {
    let repository: RegistroRepository
    public init(repository: RegistroRepository) {
        self.repository = repository
    }
    public func login(email: String, password: String) -> AnyPublisher<LoginState, Never> {
        return Future<LoginState, Never> { [weak self] promise in
            self?.repository.login(email: email, password: password) { (result: Result<Bool, LoginRepositoryError>) in
                switch result {
                case .success(_):
                    return promise(.success(.success))
                case .failure(let error):
                    switch error {
                    case .wrongPassword:
                        return promise(.success(.wrongPassword))
                    case .userNotExist:
                        return promise(.success(.error))
                    case .emailValidationPending:
                        return promise(.success(.emailValidationPending))
                    }
                }

            }
        }.eraseToAnyPublisher()
    }
}

LoginViewModel.swift
import Foundation
import DomainRadarAir
import Combine

public final class LoginViewModel: ObservableObject {
    private let loginUseCase: LoginUseCase

    public init(loginUseCase: LoginUseCase) {
        self.loginUseCase = loginUseCase
    }

    public func login(email: String?, password: String?) -> AnyPublisher<LoginState, Never> {
        guard let email=email, !email.isEmpty else {
            return Just<LoginState>(.invalidEmail).eraseToAnyPublisher()
        }
        guard let password=password, !password.isEmpty else {
            return Just<LoginState>(.invalidPassword).eraseToAnyPublisher()
        }

        return loginUseCase.login(email: email, password: password)
    }
}

Then in the LoginViewController.swift
    @IBAction func loginClick(_ sender: Any) {
            viewModel.login(email: emailTF.text, password: passwordTF.text)
                .print("State: ")
                .sink { [weak self] state in
                    guard let self = self else { return }
                    switch state {
                    // handle all cases
                    }
                .store(in: &cancellables)
    }

What do you think of this approach, passing AnyPublisher object from UseCase to ViewController through ViewModel?
Thanks in advance for your opinions.


texts:
I wrote an Ajax function, which should be used in a framework to interact with a webserver.

The (self-written) Java-Webserver can be used to fetch files and folder-contents, create files and folders, and delete them.

/**
 * Performs an Ajax-Request
 * @param  {string}   method            HTTP-Method
 * @param  {string}   url
 * @param  {string}   postData          optional; HTTP-body
 * @param  {string}   contentType       optional; default: "multipart/form-data"
 * @param  {object}   authentication    optional; loginCredentials for basicAuth; {"user": "userName", "password": "password"}
 * @param  {function} callback          optional; called, if the operation succeeded;
 *                                              Parameter: (string) response-body
 * @param  {function} errorCallback     optional; called, if the operation failed;
 *                                              Parameter: 1 = (number) statusCode; (==0, if the given parameters were invalid)
 *                                                         2 = (string) statusText; (or errorMessage, if statusCode == 0)
 */
function ajax(method, url, postData, contentType, authentication, callback, errorCallback) {
    if(typeof(errorCallback) != 'function'){
        errorCallback = function(){};                           //Dummy-function to reduce code
    }

    //Validate the input parameters
        if(["GET", "HEAD", "POST", "PUT", "DELETE"].indexOf(method) < 0){
            return errorCallback(0, "Invalid method");
        }
        if(postData && ["HEAD", "POST"].indexOf(method) < 0){          //Other methods don't support postData
            return errorCallback(0, "Invalid method for postData");
        }
    //Get a cross-browser XML-HTTP-Object:
        var req = createXMLHTTPObject();
        if (!req) {
            return errorCallback(0, "Ajax is not supported");   //Oops! Something bad happened
        }
        req.open(method, url, true);    //async = true
    //Manipulate header-fields:
        //req.setRequestHeader('User-Agent','XMLHTTP/1.0');
        if(postData){
            if(contentType){
                req.setRequestHeader('Content-type', contentType);
            }else{
                req.setRequestHeader('Content-type', 'multipart/form-data');
            }
            //key-value pairs with binary data or big payloads:
            //    multipart/form-data
            //key-value pairs with few non-alphanumerical symbols:
            //    application/x-www-form-urlencoded
            //binary data:
            //    application/octet-stream
        }
        if(authentication){
            req.setRequestHeader("Authorization", "Basic " + btoa(authentication.user + ":" + authentication.password));    //btoa() = encode string to base64
        }
        req.overrideMimeType("text/plain; charset=utf-8");      //The browser must not execute javascript-files, if they're loaded with this method
    //Prepare execution:
        req.onreadystatechange = function () {
            if (req.readyState != 4) {
                return;
            }
            if (req.status != 200 && req.status != 304) {
                return errorCallback(req.status, req.statusText);
            }
            if(typeof(callback) == 'function'){
                callback(req.response);
            }
        }
        if (req.readyState == 4){
            return;
        }
        req.send(postData);
}

The createXMLHTTPObject()-Method returns either an XMLHttpRequest-Object, or an ActiveXObject-Object to reach cross-browser compatibility.

The whole function should be cross-browser compatible, but doesn't have to support older browsers, as the Framework itself depends upon HTML5.

The code is based on this example

As I'm not 100% familiar with the HTTP-Protocol, I have the following questions:

Did I forget an important part of HTTP/RESTful services that might be needed in a framework?
Can there be efficiency-improvements?
Are there any other bugs/inconsistencies/possible improvements?


texts:
I have a synchronized list that I use as a taskqueue. In this queue I have some long values that need to be proceed and create heavy I/O and delay.  I thought of using threads to get things done faster.

Is there a better way to implement all 50 threads to wait than using t.join();?  Is there anything wrong with the way I access the queue in my run() implementation?

Implementation:

public class Start {

    private static List<Long> queue = Collections.synchronizedList(new ArrayList<Long>());
    private static HashSet<MyThread> threads = new HashSet<MyThread>();

    public static void main(String[] args) throws InterruptedException {
        // add elements to workqueue
        for(int i = 0; i < 100000; i++) {
            queue.add(new Date().getTime());
        }

        // create 50 new threads
        for (int i = 0; i < 50; i++) {
             MyThread t = new MyThread(queue);
             t.start();
             threads.add(t);
        }

        // wait for all 50 threads to finish
        for (MyThread t : threads) {
            t.join();
        }

        System.out.println("Done");
    }
}

Thread:

public class MyThread extends Thread {
    private List<Long> queue = null;

    public MyThread(List<Long> queue) {
        this.queue = queue;
    }

    @Override
    public void run() {
        boolean _break = false;
        int size = 0;
        long task = -1;
        while(true) {
            synchronized (queue) {
                if(!queue.isEmpty()) {
                    size = queue.size();
                    // get task for worker
                    task = queue.remove(0);
                } else {
                    _break = true;
                }
            }
            if(_break == true) {
                System.out.println("Thread-" + this.getId() + " Size: 0");
                break;
            } else {
                // do some stuff with the task
                // ...
                // ...
                System.out.println("Thread-" + this.getId() + " Size: " + size);
            }
        }
    }
}


texts: Class Design : Parsers for different file type and ParserFactory

texts:
I have come up with a class design for parsers (for xml,csv etc) and parser factory. I will be using it in my project.I will be configuring these as beans in the spring context file. I would like to get opinion on the class design.

public interface Parser<T> {
    String fileFormatSupported();
    List<T> parse(File file);
    boolean supports(Class<?> clazz);
    boolean validate(File file);
}
public abstract class AbstractCSVFileParser<T> implements Parser<T>{
    private static final String FILE_FORMAT = "csv";
    @Override
    public final String fileFormatSupported() {
        return FILE_FORMAT;
    }
}
public class CSVToDeviceportServer extends AbstractCSVFileParser<DeviceportServer> {
    @Override
    public boolean supports(Class<?> clazz) {
        return DeviceportServer.class.isAssignableFrom(clazz);
    }
    @Override
    public  List<DeviceportServer> parse(File file) { /* logic*/ }
    @Override
    public boolean validate(File file) { /* logic */  }
}
public class CSVToDeviceParser extends AbstractCSVFileParser<Device> {
    @Override
    public boolean supports(Class<?> clazz) {
        return Device.class.isAssignableFrom(clazz);
    }
    @Override
    public List<Device> parse(File file) {  /* logic */  }
    @Override
    public boolean validate(File file) { /* logic */ }
}
public class ParserFactory {
    @Autowired
    private List<Parser<?>> parsers;

    private Map<String, List<Parser<?>>> parserMap;

    public List<Parser<?>> getParsers() {
        return parsers;
    }
    @PostConstruct
    public void afterPropertiesSet() throws Exception{
        if(this.parsers == null) {
            throw new IllegalStateException("Parsers not initialized");
        }
        parserMap = new HashMap<>(2);
        for(Parser<?> parser : parsers) {
            if (parserMap.containsKey(parser.fileFormatSupported())) {
                parserMap.get(parser.fileFormatSupported()).add(parser);
            }else {
                List<Parser<?>> parserList = new ArrayList<>();
                parserList.add(parser);
                parserMap.put(parser.fileFormatSupported(), parserList);
            }
        }
    }
    public Parser<?> getParser(Class<?> clazz, String format) {
        for(Parser<?> parser : parserMap.get(format)) {
            if(parser.supports(clazz)) return parser;
        }
        throw new IllegalStateException("Could not find parser for the format");
    }
}

I'm adding parser classes only for the CSV type of files, but there are other types of parsers for xml, json. They will have same class design as the CSV file parsers.


texts:
We are new into hibernate, in our project for saving an entry the below given code is used, please have a look.

public void save(Object obj) {
    Session session = null;
    Transaction transaction = null;
    try {
        session = sessionFactory.getCurrentSession();
        transaction = session.beginTransaction();
        session.save(obj);
        session.flush();
        transaction.commit();
    } catch (JDBCException jde) {
        logger.fatal("Error occured in database communication", jde);
        transaction.rollback();
        throw new RuntimeException(jde);
    } finally {
        if (session.isOpen()) {
            session.close();
        }
    }
}

Is this the right way to do (Considering performance and Security) ?
Is this thread safe? as there may be number of users at the same time.

Bonus Question:is there any way to make this code better in Java 8 ?

ps:This method is written in our DatabaseUtil class.


texts: Sorting a PHP array in a discontinuous manner

texts:
I start with an array containing some 'ids' and some 'values'.

What I need is to organize the 'ids' in a new array to be, if possible, apart when the 'values' they are associated with are alike.

So I came up with a solution.  If there is too much of a value type, the spreading is uneven.  So if one of you has a different, better, solution, I'm all ears!

Here is what I came up with:

function discontinus_sort($to_sort, $order_by, $id){

    while (count(array_count_values($to_sort)) >1) {

    $order[] = [$id => key($to_sort) , $order_by => $to_sort[key($to_sort)]];

    $holder = $to_sort[key($to_sort)];

    unset($to_sort[key($to_sort)]);

    reset($to_sort);

        if (isset($to_sort[key($to_sort)])) {

            while( $holder == $to_sort[key($to_sort)] ) {
            next($to_sort);
            }
        }
    }

while ($to_sort) {

    $order[] = [$id => key($to_sort) , $order_by => $to_sort[key($to_sort)]];

    unset($to_sort[key($to_sort)]);

}

return $order;

}

And for an example:

$test[0=>'red',1=>'red',2=>'red',3=>'crimson',4=>'aqua',5=>'chartreuse',6=>'green',7=>'chartreuse',8=>'red',9=>'crimson',10=>'crimson',11=>'aqua',12=>'aqua',13=>'green',14=>'crimson'];

$test_order = discontinus_sort($test, 'couleur', 'id');

foreach ($test_order as $key) {

echo '

';
}

If you change too many values, let's say by red, you'll end up with a big stack of red at the end.


texts: Scala implicit conversion to add methods to Int

texts:
I started learning Scala, and like most functional languages, things get messy pretty quickly for a beginner.

Here I have built a wrapper class for Ints so that I can declare additional functions for the Int class. For example, I want to be able to do something like 1.isPrime, and it should call a function that tells me if the given number is prime or not.

Here is my code:

package object Arithmetic {
    trait S99Int { me =>
        var value: Int = 0
        implicit def int2S99Int(value: Int):me.type = {
            me.value = value; me
        }
    }
}

The above creates the implicit conversions that enable any class that conforms to the trait, to be able to declare additional functions for Ints. For example, I can now do this:

import Arithmetic._

object S99IntPrime extends S99Int {
    import scala.math.{sqrt, abs}

    def isPrime: Boolean = value match {
        case -1|0|1 => false
        case p      => Stream.cons(2,
        Stream.range(3, sqrt(abs(p)).toInt + 1, 2)) forall (p % _ != 0)
    }

    def main(args: Array[String]): Unit = {
        println(args.head.toInt.isPrime)
    }
}

I am mostly asking this question about the first snippet I posted. What are the advantages/disadvantages with declaring the base object like I have? Recommendations? Warnings? I just started learning Scala, so any advice will save me hours of Googling.


texts: Configuring toString via a public static variable

texts:
Sometimes I need toString() to be quite verbose, normally I don't. It can't be nicely solved by using other methods as toString() is what gets shown in debugger (and also in the logs unless I call some method explicitly). As nobody should ever rely on its behavior, I wonder if the following is acceptable

public static boolean volatile verboseToString;

public String toString() {
    return toString(verboseToString);
}

public String toString(boolean verbose) {
    if (verbose) {
        return longDescription();
    } else {
        return shortDescription();
    }
}

Is there any better solution?


texts:
I wrote a calculator that can solve equations with variables using matplotlib and sympy.
I am looking for tips on performance and style.
How can I improve on this calculator? Is it a good idea to use sympy for this purpose?
Repl.it
import sympy
import matplotlib.pyplot as plt
class Iterator:
  name, equation, val = None, None, None
  def __repr__(self):
    return self.__str__()
  def __init__(self, nameIn, equationIn, valIn):
    self.name, self.equation, self.val = nameIn, equationIn, valIn
  def __str__(self):
    return self.get_name() + "," + str(self.get_value())
  def iterate(self):
    replaced = self.equation.replace(self.name, str(self.val))
    self.val = sympy.sympify(replaced)
  def get_name(self):
    return self.name
  def get_value(self):
    return self.val
def graph():
  numTimes = input("How many points ")
  x = input("What to calculate ")
  points = []
  i = 0
  numInputs = int(input("How many variables "))
  j = 0
  replaced = []
  iterators = []
  while numInputs > j:
    name = input("What's the variabe name ")
    iter = input("What's the iteration equation ")
    val = int(input("What's the starting value "))
    iterators.append(Iterator(name, iter, val))
    j += 1
  while i < int(numTimes):
    replaced = x.replace("n", str(i))
    for j in iterators:
      replaced = replaced.replace(j.get_name(), str(j.get_value()))
      j.iterate()
    final = sympy.sympify(replaced)
    right_type = int(final)
    points.append(right_type)
    i += 1
  plt.plot(points)
  plt.ylabel(input("What's the y label "))
  plt.show()
while(True):
  command = input(">> ")
  if command == "graph":
    graph()
  elif command == "help":
    print("""
    msh.
    Used for graphing.
    Commands:
    graph: an interactive graphing calculator
    help: bring up this message
    quit: exit msh
    """)
  elif command == "quit":
    break


texts: Rendering three vertical dots using SCSS

texts:
I have a pretty simple question but I can't seem to find a solution for it. I have the following SCSS code (can be found below) which works fine, but I think it could be simplified to get rid of the double code.

I'm trying to create 3 simple dots with CSS. I figured I could use one div and the :before and :after selectors. I'm looking for a pure (S)CSS solution and don't want to use icons/images. I have a working example but I feel like it could be a lot better structured.

Mainly I'm looking to change the selectors so I can get a format like:

div {
  // Styling for the div in it's normal state.
  [selector for div itself] &:after, &:before {
    // Styling for the div in it's normal state AND for it's :before and :after state
  }
  &:after, &:before {
    // Styling for JUST the :before and :after state
  }
  &:after {
    // Styling for JUST the :after state
  }
  &:before {
    // Styling for JUST the :before state
  }
}

Current code

SCSS:

.row-options-icon{
  padding: 2rem;
  &:hover{
    div, div:after, div:before{
      background-color: black;
    }
  }
  div {
    position: relative;
    border-radius:100px;
    background-color:gray;
    width:.5rem;
    height:.5rem;
    &:after, &:before {
      content: '';
      position: absolute;
      border-radius:100px;
      background-color:gray;
      width:.5rem;
      height:.5rem;
      display: inline-block;
    }
    &:after {
      top: -1rem;
    }
    &:before {
      top: 1rem;
    }
  }
}

HTML:

Working Codepen example


texts:
I've attempted to write a program to find the largest palindrome in a sentence. Spaces are included and characters are case-sensitive.  Can you suggest better ways of doing this?

//public static void main(String args[])--

String source = "my malayalam is beautiful";
//Find the the largest palindrom in this sentence

StringBuilder sb = new StringBuilder( source);
String p = sb.reverse().toString();
System.out.println(p);
System.out.println(source);
int largest = 0;
try{
    for (int start=0; start <=source.length(); start++ ){
        for (int end=start+2; end < source.length(); end++){
            if (largest < (end-start)){
                String sub = source.substring(start, end);
                if (p.indexOf(sub) > 0){
                    largest = sub.length();
                    System.out.println(sub+" "+largest);
                }
            }
        }
    }
}
catch(Exception e){
    System.out.println("2");
    e.printStackTrace();
}


texts:
Implementation:

void ReverseArray<T>(T[] a)
{
    ReverseArray(a,0,a.Length-1);
}

void ReverseArray<T>(T[] a,int lo,int hi)
{
    if(lo >= hi) return;

    // swap
    var temp = a[lo];
    a[lo] = a[hi];
    a[hi] = temp;

    ReverseArray(a,lo+1,hi-1);
}

Usage:

int[] arr = {1,2,3,4,5,6,7,8};
ReverseArray(arr); // reverses the array

How can I improve this?


texts: Outlook VBA-Macro for to check mails concerning recipients and attachments

texts:
Every week I've got to send a report to a clerk. I also have to add his deputy in case the clerk isn't available.
For not to forget the second recipient and the attachment I've wrote myself this VBA-Macro.
Perhaps one could enhance it in a way that it works with more then two recipients?
Any comments and suggestions welcome!

' Main Sub which defines the mail-addresses to check. Then checks if one
'  of the addresses is used. In case of used it checks the remaining
'  constraints.

Private Sub Application_ItemSend(ByVal Item As Object, Cancel As Boolean)
    Dim firstRecipient As String

    ' Define the addresses to check for.
    Const FIRST_ADDRESS = "main.clerk@smth.com" ' Main recipient clerk
    Const SECOND_ADDRESS = "deputy.clerk@smth.com" ' Deputy

    On Error GoTo stopSending

    ' Getting the first mail address from the outlook GUI.
    firstRecipient = Application.ActiveInspector.CurrentItem.Recipients.Item(1).Address

    ' If the first recipient is the specified clerk then check for the deputy.
    If (InStr(1, firstRecipient, FIRST_ADDRESS, vbTextCompare) <> 0) Then

      If checkStateOfMail(SECOND_ADDRESS, True) = False Then
        Cancel = True
        Exit Sub
      End If

    ' If the first recipient is the deputy then check for the specified clerk.
    ElseIf (InStr(1, firstRecipient, SECOND_ADDRESS, vbTextCompare) <> 0) Then

      If checkStateOfMail(FIRST_ADDRESS, True) = False Then
        Cancel = True
        Exit Sub
      End If

    End If

    ' ... if none of both is specified as recipient then just go on.

    Exit Sub

stopSending:
    MsgBox "Runtime error occured.", vbCritical, "Runtime error!"
    Cancel = True

End Sub

' If a doubtful condition has been detected then the user is asked if to cancel
'  cancel or not.

' Parameter
' 1. String - Text for the message box.
' 2. String - Title for the message box.

' Return
' Boolean - Answer if sending shall be cancelled or not.

Function askToCancel(boxMessage As String, boxTitle As String) As Boolean
  Dim answer As String

  answer = MsgBox(boxMessage & vbLf & "Send mail anyway?", vbYesNoCancel, boxTitle)

  If answer = vbNo Then
    askToCancel = True
  ElseIf answer = vbCancel Then
    askToCancel = True
  Else
    askToCancel = False
  End If

End Function

' Optional: Checks if an mail-attachment exists.
' Checks if two recipients exist. If case of two recipient it checks the
' correctness of the second address.

' Parameter
' 1. String - Expected second address.
' 2. Boolean - Checking for attachment or not.

' Return
' Boolean - Mail in correct state or not.

Function checkStateOfMail(expectedSecond As String, checkAttachment As Boolean) As Boolean
  Dim olObj As Object
  Dim attachmentCount As Variant
  Dim secondRecipient As String

  On Error GoTo errorOccured

  Set olObj = Application.ActiveInspector.CurrentItem

  If checkAttachment = True Then
    ' Get the count of mail attachments.
    attachmentCount = olObj.Attachments.count

    If attachmentCount = 0 Then

      If askToCancel("E-Mail Attachment doesn't exist.", "Caution - Attachment") = True Then
        checkStateOfMail = False
        Exit Function
      End If

    End If
  End If
  ' Two recipients are expected.
  If olObj.Recipients.count < 2 Then

    If askToCancel("Second recipient not available.", "Forgot 2nd recipient?") = True Then
      checkStateOfMail = False
      Exit Function
    End If

  Else
    ' Two recipients are available. But the second address could be wrong.
    secondRecipient = olObj.Recipients.Item(2).Address

    If InStr(1, secondRecipient, expectedSecond, vbTextCompare) = 0 Then

      If askToCancel("Second recipient isn't correct.", "Caution!") = True Then
        checkStateOfMail = False
        Exit Function
      End If

    End If

  End If

  checkStateOfMail = True
  Exit Function

errorOccured:
    MsgBox "Runtime error occured in sub procedure.", vbCritical, "Runtime error!"
    Exit Function

End Function


texts:
I created a templated Hash Map class in C++, which supports most of the basic C++ types (e.g. int, float, char...). I would like some feedback regarding my implementation and what is bad and can be improved.

#ifndef _LIB_HASHMAP
#define _LIB_HASHMAP
#include <exception>
#include <string>

namespace lib{

    namespace details{

        unsigned int generate_hash(const int& key, const size_t& hash_map_size){
            return key%hash_map_size;
        }

        unsigned int generate_hash(const std::string& key, const size_t& hash_map_size){
            return key.size()%hash_map_size;
        }

        unsigned int generate_hash(const char* key, const size_t& hash_map_size){
            size_t position = 0;
            for (size_t i=0; key[i]!='\0'; i++){
                position += key[i];
            }
            return position%hash_map_size;
        }

    }

    template <typename T, typename U>
    class hash_map{

    private:
        struct hash_entry{
            T key;
            U value;
            hash_entry(){}
            hash_entry(const T& _key, const U& _value)
                : key(_key), value(_value){}
        };
        hash_entry* hash_entries;
        unsigned int* filled_positions;
        unsigned int hash_map_size;
        unsigned int num_entries;

    public:
        typedef const hash_entry* const_iterator;
        typedef hash_entry* iterator;
        explicit hash_map(unsigned int);
        ~hash_map();
        iterator begin();
        iterator end();
        const_iterator cbegin();
        const_iterator cend();
        unsigned int size();
        void add(const T&, const U&);
        U& operator[](const T&);
    };

    template <typename T, typename U>
    hash_map<T,U>::hash_map(unsigned int _size):
        hash_entries(new hash_entry[_size]),
        filled_positions(new unsigned int[_size]()),
        hash_map_size(_size),
        num_entries(0){
    }

    template <typename T, typename U>
    hash_map<T,U>::~hash_map(){
        delete[] filled_positions;
        delete[] hash_entries;
    }

    template <typename T, typename U>
    typename hash_map<T,U>::const_iterator hash_map<T,U>::cbegin(){
        return hash_entries;
    }

    template <typename T, typename U>
    typename hash_map<T,U>::const_iterator hash_map<T,U>::cend(){
        return hash_entries+hash_map_size;
    }

    template <typename T, typename U>
    typename hash_map<T,U>::iterator hash_map<T,U>::begin(){
        return hash_entries;
    }

    template <typename T, typename U>
    typename hash_map<T,U>::iterator hash_map<T,U>::end(){
        return hash_entries+hash_map_size;
    }

    template <typename T, typename U>
    unsigned int hash_map<T,U>::size(){
        return hash_map_size;
    }

    template <typename T, typename U>
    void hash_map<T,U>::add(const T& _key, const U& _value){
        if (num_entries >= hash_map_size){
            throw std::out_of_range("std::out_of_range : hash_map full");
        }
        unsigned int position = details::generate_hash(_key,hash_map_size);
        while (filled_positions[position]){
            position = (position+1)%hash_map_size;
        }
        filled_positions[position] = 1;
        hash_entries[position] = hash_entry(_key,_value);
        num_entries += 1;
    }

    template <typename T, typename U>
    U& hash_map<T,U>::operator[](const T& _key){
        unsigned int position = details::generate_hash(_key,hash_map_size);
        unsigned int count = 0;
        while (hash_entries[position].key != _key){
            if (count > hash_map_size){
                throw std::invalid_argument("std::invalid_argument : key not in hash_map");
            }
            position = (position+1)%hash_map_size;
            count += 1;
        }
        return hash_entries[position].value;
    }

}

#endif // _LIB_HASHMAP


texts: Find the duplicate in a sorted array In less-than O(n)

texts:
Assumptions:

The array is sorted.
There is only one duplicate.
The array is only populated with numbers [0, n], where n is the length of the array.

Example array: [0,1,2,3,4,5,6,7,8,8,9]

Here is my implementation:

public static int DuplicateBinaryFind(int[] arr, int left, int right)
{
   int dup =0;

   if(left==right)
   {
      dup = left;
   }
   else
   {
        int middle = (left+right)/2;
        if(arr[middle]<middle)
        {
          dup = DuplicateBinaryFind(arr,left, middle-1);

        }
        else
        {
           dup = DuplicateBinaryFind(arr, middle+1, right);
        }
   }

   return dup;

}

Is this considered as good solution to the problem as it finds the duplicate in \$O(\log n)\$?


texts:
The reliability polynomial (specifically, the all-terminal reliability polynomial) is, given a value \$0 \le p \le 1\$, outputs the probability that a given graph \$G\$ is connected.

Note: at the link given, the probability is given to an edge being deleted, and not to an edge existing (which is the definition we will use here).

Of course, if the graph is already not connected, then it has probability 0 that it is connected. If the graph has exactly 1 vertex and no edges, it always will be connected (so has reliability polynomial 1).

The usual "brute-force" calculation of the polynomial is by the "Factoring Theorem": for any edge \$e\$ in the graph \$G\$:

$$Rel(G; p) = p*Rel(G*e; p) + (1-p)*Rel(G/e; p)$$

where \$G*e\$ is the resulting graph of contracting the edge \$e\$, and \$G/e\$ is that of deleting the edge \$e\$.

I implemented this calculation using Sympy (for multiplying polynomials) and networkx (for using graphs). I would like to get some feedback on the structure of the code as well as readability.

Note: I actually do need MultiGraph here because contracting an edge will introduce parallel edges, which do make a difference in the calculation.

import networkx as nx
import random
import sympy

p = sympy.symbols('p')

def relpoly(G):
    H = nx.MultiGraph(G)
    rel = _recursive(H)
    return sympy.simplify(rel)

def _recursive(G):
    # If the graph is not connected, then it has a rel poly of 0
    if not nx.is_connected(G):
        return sympy.Poly(0, p)

    # if # edges > 0, then we perform the two subcases of the
    #   Factoring theorem.
    if len(G.edges()) > 0:
        e = random.choice(G.edges())
        contracted = nx.contracted_edge(G, e, self_loops=False)
        G.remove_edge(*e)
        rec_deleted = _recursive(G)
        rec_contracted = _recursive(contracted)
        s = sympy.Poly(p)*(rec_contracted) + sympy.Poly(1-p)*(rec_deleted)
        return s

    # Otherwise, we only have 0 edges and 1 vertex, which is connected,
    #   so we return 1.
    return sympy.Poly(1, p)

print(relpoly(nx.petersen_graph()))


texts: Find the smallest positive number missing from an unsorted array

texts:
this is the original question
https://www.geeksforgeeks.org/find-the-smallest-positive-number-missing-from-an-unsorted-array/
You are given an unsorted array with both positive and negative elements. You have to find the smallest positive number missing from the array in O(n) time using constant extra space. You can modify the original array.

Input: {2, 3, 7, 6, 8, -1, -10, 15}   Output: 1
Input:  { 2, 3, -7, 6, 8, 1, -10, 15 }  Output: 4
Input: {1, 1, 0, -1, -2}                Output: 2

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

namespace ArrayQuestions
{

[TestClass]
public class FindTheSmallestNonnegativeNumberNoyInArray
{
    [TestMethod]
    public void FindTheSmallestNonnegativeNumberNoyInArrayTest()
    {
        int[] array = {2, 3, 7, 6, 8, -1, -10, 15};
        int result = FindSmallestPositiveHash(array);
        int expected = 1;
        Assert.AreEqual(expected, result);
    }

   [TestMethod]
    public void FindTheSmallestNonnegativeNumberNoyInArrayTest2()
    {
        int[] array = { 2, 3, -7, 6, 8, 1, -10, 15 };
        int result = FindSmallestPositiveHash(array);
        int expected = 4;
        Assert.AreEqual(expected, result);
    }
    private int FindSmallestPositiveHash(int[] array)
    {
        HashSet<int> set = new HashSet<int>();
        int maxPositive = 0;
        for (int i = 0; i < array.Length; i++)
        {
            if (!set.Contains(array[i]))
            {
                maxPositive = Math.Max(maxPositive, array[i]);
                set.Add(array[i]);
            }
        }
        for (int i = 1; i < maxPositive; i++)
        {
            if (!set.Contains(i))
            {
                return i;
            }
        }
        return maxPositive + 1;
    }
}
}

I know there is a better solution, I tried to implement the hash based solution please comment or runtime and performance.
Thanks


texts: Scraping news articles from various pages

texts:
Scraping news articles from various web page is the main goal of this code. For starting all spiders(web crawlers) at the same time, I try to implement the facade design pattern. It works but I feel the constructor of SpiderFacade class can be improved. Is there better way to do it or better design pattern to do it ?

Abstract Spider

public abstract class NewsSpider {
    public void crawl() {
    }
}

Custom Spider1

public class NYTimesSpider extends NewsSpider {

   private final NewsService newsService;

   public NYTimesSpider(NewsService newsService) {
       this.newsService = newsService;
   }

   @Override
   public void crawl() {
       // crawl logic
   }
}

Custom Spider2

public class BbcSpider extends NewsSpider {

   private final NewsService newsService;

   public BbcSpider(NewsService newsService) {
       this.newsService = newsService;
   }

   @Override
   public void crawl() {
       // crawl logic
   }
}

Facade Class

public class SpiderFacade {

    private final List<NewsSpider> spiderList;

    public SpiderFacade(NewsService newsService) {
        spiderList = Arrays.asList(
                new NYTimesSpider(newsService),  // the wrong part in my opinion
                new BbcSpider(newsService)
        );
    }

    public void startCollectingNews() {
        spiderList.forEach(NewsSpider::crawl);
    }
}

Starting Spiders

 SpiderFacade spiderFacade = new SpiderFacade(newsService);
 spiderFacade.startCollectingNews();


texts: One object to handle all my database manipulation needs

texts:
I have created an object to handle all my database manipulation needs. Here is my object constructor and one of its functions:

class dataMonster{
    var $sn = '';
    var $un = '';
    var $pw = '';
    var $dn = "";

    function update($table, $records, $set_value, $compare, $compare_value){

        $table=preg_replace('/[^0-9a-zA-Z_]/', '', $table);
        $records=preg_replace('/[^0-9a-zA-Z_,]/', '', $records);
        $compare=preg_replace('/[^0-9a-zA-Z_,]/', '', $compare);

        $dsn = "mysql:host=".$this->sn.";dbname=".$this->dn.";charset=utf8";
        $opt = array(
            PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
            PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
        );
        ini_set('display_errors', 'On');

        $return_check = $pdo = new PDO($dsn, $this->un, $this->pw, $opt);
        if($return_check === false){
            echo 'PDO failed';
        }
        $return_check = $stm = $pdo->prepare("UPDATE $table SET $records = ? WHERE $compare = ?");
        if($return_check === false){
            echo 'prepare failed';
        }
        $return_check = $stm->execute(array($set_value, $compare_value));
        if($return_check === false){
            echo 'execute failed';
        }
    }
}

It is then instantiated and called as such:

$dm = new dataMonster();
$dm->sn = 'localhost';
$dm->un = 'xtremeco_admin';
$dm->pw = 'fMMA1EJJuz8I';
$dm->dn = 'xtremeco_users';

$dm->update('users', 'sessionid', $session_id, 'username', $user_name);

The class constructor is held in a separate file and imported into the project I'm working on. I know the standard is to code in a whitelist of acceptable tables and columns to prevent injection but I think I have successfully safe guarded against it. No user input makes it into the statement itself. My goal is to create a file that can just be imported and run with no editing. But in doing so, am I leaving myself open to attack?


texts: Swapping two integer numbers with no temporary variable

texts:
I tried to swap 2 integer numbers without using an additional variable as a traditional swap.

Is it legal in C++? My VC compiler doesn't complain nor gives any warning about it. If so, how can I improve this script?

#include <iostream>

int main()
{
    int a = 20;
    int b = 66;

    // before swapping
    std::cout << a  << ' ' << b  << '\n';

    // swap
    a ^= b ^= a ^= b;

    // after swapping
    std::cout << a << ' ' << b << '\n';
}

For this code:

int a = 20;
int b = 66;
a ^= b ^= a ^= b;

Assembler output for VC++ 2013:

_b$ = -20                     ; size = 4
_a$ = -8                      ; size = 4

mov   DWORD PTR _a$[ebp], 20          ; 00000014H
mov   DWORD PTR _b$[ebp], 66          ; 00000042H

mov   eax, DWORD PTR _a$[ebp]
xor   eax, DWORD PTR _b$[ebp]
mov   DWORD PTR _a$[ebp], eax

mov   ecx, DWORD PTR _b$[ebp]
xor   ecx, DWORD PTR _a$[ebp]
mov   DWORD PTR _b$[ebp], ecx

mov   edx, DWORD PTR _a$[ebp]
xor   edx, DWORD PTR _b$[ebp]
mov   DWORD PTR _a$[ebp], edx

For this code:

int a = 20;
int b = 66;

int t = a;
a = b;
b = t;

Assembler output for VC++ 2013:

_t$ = -32                     ; size = 4
_b$ = -20                     ; size = 4
_a$ = -8                      ; size = 4

mov   DWORD PTR _a$[ebp], 20          ; 00000014H
mov   DWORD PTR _b$[ebp], 66          ; 00000042H

mov   eax, DWORD PTR _a$[ebp]
mov   DWORD PTR _t$[ebp], eax

mov   eax, DWORD PTR _b$[ebp]
mov   DWORD PTR _a$[ebp], eax

mov   eax, DWORD PTR _t$[ebp]
mov   DWORD PTR _b$[ebp], eax


texts:
This essentially reads a specially-structured file from the scanner and then parses random phrases and prints them:

{
<start>
<greeting> <object>
}

{
<greeting>
hello
bonjour
aloha
}

{
<object>
world
universe
multiverse
}

Possible random phrases could be: "hello world", "bonjour universe", etc...

Does anyone have some ideas as to how I might decrease the runtime? I heard you could run your code in parallel using multiple threads but was both unsure exactly how to do this and whether it would help at all? The slightest increase in runtime would be beneficial (having a little competition to see who can do it the fastest).

It is not considered cheating so long as I do the majority of the programming, so please just point me in the right direction and provide suggestions.

package comprehensive;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Random;
import java.util.Scanner;

/**
 * Generates random phrases by reading the specified grammar file
 * and outputting the number of phrases specified by the user.
 * @author Jun Tang and John Newsome
 *
 */
public class RandomPhraseGenerator {

    public static HashMap<String,ArrayList<String>> map;

    public static void main(String[] args) throws FileNotFoundException{
        Scanner k = new Scanner(new File(args[0]));
        int numPhrases = Integer.parseInt(args[1]);
        addKeys(k);
        while(numPhrases > 0){
            parseStrings();
            numPhrases--;
        }
    }

    /**
     * Assimilates all of the keys and their associated values into map (a public static hashmap).
     * @param scan The scanner that is reading from the specified file.
     */
    public static void addKeys(Scanner scan){
        map = new HashMap<String, ArrayList<String>>();
        while(scan.hasNextLine()){
            if(scan.nextLine().equals("{")){
                String key = scan.nextLine();
                map.put(key, new ArrayList<String>());
                String next = scan.nextLine();
                while(!next.equals("}")){
                    map.get(key).add(next);
                    next = scan.nextLine();
                }
            }
        }
    }

    /**
     * Parses random String phrases from map and prints them.
     * Must already have assimilated keys and values prior by using the addKeys() method.
     */
    public static void parseStrings(){
        Random random = new Random();
        StringBuilder strBuf = new StringBuilder((map.get("<start>").get(0)));
        int firstInstance  = strBuf.indexOf("<", 0);
        int secondInstance = strBuf.indexOf(">", firstInstance);
        while(firstInstance >= 0 && secondInstance >= 0){
            String nonTerminal = strBuf.substring(firstInstance, secondInstance+1);
            strBuf.replace(firstInstance, secondInstance+1, (map.get(nonTerminal).get(random.nextInt(map.get(nonTerminal).size()))));
            firstInstance  = strBuf.indexOf("<", firstInstance);
            secondInstance = strBuf.indexOf(">", firstInstance);
        }
        System.out.println(strBuf);
    }
}


texts:
Ask user to input 10 integers and then print the largest odd number that was entered. If no odd number was entered, print a message to that effect.

The above exercise is from chapter 2 of Computation and Programming Using Python by John Guttag. So far, the book has covered variable assignment, print function, conditional branching, and loops. The book is about problem solving and uses Python only as a tool to solve problems and it is meant to be used with Python 2.x. I need to know if my solution to the exercise can be "straightened up" in any way.

numbers_entered = []

for _ in range(10):
    number = raw_input('Enter an integer: ')
    if number.isdigit():
        number = int(number)
        numbers_entered.append(number)
    else:
        print 'That was not an integer!'

odd_numbers = []

for item in numbers_entered:
    if item % 2 != 0:
        odd_numbers.append(item)

if odd_numbers:
    print 'The largest odd number entered was %s.' % str(max(
            odd_numbers))
else:
    print 'No odd number was entered.'


texts: Making VBA generated dynamic SQL statements safe against injection

texts:
I need to use SQL extensively in VBA macros that I write. Since the DB is from our enterprise application, I use vendor's library for this.

I generate dynamic queries, sometimes with many JOINs and UNIONs, and the queries can be quite complex.

The procedure that I coded screams "I'm open to SQL injection". The macros using this function are all internal but I need to make it safe anyway.

How can I make the below code only run SELECT statements and safe against injections?

Please note that it is not possible to make views for all possible SELECT statements and use them instead, according to the parameters, one or more DB's need to be queried and UNION'd sometimes.

How can I safely query an arbitrary number of columns with an arbitrary number of constraints from an arbitrary number of tables in an arbitrary number of DBs?

'***************************************************************************'
'Evaluates and executes the passed query and returns the results            '
'Parameters:                                                                '
'   Query: The main query body with optional placeholders like #0 starting  '
'               with 0                                                      '
'   Args : Optional arguments to replace placeholders                       '
'Returns:                                                                   '
'   The resulting recordset                                                 '
'***************************************************************************'
Public Function DirectQuery( _
    Query As String, _
    ParamArray Args() As Variant _
) As NetRS
'Declarations **************************************************************'
Dim ReturnRs As NetRS
Dim Params As Variant
'***************************************************************************'
    On Error GoTo ErrorHandler
    'This code shouldn't be used
    MsgBox "This code is dangerous. Don't copy-paste and use it."
    Exit Function
    Params = Args
    Set ReturnRs = 3rdPartyObject.NewRecordset(DBConnection)
    ReturnRs.Open EvaluateQuery(Query, Params)
    Set DirectQuery = ReturnRs
    Set ReturnRs = Nothing
Exit Function
ErrorHandler:
End Function
'***************************************************************************'

'***************************************************************************'
'Evaluates the arguments in a query string and returns the formed query     '
'Parameters:                                                                '
'   Query: The main query body with optional placeholders like #0 starting  '
'               with 0                                                      '
'   Args : Optional arguments to replace placeholders                       '
'Returns:                                                                   '
'   The formed query string                                                 '
'***************************************************************************'
Public Function EvaluateQuery( _
    Query As String, _
    ParamArray Args() As Variant _
) As String
'Declarations **************************************************************'
Dim i As Integer
Dim Params As Variant
'***************************************************************************'
    On Error GoTo ErrorHandler
    Params = Args
    EvaluateQuery = Query
    For i = LBound(Params(0)) To UBound(Params(0))
        EvaluateQuery = Replace(EvaluateQuery, "#" & i, Params(0)(i))
    Next i
Exit Function
ErrorHandler:
    EvaluateQuery = ""
End Function
'***************************************************************************'


texts:
I developed this feature that I think can be improved quite a bit. The result is the desired one, but it took me many lines of code. Any idea to optimize it?
import json
import urllib.request

dni = 71179047

def get_cuit(dni):
    request = urllib.request.Request('https://www.cuitonline.com/search.php?q=' + str(dni))
    response = urllib.request.urlopen(request)
    data_content = response.read()
    html = data_content.decode('ISO-8859-1')
    cuit = re.findall(r"\(?\b[0-9]{2}\)?-?[0-9]{7,8}-[0-9]{1}\b", html)[0]
    result = re.sub('[^0-9]','', cuit)
    return result

get_cuit(dni)


texts: How to improve this session cache to search faster

texts:
I have this code which will store user session credentials:

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

public class SessionCache
{

    /**
     * Default Constructor
     */
    public SessionCache()
    {
    }

    /**
     * Map which which will store Connections Objects by connection_id
     */
    private static final Map<String, ActiveConnections> cache = new LinkedHashMap<>();

    /**
     * Object which will store connection credentials
     */
    public class ActiveConnections
    {

        private int one;
        private int two;
        private int three;

        public ActiveConnections(int one, int two, int three)
        {
            this.one = one;
            this.two = two;
            this.three = three;
        }

        public int getOne()
        {
            return one;
        }

        public void setOne(int one)
        {
            this.one = one;
        }

        public int getTwo()
        {
            return two;
        }

        public void setTwo(int two)
        {
            this.two = two;
        }

        public int getThree()
        {
            return three;
        }

        public void setThree(int three)
        {
            this.three = three;
        }

    }

    /**
     * Get Connection credentials by connection_id
     *
     * @param connection_id
     * @return
     */
    public Object getCache(String connection_id)
    {
        return cache.get(connection_id);
    }

    /**
     * Insert new Connection Object into the cache
     *
     * @param connection_id
     * @param one
     * @param two
     * @param three
     */
    public void addCache(String connection_id, int one, int two, int three)
    {
        /**
         * @ You may want to check if entry already exists for connection depends on logic in your application.
         * @ Otherwise this will replace any previous entry for connection_id
         */
        if (!cache.containsKey(connection_id))
        {
            cache.put(connection_id, new ActiveConnections(one, two, three));
        }

    }

    /**
     * Remove Connection from the cache based on connection_id
     *
     * @param connection_id
     */
    public void removeCache(String connection_id)
    {
        cache.remove(connection_id);
    }

    /**
     * Get the number of all connections
     *
     * @return
     */
    public int countCacheSize()
    {
        return cache.size();
    }

    /**
     * Clear all cache
     */
    public void flushCache()
    {
        cache.clear();
    }

    public List<String> sendAllKeys()
    {
        List<String> list = new ArrayList<>(cache.keySet());
        return list;
    }

    public Object sendKeyValue(int key)
    {
        Object mapKey = cache.keySet().toArray()[key];
        return mapKey;
    }

}

Can you help me to improve this code?
I would like to make a while cycle which searches for a value into the Map every 5 seconds for example expired session. Could you please help me to improve the code and make it lightweight as much as possible.


texts:
From this hackerrank:

  Problem Statement

  The Head Librarian at a library wants you to make a program that
  calculates the fine for returning the book after the return date. You
  are given the actual and the expected return dates. Calculate the fine
  as follows:

  If the book is returned on or before the expected return date, no fine
  will be charged, in other words fine is 0.
  If the book is returned in
  the same calendar month as the expected return date, Fine = 15 Hackos
  × Number of late days
  If the book is not returned in the same calendar
  month but in the same calendar year as the expected return date, Fine
  = 500 Hackos × Number of late months
  If the book is not returned in the same calendar year, the fine is fixed at 10000 Hackos. Input

  You are given the actual and the expected return dates in D M Y format in
  two separate lines. The first line contains the D M Y values for the
  actual return date and the next line contains the D M Y values for the
  expected return date.

My development philosophy was to TDD this. First write code that reads the date correctly, then start implementing the test cases from the problem statement.

I did not put anything in a separate class.

My code passed all their test cases but looks ugly as heck. Any suggestions for improvement would be appreciated!

import datetime

def testFine(dueDate, returnDate, actualFine):
    fine = getFine(dueDate, returnDate)
    if (fine != actualFine):
        print( "Test FAILED for duedate %s and returnDate %s with fine: %d but expected:%d." %( dueDate, returnDate, fine, actualFine) )

    else:
       print( "Test passed for duedate %s and returnDate %s with fine: %d." % ( dueDate, returnDate, fine) )

def tests():

    #If the book is not returned in the same calendar year, the fine is fixed at 10000 Hackos.
    testFine(datetime.date(2015,5,5), datetime.date(2016,5,6),10000)

    #If the book is returned on or before the expected return date, no fine will be charged, in other words fine is 0.
    testFine(datetime.date(2015,5,5), datetime.date(2015,5,5),0)
    testFine(datetime.date(2015,5,5), datetime.date(2015,5,3),0)
    #If the book is returned in the same calendar month as the expected return date, Fine = 15 Hackos × Number of late days

    testFine(datetime.date(2015,5,5), datetime.date(2015,5,6),15)
    testFine(datetime.date(2015,2,5), datetime.date(2015,2,10),75)

    #If the book is not returned in the same calendar month but in the same calendar year as the expected return date, Fine = 500 Hackos × Number of late months

    testFine(datetime.date(2015,2,5), datetime.date(2015,3,1),500)
    testFine(datetime.date(2015,2,5), datetime.date(2015,6,1),2000)

def getFine(dueDate, returnDate):

    if (returnDate.year > dueDate.year):
        return 10000

    if (returnDate.year == dueDate.year and returnDate.month == dueDate.month and returnDate.day > dueDate.day):
        return 15*(returnDate.day-dueDate.day)

    if (returnDate.year == dueDate.year and returnDate.month > dueDate.month):
        return 500*(returnDate.month-dueDate.month)

    return 0

def getDateFromCin():
    s = input()
    nums = [int(n) for n in s.split(" ")]
    return datetime.date(nums[2], nums[1],nums[0])

def testFunc():
    testline = input()

    print (testline + "test")
    return

def cinMain():
    returnDate = getDateFromCin()
    dueDate = getDateFromCin()
    fine = getFine(dueDate, returnDate)
    print (fine)

def main():
    tests()

cinMain()


texts: Select the correct input when using input group after pressing a button

texts:
Introduction: I'm creating a form using bootstrap and I have different input groups with the same structure and functionality.

All of them have a '-' button on the left and a '+' button on the right of the input field and, when one of them is pressed, the input value has to change.

Problem: As the buttons are inside a div with class="input-group-btn" and they are not siblings of the input field, I don't know which is the best way to select it.

I have managed to make it work but I'm not sure if it's the best way to do it.

JavaScript and HTML

$(".increase").click(function() {
  var amount = parseInt($(this).parents('.input-group').children('input').val());
  if (amount < 20) {
    $(this).parents('.input-group').children('input').val(amount + 1);
  }
});

$(".decrease").click(function() {
  var amount = parseInt($(this).parents('.input-group').children('input').val());
  if (amount > 0) {
    $(this).parents('.input-group').children('input').val(amount - 1);
  }
});
<form class="form-inline">

        <button type="button" class="btn btn-default decrease">
        </button>

      <input type="text" class="form-control" id="capacity" value="0" disabled="">

        <button type="button" class="btn btn-default increase">
        </button>

        <button type="button" class="btn btn-default decrease">
        </button>

      <input type="text" class="form-control" id="rooms" value="0" disabled="">

        <button type="button" class="btn btn-default increase">
        </button>

</form>

Bootply: http://www.bootply.com/EA5a48SCdg


texts: Better way to repeatedly use istringstream in "counting minutes" challenge

texts:
I was doing this easy challenge "Counting Minutes I" from Coderbyte.com where you just calculate the number of minutes between two given times.

The second time is always after the first, although it may look to be before but mean it's during the next day.

The format of their test cases is "hour1:minute1-hour2:minute2" such as "12:30am-12:00pm" where the difference would be 11.5 hours = 1425 minutes.

In converting different parts of the string containing the times to ints I've been using istringstream but creating a new one each time I call the function to set the ints. It seems like this is a sloppy way of accomplishing this, is there a better way like creating one istringstream in my main CountingMinutesI function and passing that as an argument to getNum then clearing it out after setting each particular int? Or is this also a bad idea?

#include <iostream>
#include <sstream>
using namespace std;

void getNum (string timeString, int& pos, int& result) {
  string temp;
  while (isdigit(timeString[pos])) {
    temp += timeString[pos];
    pos++;
  }
  istringstream iss (temp);
  iss >> result;
}

void to24HourTime(string timeString, int& pos, int& hourToConvert) {
  if (timeString[pos] == 'p' && hourToConvert != 12)
    hourToConvert += 12;
  if (timeString[pos] == 'a' && hourToConvert == 12)
    hourToConvert = 0;
}

int CountingMinutesI(string str) {

  int hour1int, hour2int, min1int, min2int, minDifference;
  int stringPos = 0;

  getNum(str, stringPos, hour1int);
  stringPos++;
  getNum(str, stringPos, min1int);

  to24HourTime(str, stringPos, hour1int);

  stringPos += 3;

  getNum(str, stringPos, hour2int);
  stringPos++;
  getNum(str, stringPos, min2int);

  to24HourTime(str, stringPos, hour2int);

  if (hour2int < hour1int) //second time is the during the next day
    hour2int += 24;
  if (hour1int == hour2int && min1int > min2int) //time difference would look negative, but is really between 23 and 24 hours
    hour2int += 24;
  if (min2int < min1int) { //simplify subtracting minutes to add to total difference
    min2int += 60;
    hour2int--;
  }

  minDifference = (hour2int - hour1int) * 60 + (min2int - min1int);

  return minDifference;

}

int main() {

  // keep this function call here
  cout << CountingMinutesI(gets(stdin));
  return 0;

}


texts: Project Euler #10 -- Summation of primes takes forever

texts:
I have resolved the Problem presented in Project Euler #10:

The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17.
Find the sum of all the primes below two million.

But this code takes too long before producing a result, 12.4195167 minutes to be exact.
What should I do to optimize this code?
public class summationOfPrimes{
public static void main(String args[]){
    long sum=0;
    outerloop:
    for(int i=2;i<2000000;i++){
        for(int j=2;j<=i;j++){
            if(i!=j&&i%j==0){
                continue outerloop;
            }
            else if(j==i){
                sum=sum+i;
            }
        }

    }

    System.out.println(sum);

}

}


texts:
I've tried to create application with MVC N-layer pattern. I asked my buddy for a shot review, and he said, "You should separate logic from controller".
But my controller only work as a ViewModel creator. I'm sure I must not create ViewModel from BusinessLayer.  I need to pass data in DTO like I did here. But what about logic that takes data from DTO and puts it in ViewModel with some rules? I completely misunderstand and need assistance.

public class HomeController : Controller
{
    public ActionResult Index()
    {
        var uploadedImages = UploadedImageHandler.GetAllUploadedImages();
        var model = new IndexViewModel(uploadedImages);
        return View(model);
    }

    [HttpPost]
    public void SetDescription(string description, int id)
    {
        UploadedImageHandler.SetDescription(description, id);
    }

    [HttpPost]
    [ValidateAntiForgeryToken]
    public JsonResult UploadImage(HttpPostedFileBase file)
    {
        var result = UploadedImageHandler.UploadFile(file);
        JsonResult json;

        if (result != null)
        {
            var uploadImageViewModel = new UploadedImagesViewModel
            {
                Compression = result.Compression,
                DateTime = result.DateTime.HasValue ? result.DateTime.Value.ToString("f") : null,
                Description = result.Description ?? "",
                ExifVersion = result.ExifVersion,
                ExposureTime = result.ExposureTime,
                GpsLatitude = result.GpsLatitude,
                GpsLongitude = result.GpsLongitude,
                ImagePath = result.ImagePath,
                Manufacturer = result.Manufacturer,
                Model = result.Model,
                UploadedImageId = result.UploadedImageId
            };
            var uploadResult = new UploadResultViewModel
            {
                Preview = new PreviewViewModel {Id = result.UploadedImageId, PreviewPath = result.PreviewPath},
                UploadedImage = uploadImageViewModel
            };
            json = new JsonResult
            {
                Data = uploadResult,
                ContentType = "text/html"
            };
        }
        else
        {
            json = new JsonResult
            {
                ContentType = "text/html"
            };
        }

        return json;
    }
}


texts: Grouping sub-arrays with nonidentical items

texts:
I have a 2D array like

[ [ 'B', 'O', 'C' ],
  [ 'J', 'B', 'F' ],
  [ 'F', 'B', 'D' ],
  [ 'F', 'D', 'W' ],
  [ 'N', 'F', 'X' ],
  [ 'X', 'J', 'F' ],
  [ 'T', 'Y', 'H' ],
  [ 'R', 'Q', 'P' ] ],

And i need to group the sub-arrays such that in the resulting 3D array each group should contain only the sub-arrays with items non identical with each other's items. Besides there shouldn't be any duplicate groups such as listing the same sub-arrays in a different order.

For the given array the result is;

[ [ [ 'B', 'O', 'C' ],
    [ 'F', 'D', 'W' ],
    [ 'T', 'Y', 'H' ],
    [ 'R', 'Q', 'P' ] ],
  [ [ 'J', 'B', 'F' ],
    [ 'T', 'Y', 'H' ],
    [ 'R', 'Q', 'P' ] ],
  [ [ 'F', 'B', 'D' ],
    [ 'T', 'Y', 'H' ],
    [ 'R', 'Q', 'P' ] ],
  [ [ 'N', 'F', 'X' ],
    [ 'T', 'Y', 'H' ],
    [ 'R', 'Q', 'P' ],
    [ 'B', 'O', 'C' ] ],
  [ [ 'X', 'J', 'F' ],
    [ 'T', 'Y', 'H' ],
    [ 'R', 'Q', 'P' ],
    [ 'B', 'O', 'C' ] ] ]

My code works fine but something back in my mind says i am doing some overkill and it can be done better. Any ideas how this job might be done any better?

var arr = [ [ 'B', 'O', 'C' ],
            [ 'J', 'B', 'F' ],
            [ 'F', 'B', 'D' ],
            [ 'F', 'D', 'W' ],
            [ 'N', 'F', 'X' ],
            [ 'X', 'J', 'F' ],
            [ 'T', 'Y', 'H' ],
            [ 'R', 'Q', 'P' ] ],
 result = arr.reduce((s,t,i,a) => t.used ? s
                                         : (s.push(a.map((_,j) => a[(i+j)%a.length])
                                                    .reduce((p,c,k) => k-1 ? p.every(t => t.every(n => c.every(v => n !== v))) ? (c.used = true, p.push(c),p) : p
                                                                           : [p].every(t => t.every(n => c.every(v => n !== v))) ? (c.used = true, [p,c]) : [p])),s),[]);
 console.log(JSON.stringify(result,null,2))

The code is slightly complicated but in the heart of it lies;

.reduce((p,c,k) => k-1 ? p.every(t => t.every(n => c.every(v => n !== v))) ? (c.used = true, p.push(c),p) : p
                                                                           : [p].every(t => t.every(n => c.every(v => n !== v))) ? (c.used = true, [p,c]) : [p]))

which will take

[ [ 'B', 'O', 'C' ],
  [ 'J', 'B', 'F' ],
  [ 'F', 'B', 'D' ],
  [ 'F', 'D', 'W' ],
  [ 'N', 'F', 'X' ],
  [ 'X', 'J', 'F' ],
  [ 'T', 'Y', 'H' ],
  [ 'R', 'Q', 'P' ] ],

and turn it into

[ [ 'B', 'O', 'C' ],
  [ 'F', 'D', 'W' ],
  [ 'T', 'Y', 'H' ],
  [ 'R', 'Q', 'P' ] ]

and will mark all sub arrays as used. Then we will rotate the given array  with a.map((_,j) => a[(i+j)%a.length]), up until an unused sub array is at index 0 position and repeat the same job.


texts: Heartbeat pattern with Websocket in JS - annoyed by global dictionary

texts:
I'm implementing a kind of 'heartbeat pattern' with websocket in JS.
The idea is: the server keeps a dictionary holding a Websocket object for each uuid (an uuid is a client).
const WebSocket = require('ws');
const wss = new WebSocket.Server({ port: 8080 });
const DELAY_TO_DECLARE_DEATH_CLIENT = 15000

let websocketsDictionary = {}
wss.on('connection', function connection(ws) {
        ws.on('message', function incoming(data) {
            data = JSON.parse(data)
            if(data.type == "REGISTER"){
                console.log("Client has registered to path " + data.path)
            }
            else if(data.type == "PUT"){
                console.log("Client says hello to " + data.path)
            }
            else if(data.type == "HEARTBEAT"){
                if(!websocketsDictionary[data.uuid]){
                    console.log("Remembering " + data.uuid)
                    websocketsDictionary[data.uuid] = {
                        ws: ws,
                        lastSeen: new Date().getTime()
                    }
                }
                else{
                    console.log("Already know " + data.uuid)
                    websocketsDictionary[data.uuid].lastSeen = new Date().getTime()
                }
            }

        })
    })

On the side, I'd like to purge each client that hasn't sent a heartbeat in a certain threshold.
function purgeDeadClients(){
    let now =  new Date().getTime
    websocketsDictionary = websocketsDictionary.filter(c => c.lastSeen - now < DELAY_TO_DECLARE_DEATH_CLIENT)
}

What I don't like is that webosocketDictionary is global, and both the callbacks from ws.on and purgeDeadClients are reading/writing in it.
Is there some pattern I could use so that the content of websocketDictionary is shared by both callbacks, without being simply declared as global ?