texts:
I have been learning C++ over the last couple of days. I know a few other programming languages well, and it hasn't been horribly difficult. I would appreciate any comments on my code so that I may improve:

Readability
CPP "style"
Efficiency
Vector vs array--which is better in this case?

Thanks in advance for any help you can give me.

//Bubblesort algorithm
#include <iostream>
#include <cstdlib>
#include <ctime>

#define pass ;

int main()
{
    // int unsorted[] = {1,2,3,4,5,6,7,8,9,10};
    int length;
    int max;
    srand(time(NULL));
    std::cout << "Please input how many numbers you want to sort and the max value on those numbers: " << std::endl;
    std::cin >> length;
    std::cin >> max;
    int unsorted[length];
    int count = -1;
    while(count++<length)
    {
        unsorted[count] = rand()%max;
    }
    //int length = sizeof( unsorted ) / sizeof( int );
    int i = 0;
    int num_changes_per_loop = 1; /* Should be set to zero at the beginning of each loop, but is nonzero here to prevent the loop from being cancelled on the first iteration */
    int general_loop_count = 0;
    while(general_loop_count++<length)
    {
        if(num_changes_per_loop==0) { break; }
        for(i=0;i<length-1;i++)
        {
            int current_value = unsorted[i];
            int adjacent_value = unsorted[i+1];
            if(adjacent_value > current_value) {pass}
            else if(current_value > adjacent_value) {
                std::cout << "These two values need to be switched!" << std::endl;
                int tmp = adjacent_value;
                unsorted[i+1] = current_value;
                unsorted[i] = tmp;
                num_changes_per_loop++;
            }
        }
    }
    std::cout << "Finished!" << std::endl;
    for(i=0;i<length;i++)
    {
        std::cout << unsorted[i] << ", ";
    }
}


texts: Print the number of unique pairs Stored in a HashSet

texts:
I'm trying to solve this fairly straight forward challenge:

  Problem Statement

  In computer science, a set is an abstract data type that can store
  certain values, without any particular order, and no repeated
  values. {1,2,3} is an example of a set, but {1,2,2} is not
  a set. Today you will learn how to use sets in java by solving this
  problem.

  You are given n pairs of strings. Two pairs (a,b) and (c,d) are
  identical if a=b and c=d. That also implies (a,b) is not same as
  (b,a). After taking each pair as input, you need to print number of
  unique pairs you currently have.

  Note: Brute force solution will not earn full points.

This works, but I'm getting a timeout on the last test case (10.000 elements to go through).

import java.io.*;
import java.util.*;

public class Solution {

    public static void main(String[] args) {
        Scanner s = new Scanner(System.in);
        Set<Pair> pairs = new HashSet<>();
        final int N = s.nextInt();

        for(int i = 0; i < N; i++) {
            String first = s.next();
            String second = s.next();

            pairs.add(new Pair(first, second));
            System.out.println(pairs.size());
        }
    }

    public static class Pair {
        String first, second;
        Pair(String first, String second) {
            this.first = first;
            this.second = second;
        }

        @Override public int hashCode() {
            return first.hashCode();
        }

        @Override public boolean equals(Object other) {
            if (other == this) {
                return true;
            }
            if (!(other instanceof Pair)) {
                return false;
            }

            Pair otherPair = (Pair) other;
            return (first.equals(otherPair.first) && second.equals(otherPair.second))
                || (first.equals(otherPair.second) && second.equals(otherPair.first));
        }

    }
}


texts: Advent of Code 2018 day 1 part 2: find the first repeated number after some increases and decreases

texts:
Here is the problem:

Part Two
You notice that the device repeats the same frequency change list over and over. To calibrate the device, you need to find
the first frequency it reaches twice.
For example, using the same list of changes above, the device would
loop as follows:
Current frequency  0, change of +1; resulting frequency  1.
Current frequency  1, change of -2; resulting frequency -1.
Current frequency -1, change of +3; resulting frequency  2.
Current frequency  2, change of +1; resulting frequency  3.
(At this point, the device continues from the start of the list.)
Current frequency  3, change of +1; resulting frequency  4.
Current frequency  4, change of -2; resulting frequency  2, which has already been seen.
In this example, the first frequency reached twice is 2. Note that your device might need to repeat its list of frequency changes many times before a duplicate frequency is found, and that duplicates might be found while in the middle of processing the list.
Here are other examples:
+1, -1 first reaches 0 twice.
+3, +3, +4, -2, -4 first reaches 10 twice.
-6, +3, +8, +5, -6 first reaches 5 twice.
+7, +7, -2, -7, -4 first reaches 14 twice.
What is the first frequency your device reaches twice?

And here is my solution:
module Main where

import           Data.List.Split

parseString :: Integer -> String -> Integer
parseString acc s =
  let num = read $ tail s :: Integer
      operator = head s
  in if operator == '+'
       then acc + num
       else acc - num

findFreq :: Integer -> [Integer] -> [String] -> (Integer, Integer, [Integer])
findFreq curr acc [] = (0, curr, acc)
findFreq curr acc (x:xs) =
  let next = parseString curr x
  in if next `elem` acc
       then (next, 0, [])
       else let f = acc ++ [next]
            in findFreq next f xs

findRepeatingFrequency :: Integer -> [Integer] -> [String] -> Integer
findRepeatingFrequency init nums xs =
  let (found, acc, lst) = findFreq init nums xs
  in if found > 0
       then found
       else findRepeatingFrequency acc lst xs

main :: IO ()
main = do
  file <- readFile "input.txt"
  let input = filter (not . null) $ splitOn "\n" file
  print (findRepeatingFrequency 0 [] input)

This is seriously slow.
Can anyone give me pointes as to how this can be done better?
I'm also keen to know specifically why this is so slow.


texts:
I've written this email program in Python, and I would like to get some feedback on it. (i.e. closing the server twice after the raw input, etc.)

import console
import socket
import smtplib
from getpass import getpass

user = raw_input('What is your name? ').title()
host_name = socket.gethostname()
print '\nThis program is being run by %s on machine name %s' % (user, host_name)

# here we collect the login information for the email
# we also collect the email provider to automatically change the server
email_provider = raw_input('Gmail, AOL, Yahoo! or Comcast? ').title()
email_user = raw_input('Type in your full email username. ') # collect the user name
email_pwd = getpass('Type in your email password. ') # collect the users password

if email_provider in ('Gmail', 'Google'):
    smtpserver = smtplib.SMTP("smtp.gmail.com",587)
if email_provider in ('Aol', 'AOL'):
    smtpserver = smtplib.SMTP("smtp.aol.com",587)
if email_provider in ('Yahoo', 'Yahoo!'):
    smtpserver = smtplib.SMTP("smtp.mail.yahoo.com",587)
if email_provider in ('Comcast'):
    smtpserver = smtplib.SMTP("smtp.comcast.net",587)

smtpserver.ehlo()
smtpserver.starttls()
smtpserver.ehlo
smtpserver.login(email_user, email_pwd)

def main():
    run_again = 'y'
    while run_again == 'y':
        # here we are collecting the Sendto email address
        # we save the input to a variable named sendto
        sendto = raw_input('Email address to send message to: ')
        to = sendto
        CC = sendto

        subj = raw_input('Subject: ')

        header = 'To: ' + to + '\n' + 'From: ' + email_user + '\n' + 'Subject: ' + subj +'\n'
        print '\nMessage Details:'
        print (header)

        assignment = raw_input('Message: ')

        msg = header + assignment + '\n'
        smtpserver.sendmail(email_user, to, msg)
        console.hud_alert('Your message has been sent!', 'success', 2.1)
        run_again = raw_input('Would you like to send another message? y or n')
        if run_again == 'n': smtpserver.close()
        else: smtpserver.close()

main()


texts:
Does this code create sufficiently hard-to-guess session tokens, assuming the server and client are communicating over HTTPS?

Take 2 (thanks to this crypto.SE answer):

(ql:quickload (list :ironclad :cl-base64))

(let ((prng (ironclad:make-prng :fortuna)))
  (defun new-session-token ()
    (cl-base64:usb8-array-to-base64-string
     (ironclad:random-data 32 prng) :uri t)))

As an additional note, the previous version was using the incorrect encryption mode (ecb, instead of ctr which is preferable for this task), and using an insecure method of generating random keys ((sha256 rand)).

If not, what else is required for that goal, and why?

Are there attacks I should be worried about other than guessing and sniffing session tokens?


texts: Print the first, last, and in-between integers of a range

texts:
Given our spec from Code Golf:

  Given two integers, output the two integers, and then the range between them.
  The order of the range must be the same as the input.

  Examples:

 Input        Output
 0,  5   ->   [0, 5, 1, 2, 3, 4]
-3,  8   ->   [-3, 8, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7]
 4,  4   ->   [4, 4]
 4,  5   ->   [4, 5]
 8,  2   ->   [8, 2, 7, 6, 5, 4, 3]
-2, -7   ->   [-2, -7, -3, -4, -5, -6]

Using our test driven approach :)

import org.junit.Test;

import java.util.List;

import static org.assertj.core.api.Assertions.*;

public class CodeGolfTest {

@Test
public void firstLastAndEverythingBetweenExampleOTo5() {

    final List<Integer> integers = CodeGolf.firstLastAndEverythingBetween(0, 5);
    assertThat(integers).isNotNull().hasSize(6).containsExactly(0,5,1,2,3,4);

}

@Test
public void firstLastAndEverythingBetweenExampleMinus3To8() {

    final List<Integer> integers = CodeGolf.firstLastAndEverythingBetween(-3, 8);
    assertThat(integers).isNotNull().hasSize(12).containsExactly(-3,8,-2,-1,0,1,2,3,4,5,6,7);

}

@Test
public void firstLastAndEverythingBetweenExample4To4() {

    final List<Integer> integers = CodeGolf.firstLastAndEverythingBetween(4, 4);
    assertThat(integers).isNotNull().hasSize(2).containsExactly(4,4);

}

@Test
public void firstLastAndEverythingBetweenExample4To5() {

    final List<Integer> integers = CodeGolf.firstLastAndEverythingBetween(4, 5);
    assertThat(integers).isNotNull().hasSize(2).containsExactly(4,5);

}

@Test
public void firstLastAndEverythingBetweenExample8To2() {

    final List<Integer> integers = CodeGolf.firstLastAndEverythingBetween(8, 2);
    assertThat(integers).isNotNull().hasSize(7).containsExactly(8,2,7,6,5,4,3);

}

@Test
public void firstLastAndEverythingBetweenExampleMinus2ToMinus7() {

    final List<Integer> integers = CodeGolf.firstLastAndEverythingBetween(-2, -7);
    assertThat(integers).isNotNull().hasSize(6).containsExactly(-2,-7,-3,-4,-5,-6);

}
}

Can we optimize further this code?

The implementation:

import java.util.ArrayList;
import java.util.List;

public final class CodeGolf {

    private CodeGolf() {
    }

    public static List<Integer> firstLastAndEverythingBetween(final int a, final int b) {

        if (a == b) {
            return addAB(a, b);
        }

        final List<Integer> result = addAB(a, b);
        int initial = getInitial(a, b);

        for (int n = 1; n < Math.abs(b - a); n++) {
            result.add(initial);
            if (b > a) {
                initial++;
            } else {
                initial--;
            }
        }

        return result;
    }

    private static int getInitial(int a, int b) {
        return (b > a) ? (a + 1) : (a - 1);
    }

    private static List<Integer> addAB(int a, int b) {
        final List<Integer> result = new ArrayList<>();
        result.add(a);
        result.add(b);
        return result;
    }
}


texts: Which way is better for converting number to string?

texts:
Sometimes there is need to change an integer to text.
I often use the following way:

"" + myNumber

But there is alternative way:

Integer.toString(myNumber)

Which one is better (performance, readability, safety)?
Or are those equal?


texts: Cleanest way to place values into strings

texts:
I am trying to standardize the way I write code. Which is the best way to place the values into a string, method 1 or 2?

string myCat = "persian";

// Method 1
Console.WriteLine("I have a wild {0} cat that likes to visit", myCat);

// Method 2
Console.WriteLine("I have a wild " + myCat + " cat that likes to visit");

I would like to point out that I am intending this for simple uses, where StringBuilder would be overkill.


texts: Generating numbers that are a product of consecutive primes

texts:
I have implemented a correct but horribly coded solution to Project Euler Problem 293.

  An even positive integer N will be called admissible, if it is a power
  of 2 or its distinct prime factors are consecutive primes. The first
  twelve admissible numbers are 2,4,6,8,12,16,18,24,30,32,36,48.

  If N is admissible, the smallest integer M > 1 such that N+M is prime,
  will be called the pseudo-Fortunate number for N.

  For example, N=630 is admissible since it is even and its distinct
  prime factors are the consecutive primes 2,3,5 and 7. The next prime
  number after 631 is 641; hence, the pseudo-Fortunate number for 630 is
  M=11. It can also be seen that the pseudo-Fortunate number for 16 is
  3.

  Find the sum of all distinct pseudo-Fortunate numbers for admissible
  numbers N less than 109.

I use several nested loops that I wish to make into some nicer functions or such. The following is the first three sections of the code, out of 10 sections required to solve the problem. Each has one more nested loop, and while the time is not an issue I would like to improve this code, but I am not sure how to implement this algorithm in a more concise manner.

What the nth section does is generate all numbers less than 1e9, that contain only the first n prime numbers(and then add numbers relating to the problem to a set).

I have tried for example to have a list of exponents for all primes, and incrementing the outermost nonzero exponent, and then backtracking when the product is larger than 1e9, however I have not been able to do anything successful.

pseudofortunate=set()

pr=generate_primes(24)

num1=1
while num1<1e9/2:
    num1*=pr[0]
    num2=num1
    while num2<1e9/3:
        num2*=pr[1]
        m=num2+3
        while True:
            if is_prime(m):
                pseudofortunate.add(m-num2)
                break
            m+=2

num1=1
while num1<1e9/2:
    num1*=pr[0]
    num2=num1
    while num2<1e9/3:
        num2*=pr[1]
        num3=num2
        while num3<1e9/5:
            num3*=pr[2]
            m=num3+3
            while True:
                if is_prime(m):
                    pseudofortunate.add(m-num3)
                    break
                m+=2

num1=1
while num1<1e9/2:
    num1*=pr[0]
    num2=num1
    while num2<1e9/3:
        num2*=pr[1]
        num3=num2
        while num3<1e9/5:
            num3*=pr[2]
            num4=num3
            while num4<1e9/7:
                num4*=pr[3]
                m=num4+3

                while True:
                    if is_prime(m):
                        pseudofortunate.add(m-num4)
                        break
                    m+=2


texts:
I should implement p0-Pollard with C++14 and a good algorithm. How may I improve my code?

#include <iostream>
#include <assert.h>

template <typename T>
T gcd(T a, T b){
//    printf("step1\n");
    if(a<0) a=-a;
    if(b<0) b=-b;

    T c = 1;// -> decltype(a+b);
    while((a%2 == 0)&&(b%2 == 0)){
//        printf("step2\n");
        a=a>>1;
        b=b>>1;
        c*=2;
    }
//    printf("step3\n");
    while(a!=b){
        if(a%b==0)
            return c*b;
        if(b%a==0)
            return c*a;
        if(a%2 == 0)
            a=a>>1;
        if(a>b)
            a=(a-b);
        if(b>a)
            b=(b-a);
        if(b%2 == 0)
            b=b>>1;
    }
    return c*a;
}

template <typename T>
T fx(T x, T a, T c, T modN){
    auto tmp = (a*x*x + c)%modN;
//    assert(tmp==0); // for tested simple numbers always tmp==0
    return tmp;
}

template <typename T>
T PoPollard(T src){
    T x1=2, x2=2, a=1, c=1, d=1;
    while(d==1){
        x1=fx(x1, a, c, src);
//        std::cout << "x1 is:" << x1 << "\n";
        x2=fx(fx(x2, a, c, src), a, c, src);
//        std::cout << "x2 is:" << x2 << "\n";

        if(x2==0) return 1; // looks like when src is simple number f(f(x))==0

        if(x1==x2){
            x1=2, x2=2;
            a++;
            continue;
        }

        d=gcd(abs(x1)-abs(x2), src);
//        std::cout << "d is:" << d << "\n";
    }
    return src/d;
}

int main()
{
    std::cout << "Hello gcd:" << gcd(256,16) << "\n";
    std::cout << "Testing Po-Pollard:" << PoPollard(4253) << "\n";
//    printf("Hello world! %ld\n", gcd(256,16));
//    printf("Testing Po-Pollard: %ld\n", PoPollard(4253));
    return 0;
}


texts: A character array of arbitary length with 'R', 'B', 'W' is needed to be sorted in that order

texts:
There is a char array of n length.  The array can have elements only from
  any order of R, B, W. You need to sort the array so that order should R,B,W
  (i.e. all R will come first followed by B and then W).

  Constraints: Time
  complexity is O(n) and space complexity should be O(1).

  Assumption:
  You can assume one swap method is given with signature swap(char[]
  arr, int index1, int index2) that swaps number in unit time.  Method
  given to implement: public sort(char[]array);

Here is my implementation of it.  A better solution from anyone is appreciated. Anyone is free to point out any mistakes.

public static void sort(char[] arr){
     int rIndex = 0, wIndex = arr.length -1;
     for (int i = 0 ; i <= wIndex;){
         if ( arr[i] == 'R' ){
             swap(arr, i , rIndex ++ );
             i ++;
         } else if (arr[i] == 'W' ){
             swap(arr, i , wIndex -- );
         }else{
            i ++;
         }
     }
}


texts: Rock, Paper Scissor game (console-based) in Python

texts:
I'm a beginner at coding with Python, and I've only made small projects, and this is one of them. One part of the code is from an answer on Stack Overflow that I made to solve a problem (is the try part) and all the other code is mine.

import random,os,time
score = {'human':0,'robot':0}
def game(): #Basic Game code.
    time.sleep(1)
    os.system('clear')
    print('IA: ' + str(score['robot']) + ' Human: ' + str(score['human']))
    print('1.Rock 2.Scissors 3.Paper')
    while True:
        try:
            choice = int(input("Input your choice:\n"))
            if choice < 1 or choice > 3: #Valid number but outside range, don't let through
                raise ValueError
            else: #Valid number within range, quit loop and the variable selection contains the input.
                break
        except ValueError: #Invalid input
            print("Enter a number from 1 to 3.")
    rchoice = random.randint(1,3)
    time.sleep(1)
    if rchoice == 1:
        print('IA choice is Rock.')
    elif rchoice == 2:
        print('IA choice is Scissors.')
    elif rchoice == 3:
        print('IA choice is Paper.')

    if (rchoice==1 and choice==2)or(rchoice==2 and choice==3)or(rchoice==3 and choice==1):
        print('IA wins!\n')
        score['robot'] += 1
        time.sleep(0.5)
    elif (rchoice == choice):
        print("Draw, let's repeat")
        time.sleep(0.5)
        game()
    else:
        print('You win!\n')
        time.sleep(0.5)
        score['human'] += 1

def startgame(): #The introduction of the game.
    os.system('clear')
    print('Rock-Paper-Scissors v.1')
    print('Developed by P.R.B.\n')
    ngames = int(input('How many games do you want to play?\n'))
    time.sleep(1)
    i = 0
    while i != ngames:
        game()
        i += 1
    print('Final Score:')
    print('IA: ' + str(score['robot']) + ' Human: ' + str(score['human']))
    if score['human'] > score['robot']:
        print('You win the game!\n')
    else:
        print('Game Over')
        print('IA wins the game!\n')

startgame()


texts: Logging into WebAPI 2 site from c# desktop application

texts:
I'm trying to login into a webapi2 site from a desktop application.  After a lot of googling, I cobbled together a working prototype. Since we are talking about security I wanted to do a peer review. I'm just starting with security design and I'm not exactly sure about my design.

The WebAPI site that is targeted is a wepapi 2 standard template out of visual studio.

I'm mainly looking for security issuesut general issues are also greatly appreciated.

One issue I'm aware of is that SSL should be added and with that ssl validation. I haven't implemented it yet.

static internal async Task<string> GetWebAPIReguest(string siteUrl, string APIController, string userName, string Password)
{
    TokenResponseModel Token = await GetBearerToken(siteUrl, userName, Password);

    HttpClient client = new HttpClient();
    client.BaseAddress = new Uri(siteUrl);
    client.DefaultRequestHeaders.Accept.Clear();
    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
    client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", Token.AccessToken);

    return await client.GetStringAsync(APIController);
}

static internal async Task<TokenResponseModel> GetBearerToken(string siteUrl, string Username, string Password)
{
    HttpClient client = new HttpClient();
    client.BaseAddress = new Uri(siteUrl);
    client.DefaultRequestHeaders.Accept.Clear();

    HttpContent requestContent = new StringContent("grant_type=password&username=" + Username + "&password=" + Password, Encoding.UTF8, "application/x-www-form-urlencoded");

    HttpResponseMessage responseMessage = await client.PostAsync("Token", requestContent);

    if (responseMessage.IsSuccessStatusCode)
    {
        string jsonMessage;
        using (Stream responseStream = await responseMessage.Content.ReadAsStreamAsync())
        {
            jsonMessage = new StreamReader(responseStream).ReadToEnd();
        }

        TokenResponseModel tokenResponse = (TokenResponseModel)JsonConvert.DeserializeObject(jsonMessage, typeof(TokenResponseModel));

        return tokenResponse;
    }
    else
    {
        return null;
    }
}

class TokenResponseModel
{
    [JsonProperty("access_token")]
    public string AccessToken { get; set; }

    [JsonProperty("token_type")]
    public string TokenType { get; set; }

    [JsonProperty("expires_in")]
    public int ExpiresIn { get; set; }

    [JsonProperty("userName")]
    public string Username { get; set; }

    [JsonProperty(".issued")]
    public string IssuedAt { get; set; }

    [JsonProperty(".expires")]
    public string ExpiresAt { get; set; }
}


texts: Practicing recursion with getElementsByClassName

texts:
I'm trying to get a good grasp on recursion by implementing document.getElementsByClassName. I've made something that works but I'd like to know if there is some blatant refactoring that should be done or perhaps some not-so-edge cases that might break it.

var getElementsByClassName = function(className){
  var result = [];
  function diveIn(motherNode, result, className){
    var maNodes = motherNode.childNodes
    for (var i = 0; i < maNodes.length; i++){
        var classes = maNodes[i].classList || [];
        classes.forEach(function(classy){
            if (classy === className){
                result.push(maNodes[i]);
            }
        })
        if (maNodes[i].childNodes[0]){
            diveIn(maNodes[i], result, className);
        }
    }
  }
  diveIn(document, result, className);
  return result;
};


texts:
I have a Document Name Table in my SQL database and Files in the Content folder.
I have two lists: ListOfFileNamesSavedInTheDB and ListOfFileNamesInTheFolder.

Basically, I am getting all file names saved in the Database and checking if it exists in the Folder, and if not, delete the file name from the database.

 var clientDocList = documentRepository.Documents.Where(c => c.ClientID == clientID).ToList();

 if (Directory.Exists(directoryPath))
            {
                string[] fileList = Directory.GetFiles(directoryPath).Select(Path.GetFileName).ToArray();
                bool fileNotExist = false;
                foreach (var file in fileList)
                {
                    foreach(var clientDoc in clientDocList)
                    {
                        if (clientDoc.DocFileName.Trim().ToUpper()==file.ToUpper().Trim())
                        {
                            fileNotExist = false;
                            break;
                        }
                    }

                    if (fileNotExist)
                    {
                        //Delete file name from Database
                    }
                }
            }

The code I have written works fine, this inquiry being purely for educational purposes. I want to know how others would do this better and cleaner. I especially hate the way I use two for loops to get data. There has to be a more efficient way.


texts: Visualization of bubble sort in progress

texts:
I've written a program showing the process of bubble sort arithmetic in C.  I need some suggestions on improving it.

#include <stdio.h>
#include <Windows.h>
#include <stdlib.h>
#include <time.h>
#define SIZE 20
#define WIDE (SIZE * 2)

void RepaintScreen(int *pData, int count, int p1, int p2)
{
    system("cls");
    char b[(WIDE + 1) * (SIZE)];
    b[0] = '\0';
    for (int i = 0; i < count; i++)
    {
        if (i == p1 || i == p2)
        {
            strcat(b, "-->");
        } else {
            strcat(b, "   ");
        }
        for (int j = 0; j < pData[i]; j++)
        {
            strcat(b, "|");
        }
        strcat(b, "\n");
    }
    printf("%s", b);
}

void BubbleSort(int *pData, int count)
{
    int iTemp;
    for (int i = 0; i < count; i++)
    {
        for (int j = count - 1; j > i; j--)
        {
            if (pData[j] < pData[j - 1])
            {
                iTemp = pData[j];
                pData[j] = pData[j - 1];
                pData[j - 1] = iTemp;
                RepaintScreen(pData, count, i, j); //refresh the screen
                Sleep(10);
            }
        }
    }
}

int main( int argc, char **argv )
{
    int data[SIZE];
    srand(time(NULL));
    //initiate data
    for (int i = 0; i < SIZE; i++)
    {
        data[i] = rand() % WIDE;
    }
    BubbleSort(data, SIZE);
    return 1;
}


texts:
I have used animate.css and jQuery as external libs. Is there a better way of doing what I have done with jQuery?

DEMO

$(document).ready(function () {

    $('#test li').on('click', function () {

        var className = $(this).attr('class');
        $('#test2 > li').each(function () {

            var prodName = $(this).data('prod');

            if (prodName == className) {

                $('#test2 > li').removeClass('bounceInRight').addClass('bounceOutRight');
                $this = $(this);
                setTimeout(function () {
                    console.log(this);
                    $('#test2 > li').addClass('hide')
                    $this.removeClass('hide bounceOutRight').addClass('bounceInRight');
                }, 400);

            }
        });
    })
});
ul#test > li {
    display: inline-block;
    padding: 10px;
    cursor: pointer;
}
#test {
    position: fixed;
    top: 0;
    left: 0;
}
#test2 {
    position: fixed;
    top: 0;
    right: 0;
    list-style: none;
}
#test2 > li {
    background: yellow;
    width: 350px;
    height: 600px;
    /* transition: height 0.3s ease, width 0.2s ease;*/
    overflow: hidden;
    margin-top: -30px;
    padding-top: 30px;
    margin-right: -50px;
}
.hide {
    display: none;
}

<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/3.2.6/animate.min.css">

1

2

3

1

2

3


texts:
Here is a simple implementation of generic method that get value from array in class and cast it to a type.

    private T GetReferenceFieldValue<T>(ReferenceRow referenceRow, string fieldName)
    {
        var referenceField = referenceRow.field.FirstOrDefault(x => x.name == fieldName);

        if (referenceField != null)
        {
            //Dictionary for actions with types
            var typeActions = new Dictionary<Type, Func<object>>
                {
                    { typeof(DateTime), () => { return DateTime.Parse(referenceField.Item.ToString()); } },
                    { typeof(int), () => { return int.Parse(referenceField.Item.ToString()); } },
                    { typeof(string), () => { return referenceField.Item.ToString(); } },
                    { typeof(Guid), () => { return new Guid(referenceField.Item.ToString()); } },
                };

            var fieldValue = typeActions[typeof(T)]();

            return (T)Convert.ChangeType(fieldValue, typeof(T));
        }

        return default(T);
    }


texts: Filter some Apache Conf to extract all ServerName and ServerAlias, then output them one per line

texts:
#!/bin/bash
#extractApacheResolutionName

GrepAndFilter="ServerName|ServerAlias"
RemoveBadMatch="s/^\s*($GrepAndFilter)\s+//gI"
RemoveTrailingWhitespaces="s/\s*$//"
RemoveComas="s/,//g"
ReplaceSpacesWithNewLines="s/ +/\s/g"

grep --line-buffered -Ei "$GrepAndFilter" /dev/stdin \
    | sed -E "$RemoveBadMatch; $RemoveTrailingWhitespaces; $RemoveComas; $ReplaceSpacesWithNewLines"

The script is to be used mainly to gather all the URLs of a remote Httpd Configuration, and output them one URL per line, such as

ssh hostname "cat /etc/httpd/conf.d/*.conf" | extractApacheResolutionName

Nb : the actual script contains a sort

... | rev | sort -u | rev

... but that's another question I asked on StackOverflow, because I would like to extract it to another piece of software.

What can I do to improve my script ?

from a readability point of view ?
from a performance point of view ?


texts:
In this SO question  I provided two answers for the batch conversion of more than 100K txt to xlsx files

I suspect any automation of Excel is too slow, but would appreciate if there is a superior (i.e. faster) approach using powershell.

$files = Get-ChildItem C:\Temp\*.txt
Write "Loading Files..."

$Excel = New-Object -ComObject Excel.Application
$Excel.visible = $false
$Excel.DisplayAlerts = $false

ForEach ($file in $files)
{

 $WorkBook = $Excel.Workbooks.Open($file.Fullname)
 $NewFilepath = $file.Fullname -replace ".{4}$"
 $NewFilepath =  $NewFilepath + ".xls"
 $Workbook.SaveAs($NewFilepath,56)

}
  Stop-Process -processname EXCEL
  $Excel.Quit()


texts: Circular doubly linked list in JavaScript

texts:
I've been studying data structures and have taken a stab at implementing a doubly LL in JavaScript. Please review and advise on any additional improvements and optimizations. I'm more interested in feedback particularly regarding the implementations of removeAt(), contains() and getItem() methods as they share similar, repetitive code:

//Blueprints
function Node(val){
  this.data = val;
  this.next = null;
  this.prev = null;
}

function DoublyList(){
  this._length = 0;
  this._isCircular = false;
  this.head = null;
  this.tail = null;
}

//Adds to the list
DoublyList.prototype.add = function(val){
  var node = new Node(val);

  if(this._length){
    this.tail.next = node;
    node.prev = this.tail;
    this.tail = node;
  }else{
    this.head = node;
    this.tail = node;
  }

  this._length++;
  return node;
}

//Check if list is empty
DoublyList.prototype.isEmpty = function(){
  return this._length===0;
}

//Contains method returns index if true
DoublyList.prototype.contains = function(val){
  if(this.isEmpty()){
    return 'List is Empty';
  }
  var currentNode = this.head, i=0;
  //if val is in 1st node
  if(currentNode.data === val){
    return 0;
  }
  //if val is in last node
  if(this.tail.data === val){
    return (this._length-1);
  }
  //if val is in middle
  while(i++ < (this._length-1)){
    if(currentNode.data === val){
      return (i-1);
    }
    currentNode = currentNode.next;
  }
  return false;
}

//Make circular
DoublyList.prototype.makeCircular = function(){
  if(!this.isEmpty()){
    this.head.prev = this.tail;
    this.tail.next = this.head;
    this._isCircular = true;
  }
}

//get data by node index
DoublyList.prototype.getItem = function(index){

  if(this.isEmpty()){
    return 'List is Empty';
  }

  if(index<0 || index > this._length){
    return 'Invalid Index!';
  }

  var currentNode = this.head, i=0;
  //if first item in list
  if(index===0){
    return currentNode.data;
  }
  //if last item in list
  if(index === (this._length-1)){
    return this.tail.data;
  }
  //if item is in middle of list
  while(i++ < index){
    currentNode = currentNode.next;
  }
  return currentNode.data;
}

DoublyList.prototype.removeAt = function(index){
  if(this.isEmpty()){
    return 'List is Empty';
  }

  if(index<0 || index > this._length){
    return 'Invalid Index!';
  }

  var currentNode = this.head, i=0;
  //if first item in list: O(1)
  if(index===0){
    this.head = currentNode.next;
    this.head.prev = this.tail;
    this.tail.next = this.head;
    this._length--;
    return this;
  }
  //if last item in list: O(1)
  if(index === (this._length-1)){
    this.tail = this.tail.prev;
    this.tail.next = this.head;
    this.head.prev = this.tail;
    this._length--;
    return this;
  }
  //if item is in middle of list: O(n)
  while(i++ < index){
    currentNode = currentNode.next;
  }
  var temp = currentNode;
  temp.prev.next = currentNode.next;
  this._length--;
  return this;
}

var doublyList = new DoublyList();

console.log('isEmpty:\n'+doublyList.isEmpty());
doublyList.add(5);
doublyList.add(10);
doublyList.add(15);
doublyList.add(20);
doublyList.add(25);
doublyList.add(30);
doublyList.add(35);
doublyList.add(40);

console.log('Added items...\n');
console.log('Original List:\n'+doublyList);
console.log('makeCircular:\n'+doublyList.makeCircular());
console.log('Circular List:\n'+doublyList);
console.log('Get 3rd item:\n'+doublyList.getItem(2));
console.log('Contains:\n'+doublyList.contains(15));
console.log('RemoveAt:\n'+doublyList.removeAt(2));


texts: Using RequireJS correctly for social plugins

texts:
I'm a beginner in JavaScript and lately I've been trying things with RequireJS, I'd like to get some feedback on how good/poor my code is and in what ways it can be improved.

My example below is just loading up social plugins - Facebook Like/Share, Twitter Tweet & Google +1. The code is functional and working.

index.html:

<!DOCTYPE html>

        <meta charset="utf-8" />
        <meta name="viewport" content="width=device-width">
        <meta name="description' content="Your description here." />
        <meta name="keywords" content="your, great, keywords" />
        <title>Your Website Title</title>
        <meta property="fb:app_id" content="1234567890" />
        <meta property="fb:admins" content="1234567890" />
        <meta property="og:title" content="Your Website Title" />
        <meta property="og:type" content="website" />
        <meta property="og:url" content="https://www.your-website.tld/" />
        <meta property="og:image" content="https://path/to/your/static/logo.png" />
        <meta property="og:description" content="Your description here." />
        <meta property="og:locale" content="en_GB" />
        <meta name="twitter:card" content="summary">
        <meta name="twitter:url" content="https://www.your-website.tld/">
        <meta name="twitter:title" content="Your Website Title">
        <meta name="twitter:description" content="Your description here.">
        <meta name="twitter:image" content="https://path/to/your/static/logo.png">
        <meta name="twitter:site" content="@your-website">
        <meta name="twitter:creator" content="@your-username">

                            Tweet

js/app.js:

requirejs.config({
    "shim": {
      "facebook": {
        exports: "FB"
      }
    },
    "baseUrl": "js/lib",
    "paths": {
      "app": "../app",
      "facebook": "//connect.facebook.net/en_GB/all",
      "facebookLike": "lib/facebook/like",
      "googlePlus": "//apis.google.com/js/plusone",
      "twitter": "//platform.twitter.com/widgets"
    }
});

requirejs(["facebook"]);
requirejs(["facebookLike"]);
requirejs(["twitter"]);
requirejs(["googlePlus"]);
requirejs(["app/main"]);

lib/facebook/like.js:

define(["facebook"], function(){
  FB.init({
    appId      : "1234567890",
    xfbml      : "true"
  });
});

app/main.js:

define(["jquery"], function($) {

 // Unused placeholder

});

Note: I haven't included jQuery in the require config because it isn't actually used here.


texts: File uploads with image previews and remove link using Array and readAsDataURL

texts:
I got my code working with vanilla JavaScript, however I'm new to JS, so I don't know if the code is robust or not. Any advice to improve the code is welcome.
Note: I just noticed a bug. The code removes the image from the DOM (is it the right term?) but it still submits the images that I deleted. Any idea how can I fix that?

 let count = 0

 function previewFiles(input) {
   const preview = document.getElementById('preview')
   const {
     files
   } = input

   Array.from(files).forEach(file => {
     const reader = new FileReader()

     reader.onload = e => {
       const div = document.createElement('div')
       const img = document.createElement('img')
       const button = document.createElement('button')

       img.src = e.target.result
       img.width = 200
       img.height = 200
       img.alt = `file-${++count}`

       button.textContent = "Delete"
       button.addEventListener('click', () => {
         preview.removeChild(div)
       })

       div.appendChild(img)
       div.appendChild(button)

       preview.appendChild(div)
     }

     reader.readAsDataURL(file)
   })
 }
    <input type="file" multiple onchange="previewFiles(this);" />


texts: Swapping pairs of characters in a String

texts:
Question: Write a program to swap pairs of characters of a String. In
  case of odd number of characters last character should remain
  unchanged.

  Examples:

  Input: HI

  Output: IH

  Input: hello there

  Output: ehll ohtree

My Code:

import java.util.*;
class SwappedPairs
{
    static String swapPairs(String str)
    {
        int len = str.length();
        int n; //array's length
        if(len%2 == 0)
        {
            n = len;
        }
        else
        {
            n=len-1;
        }
        char []arr = new char[n];
        for(int i = 0; i< n; i++)
        {
            arr[i] = str.charAt(i);
        }
        StringBuffer str1 = new StringBuffer(n);
        for(int i = 0; i<=n-2; i= i+2)
        {
            char temp = arr[i];
            arr[i] = arr[i+1];
            arr[i+1] = temp;
            str1 = str1.append(arr[i]).append(arr[i+1]);
        }

        if(len%2 != 0)
        {
             str1 .append(str.charAt(len-1));
        }
        str = str1.toString();
        return str;
    }

    public static void main(String[] args)
    {
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter a string: ");
        String str = sc.nextLine();
        System.out.println(swapPairs(str));
    }
}

Any suggestion on how to improve it? (It gives the desired output)


texts:
Code dump:

function factor(n) {
    function count(a) {
        if (a.length == 0) {
            return [];
        } else {
            var x = a.pop();
            var l = count(a);
            if (l[x] == undefined) {
                l[x] = 0;
            }
            l[x]++;
            return l;
        }
    }
    function decomp(comp, fac) {
        if (comp == 1) {
            return [];
        }
        if (fac == 1) {
            return [ comp ];
        }
        if (comp % fac == 0) {
            return decomp(fac, fac - 1).concat(decomp(comp / fac, fac));
        } else {
            return decomp(comp, fac - 1);
        }
    }
    return count(decomp(n, n)).map(function(a, b) {
        return [ b, a ];
    }).filter(function(a, b) {
        return a[1];
    }).map(function(a, b) {
        return "" + a[0] + "^" + a[1];
    }).reduce(function(a, b) {
        return a + " * " + b;
    }).replace("^1", "");
}

It's mainly because I've been into functional programming lately that I tried a loopless, stateless, functional algorithm; I know that this example is absolutely facetious and that no one would do this in real life. That said, are there ways I can make this:

More efficient (e.g. less data),
More concise (which keeping the cool functional aspect), or
More functional (in a good way) in paradigm?


texts: Get list of indices from searching for values in list of lists

texts:
I have a list of lists of numbers. The numbers are in sequential order, ranging from 0 to n and each number only appears once. I want to loop over all the numbers in the list of lists and return the index of the list containing that number.

list_of_lists = [[2,3,4,5,6],[0,1,7]]

desired_output = [1,1,0,0,0,0,0,1]

I came up with something, but I'm thinking there has to be a way to do this without doing a list comprehension for each number. Performance is an issue

def get_indices(list_of_lists):

    indices = [0]*len([n for l in list_of_lists for n in l])

    for i in range(len(indices)):
        indices[i] = [ k for k,n in enumerate(list_of_lists) if i in n][0]

    return indices


texts:
This is problem 50 in https://wiki.haskell.org/99_questions/46_to_50. The website has more elegant Haskell solutions, but I wanted to get feedback on how the code I wrote on my own below could be improved.

import Data.List

data Tree a = Leaf a Int | Internal (Tree a) (Tree a) Int

instance (Eq a) => Eq (Tree a) where
 (Leaf a ac)         == (Leaf b bc)  = (a == b) && (ac == bc)
 (Internal a1 a2 ac) == (Internal b1 b2 bc) = (a1 == b1) && (a2 == b2) && (ac == bc)
 _   == _  = False

instance (Eq a) => Ord (Tree a) where
 a <= b = (freq a) <= (freq b)

freq :: Tree a -> Int
freq (Leaf _ c) = c
freq (Internal _ _ c) = c

leafMap :: [(a, Int)] -> [Tree a]
leafMap list = map (\(a, count) -> Leaf a count) list

extractMinFreq :: (Eq a) => [Tree a] -> (Tree a, [Tree a])
extractMinFreq list = (mf , delete mf list)
                      where mf = minimum list

collapseLowest :: (Eq a) => [Tree a] -> [Tree a]
collapseLowest list = (collapsePair s1 s2):xs
                        where
                        (s1,y) = extractMinFreq list
                        (s2, xs) = extractMinFreq y

treeBuilder :: (Eq a) => [Tree a] -> Tree a
treeBuilder list = case len of
                        0 -> error "Empty"
                        1 -> list !! 0
                        _ -> treeBuilder $ collapseLowest list
                    where len = length list

collapsePair :: Tree a -> Tree a -> Tree a
collapsePair x y = Internal x y $ (freq x) + (freq y)

prefixBuilder :: Tree Char -> String -> [(Char, String)]
prefixBuilder (Leaf a _) prefix = [(a, prefix)]
prefixBuilder (Internal a b _) prefix = (prefixBuilder a $ prefix ++ "0") ++
                                        (prefixBuilder b $ prefix ++ "1")

huffman :: [(Char, Int)] -> [(Char, String)]
huffman list = prefixBuilder (treeBuilder $ leafMap list) ""

main = print $ huffman [('a',45),('b',13),('c',12),('d',16),('e',9),('f',5)]


texts: Balancing Brackets Algorithm: Stack Data Structure

texts:
I am currently refining my understanding of data structures and as such, decided to implement a popular application of the Stack. Below you will find my implementation of the Balancing Symbols algorithm written in JavaScript.

My basic questions are:

How clean would you rate my code?
Is time complexity O(n): Linear?
How can I improve?

function isBalanced(arr){
  var stack = new Stack();
  var last;

  arr.forEach(function(curr){
    if (curr === '(' || curr === '[' || curr === '{') {
      stack.push(curr);
    }

    if (curr === ')' || curr === ']' || curr === '}') {
      last = stack.peek() + curr;
      if (last === '()' || last === '[]' || last === '{}') {
        stack.pop();
      }
    }
  });

  var result = (stack.length() === 0) ?  true : false;
  console.log(result);
}

var symbols = ['{', '(', ')', ']'];

isBalanced(symbols);


texts: First readers-writers problem using a single condition

texts:
For the first readers-writers problem, in which readers can access a given resource simultaneously, is the following Python3 solution correct?

Problem parameters:

One set of data is shared among a number of threads
Only one writer may write at a time, and no other thread can read the resource
If at least one reader is reading, no other thread can write
Multiple readers can read the resource without blocking each other

import threading, time
from multiprocessing import Condition

class SharedResource():
    def __init__(self):
        self.val = 0

# The class solving this problem
class RWLock:
    def __init__(self):
        self.cond = Condition()
        self.readers = 0

    def read_acquire(self):
        self.cond.acquire()
        self.readers += 1
        self.cond.release()

    def read_release(self):
        with self.cond:
            self.readers -= 1
            if (self.readers == 0):
                self.cond.notify_all()

    def write_acquire(self):
        self.cond.acquire()
        if (self.readers > 0):
            self.cond.wait()

    def write_release(self):
        self.cond.release()

def read(lock, res):
    while True:
        lock.read_acquire()
        print(threading.current_thread().ident, "Reading:",res.val)
        time.sleep(0.5)
        lock.read_release()

def write(lock, res):
    while True:
        lock.write_acquire()
        print(threading.current_thread().ident, "Writing")
        res.val += 1
        time.sleep(1)
        lock.write_release()

if __name__ == '__main__':
    lock = RWLock()
    res = SharedResource()

    for i in range(10):
        t = threading.Thread(target=read, args=(lock,res,))
        t.start()

    for i in range(10):
        t = threading.Thread(target=write, args=(lock,res,))
        t.start()

I did not find any solution online using a single condition, and have been trying to find a loophole in this one. From what I have gathered, it fulfills the problem's requisites.

Two questions:

Does the solution fulfill the problem's requisites?
Is the above code correct?

What are your thoughts on this?


texts: Refactor the method which is the sequence of the similarly looking steps to (or towards) the design patterm(s)

texts:
I need some help to understand if the code below could be refactored to something less straightforward, less repetitive and more towards any appropriate pattern.

What I feel uncomfortable with in the code is the flow of repetitive tasks with the same pattern like:

// Get the result from some operation (API call / or any other operation);
// Check if the result is somehow valid;
// If it is not valid, set the response object accordingly and return early;
// If it is valid, continue with the next step with the overall same logic but different details.

Does the code look like being able to get refactored to (or towards) some usefully applicable here design pattern?

Would love to hear any feedback on it.

Here is the code:

/**
 * Check if the given email exists in the SendGrid recipients global list
 * and its custom field 'status' has the value 'subscribed'.
 *
 * @param  string  $email The email to check.
 *
 * @return object  (object)['isfound'=>false, 'issubscribed'=>false];
 */
public function getSubscriberStatus(string $email): object
{
    $result = (object) ['isfound' => null, 'issubscribed' => null];

    /**
     * Find the email in the SendGrid global list.
     */
    $endpoint = "contactdb/recipients/search?email=$email";
    $found = $this->callSendGrid('GET', $endpoint);
    if ($found->status !== 200) {
        Log::error(sprintf('[SENDGRID] Error while searching the email: %s in the SendGrid list, status: %s, message: %s', $email, $found->status, $found->message));
        $result->isfound = false;
        $result->issubscribed = false;
        return $result;

        // throw new \Exception("Error while searching the email: $email in the SendGrid list");
    }

    if (!($found->data->recipient_count > 0)) {
        $result->isfound = false;
        $result->issubscribed = false;
        return $result;
    }

    /**
     * Find the recipient with email exactly matching the required one.
     */
    $recipient = collect($found->data->recipients)->first(function ($item) use ($email) {
        return $item->email === $email;
    });

    /**
     * No exactly matching emails.
     */
    if (!$recipient) {
        $result->isfound = false;
        $result->issubscribed = false;
        return $result;
    }

    $result->isfound = true;

    /**
     * Get the status field of the recipient's 'custom_fields' array.
     */
    $status = collect($recipient->custom_fields)->first(function ($item) {
        return $item->name === 'status';
    });

    if ($status->value !== 'subscribed') {
        $result->issubscribed = false;
        return $result;
    }

    $result->issubscribed = true;
    return $result;
}


texts:
I move back and forth between Python and C++ and I often need a nice/quick way to output STL objects to the screen for debugging purposes. I'd like the output to match the output of a comparable Python object, thus I have different templates for vectors, sets, etc...

Is this the best way to go about this?

template <class T>
ostream& operator<<(ostream& s, const vector<T> &A) {
  if(A.empty())
    return s << "[]";

  s << "[";
  typename vector<T>::const_iterator itr_penultimate = --A.end();
  typename vector<T>::const_iterator itr = A.begin();

  while(itr != itr_penultimate) {
    s << *itr << ", ";
    itr++;
  }
  return s << *itr << "]";
}


texts: Python palindrome function; is it possible to write it without using string conversion?

texts:
I hope this question is okay to ask on Code Review; this is a little function I wrote in Python 2.7.12 that checks if a number is a palindrome. It works fine but I'd like to know if there is a purely mathematical way to do it without using string conversion.

Here is the function:

def is_palindrome(n):
    forward = str(n)
    backward = []

    i = len(forward) - 1
    while i >= 0:
        backward.append(forward[i])
        i -= 1

    backward = "".join(backward)

    if backward == forward:
        return True
    else:
        return False

How would one go about solving such a problem without using string conversion?


texts: Checking if a LinkedList is a palindrome

texts:
I would like to know if my code is \$O(n)\$ space complexity.
The code checks if a doubly linked list is Palindrome.

public boolean isPalindromeList(LinkedList<Integer> list) {
        boolean isPalindrome = true;
        Stack<Integer> s = new Stack<Integer>();
        Iterator<Integer> iterator = list.iterator();
        // step1: iterate over the list and each put the element in the Stack
        while (iterator.hasNext()) {
            s.push(iterator.next());
        }
        // step2: pop elements from Stack and compare it while iterating through
        // the list
        Iterator<Integer> iterator2 = list.iterator();
        while (iterator2.hasNext()) {
            if (s.pop() != iterator2.next()) {
                return false;
            }
        }
        // for example List = {1,2,5,3}. Stack.pop()=3 do compare 3 == 1 if no
        // return false else continue
        // repeat pop() and compare with next element in the List
        return isPalindrome;
    }

According to my understanding, it's \$O(1)\$ space complexity, because it's just changing the node that iterator points to, not creating a new variable or reference. But, I'm not sure if pointing to another object results in creating a new variable in Java Stack memory referencing the current node object in the heap space.


texts:
Any advice on how to make this code; cleaner, more effective, just overall better!
Program setup object that is coming from the database. it loop the object adding to the viewmodel object. Then the object has a certain properties base on type. The config type will only have the setting and value objects.
class Program
{
    static void Main(string[] args)
    {
        //Setting up fake objects
        List<Meeting> meetingList = new List<Meeting>();
        meetingList.Add(new Meeting() { Id =1 ,Name="a", Type= "System"  });
        meetingList.Add(new Meeting() { Id = 2, Name = "b", Type = "System" });
        meetingList.Add(new Meeting() { Id = 3, Name = "c", Type = "Config", Setting="Control", Value="2"  });
        meetingList.Add(new Meeting() { Id = 4, Name = "d", Type = "Config", Setting = "Control", Value = "3" });
        meetingList.Add(new Meeting() { Id = 5, Name = "e", Type = "Config", Setting = "", Value = "" });

        //Real Code
        List<Meeting> meetingviewmodel = new List<Meeting>();
        foreach (var meeting in meetingList)
        {
           Meeting mvm = new Meeting();
           meeting.Id = mvm.Id;
           meeting.Name = mvm.Name;
           meeting.Type = mvm.Type;
           if (meeting.Type == "System")
           {
               meetingviewmodel.Add(mvm);
           }
           if (meeting.Type == "Config" && meeting.Setting != null)
           {
              meeting.Setting = mvm.Setting;
              meeting.Value = mvm.Value;
              meetingviewmodel.Add(mvm);

            }
        }
    }

    class Meeting
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string Type { get; set; }
        public string Setting { get; set; }
        public string Value { get; set; }
    }
}


texts:
To delete a key from a trie, there are four cases:

For the explanation of trie data structure, please check
the following link:
http://www.geeksforgeeks.org/trie-insert-and-search/

(1) Key is not in the trie.

(2) Key present in the trie as a unique key.

(3) Key is the prefix of another longer key.

(4) Key presents in the trie, having at least one other key as prefix key.

The following code is my implementation of deleting a key from a trie.

struct trie_node
{
    int mark;
    struct trie_node* children[ALPHABET_SIZE];
};

struct trie
{
    struct trie_node* root;
    int count;
};

// check if a trie node has no children
bool isFreeNode(struct trie_node* p)
{
    int i;
    for(i = 0; i < ALPHABET_SIZE; ++i)
    {
        if(p->children[i])
            return false;
    }
    return true;
}

bool isLeafNode(struct trie_node* p)
{
    return p->mark == 1;
}

bool deleteHelper(struct trie_node* root, char* key, int level, int len)
{
    int ind;
    //check if the key is in the trie.
    if(root!=NULL)
    {
        if(level==len)
        {
            //check if the key is in the trie.
            if(root->mark==1)
            {
                root->mark = 0;

                //Is it an unique key?
                            if(isFreeNode(root))
                {
                    return true;
                }
                return false;
            }
        }
        else
        {
            ind = *(key+level) - 'a';
            if(deleteHelper(root->children[ind], key, level+1, len))
            {
                free(root->children[ind]);
                root->children[ind] = NULL;

                //check if the node is an unique key node. Case (2) and
                            //and case (4) can both generates unique key node.
                            if(!isLeafNode(root) && isFreeNode(root))
                {
                    return true;
                }
                return false;
            }
        }
    }
    return false;
}

void deleteKey(struct trie* trie, char* key)
{
    int len = strlen(key);
    if(len>0)
    {
        //check if the key is the only one in the trie
            if(deleteHelper(trie->root, key, 0, len))
        {
            free(trie->root);
        }
    }
}


texts:
I have a switch statement that checks whether or not one string matched another that was stored in an array. However, there are multiple cases in which the same result is returned for multiple matches. I originally had a large amount of if/else checks, but tried to shorten that down with the switch statement. I was wondering, is there anyway to shorten down this switch statement?

function checkLoc(xstreets) {
            var address;
            if(xstreets[2] == undefined) {
                address = xstreets[0]+" & "+xstreets[1]+" Chicago IL";
            }
            else {
                switch(xstreets[2]) {
                    case "aon":
                        address = "Aon Center Chicago IL";
                        break;
                    case "trump":
                        address = "401 North Wabash Avenue, Chicago, IL";
                        break;
                    case "pritzker":
                        address = "Pritzker Park Chicago IL";
                        break;
                    case "hyde":
                    case "hydepark":
                    case "uofc":
                    case "uchicago":
                        address = "5801 South Ellis Avenue, Chicago, IL";
                        break;
                    case "reg":
                        address = "1100 E 57th St, Chicago, IL 60637";
                        break;
                    case "willis":
                    case "wttw":
                        address = "233 South Wacker Drive, Chicago, IL";
                        break;
                    case "600":
                        address = "600 West Chicago Avenue, Chicago, IL";
                        break;
                    default:
                        address = xstreets[0]+" & "+xstreets[1]+" Chicago IL";
                        break;
                }
            }
            return address;
        }


texts: Map a hierarchy of nested DTO objects to a list of business objects

texts:
Consider I download my data into this data structures:

public class AThingDTO
{
   int AID { get; set; }
   string AName { get; set;}
   Dictionary<int, BThingDTO> BThingsColl { get; set;}
}

public class BThingDTO
{
   int BID { get; set; }
   string BName { get; set;}
   int AID { get; set; }
   List<CThingDTO> CThingsColl { get; set;}
}

public class CThingDTO
{
   int CID { get; set; }
   string CName { get; set;}
   int BID { get; set; }
   int AID { get; set; }
}

Consider I want to map it into this data structures:

public class AThing
{
   int AID { get; set; }
   string AName { get; set;}
   List<BThing> BThingsColl { get; set; } = new List<BThing>();
}

public class BThing
{
   int BID { get; set; }
   string BName { get; set;}
   List<CThing> CThingsColl { get; set;} = new List<CThing>();
}

public class CThing
{
   int CID { get; set; }
   string CName { get; set;}
}

I did like this:

public List<AThing> MapFromDTO(Dictionary<int, AThingDTO> dtoThingsHierarchy)
{
    var mappedThings = new List<AThing>();

    foreach (var aThingDto in dtoThingsHierarchy)
    {
        var aThing = new AThing();
        aThing.AID = aThingDto.AID;
        aThing.AName = aThingDto.AName;

        foreach (var bThingDto in BThingsColl.Values)
        {
            var bThing = new BThing();
            bThing.BID = bThingDto.BID;
            bThing.BName = bThingDto.BName;

            foreach (var cThingDto in CThingsColl)
            {
                var cThing = new CThing();
                cThing.CID = cThingDto.CID;
                cThing.CName = cThingDto.CName;

                bThing.CThingsColl.Add(cThing);
            }

            aThing.BThingsColl.Add(bThing);

        }

        mappedThings.Add(aThing);

    }

    return mappedThings;
}

Is there a more elegant way / more expressive way to express this mapping? Maybe with LINQ?


texts:
I have a short function written in JavaScript using jQuery which takes a message and appends it to a div. It does this one character at a time with a small delay between characters, and then returns the time that it took it will take for the function to finish running.
const log = $('#log')

function logMessage(message, type) {
    log.append('

')
    log.children().last().addClass(type);
    for (let charIndex = 0; charIndex < message.length; charIndex++)
        setTimeout(() => {
            log.children().last().append(message[charIndex])
        }, charIndex * 10)
    return message.length * 10
}

This code feels a little bit unoptimized but I'm not sure what would be a better of going about doing this.


texts: Dividing valuable items so that two persons get the most similar value possible

texts:
You have n items, each one of those has a certain value, represented here as an integer.
  How do you give to two persons the most similar value?

No comment from me here as my code already contains much documentation.

from itertools import combinations, chain
import doctest

def all_subsets(lst):
    """
    Returns all the possibilities of taking n elements of the
    lst, where n goes from 0 to len(lst) - 1

    >>> list(all_subsets([1,2,3]))
    [(), (1,), (2,), (3,), (1, 2), (1, 3), (2, 3)]
    """
    return chain.from_iterable(combinations(lst, i) for i in range(len(lst)))

def partitions(items):
    """
    All the possible ways to divide the items in two.

    >>> list(partitions([1,2,3]))
    [((1,), (2, 3)), ((2,), (1, 3)), ((3,), (1, 2)), ((1, 2), (3,)), ((1, 3), (2,)), ((2, 3), (1,))]
    """
    return ((a,b)
             for a in all_subsets(items)
               for b in all_subsets(items)
                 if set(a).union(set(b)) == set(items) and\
                    not set(a).intersection(set(b)))

def evenly_divide(items):
    """
    You have n items, each one of those has a certain value,
    represented here as an integer.

    How do you give to two persons the most similar value?

    This problem is NP-complete.
    This function finds the optimal solution by bruteforce.

    >>> evenly_divide( [1,2,3] )
    ((3,), (1, 2))
    >>> evenly_divide( [9, 12, 14, 17, 23, 32, 34, 40, 42, 49] )
    ((9, 12, 32, 34, 49), (14, 17, 23, 40, 42))
    """
    def difference(parts):
        first_part, second_part = parts
        return abs(sum(first_part) - sum(second_part))

    return min(partitions(items), key=difference)

def fevenly_divide(items):
    """
    You have n items, each one of those has a certain value,
    represented here as an integer.

    How do you give to two persons the most similar value?

    This problem is NP-complete.

    This function finds an approximate solution by sorting the items, and
    then giving the next item to the most poor guy.

    >>> fevenly_divide( [1,2,3] )
    ([2, 1], [3])
    >>> fevenly_divide( [9, 12, 14, 17, 23, 32, 34, 40, 42, 49] )
    ([42, 40, 32, 14, 9], [49, 34, 23, 17, 12])
    """
    first_guy = []
    second_guy = []
    for item in reversed(sorted(items)):
        if sum(first_guy) < sum(second_guy):
            first_guy.append(item)
        else:
            second_guy.append(item)
    return first_guy, second_guy

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


texts: Booking system ala airbnb many to many laravel relationship?

texts:
I'm trying to create a system to log all bookings for a few airbnb hosts, at first I had two models Home and Guest, where a home can have many guests and a guest could book for many homes,
then I thought about creating a guest_home pivot table to link both tables... then things got complicated in my head, what about a Booking model, and (have that booking model act as a pivot table ?) , to me doing new Booking() seemed better than attaching ids to home model?
How could you guys go about this, it's making my brain malt right now...
I thought of doing something like this in my BookingController:
public function createBooking(Request $request)
    {

        $guestIds = Guest::latest()->take(3)->pluck('id');
        $home = Home::findOrFail($request->input('home_id', 2));

        $booking = new Booking();
        $booking->home_id = $home->id;
        $booking->guests()->attach($guestIds);
        $booking->save();

        return response()->json([
            'booking' => $booking,
        ]);

    }

Should I create home_guest pivot table, is a pivot table even needed? what models would I link, please bear with me, so far this is what I got:
Models
class Guest extends Model
{

    public function bookings()
    {
        return $this->belongsToMany('App\Models\Home', 'bookings', 'guest_id', 'home_id');
    }

}

class Home extends Model
{

    public function guests()
    {
        return $this->belongsToMany('App\Models\Guest', 'bookings', 'home_id', 'guest_id');
    }

    public function bookings()
    {
        return $this->hasMany('App\Models\Booking');
    }

}

class Booking extends Model
{
    //Is Booking needed or I could make a pivot table like home_guest called 'bookings' ?
    public function guests()
    {
        return $this->belongsToMany('App\Models\Guest', 'booking_guest', 'booking_id', 'guest_id');
    }

}

Migrations:
Schema::create('bookings', function (Blueprint $table) {
            $table->increments('id');
            $table->unsignedInteger('home_id')->index();
            $table->foreign('home_id')->references('id')->on('homes')->onDelete('cascade')->onUpdate('cascade');
            $table->unsignedInteger('guest_id')->nullable()->index();
            $table->foreign('guest_id')->references('id')->on('guests')->onDelete('cascade')->onUpdate('cascade');
            $table->timestamps();
        });

Schema::create('homes', function (Blueprint $table) {
            $table->increments('id');
            $table->unsignedInteger('host_id')->index();
            $table->foreign('host_id')->references('id')->on('hosts')->onDelete('cascade')->onUpdate('cascade');
            $table->string('fullAddress')->unique();
            $table->integer('rooms')->unique();
            $table->timestamps();
        });

Schema::create('guests', function (Blueprint $table) {
            $table->increments('id');
            $table->string('fullName')->unique();
            $table->string('identificationType')->unique();
            $table->text('country')->nullable();
            $table->timestamps();
        });
```


texts:
I have a problem with my interface-design. I especially ask for help with the overloaded compute-Method.

For a calculator I work with these Interfaces:

public interface ICalculator{
    public double compute(String expression) throws IllegalArgumentException;
}

public interface IParameterizedCalculator extends ICalculator {
    public double setParameter(String parameter, double value) throws IllegalArgumentException;

    public double getParameter(String parameter) throws IllegalArgumentException;

    // IllegalArgumentException when expression is null or malformed
    // IllegalStateException when a parameter in the expression was not set prior to this method
    double compute(String expression) throws IllegalArgumentException, IllegalStateException;
}

public interface IPersistentCalculator extends ICalculator {
    // IllegalStateException when no expression is stored
    double compute() throws IllegalStateException;

    void store(String expression) throws IllegalArgumentException;
}

IParameterizedCalculator adds an Exception to compute. As the previously stateless ICalculator suddenly became stateful I see no way than to add this exception.
IPersistantCalculator doesn't modify the original compute(String), but overloads it with compute(), which also has a state and therefore throws an IllegalStateException (but not necessarily an IllegalArgumentException, as the only way to store an expression is through the store(String)-Method and I don't care if someone hacks my code via reflection or debugger). However this IllegalStateException has a different reason (another "state" if you want).

I have three questions now:

How do I properly extend the throws-clause to indicate that my derived methods will throw more than their parent?
How do I communicate this in a class MyCalculator implements IPersistentCalculator, IParameterizedCalculator (which only exposes a single compute(String)-method)?
How do I communicate that the MyCalculator.compute()-Method may throw IllegalStateException when a parameterized expression has been stored?


texts:
I am defining a subclass of a the python dictionary object mpCmd where every item is converted to a lambda.  The intended usage is that every item in the dictionary can be called with a single list argument (row) that will return a value based on row.  Integers and optionally strings are considered indexes of the row. When converted to indexes, strings are converted as though they were Excel style column names.

A single integer n will become lambda row: row[n]. A tuple with a function and a sequence of indexes transforms as

(func, (n1, n2, n3)) => lambda row: func(row[n1], row[n2], row[n3])

Here are some basic examples

>>>command = mpCmd({0: 0, 'B': (sum, ([1, 2, 4],)), 'C': 'SPAM'})
>>>command[0](['Idle', 'Palin', 'Cleese', 'Chapman', 'Gilliam', 'Jones']))
'Idle'
>>>command[1]([1, 2, 3, 4, 5])
10
>>>command[2](ANYTHING)
'SPAM'

I have tested it and it works.  Any advice appreciated, even if it's just confirming this is black magic.

def rmap(func, sequence):
    return [rmap(func, i) if isinstance(i, (tuple, list))
            #elif isinstance(i, dict) ???
            else func(i)
            for i in sequence]

def name_to_index(col_name):
    """Converts Excel Style column name to zero offset index
    """
    return reduce((lambda index, char: index*26 + int(char, 36) - 9),
                  col_name, 0) - 1

class mpCmd(dict):
    """Stores user defined maps and converts them to f(vector) = scalar

    Every item stored in mpCmd will be converted to int: (lambda row: some_func)
    """

    def __init__(self, map_dict, offset=0,
                 int_is_index=True, str_is_name=False):
        self.offset = offset
        self.int_is_index = int_is_index
        self.str_is_name = str_is_name
        super(mpCmd, self).__init__(self._convert_dict(map_dict))

    # Override setters, do no override accessors
    def __setitem__(self, key, val):
        super(mpCmd, self).__setitem__(*self._convert_item(key, val))

    def update(self, other):
        super(mpCmd, self).update(self._convert_dict(other))

    # Macro functions
    def _convert_dict(self, other):
        return {self._convert_key(key): self._convert_val(val)
                    for key, val in other.items()}

    def _convert_item(self, key, val):
        return self._convert_key(key), self._convert_val(val)

    # actual replacement
    def _convert_val(self, val):
        if (isinstance(val, int) and self.int_is_index
                or isinstance(val, str) and self.str_is_name):
            return (lambda row, index=self._convert_key(val): row[index])

        elif isinstance(val, (tuple, list)):
            func, indexes = val
            assert callable(func)
            indexes = rmap(self._convert_key, indexes)
            return (lambda row: func(*rmap((lambda i: row[i]), indexes)))

        else:
            return (lambda *args, **kwargs: val)

    def _convert_key(self, key):
        if isinstance(key, str):
            return name_to_index(key)
        elif isinstance(key, int):
            return key - self.offset
        else:
            raise TypeError


texts: Generic Singly-Linked List implementation

texts:
I'm looking for some feedback regarding my implementation of a generic singly-linked list in C#. I'm also looking for some tips on how to implement other techniques such as using IEnumerable or other .NET interfaces I'm currently not aware of.

Node.cs

using System;
namespace SinglyLinkedLists
{
    public class Node<T>
    {
        private Node<T> _next;
        private T _data;

        public Node<T> next{
            get { return _next; }
            set { _next = value; }
        }

        public T data{
            get { return _data; }
            set { _data = value; }
        }

        public Node(T newData){
            this._data = newData;
            this._next = null;
        }

        public static void printNodes(Node<T> head){
            Node<T> currentNode = head;
            while (currentNode != null){
                Console.WriteLine(currentNode.data);
                currentNode = currentNode.next;
            }
        }
    }
}

SinglyLinkedLists.cs

using System;
namespace SinglyLinkedLists
{
    public class SinglyLinkedLists<T>
    {
        private Node<T> head;
        private Node<T> previous;
        private Node<T> current;
        private Node<T> tail;

        private int numberOfNodes = 0;

        public SinglyLinkedLists()
        {
            head = null;
            previous = null;
            current = null;
            tail = null;
        }

        public void PrintList(){
            Node<T> current = head;
            while (current != null){
                Console.WriteLine(current.data);
                current = current.next;
            }
        }

        public void AddLast(T data){
            Node<T> newNode = new Node<T>(data);
            if (tail == null){
                head = tail = newNode;
            }
            else{
                tail.next = newNode;
                tail = newNode;
            }
            numberOfNodes++;
        }

        public void AddLastTwo(T data){
            Node<T> newNode = new Node<T>(data);

            if (head == null){
                head = newNode;
            }
            else{
                current = head;
                while (current.next != null){
                    current = current.next;
                }
                current.next = newNode;
            }
            numberOfNodes++;
        }

        public void RemoveNode(T data){
            Node<T> nodeToRemove = new Node<T>(data);
            current = head;

            if(head.data.Equals(nodeToRemove.data)){
                current = head.next;
                head = current;
            }
            else{
                while (current != null){
                    if (current.data.Equals(nodeToRemove.data)) {
                        previous.next = current.next;
                        current = previous;
                    }
                    else{
                        previous = current;
                        current = current.next;
                    }
                }
            }
            numberOfNodes--;
        }

        public int ListSize(){
            return numberOfNodes;
        }

        public bool InList(T data){
            Node<T> nodeToLookFor = new Node<T>(data);
            Node<T> current = head;
            while (current != null){
                if (current.data.Equals(nodeToLookFor.data)){
                    return true;
                }
                current = current.next;
            }
            return false;
        }

    }
}


texts: Function to copy characters from one buffer to another given the maximum size

texts:
#include <iostream>
#include <vector>
#include <algorithm>

template <typename T>
int copy_max(T& to, T& from, unsigned char delim, size_t limit)
{
    typename T::iterator pos = std::find(from.begin(), from.end(), delim);
    typename T::iterator prev_pos = pos;

    if(pos == from.end())
    {
        return -1;
    }

    size_t index = std::distance(from.begin(), pos);

    while(pos != from.end()
    && index <= limit)
    {
        prev_pos = pos;
        pos = std::find(pos + 1, from.end(), delim);
        index = std::distance(from.begin(), pos);
    }

    index = std::distance(from.begin(), prev_pos);

    if(index == 0)
    {
        return -1;
    }
    to.insert(to.begin(), from.begin(), prev_pos);
    from.erase(from.begin(), prev_pos);
    return index;
}

void output(const std::vector<unsigned char>& va, const std::vector<unsigned char>& vb )
{
    std::string str(va.begin(), va.end());
    std::cout << "To: " << str << std::endl;
    str.assign(vb.begin(), vb.end());
    std::cout << "From: " << str << std::endl;
}
static int case_num = 1;
#define expect(a, b) \
std::cout << "[" << case_num ++ << "] "; \
if(a == b) \
std::cout << #a << " == " << #b << " TRUE " << std::endl;\
else {\
std::cout << "FAIL " << #a << " != " << #b << " FALSE " << std::endl;\
throw new int;\
}

int main() {
    std::string b = "Hi\x24The\x24HowAreYou\x24?";
    std::vector<unsigned char> va;
    std::vector<unsigned char> vb(b.begin(), b.end());

    int index = copy_max(va, vb, '\x24', 5);
    expect(index, 2);
    output(va, vb);

    va.clear();
    index = copy_max(va, vb, '\x24', 5);
    expect(index, 4);

    va.clear();
    index = copy_max(va, vb, '\x24', 5);
    expect(index, -1);

    return 0;
}

Don't mind the main() function and testing macros, this is just something I threw together in a matter of minutes.


texts: Fizzbuzz in COBOL, Verbose dinosaur style

texts:
I was long a professional in COBOL, but noone ever dared comment my style. As the FizzBuzz seems fashion here, I made one. Verbose, of course, we're speaking about COBOL. I know I could have made in 15 lines, but decided instead to provide the full structure for a production program. Result makes 87 lines.

I'll be happy to read your thoughts, comments, critics, or executions. Made on OpenCOBOLIDE.

  ******************************************************************
  * Author:Gazzz0X2Z                                              *
  * Date:2015, Dec the 12th                                      *
  * Purpose:FizzBuzz, what else?                                 *
  * Tectonics: cobc                                               *
  ******************************************************************
   IDENTIFICATION DIVISION.
  *-*-*-*-*-*-*-*-*-*-*-*-*-
   PROGRAM-ID. FIZZBUZZ.
  *-*-*-*-*-*-*-*-*-*-*--
   ENVIRONMENT DIVISION.
  *-*-*-*-*-*-*-*-*-*-*--
   CONFIGURATION SECTION.
  *----------------------
   INPUT-OUTPUT SECTION.
  *----------------------
   DATA DIVISION.
  *-*-*-*-*-*-*-*-
   FILE SECTION.
  *-------------------------
   WORKING-STORAGE SECTION.
  *-------------------------
   01  WS-DATA.
       05  WS-COUNTS.
           10  WS-FIRST        PIC 9(4)    VALUE ZERO.
           10  WS-LAST         PIC 9(4)    VALUE 20.
           10  WS-POSN         PIC 9(4).
       05  WS-RESULTS.
           10  WS-RS00         PIC 9(4).
           10  WS-RM05         PIC 9(4).
               88  WS-ML05                 VALUE ZERO.
           10  WS-RM03         PIC 9(4).
               88  WS-ML03                 VALUE ZERO.
       05  WS-DISPLAY-STRING   PIC X(10).
       05  WS-DISPLAY-NUM REDEFINES WS-DISPLAY-STRING.
           10  WS-FIZZBUZZ-PRI PIC X(3).
           10  WS-FIZZBUZZ-INT PIC Z(3)9.
           10  WS-FIZZBUZZ-SUI PIC X(3).
       05  WS-DISPLAY-ALPHA REDEFINES WS-DISPLAY-STRING.
           10  WS-FIZZBUZZ-STR PIC X(10).
               88  WS-IS-OTHER             VALUE "*  0000  *".
               88  WS-IS-FIZZ              VALUE "*  FIZZ  *".
               88  WS-IS-BUZZ              VALUE "*  BUZZ  *".
               88  WS-IS-FIZZBUZZ          VALUE "*FIZZBUZZ*".

  *-*-*-*-*-*-*-*-*-*-*
   PROCEDURE DIVISION.
  *-*-*-*-*-*-*-*-*-*-*
   MAIN-PROCEDURE.
        PERFORM    10000-BEGIN
        PERFORM    20000-MAIN
           VARYING WS-POSN FROM WS-FIRST BY 1
             UNTIL WS-POSN > WS-LAST
        PERFORM    30000-END
        .
        STOP RUN.
  *
   10000-BEGIN.
       DISPLAY "**********"
       .
  *
   20000-MAIN.
       PERFORM 40000-COMPUTE-FIZZBUZZ
       DISPLAY WS-DISPLAY-STRING
       .
  *
   30000-END.
       DISPLAY "**********"
       .
  *
   40000-COMPUTE-FIZZBUZZ.
       DIVIDE WS-POSN BY 5 GIVING WS-RS00 REMAINDER WS-RM05
       DIVIDE WS-POSN BY 3 GIVING WS-RS00 REMAINDER WS-RM03
       EVALUATE TRUE
           WHEN (WS-ML05 AND WS-ML03)
               SET WS-IS-FIZZBUZZ  TO TRUE
           WHEN WS-ML05
               SET WS-IS-BUZZ      TO TRUE
           WHEN WS-ML03
               SET WS-IS-FIZZ      TO TRUE
           WHEN OTHER
               SET WS-IS-OTHER     TO TRUE
               MOVE WS-POSN        TO WS-FIZZBUZZ-INT
       END-EVALUATE
       .
  *
   END PROGRAM FIZZBUZZ.

Result :

**********
*FIZZBUZZ*
*     1  *
*     2  *
*  FIZZ  *
*     4  *
*  BUZZ  *
*  FIZZ  *
*     7  *
*     8  *
*  FIZZ  *
*  BUZZ  *
*    11  *
*  FIZZ  *
*    13  *
*    14  *
*FIZZBUZZ*
*    16  *
*    17  *
*  FIZZ  *
*    19  *
*  BUZZ  *
**********


texts:
I have written a simple script for managing our Tomcat and Apache instances for deployment. What this script basically does is, when called, it copies the ROOT.war from its pwd and pushes them to two Tomcat instances. Before that, it removes the old ROOT.war file and ROOT folder, restarts them, cleans the log files, restarts both Tomcat instances and Apache webserver (load-balancer and failover guy).

I have just pasted commands in a script and thought would learn more about it when I optimize this script, such as adding checks.

#!/bin/bash
sh /home/deploy/tomcatfirst/bin/catalina.sh stop
rm -rf /home/deploy/tomcatfirst/webapps/ROOT/
rm -rf /home/deploy/tomcatfirst/logs/
rm /home/deploy/tomcatfirst/webapps/ROOT.war
cp ROOT.war /home/deploy/tomcatfirst/webapps/
mkdir /home/deploy/tomcatfirst/logs

sh /home/deploy/tomcatfirst/bin/catalina.sh stop
rm -rf /home/deploy/tomcatsecond/webapps/ROOT/
rm /home/deploy/tomcatsecond/webapps/ROOT.war
rm -rf /home/deploy/tomcatsecond/logs/
mv ROOT.war /home/deploy/tomcatsecond/webapps/
mkdir /home/deploy/tomcatsecond/logs

sh /home/deploy/tomcatfirst/bin/catalina.sh start
sh /home/deploy/tomcatsecond/bin/catalina.sh start
service apache2 restart


texts: Swapping int with string using getchar() and putchar()

texts:
I wrote code that replaces integers from 0 to 3 with strings. I was only allowed to use getchar() and putchar(). If the input is 1, the output will become "one".

#include <stdio.h>

int main()
{

int c;

char* arr[4] = {"zero", "one", "two","three"};

int i;

  while ((c = getchar ()) != EOF)
    {

        if(c==0+'0'){
        char* str = arr[0];
    for (i = 0; str[i] != '\0'; i++) {

    putchar(str[i]);

}
}

else if(c==1+'0'){
char* str = arr[1];
      for (i= 0; str[i] != '\0';i++) {

    putchar(str[i]);

}
}

else if(c==2+'0'){
char* str = arr[2];
      for (i = 0; str[i] != '\0'; i++) {
        putchar(str[i]);

}
}
else if(c==3+'0'){

    char* str = arr[3];
     for (i = 0; str[i] != '\0'; i++) {
    putchar(str[i]);

}
}

        else
        putchar(c);

   }

return 0;

}

The code is pretty long. Is there a shorter way to write it?


texts:
In my DAL currently I'm handling exceptions as follows. Is it in an acceptable level?

Note : I'm using MVP in this Winforms application.

    public bool InsertAccount(IBankAccount ba)
    {
        string selectStatement = @"IF NOT EXISTS (SELECT ac_no FROM BankAccount WHERE ac_no=@ac_no) BEGIN INSERT INTO BankAccount (ac_no, emp_id, ac_name, bank_name, ac_type," +
                                  "ent_date, ent_by, remarks, file_no, status) VALUES (@ac_no, @emp_id, @ac_name, @bank_name, @ac_type, @ent_date, @ent_by, @remarks, @file_no, @status) END";

        using (SqlConnection sqlConnection = new SqlConnection(db.ConnectionString))
        {
            using (SqlCommand sqlCommand = new SqlCommand(selectStatement, sqlConnection))
            {
                try
                {
                    sqlConnection.Open();
                    sqlCommand.Parameters.Add("@ac_no", SqlDbType.Char).Value = ba.AccountNumber;
                    sqlCommand.Parameters.Add("@emp_id", SqlDbType.Int).Value = ba.EmployeeID;
                    sqlCommand.Parameters.Add("@ac_name", SqlDbType.VarChar).Value = ba.AccountName;
                    sqlCommand.Parameters.Add("@bank_name", SqlDbType.VarChar).Value = ba.BankName;
                    sqlCommand.Parameters.Add("@ac_type", SqlDbType.VarChar).Value = ba.AccountType;
                    sqlCommand.Parameters.Add("@ent_date", SqlDbType.DateTime).Value = ba.EnteredDate;
                    sqlCommand.Parameters.Add("@ent_by", SqlDbType.VarChar).Value = "ABCD";
                    sqlCommand.Parameters.Add("@remarks", SqlDbType.VarChar).Value = ba.Remarks;
                    sqlCommand.Parameters.Add("@file_no", SqlDbType.Int).Value = ba.FileNo;
                    sqlCommand.Parameters.Add("@status", SqlDbType.Bit).Value = ba.Active;

                    sqlCommand.ExecuteNonQuery();
                    return true;
                }
                catch (Exception e) { MessageBox.Show(("Error: " + e.Message)); }
                if (sqlConnection.State == System.Data.ConnectionState.Open) sqlConnection.Close();
                return false;
            }

        }
    }


texts: Accessing nested data properties in Handlebars

texts:
I am using HandlebarsJS for my templating needs.

I have a nested object:

{
    "amount": {
        "preTax": 15.99,
        "tax": 0.0,
        "currencyCode": "USD",
        "total": 15.99
    }
}

And I have the following template:

{{#amount}}

PreTax is {{preTax}}. Tax is {{tax}}. Currency Code is {{currencyCode}} and total is {{total}}

{{/amount}}

Is this the best practice for accessing nested properties within a property? Like declaring the block for the data property or I need to use with?

Like so:

{{#with amount}}

PreTax is {{preTax}}. Tax is {{tax}}. Currency Code is {{currencyCode}} and total is {{total}}

{{/with}}

I know that both approaches work. And in mustache-js I always used the former approach.


texts:
I'm having trouble improving the performance of the solution to the Project Euler problem #34

145 is a curious number, as 1! + 4! + 5! = 1 + 24 + 120 = 145.
Find the sum of all numbers which are equal to the sum of the factorial of their digits.
Note: as 1! = 1 and 2! = 2 are not sums they are not included.

I've done the following :
    private static readonly int max = (int)Factorial(9)*7;
    private static void Main()
    {
        long sum = 0;
        Stopwatch sw = new Stopwatch();
        sw.Start();
        for (int i = 3; i <= max; i++)
        {
            if (IsCuriousNumber(i))
            {
                sum += i;
            }
        }
        sw.Stop();
        Console.WriteLine(sum);
        Console.WriteLine("Time to calculate in milliseconds : {0}", sw.ElapsedMilliseconds);
        Console.ReadKey();
    }

    private static long Factorial(int input)
    {
        int sum = 1;
        for (int i = 1; i <= input; i++)
        {
            sum *= i;
        }
        return sum;
    }

    private static bool IsCuriousNumber(long input)
    {
        char[] digits = input.ToString().ToCharArray();
        long sum = digits.Sum(t => Factorial((int) char.GetNumericValue(t)));
        return sum == input;
    }

It's pretty much self-explanatory .. We have a method to find the factorial of specific number and one more method that checks if a number is "curious" as described in the problem above. We do this by simply converting the input to a char array than we have a variable that just sum's up all the factorials of the digits in the number.


texts: SQL Query to check if 100+ (or Dynamic) columns in table is null

texts:
Let assume a table has more than 100 of columns & I want to display all the rows when all of its columns (Col1, Col2, ..., ColN) are nulls except for the column(s) I mentioned (PK).

This is just a sample table I created to explain this question.

Sample Table with data

+----+------+------+------+------+
| PK | Col1 | Col2 | Col3 | Col4 |
+----+------+------+------+------+
|  1 | 45   | 12   | 171  | 15   |
|  2 | 13   | NULL | 15   | NULL |
|  3 | 17   | 14   | 130  | NULL |
|  4 | 10   | 11   | 110  | 12   |
|  5 | 45   | 15   | 185  | 54   |
|  6 | NULL | NULL | NULL | NULL |
|  7 | 16   | 48   | NULL | 25   |
|  8 | NULL | NULL | NULL | NULL |
|  9 | 13   | 45   | 41   | 64   |
| 10 | NULL | NULL | NULL | NULL |
| 11 | 21   | 12   | 165  | 56   |
| 12 | NULL | NULL | NULL | NULL |
+----+------+------+------+------+

Image: https://i.stack.imgur.com/z17GK.png

In this case, 6, 8, 10 and 12 rows (Column name: PK) are the result I want to see since all of the columns (Col1 to Col4) are null except for the PK column.

Desired Output

+----+------+------+------+------+
| PK | Col1 | Col2 | Col3 | Col4 |
+----+------+------+------+------+
|  6 | NULL | NULL | NULL | NULL |
|  8 | NULL | NULL | NULL | NULL |
| 10 | NULL | NULL | NULL | NULL |
| 12 | NULL | NULL | NULL | NULL |
+----+------+------+------+------+

Image: https://i.stack.imgur.com/prwFo.png

The typical way to do this is to write a query like this.

SELECT * FROM TableName WHERE COALESCE(Col1, Col2, Col3, Col4) is null

If the above table has more 100 columns as I said, writing this query will be hard especially if you have to do it often.

Therefore, I have created a query like this.

DECLARE @query NVARCHAR(MAX);

SELECT @query = ISNULL(@query+', ','') + [name]
                FROM  sys.columns
                WHERE object_id = OBJECT_ID('TableName')
                AND  [name] != 'PK';

SET @query = N'SELECT * FROM TableName WHERE COALESCE('+ @query +') IS NULL';

EXECUTE(@query)

Does this SQL code follow common best practices? How is the quality of this code? (Ex: Performance)


texts: Script that parses the Chase.com page for my recent payments

texts:
I wrote this code earlier to parse Chase.com's online transactions page. It's written in WinForms.

stepBtn is a button that starts this.
wb is a WebBrowser that is already navigated to the page.

Can you give me advice? I'm primarily looking for optimizations, but any other advice would be great.

private void stepBtn_Click(object sender, EventArgs e)
{
    List<string> date = new List<string>();
    List<string> desc = new List<string>();
    List<double> amt = new List<double>();
    //Parse for date
    var links = wb.Document.GetElementsByTagName("span");
    foreach (HtmlElement link in links)
    {
        if (link.InnerText != null)
        {
            string inner = link.InnerText.Trim();
            if (inner == "Pending" || Regex.IsMatch(inner, @"^(0[1-9]|1[012])[- \/.](0[1-9]|[12][0-9]|3[01])[- \/.](19|20)\d\d$"))
            {
                date.Add(inner);
            }
        }
    }

//Parse for description
links = wb.Document.GetElementsByTagName("td");
foreach (HtmlElement link in links)
{
    if (link.GetAttribute("classname") == "cellStyle")
    {
        desc.Add(link.InnerText);
    }
}

//Parse for amount
//Assuming I never make a $1000+ purchase, every number < 1000 will be shown. That way, the balance is not included.
links = wb.Document.GetElementsByTagName("td");
int times = 0; //There are two $xxxx.xx before what I want to parse, the present and available balance.
foreach (HtmlElement link in links)
{
    if (times > 2 && link.InnerText != null && link.InnerText.Trim().Length >= 5)
    {
        string inner = link.InnerText.Trim();
        if (inner.Substring(0, 1) == "$" && Convert.ToDouble(inner.Substring(1)) < 1000)
        {
            amt.Add(Convert.ToDouble(inner.Substring(1)));
        }
    }
    times++;
}

//Check to make sure all lists have the same length
if (date.Count != amt.Count || amt.Count != desc.Count)
{
    MessageBox.Show("The three arrays do not have the same length.\n\nDate: " + date.Count + "\nAmt: " + amt.Count + "\nDesc: " + desc.Count, Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
    return;
}

//Output the arrays to the first checklist
for (int i = 0; i < date.Count; i++)
{
    firstCheck.Items.Add(date[i] + ": " + desc[i] + " (" + amt[i] + ")");
}
}


texts:
In my application, I need to allow the user to store variables.  Variables can only be of specific types, but I effectively handle all variables the same way no matter the type.  I would also like to avoid any casting.  Therefore, I have several HashMaps for each variable type, which is causing lots of duplicated code.  Is there a way to simplify my class?

public class VariableSet {

    private final Map<String, PlayerVariable> players;
    private final Map<String, NumberVariable> numbers;
    private final Set<String> notRemovable;
    private final Set<String> usedVariableNames;

    public VariableSet(){
        players = new HashMap<String, PlayerVariable>();
        numbers = new HashMap<String, NumberVariable>();
        notRemovable = new HashSet<String>();
        usedVariableNames = new HashSet<String>();
        addVariable("Current Player", new PlayerVariable(), players, false);
    }

    public PlayerVariable addPlayer(String variableName){
        PlayerVariable var = new PlayerVariable();
        addVariable(variableName, var, players, true);
        return var;
    }

    public NumberVariable addNumber(String variableName){
        NumberVariable var = new NumberVariable();
        addVariable(variableName, var, numbers, true);
        return var;
    }

    private <T extends Variable<?>> void addVariable(String variableName, T variable, Map<String, T> map, boolean removable){
        if (usedVariableNames.contains(variableName)){
            throw new VariableExistsException();
        }
        usedVariableNames.add(variableName);
        map.put(variableName, variable);
        if (!removable){
            notRemovable.add(variableName);
        }
    }

    public void removeNumber(String variableName){
        removeVariable(variableName, numbers);
    }

    public void removePlayer(String variableName){
        removeVariable(variableName, players);
    }

    private <T extends Variable<?>> void removeVariable(String variableName, Map<String, T> map){
        if (notRemovable.contains(variableName)){
            throw new VariableNotRemovableException();
        }
        usedVariableNames.remove(variableName);
        map.remove(variableName);
    }

    public boolean hasPlayerVariable(String variableName){
        return players.containsKey(variableName);
    }

    public boolean hasNumberVariable(String variableName){
        return numbers.containsKey(variableName);
    }

    public Set<String> getVariableNames(){
        return usedVariableNames;
    }

    public void setPlayer(String variableName, PlayerVariable player){
        players.put(variableName, player);
    }

    public void setNumber(String variableName, NumberVariable number){
        numbers.put(variableName, number);
    }
}

All variables extend the same abstract class, so using generics is probably the preferred method, but I can't figure out a way to create a data structure that automatically picks the correct variable type without casting.


texts:
I have created a function that helps me generate pagination really easily but I am concerned about its performance mainly.

The function accepts 2 parameters:

A list of items (has meaning in the framework I'm using) which contains information about the state of pagination itself and state of the storage layer - more precisely:

page the current page
perpage how many items are being shown per page
total the total amount of items in storage.

Parameter name - allows to customize the query string parameter key, which is by default named page - http://example.com/news?page=1.

public function paginationControls(BaseList $list, $parameter = 'page') {

    if (!isset($list->pagination)) {
        return 'Error: List has not been supplied with pagination details.';
    }

    // if total results are less than the results displayed on each page
    // then do not render controls
    if ($list->pagination->perpage >= $list->pagination->total) {
        return null;
    }

    // Keep track of current query string parameters
    $query = trim(preg_replace('/' . $parameter . '\=\d+\&?/', '', $_SERVER['QUERY_STRING']), '&');
    if (strlen($query)) {
        $query .= '&';
    }
    $query .= $parameter . '=';

    $makeanchor = function($page, $current = false) use ($query) {
        if ($current) {
            $url = '#';
            $class = 'pagination anchor current';
        } else {
            $url = '?' . $query . $page;
            $class = 'pagination anchor';
        }

        return $this->a($url, $page + 1, null, ['class' => $class]);
    };

    $page = $list->pagination->page;
    $pages = ceil($list->pagination->total / $list->pagination->perpage);

    // If page is greater than 3 then display link to first page
    $output = $page > 3 ? ($makeanchor(0) . ' ... ') : '';

    // Add controls for 3 pages before current page
    $tmp = '';
    for ($i = 1; $i <= 3 && $page - $i >= 0; $i++) {
        $tmp = $makeanchor($page - $i) . $tmp;
    }

    // Add current page indicator
    $output .= $tmp . $makeanchor($page, true);

    // Add controls for 3 pages after current page
    for ($i = 1; $i <= 3 && $page + $i + 1 <= $pages; $i++) {
        $output .= $makeanchor($page + $i);
    }

    // If there are more than 3 pages after the current page
    // Then add control for last page
    if ($page + $i < $pages) {
        $output .= ' ... ' . $makeanchor($pages - 1);
    }

    return $output;
}

And here are the respective helper functions

public function a($url, $text = null, $target = null, array $attributes = array()) {

    $attributes['href'] = $url;

    if ($target !== null) {
        $attributes['target'] = $target;
    }

    if ($text === null) {
        $text = $attributes['href'];
    }

    return '<a' . $this->parseAttributes($attributes) . '>' . html($text) . '</a>';
}

private function parseAttributes($attributes) {
    $string = '';

    foreach ($attributes as $attribute => $value) {
        $string .= ' ' . html($attribute) . '="' . html($value) . '"';
    }

    return $string;
}

In a class far, far away

function html($string, $flag = ENT_QUOTES, $encoding = 'UTF-8') {
    return htmlspecialchars($string, $flag, $encoding);
}

I'm mainly interested in optimizing this function in terms of performance, it would be very much appreciated if someone more experienced than me can have a say on this.