texts: Random Delay Generator for Workflow Foundation

texts:
Problem statement: In Windows Workflow Foundation we have a long running state machine.  We had an issue with SQL server deadlocks putting workflows into a suspended state.  Since Workflow instances are independent actors, we cannot easily coordinate these calls.  As part of our workflow error handling strategy, if the offending activity receives a sql exception, we want to delay and try again and do this in a loop up to a certain number of retries.

We need a (semi) random int. Now the proper thing to do is generate one random list and use the next(min,max), but each workflow instance is an independent actor and I don't want to make a central service just for this.

My strategy, is by using the leftmost digits of DateTime->Ticks as the random seed, this will generate a random enough number for a delay activity. The plan is that eventually all workflows will advance to their next state.  Performance is not a concern. I know random is an expensive class to spin up, but I can live with it.

Example:
There are 100 workflow instances that are scheduled to change state because a new workday has started. They all want to call sql at the same time.  Workflow Instances 90,91,and 92 make calls at the same time.  90 goes through just fine, but causes a deadlock for 91 and 92.

So 91 and 92 go into a delay activity, but before we go into the delay, we need to set a somewhat random number of seconds to wait.

All Workflow Instances have a minSeconds = 10 and maxSeconds = 600

Workflow Instance 1 : never calls our random generator

Workflow Instance 2 : never calls our random generator

Workflow Instance 90: never calls our random generator

Workflow Instance 91 : hits a deadlock calls generator which returns 63

Workflow Instance 92 : hits a deadlock calls generator which returns 123

Since 91 and 92 have to wait a different number of seconds, 91 waits less time, executes, then 60 seconds later 92 wakes up from the delay and calls our large transactional stored procedure and ... no more deadlocks.

  public sealed class RandomSecondsGenerator : CodeActivity<int>
    {
        [RequiredArgument]
        public InArgument<int> MinSeconds { get; set; }

        [RequiredArgument]
        public InArgument<int> MaxSeconds { get; set; }

        /// <summary>
        /// Usage,
        /// 1. Create a workflow variable, as an int, to hold the number of seconds.
        /// 2. Create a workflow variable, as a timespan, to hold the conversion from int to timespan.
        /// Call this Activity, and set the result to the in variable
        /// Use the assignment activity to convert the int to a timespan like below
        /// timespanToWait = TimeSpan.FromSeconds(secondsToWait);
        /// Add the delay activity to the workflow ...
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        protected override int Execute(CodeActivityContext context)
        {
            var ticks = DateTime.Now.Ticks;
            var intArray = ticks.ToString().Reverse().Take(8);
            var backTogether = intArray.Aggregate("", (current, item) => current + item);
            var seed = Convert.ToInt32(backTogether);
            var rand = new Random(seed);

            var min = context.GetValue(MinSeconds);
            var max = context.GetValue(MaxSeconds);
            var secondsToWait = rand.Next(min, max);
            return secondsToWait;
        }
    }
}


texts:
This is a recursive approach using DFS to counting the number of islands. However, I would like to improve performance, while keeping the code clean concise and readable. Better yet can this be solved using bitwise operations?

var numIslands = function(grid) {

  const search = (row, col, grid) => {
    if (row < 0 || col < 0 ||
      row > grid.length - 1 || col > grid[row].length - 1 ||
      grid[row][col] === '0') {
      return;
    }
    grid[row][col] = '0';
    search(row - 1, col, grid);
    search(row, col - 1, grid);
    search(row + 1, col, grid);
    search(row, col + 1, grid);
  }
  let count = 0;
  grid.forEach((row, index) => {
    row.forEach((value, i) => {
      if (value === "1") {
        search(index, i, grid)
        count++
      }
    })
  })
  return count
}
console.log(numIslands([
  ["1", "1", "1"],
  ["1", "1", "0"],
  ["1", "1", "1"],
  ["0", "1", "0"],
  ["1", "1", "1"]
]))

console.log(numIslands([
  ["1", "1", "1"],
  ["0", "0", "0"],
  ["1", "1", "1"],
  ["0", "0", "0"],
  ["1", "1", "1"]
]))


texts: Way to delegate command to methods in different files

texts:
What I want to do is for an example command have it defined in its own file - e.g. command.js - and the same for the other methods. I want to make a separate file for every module - for example "command.js", "vanish.js" and I can not think of a way to call the methods without making a big switch statement in a file where I would require all the "modules".
This is how I do it currently:
const client = require('../../../src/bot');
const logger = require('../../../config/logger');
const {isCommand} = require('../../../helpers/checkCommand');
const {addCommand, deleteCommand, updateCommand} = require('../../../db/commandFunctions')
const isAuthorized = require('../isAuthorized');
const builtInCmdHelpers = require('../builtInCommandHelpers');

const USER_MODULES = 'everyone';
const MOD_MODULES = 'moderator';

const executeBuiltInCommand = async ({channel, args}, userstate) => {
  const isSubArg = await isCommandSubArg(args[1]);
  if(isSubArg) await builtInCmdHelpers[args[1]].apply(null, [{channel, args}, userstate]);
};

const command = async ({channel, args}, userstate) => {
  const canExecute = await isAuthorized(channel, userstate.badges, MOD_MODULES);
  if(canExecute) await executeBuiltInCommand({channel, args}, userstate);
};

const vanish = async ({channel}, {username}) => {
  const canExecute = await isAuthorized(channel, username, USER_MODULES);
  if(canExecute) {
    client.timeout(channel, username, 1, "VANISH")
      .catch((err) => {
      logger.error(err);
    });
  }
};

module.exports = {
  command,
  vanish,
};

This is how i execute the commands currently:
const executeBuiltIn = async ({channel, args}, userstate) => {
  await builtin[args[0]].apply(null, [{channel, args}, userstate]);
};


texts:
Similar to other GTIN validations, the function should take the entire string of the read in barcode, calculate the check digit, and compare it to the check digit on the code. For example, the code 6291041500213 would take the first 12 digits (629104150021) and calculate the answer of 3.

this code should work for GTIN-8, GTIN-12, GTIN-13, GTIN-14, GSIN, SSCC.

I was hoping to get some feedback on the test cases and on the code itself on where it can be DRYed or made more explicit. I realized later on that Elixir now has a built in mod fuction which I'll switch to (I read an older Jose article that said it did not)...I think I need to also clean up the areas where it returns {:ok} and {:error}.

Code:

  @doc """
  Check for valid  GTIN-8, GTIN-12, GTIN-13, GTIN-14, GSIN, SSCC codes

  Returns `{:ok}` or `{:error}`

  ## Examples

      iex> gtin_check_digit("6291041500213")
      {:ok}

      iex> gtin_check_digit("6291041500214")
      {:error}
  """
  @spec gtin_check_digit(string) :: { atom }
  def gtin_check_digit(number) do
    {code, check_digit} = String.split_at(number, String.length(number) - 1)
    calculated_check_digit = code
      |> multiply_and_sum_array
      |> subtract_from_nearest_multiple_of_ten

    case calculated_check_digit == String.to_integer(check_digit) do
      true -> {:ok}
      _ -> {:error}
    end
  end

  @doc """
  Calculates the sum of the digits in a string and multiplied value based on index order

  Returns sum of values

  ## Examples

      iex> multiply_and_sum_array("629104150021")
      57

  """
  @spec multiply_and_sum_array(string) :: number
  def multiply_and_sum_array(number) do
    number
      |> String.codepoints
      |> Enum.map(fn(x) -> String.to_integer(x) end)
      |> Enum.reverse
      |> Stream.with_index
      |> Enum.reduce(0, fn({num, idx}, acc) ->
        acc + (num * mult_by_index_code(idx))
      end)
  end

  @doc """
  Calculates the difference of the highest rounded multiple of 10

  Returns the difference of the highest rounded multiple of 10

  ## Examples

      iex> subtract_from_nearest_multiple_of_ten(57)
      3

  """
  @spec subtract_from_nearest_multiple_of_ten(number) :: number
  def subtract_from_nearest_multiple_of_ten(number) do
    mod(10 - mod(number, 10), 10)
  end

  #def mult_by_index_code(index) when mod(index, 2) == 0, do: 3 #these did not work because I cannot call mod within the `when`
  #def mult_by_index_code(index), do: 1
  def mult_by_index_code(index) do
    case mod(index, 2) do
      0 -> 3
      _ -> 1
    end
  end

  defp mod(x,y) when x > 0, do: rem(x, y);
  defp mod(x,y) when x < 0, do: rem(y+x, y);
  defp mod(0,_y), do: 0

Tests

 test "gtin_check_digit function with valid number" do
    number = "6291041500213"
    assert {:ok} == gtin_check_digit(number)
  end

  test "gtin_check_digit function with invalid number" do
    number = "6291041500214"
    assert {:error} == gtin_check_digit(number)
    assert {:error} == gtin_check_digit("6291041533213")
  end

  test "mult_by_index_code function" do
    assert mult_by_index_code(1) == 1
    assert mult_by_index_code(2) == 3
    assert mult_by_index_code(3) == 1
    assert mult_by_index_code(4) == 3
  end

  test "multiply_and_sum_array function" do
    number = "629104150021"
    #number = [6,2,9,1,0,4,1,5,0,0,2,1]
    assert 57 == multiply_and_sum_array(number)
  end

  test "subtract_from_nearest_multiple_of_ten function" do
    assert 3 == subtract_from_nearest_multiple_of_ten(57)
  end

As I refine this, I'll create a hex package to use a common utility library for the elixir community.


texts: Working on key-value disk cache written in plain C. Is there any errors?

texts:
I'm an objective-c developer. But i'm getting familar with C. I wrote it for my own develpment in C. Please point on some errors!

The point is to store/read bytes in file named "key" in cachePath directory.

Cache.h

typedef const struct Cache *CacheRef;

/* Returns cache reference for corresponding cache path */
/* NOTE: cache path should exist */

CacheRef CacheAtPath(const char *cachePath);

/* Sets bytes for key */
/* Returns 0 if failed */

int SetBytesForKey(CacheRef cache, const void *bytes, unsigned long length, const char *key);

/* Gets bytes for key */
/* Returns 0 if failed */

int GetBytesForKey(CacheRef cache, void **bytes, unsigned long *length, const char *key);

Cache.c

#include "Cache.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

struct Cache {
    char *path;
};

char *_FilePathForKey(CacheRef cache, const char *key);
FILE *_FileForKey(CacheRef cache, const char *key, const char *access);

char *_FilePathForKey(CacheRef cache, const char *key){
    size_t pathLength = strlen(cache->path) + strlen(key);
    char *path = malloc(pathLength);
    strcpy(path, cache->path);
    strcat(path, key);

    return path;
}

FILE *_FileForKey(CacheRef cache, const char *key, const char *access)
{
    char *filePath = _FilePathForKey(cache, key);
    if (filePath == NULL) return NULL;

    FILE *file = fopen(filePath, access);

    free(filePath);

    return file;
}

CacheRef CacheAtPath(const char *cachePath){
    struct Cache *cache = malloc(sizeof(struct Cache));
    cache->path = malloc(strlen(cachePath));
    strcpy(cache->path, cachePath);
    return (CacheRef)cache;
}

int SetBytesForKey(CacheRef cache, const void *bytes, unsigned long length, const char *key)
{
    if (cache == NULL) return 0;

    FILE *file = _FileForKey(cache, key, "wb");

    if (file == NULL) return 0;

    int result = (int)fwrite(bytes, length, 1, file);

    fclose(file);

    return result;
}

int GetBytesForKey(CacheRef cache, void **bytes, unsigned long *length, const char *key)
{
    void *buffer = NULL;
    size_t bufferSize = 0;

    FILE *file = _FileForKey(cache, key, "rb");

    if (file == NULL) return 0;

    fseek(file, 0, SEEK_END);
    bufferSize = ftell(file);
    fseek(file, 0, SEEK_SET);

    buffer = malloc(bufferSize);

    int result = 0;
    if (buffer) {
        result = (int)fread(buffer, bufferSize, 1, file);
        if (result) {
            *length = bufferSize;
            *bytes = buffer;
        } else {
            *length = 0;
            *bytes = NULL;
        }
    }
    fclose(file);

    return result;
}


texts:
In an effort to learn  C# / improve my coding skills, I've started working on the Project Euler problems. I see that I may have been overthinking things a bit after finishing problem 7:

  By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can
  see that the 6th prime is 13.

  What is the 10 001st prime number?

But even so I believe that my solution should be faster than what is presented in the problem overview. While this may not be an issue when searching for a "small" number of primes, the previous problems have focused quite a bit on optimizing the codes so I am wondering if I have missed something  obvious.

In other words, how does my code compare to the pseudocode presented in the overview of the problem? Are there any obvious mistakes I make in my code?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Diagnostics;

namespace ProjectEulerTasks
{
    class Program
    {
        static void Main(string[] args)
        {
            int no_of_primes_found = 0;
            int current_number = 0;
            List<int> found_primes = new List<int>();
            bool n_minus_found = false;
            bool n_plus_found = false;

            found_primes.Add(2);
            found_primes.Add(3);
            found_primes.Add(5);
            found_primes.Add(7);
            found_primes.Add(11);
            found_primes.Add(13);

            current_number = 12;
            no_of_primes_found = 6;

            while (no_of_primes_found < 10001)
            {
                current_number += 6;
                n_minus_found = false;
                n_plus_found = false;
                foreach (int current_prime in found_primes)
                {
                    if (!n_minus_found && (current_number - 1) % current_prime == 0)
                    {
                        n_minus_found = true;
                    }
                    if (!n_plus_found && (current_number + 1) % current_prime == 0)
                    {
                        n_plus_found = true;
                    }
                    if (n_minus_found && n_plus_found)
                    {
                        break;
                    }
                }
                if (!n_minus_found)
                {
                    found_primes.Add(current_number - 1);
                    no_of_primes_found = no_of_primes_found + 1;
                }
                if (!n_plus_found && no_of_primes_found < 10001)
                {
                    found_primes.Add(current_number + 1);
                    no_of_primes_found = no_of_primes_found + 1;
                }
            }
            System.Diagnostics.Debug.Print(Convert.ToString(no_of_primes_found));
            System.Diagnostics.Debug.Print(Convert.ToString(found_primes[found_primes.Count - 1]));
        }
    }
}

Project Euler pseudocode:


texts: Loading text into an array when fields are in random order

texts:
This script reads records from a CSV file of customer names and addresses. The first record of the file is the header (field names); the fields could be in any order, and sometimes have different variations on the field names.

I import the header into a one-dimensional array of field names, and use this loop to assign a variable to each column number:

' Read the first line from the file.
  TextLine = MyFile.ReadLine

' Split the line into an array
  arrCustomers = Split(TextLine, ",")

For i = 0 To  UBound(arrCustomers, 1)
    Select Case LCase(arrCustomers(i))
        case "customer name", "custname", "name"
              CustName  = i
        case "customer number", "custno","custnum"
              CustNo  = i
        case "address", "street"
              Address = i
        case "city"
              City = i
        case "country"
              Country = i
        case "state"
              State = i
        case else
            ' list of unused fields
            s = s & ", " & arrCustomers(i)
    End Select
Next

msgbox "These fields are unused: " & s

For instance, if "Customer Name" is in field 3, then CustName = 3 and arrCustomers(CustName) is the Customer Name field of the current record.

This loop processes each record:

Do While MyFile.AtEndOfStream <> True
  ' Read the first line from the file.
    TextLine = MyFile.ReadLine
  'Split the line into an array
    arrCustomers = Split(TextLine, ",")
  'Process the current record
    msgbox "Our customer " & arrCustomers(CustName) & " lives in " & arrCustomers(City) & ", " & arrCustomers(State)
Loop

My main problem is that the Case statements in the first loop must include every possible value for the field names. If the address field is called "Address1" or something else I didn't forsee, the Address variable becomes 0, and arrCustomers(Address) becomes the same as whatever's in the first column.

I suspect that there's a well-known algorithm somewhere for loading an array when the fields could be different each time – one that's better than my method. If not, maybe there's a way to map the "unused fields" on the fly?


texts:
As writing code to handle error-checked input or to present functions to execute to the user is boring and error-prone, I wrote a module to automate these tasks:

user_interface.py

def general_input(prompt="", type_=str, min_=None, max_=None,
                  max_length=None, set_=None, cap_sensitive=True,
                  help_=lambda: 0):
    """
    Takes care of input validation, by diplaying meaningful
    messages to the user in case of invalid input.

    @ prompt: The text to be shown to the user.
    @ type_: The type the input must be convertible to. (And will be converted to).
    @ max_length: The maximum length of the input.
    @ set_: The set of things the input must in. (This may be a `range` object or any iterable).
    @ cap_sensitive: If False the input will be lowercased. (Defult True)
    @ help_: What to do when the user types in `help`
    """
    while True:
        input_ = input(prompt)
        input_ = input_ if cap_sensitive else input_.lower()
        if input_ == "help":
            help_()
            continue
        try:
            if not type_:
                type_ = type(input_)
            input_ = type_(input_)
        except ValueError:
            print("Expected input of type {} but got {}".format(
                type_, type(input_)))
            continue
        if max_length and len(input_) > max_length:
            print("Input is too long, the max length allowed is {}".format(
                max_length))
            continue
        if set_ and input_ not in set_:
            # Fixing that the last item in ranges is exclusive (weird for normal users)
            to_print_set = None
            if type(set_) == range:
                to_print_set = range(min(set_), max(set_))
            print("Input is not in the set of possible inputs, enter one of {}".format(
                to_print_set or set_))
            continue
        return input_

def menu(functions):
    """
    Allows for easy presentation to the user of functions, also
    allowing him to get fast help.
    """
    functions = list(sorted(functions, key=lambda fun: fun.__name__))
    for index, func in enumerate(functions):
        print("{} - {}".format(
            index + 1, func.__name__))
    def help_():
        function_to_be_explained = general_input("Which function do you want help on? ",
                                type_=int, set_=range(0,len(functions))) - 1
        help(functions[function_to_be_explained])

    user_choice = general_input("Which function do you want to execute? (Type `help` for help). ",
                                type_=int, set_=range(0,len(functions)+1),
                                help_= help_) - 1
    print(functions[user_choice](eval(input("Comma separated args for `{}`: ".format(
          functions[user_choice].__name__))))); print()

def menu_for_module(module, private_shown=False):
    """
    Shows a menu containing all the functions in a module
    """
    priv_cond = lambda fun: fun.__name__.startswith('_') if not private_shown else False
    menu([i for i in module.__dict__.values() if type(i) == type(lambda:0) and not priv_cond(i)])


texts: Scan files and pick overlapped hex codes

texts:
Problem

Two folders having files with nameEfile that store lines starting with hex codes.

Print those hex codes that overlap in both folders.

Solution

import os
import sys
import re

def process_cache(cache):
    event_code_set = set()
    for file_name, multi_line_content in cache.items():
        if file_name.endswith('Efile'):
            for line in multi_line_content.splitlines():
                line = line.rstrip('\\') # trailing backslash, if exist
                if bool(re.search(r'^0[xX][0-9a-fA-F]+', line)):
                    # Take the hexcode
                    obj = re.search(r'^0[xX][0-9a-fA-F]+', line)
                    event_code_set.add(obj.string[obj.start():obj.end()])
    return event_code_set

def scan_files(dir):
    cache = {}
    for root, dirs, files in os.walk(dir):
        for name in files:
            if name in ('Efile'):
                path = os.path.join(root, name)
                with open(path,'r') as file:
                    cache[path] = file.read()
    return cache

cache1 = scan_files(sys.argv[1])
cache2 = scan_files(sys.argv[2])

cache1_event_code_set = process_cache(cache1)
cache2_event_code_set = process_cache(cache2)

overlap_event_codes = cache1_event_code_set & cache2_event_code_set
print(overlap_event_codes)

For a typical three entries in a file, with comments(#),

0x00010d35 D 11 G 3,0x10009,N R XY.Condition,   "({a 0x40001} == {H 0x166}) && ({a 0x11ff8} == {I 15})","0x0763ffc2 "
# Below event codes are from vendor xyz
0x84900c5 M 22 Y 1,0x03330469,4,5,6,7,8
0x04b60ff6 L 50 U \
          0x04c60e07,102 && ({a 0x11ff8} == {I 15})","0x0763ffc2 "

Picking 0x00010d35, 0x04b60ff6 & 0x84900c5 is the task. Rest of the line is supposed to be ignored

Some entries are multi-line with trailing backslash.

Each file is in megabytes. Total files in both folders - 80

1) Please suggest optimization in the below code, because pattern check is done twice.

        if bool(re.search(r'^0[xX][0-9a-fA-F]+', line)):
            # Take the hexcode
            obj = re.search(r'^0[xX][0-9a-fA-F]+', line)
            event_code_set.add(obj.string[obj.start():obj.end()])

2) Please suggest coding style optimizations for tree walk, cache and command line arguments.


texts:
I have started working on the code below here. I want to practice my C coding skills.

It is a grading program: given a set of subject marks, calculates the sum, average and it converts the computed average to an alphabetic grade letter.

I would love to be pointed out any mistakes that I have made or any opinions to make my code more presentable.

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

int main()
{
    char name[100];
    int physics,chemistry,maths,biology,business,total_marks;
    // physics,chemistry,maths,biology,business are just but subjects names.
    float mean;

    printf("Please enter your name \n");
    fgets(name,100,stdin);
    {

    printf("Please enter the marks for physics \n");
    scanf("%d",&physics);

    printf("Please enter the marks for chemistry \n");
    scanf("%d",&chemistry);

    printf("Please enter the marks for maths \n");
    scanf("%d",&maths);

    printf("Please enter the marks for biology \n");
    scanf("%d",&biology);

    printf("Please enter the marks for business\n");
    scanf("%d",&business);

    total_marks=physics+chemistry+maths+biology+business;
    mean= (float)total_marks/5;}

    printf("%s\t",name);
    printf(" HAS TOTAL MARKS OF : %d,\t",total_marks);
    printf(" MEAN OF :  %.2f\t",mean, round(mean) );

if (mean>=70)
   printf("AND THE  GRADE IS A  \n");

if(mean>=60 && mean<69)
   printf("AND THE  GRADE IS B  \n");

if(mean>=50 && mean<59)
   printf("AND THE  GRADE IS C  \n");

if(mean>=40 && mean<49)
   printf("AND THE  GRADE IS D  \n");

if (mean<40)
   printf("AND THE  GRADE IS E \n");

   printf(" Thank you for your time  \n");

   return 0;
}


texts: Calculate someone's pay, including overtime

texts:
In this problem, you need to calculate someone's pay by multiplying their salary (double)by the hours (int) worked. If they worked for more than 8 hours, you pay them 1.5 times their salary for however many hours more they worked.
Here is my solution.

public static double pay(double a, int b) {
if (b > 8) {
    return (a * 8) + ((b - 8)*(a * 1.5));
}
else {
    return (a * b);
}}

Wondering if there is any way to do it without if else statements since the course hasn't taught those yet.


texts:
Are there any ways to make this calculator script for Python better or simpler?

thelist = ["Add", "add", "Multiply", "multiply", "Divide", "divide","Subtract", "subtract"]

def Multiply(x,y):
z = x * y
print(z)

def Divide(x,y):
x = float(x)
y = float(y)
z = x / y
print(z)

def Add(x,y):
z = x + y
print(z)

def Subtract(x,y):
z = x - y
print(z)

while True:
    operation = input("What would you like to do? Multiply/Divide/Add/Subtract ")
    if operation in thelist:
        break
    else:
        print("That was not an option..")

if operation == "Multiply" or operation == "multiply":
    while True:
        try:
            x = int(input("First number: "))
            break
        except ValueError:
            print("Make sure to enter a number.")
    while True:
        try:
            y = int(input("Second number: "))
            break
        except ValueError:
            print("Make sure to enter a number...")
    Multiply(x,y)
elif operation == "subtract" or operation == "Subtract":
    while True:
        try:
            x = int(input("First number: "))
            break
        except ValueError:
            print("Make sure to enter a number.")
    while True:
        try:
            y = int(input("Second number: "))
            break
        except ValueError:
            print("Make sure to enter a number.")
    Subtract(x,y)
elif operation == "Add" or operation == "add":
    while True:
        try:
            x = int(input("First number: "))
            break
        except ValueError:
            print("Make sure to enter a number..")
    while True:
        try:
            y = int(input("Second number: "))
            break
        except ValueError:
            print("Make sure to enter a number.")
    Add(x,y)
elif operation == "Divide" or operation == "divide":
    while True:
        try:
            x = int(input("First number: "))
            break
        except ValueError:
            print("Make sure to enter a number.")
    while True:
        try:
            y = int(input("Second number: "))
            break
        except ValueError:
            print("Make sure to enter a number.")
    Divide(x,y)
else:
    pass


texts: Coding style and best practice regarding exception-handling

texts:
I need comments on my JPA code. Am I doing it correctly? I need some advice on best practices in Java.

I have this method below:

public Comics add(Comics comics) {
    EntityManager em = EMF.get().createEntityManager();
    EntityTransaction tx = null;
    try{
        tx = em.getTransaction();
        tx.begin();

        em.persist(comics);

        tx.commit();
    }catch(Exception ex){
        ex.printStackTrace();
        if(tx != null && tx.isActive())
            tx.rollback();
    } finally{
        em.close();
    }

    return comics;
}

When I called the method, I just have:

ComicsAccess access = new ComicsAccess();
access.add( comics );

I got no error on the above code, what I want are some suggestions on my coding style. Is the above good code if used in production?


texts: Outputting the Manufacturer ID of a processor using CPUID with inline ASM

texts:
This outputs the manufacturer string associated with your CPU using the CPUID instruction. I wrote this up for a homework assignment, then found out that I didn't need to.

When run on my (virtual) machine, I get the following output:

EAX: 16
EBX: 756e6547
ECX: 6c65746e
EDX: 49656e69

GenuineIntel

What I'd like commented on:

I'm not super-proficient yet in bit manipulation. Originally, print_register had a for loop that iterated the mask directly, like

for (int32_t mask = 0xFF;; mask <<= 8) {

This worked until I realized that I needed to right-shift the result of the bitwise AND, and couldn't figure out how to get the bits shifted from the mask. I ended up going for a less efficient solution of iterating bit-counts and creating the mask each iteration. This feels like a naïve approach though.
Anything else notable. I'm starting to venture into increasingly unknown territory here, so anything would help.

Note that although inline asm seems to be considered bad practice to use in many cases, using it was the point of the exercise here. I know wrapper macros exist that would clean this up a bit.

#include <stdio.h>
#include <stdint.h>

void print_register(int32_t reg_value) {
    for (int shifted = 0; shifted < 0x20; shifted += 8) {
        int32_t mask = 0xFF << shifted;
        int32_t matched = (reg_value & mask) >> shifted;
        printf("%c", matched);
    }
}

int main() {
    int32_t out_eax = -1;
    int32_t out_ebx = -1;
    int32_t out_ecx = -1;
    int32_t out_edx = -1;

    int32_t leaf = 0;

    asm volatile ("cpuid"
                  :  "=a"(out_eax),  // 0
                     "=b"(out_ebx),
                     "=c"(out_ecx),
                     "=d"(out_edx)
                  :  "0"(leaf));

    printf("EAX: %x\nEBX: %x\nECX: %x\nEDX: %x\n\n",
           out_eax, out_ebx, out_ecx, out_edx);

    print_register(out_ebx);
    print_register(out_edx);
    print_register(out_ecx);

    printf("\n");
}


texts: Replace2 using start and end rather than length

texts:
If you already know the start and ending character positions of text you want to replace, this bypasses the need to calculate the length. It just helps eliminate a step by not requiring you to calculate the length because this uses start_num and end_num directly as parameters. It can be used as an Excel function or a VBA function.
Public Function Replace2(ByVal old_text As String, _
                  ByVal start_num As Long, _
                  ByVal end_num As Long, _
                  ByVal new_text As String) As String
    'Replaces old_text from character positions start_num to end_num with new_text;
    '   does not delete any old_text characters when end_num < start_num.
    '   e.g. when end_num is 0.

    'Replace2 is designed to help when it's more convenient to code using start and
    '   end positions rather than being forced to calculate a length.

    'Replace2 can be used as an Excel or VBA function as an alternative to the
    '   Worksheet.Replace function with the following design differences:
    '      1. Replace2 uses a start_num and end_num pair rather than a start_num
    '         with a length.
    '      2. Replace2 is also more forgiving of parameter error, it's designed to
    '         properly interpret and correct start_num and end_num value errors. E.g.
    '         This ensures the start_num falls between 1 and old_text length + 1
    '            and ensures the end_num falls between 0 and old_text length.
    '      3. An end_num of 0 or end_num < start_num does not delete any old_text characters.
    '      4. new_text is inserted just prior to the start_num position in the old_text.

    Dim LenOldText As Long
    LenOldText = Len(old_text)
    If start_num < 1 Then start_num = 1
    If end_num < 0 Then end_num = 0
    If start_num > LenOldText Then start_num = LenOldText + 1
    If end_num > LenOldText Then end_num = LenOldText
    If end_num < start_num Then end_num = start_num - 1
    Replace2 = Left(old_text, start_num - 1) & new_text & Right(old_text, LenOldText - end_num)
End Function


texts:
I have written code to get all the MAC addresses in from systems having multiple MAC addresses and I think there's something which needs to be corrected albeit the code runs fine.

Note: I have just tested it on Android.

import re

def getMacs():
    macs = []
    file = os.popen("getmac").read()
    file = file.split("\n")

    for line in file:
        found = re.search(r'([0-9A-F]{2}[:-]){5}([0-9A-F]{2})', line, re.I)
        if found:
            mac = found.group().replace('-', ':')
            macs.append(mac)

    return macs


texts:
I have the following ajax call and if it errors, I have a default error message stored in a constant which I'll use if the response doesn't contain a custom message. When I look at this, I keep thinking it could be done better. Can anyone suggest how I can do it better?

function requestService(){
            $.ajax({
                dataType: 'json',
                type: 'POST',
                url: '/myurl',
                contentType: CONTENT_TYPE,
                timeout: AJAX_TIMEOUT,
                success: function(data, textStatus, jqXHR){
                    populateData(JSON.parse(jqXHR.responseText))
                },
                error: function(err){
                    var errorMessage = AJAX_ERROR;
                    try {
                        errorMessage = JSON.parse(err.responseText).messages.messages[0].description;
                    }
                    catch(error) {
                        //There was an problem finding an error message from the server. The default message will be used.
                    }
                    displayError(errorMessage)
                },
                complete: function(){
                    console.log("complete");
                }
            });
        };


texts: Calculate AB significance with Control and Treatment Objects

texts:
I am working on an AB tool in JavaScript using the following:

Calculate the Conversion rate based on the conversions divided by the hits.
Calculate the Z Score by passing in the control and treatment objects.
Determine the confidence of the Z Score with Cumulative Normal Distribution.

How accurate is this?

/**
  Example input:

  var a = {
    'hits' : 15,
    'conversions' : 2
    };

  var b = {
     'hits' : 15,
     'conversions' : 6
  };
 */

/**
 * Calculation of conversion rate
 * @param t
 * @returns {number}
 */
function cr(t) {
    return t.conversions / t.hits;
}

/**
 * Calculation of score
 * @param c
 * @param t
 */
function calcZScore(c, t) {
    var z = cr(t) - cr(c);
    var s = (cr(t) * (1 - cr(t))) / t.hits + (cr(c) * (1 - cr(c))) / c.hits;
    return Math.sqrt(s);
}

/**
 * Calculate the Cumulative Normal Distribtion
 *
 * @param x
 * @returns {number}
 */
function cumNorDist(x) {
    var b1 = 0.319381530;
    var b2 = -0.356563782;
    var b3 = 1.781477937;
    var b4 = -1.821255978;
    var b5 = 1.330274429;
    var p = 0.2316419;
    var c = 0.39894228;

    if (x >= 0.0) {
        t = 1.0 / ( 1.0 + p * x );
        return (1.0 - c * Math.exp(-x * x / 2.0) * t *
        ( t * ( t * ( t * ( t * b5 + b4 ) + b3 ) + b2 ) + b1 ));
    } else {
        t = 1.0 / ( 1.0 - p * x );
        return ( c * Math.exp(-x * x / 2.0) * t *
        ( t * ( t * ( t * ( t * b5 + b4 ) + b3 ) + b2 ) + b1 ));
    }
}

/**
 * Given a conversion rate, calculate a recommended sample
 * size
 * E.g: 0.25 worst, 0.15, 0.05 best at a 95% confidence
 * @param conv
 * @returns {Array}
 */
function sampleSize(conv) {
    var a = 3.84145882689;
    var res = [];
    var bs = [0.0625, 0.0225, 0.0025];
    var len = bs.length;
    for (var i = 0; i < len; i++) {
        res.push(((1 - conv) * a / (bs[i] * conv)));
    }
    return res;
}

/**
 * Calculate the significance between Control and Treatment [A/B/C]
 *
 * @param controlObj
 * @param treatmentObj
 */
function calculateSig(controlObj, treatmentObj) {

    if (typeof controlObj !== 'object') {
        console.log(outputErrorFor('Control Object'));
    }

    if (typeof controlObj !== 'object') {
        console.log(outputErrorFor('Control Object'));
    }

    var zScore;
    var confidence;
    var confidencePercentage;
    var cRatio;

    var cNumHits = controlObj.hits;
    var cNumConver = controlObj.conversions;
    var tNumHits = treatmentObj.hits;
    var tNumConver = treatmentObj.conversions;

    var cConversionRate = (cNumConver / cNumHits) * 100;
    var tConversionRate = (tNumConver / tNumHits) * 100;

    cConversionRate += '%';
    tConversionRate += '%';

    zScore = calcZScore(controlObj, treatmentObj);
    confidence = cumNorDist(zScore);
    confidencePercentage = confidence * 100;

    console.log("Control Hits is:", cNumHits);
    console.log("Control Conversions is:", cNumConver);
    console.log("Treatment Hits is:", tNumHits);
    console.log("Treatment Conversions is:", tNumConver);

    console.log("Results are in:");

    console.log("Control Conversion Rate is:", cConversionRate);
    console.log("Treatment Conversion Rate is:", tConversionRate);

    console.log("Z Score is:", zScore);
    console.log("Confidence is:", confidence);
    console.log("Confident percentage is:", confidencePercentage);
}

/**
 *
 * @param name
 * @returns {string}
 */
var outputErrorFor = function (name) {
    return 'The passed in parameter must be an object and contain two properties: "hits" and "conversions" for: ' + name;
};

This is a ported version of this repo. (credit to the author)

Side note: With the Z Score, how can I find the P Value?


texts: Collision Detection in a 2D shooter game

texts:
I have the following code that works just fine for collision detection. The only problem is its size and its performance. I'm trying to do it and many other things 60 times per second, which doesn't work out very well. Is there any way to condense it as it's much the same stuff over and over again?

for(int x=0; x<40; x++) {
     for(int y=0; y<28; y++) {
        if(tiles[x][y]==0) {
            if(keyManager.up) {
                Rectangle player = new Rectangle(you.getX(), you.getY()-1, 10, 10), tile = new Rectangle(x*25, y*25, 25, 25);
                if(player.intersects(tile)) {
                    return;
                }
                if(x==39 && y==27) {
                    you.setY(you.getY()-1);
                }
            } if(keyManager.down) {
                Rectangle player = new Rectangle(you.getX(), you.getY()+1, 10, 10), tile = new Rectangle(x*25, y*25, 25, 25);
                if(player.intersects(tile)) {
                    return;
                }
                if(x==39 && y==27) {
                    you.setY(you.getY()+1);
                }
            } if(keyManager.left) {
                Rectangle player = new Rectangle(you.getX()-1, you.getY(), 10, 10), tile = new Rectangle(x*25, y*25, 25, 25);
                if(player.intersects(tile)) {
                    return;
                }
                if(x==39 && y==27) {
                    you.setX(you.getX()-1);
                }
            } if(keyManager.right) {
                Rectangle player = new Rectangle(you.getX()+1, you.getY(), 10, 10), tile = new Rectangle(x*25, y*25, 25, 25);
                if(player.intersects(tile)) {
                    return;
                }
                if(x==39 && y==27) {
                    you.setX(you.getX()+1);
                }
            }
        }
    }
}


texts:
I thought it would be a good idea to take some easy to solve (by hand) problems and model them in Prolog for practice. Here is a problem I modeled in Prolog:

  A messy kid wrote a multiplication problem.

  Alice saw 100 x 6.
  Bob saw 101 x 6.
  Dan saw 102 x 9.

  Each one only misread one digit. What is the real solution to the problem?

It proved to be (much) trickier to model than solve by hand, but here is what I came up with:

%- Read person saw number at position.
saw(alice, 1, 0).
saw(alice, 0, 1).
saw(alice, 0, 2).
saw(alice, 6, 3).

saw(bob, 1, 0).
saw(bob, 0, 1).
saw(bob, 1, 2).
saw(bob, 6, 3).

saw(dan, 1, 0).
saw(dan, 0, 1).
saw(dan, 2, 2).
saw(dan, 9, 3).

%- Consider the case when two people see one number and one person saw a anoth-
% er number. This doesnt actually mean the person "definitely" misread the nu-
% mber, but if the problem can be solved it measns they definitely did.
definitely_misread(Person, Digit, Position) :-
  saw(Person, Digit, Position),
  saw(Q, D, Position), Q \== Person, D \== Digit,
  saw(R, D, Position), R \== Q, R \== Person.

%- Read a person misread the digit at poisition at position.
misread(Person, Digit, Position) :-
  saw(Person, Digit, Position),
  not((definitely_misread(Person, D, P), D \== Digit, P \== Position)),
  (saw(Q, D1, Position), Q \== Person, D1 \== Digit),
  (saw(R, D2, Position), R \== Q, R \== Person, D2 \== Digit).

%- Resolve if the question is actually the correct digit at that position.
correct(Digit, Position) :-
  (saw(alice, Digit, Position), not(misread(alice, Digit, Position)));
  (saw(bob, Digit, Position), not(misread(bob, Digit, Position)));
  (saw(dan, Digit, Position), not(misread(dan, Digit, Position))).

And thus one can get the correct solutions by calling correct (although, it displays some digit position pairings multiple times):

?- correct(D, P).
D = 1,
P = 0 ;
D = 0,
P = 1 ;
D = 6,
P = 3 ;
D = 1,
P = 0 ;
D = 0,
P = 1 ;
D = 6,
P = 3 ;
D = 1,
P = 0 ;
D = 0,
P = 1 ;
D = P, P = 2 ;
false.


texts: java.sql.Timestamps: There's gotta be an easier way

texts:
I have a function that counts how many "assists" a team performs during the course of their day.  The way I've written it feels bulky and inefficient using GregorianCalendar.

Basically, the function counts specific types of assistance then returns the information in an object.

Does anyone know of a cleaner way to do this?

public static AssistReportData getAssistReportByDate(int teamId, Date date) throws ClassNotFoundException, SQLException {
    AssistReportData ard = null;
    Connection conn = getConnection();

    String query = "SELECT assistanceProvided FROM fauassist WHERE teamId=? AND timeOut BETWEEN ? AND ?;";

    PreparedStatement ps = conn.prepareStatement(query);
    ps.setInt(1, teamId);
    GregorianCalendar gc = new GregorianCalendar();
    gc.setTime(date);
    gc.set(Calendar.HOUR, 0);
    gc.set(Calendar.MINUTE, 0);
    gc.set(Calendar.SECOND, 0);
    ps.setTimestamp(2, new java.sql.Timestamp(gc.getTime().getTime()));
    GregorianCalendar gc2 = new GregorianCalendar();
    gc2.setTime(date);
    gc.set(Calendar.HOUR, 59);
    gc.set(Calendar.MINUTE, 59);
    gc.set(Calendar.SECOND, 59);
    ps.setTimestamp(3, new java.sql.Timestamp(gc2.getTime().getTime()));

    ResultSet rs = ps.executeQuery();
    while (rs.next()) {
        ard = new AssistReportData();
        ard.setTeam(teamId);
        switch (rs.getString("assistanceProvided")) {
            case ("TEAM EFFORT"):
                ard.addTeamEffort(1);
                break;
            case ("OUTSIDE AGENCY"):
                ard.addOutsideAgency(1);
                break;
            case("SEARCH WARRANT"):
                ard.addSearchWarrant(1);
                break;
            case("TRANSPORT"):
                ard.addTransport(1);
            default:
        }
    }
    return ard;
}


texts: Determine if 2 lists with similar objects contain a partial duplicate

texts:
I have two lists of Person objects. I need to compare the lists to determine if items in list1 exist in list2 and vice versa.

This is not a straight equals() scenario as the objects are not the same, but may have identical field values. It is those values that I need to compare.

Currently, I am using Java 8's Streams API to return either a match or null:

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

public class Main {

    public static void main(String[] args) {

        ArrayList<Person> originalPeople = new ArrayList<>();
        ArrayList<Person> newPeople = new ArrayList<>();

        originalPeople.add(new Person("William", "Tyndale"));
        originalPeople.add(new Person("Jonathan", "Edwards"));
        originalPeople.add(new Person("Martin", "Luther"));

        newPeople.add(new Person("Jonathan", "Edwards"));
        newPeople.add(new Person("James", "Tyndale"));
        newPeople.add(new Person("Roger", "Moore"));

        // Create a list of people that no longer exist in the new list
        for (Person original : originalPeople) {
            if (getPersonInList(
                    newPeople, original.getFirstName(), original.getLastName()) == null) {
                System.out.printf("%s %s is not in the new list!%n",
                        original.getFirstName(), original.getLastName());
            }
        }
    }

    private static Person getPersonInList(
            final List<Person> list, final String firstName, final String lastName) {

        return list.stream()
                .filter(t -> t.getFirstName().equalsIgnoreCase(firstName))
                .filter(t -> t.getLastName().equalsIgnoreCase(lastName))
                .findFirst().orElse(null);
    }
}

class Person {

    private final String firstName;
    private final String lastName;

    Person(String firstName, String lastName) {
        this.firstName = firstName;
        this.lastName = lastName;
    }

    String getFirstName() {
        return firstName;
    }

    public String getLastName() {
        return lastName;
    }
}

In my real-world application, however, both lists have over 30,000 items and this is very time-consuming.

Is there a better way to perform this comparison? I would want this to work both ways as well, so if there are items in newPeople that were not in originalPeople, I would want that list as well.


texts: Break music player into usable components in SwiftUI

texts:
I created a music player using swiftUI.I need to ask a question when I break up my player into usable components. How should I take this approach with the music player? because the music player is one view can't break up?
import SwiftUI

struct ContentView: View {
    var body: some View {
        VStack {
            Image("albumCover")
            HStack{
                VStack {
                    Text("Album name")
                    Text("Artist name")
                }
                Spacer()
                Button(action: /*@START_MENU_TOKEN@*/{}/*@END_MENU_TOKEN@*/) {
                     Image(systemName: "heart")
                }
            }.padding()
            HStack{
                Text("0")
                Slider(value: /*@START_MENU_TOKEN@*//*@PLACEHOLDER=Value@*/.constant(10)/*@END_MENU_TOKEN@*/)
                Text("-5:00")
            }.padding()

            HStack{
                Button(action: /*@START_MENU_TOKEN@*/{}/*@END_MENU_TOKEN@*/) {
                     Image(systemName: "shuffle")
                }
                Spacer()
                Button(action: /*@START_MENU_TOKEN@*/{}/*@END_MENU_TOKEN@*/) {
                     Image(systemName:"backward.end")
                }
                Spacer()
                Button(action: /*@START_MENU_TOKEN@*/{}/*@END_MENU_TOKEN@*/) {
                     Image(systemName: "play")
                }
                Spacer()
                Button(action: /*@START_MENU_TOKEN@*/{}/*@END_MENU_TOKEN@*/) {
                     Image(systemName: "forward.end")
                }
                Spacer()
                Button(action: /*@START_MENU_TOKEN@*/{}/*@END_MENU_TOKEN@*/) {
                     Image(systemName: "repeat")
                }

            }.padding()

                HStack{
                    Button(action: /*@START_MENU_TOKEN@*/{}/*@END_MENU_TOKEN@*/) {
                         Image(systemName: "hifispeaker")
                    }

                    Spacer()
                    Button(action: /*@START_MENU_TOKEN@*/{}/*@END_MENU_TOKEN@*/) {
                         Image(systemName: "music.note.list")
                    }

                }.padding()

        }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}


texts: Should a piece of code only ever called once be a separate method?

texts:
I'm curious when a piece of code should be its own method or just left alone. This came up when I was creating a "work item" from the thread pool. When passing the argument to the "WaitCallback" object, I would argue that if the code that will run will ONLY run when this thread is being run, then it's OK to wrap the code inside of an Action delegate. If other places need to run this same code, then I understand separating it into a new method.

So, for example, what's better practice?

This --

ThreadPool.QueueUserWorkItem(new WaitCallback((state) =>
{
    Contract.SaveContract(Customer);
     pushResultNotification = DoPushContact();
      MyDispatcher.BeginInvoke((Action)(() => actionNotification.CompleteAction()), null);
}));

Or this --

ThreadPool.QueueUserWorkItem(new WaitCallback(DoStuff));

private void DoStuff(object state)
{
    Contract.SaveContract(Customer);
    pushResultNotification = DoPushContactToGp();
    MyDispatcher.BeginInvoke((Action)(() => actionNotification.CompleteAction()), null);
}


texts:
In table first value I have value with datatype = Start

I need to calculate difference first value - midnight

Last value is with datatype =Stop

I need to calculate difference midnight - last item

For other I need to calculate datatype.Stop - previous.datatype=Start

Here is ViewModel that I use for repo method

public class HeatMapViewModel
{
    public decimal? Latitude2 { get; set; }
    public decimal? Longitude2 { get; set; }
    public int coeff = 2;
    public int Difference;
    public DateTime Date { get; set; }
}

I wrote this code in repo method

public List<HeatMapViewModel> GetStops()
{
    using (TraxgoDB ctx = new TraxgoDB())
    {
        List<HeatMapViewModel> items = new List<HeatMapViewModel>();

        var firstitem = ctx.Logging.Where(x => x.Datatype == Datatype.Start).AsEnumerable().FirstOrDefault();

        var midnight = new DateTime(firstitem.CurrentDateTime.Year, firstitem.CurrentDateTime.Month, firstitem.CurrentDateTime.Day, 00, 00, 00);
        TimeSpan difference = (firstitem.CurrentDateTime - midnight);
        var difference_after_midnight = (int)difference.TotalMinutes;

        items.Add(new HeatMapViewModel
        {
            Latitude2 = firstitem.Latitude,
            Longitude2 = firstitem.Longitude,
            Difference = difference_after_midnight,
            Date = firstitem.CurrentDateTime
        });

       var lastItem = ctx.Logging.Where(x => x.Datatype == Datatype.Stop).AsEnumerable().LastOrDefault();
       var before_midnight = new DateTime(lastItem.CurrentDateTime.Year, lastItem.CurrentDateTime.Month, lastItem.CurrentDateTime.Day, 23, 59, 00);
       TimeSpan difference_before = (before_midnight - lastItem.CurrentDateTime);
       var difference_before_midnight = (int)difference_before.TotalMinutes;

       items.Add(new HeatMapViewModel
       {
            Latitude2 = lastItem.Latitude,
            Longitude2 = lastItem.Longitude,
            Difference = difference_before_midnight,
            Date = firstitem.CurrentDateTime
        });

        var allitems = ctx.Logging;
        var filteredQuery = allitems.Where(x => x.Datatype == Datatype.Start || x.Datatype == Datatype.Stop).OrderByDescending(x => x.LogID).ToList();

        for (int i = 1; i < filteredQuery.Count; i++)
        {
            if (filteredQuery[i].Datatype == Datatype.Stop && filteredQuery[i - 1].Datatype == Datatype.Start)
            {
                TimeSpan differenceTicks = filteredQuery[i - 1].CurrentDateTime - filteredQuery[i].CurrentDateTime;

                items.Add(new HeatMapViewModel
                {
                    Latitude2 = filteredQuery[i].Latitude,
                    Longitude2 = filteredQuery[i].Longitude,
                    Difference = (int)differenceTicks.TotalMinutes,
                    Date = firstitem.CurrentDateTime
                });
            }
        }
        return items;
    }
}

Here is data from db

It works great, but I need to know if I can modify it?


texts: finding definite integrals in Python using Trapezium rule

texts:
I wrote this program which finds the definite integral of a function. Where in the program could I optimize this code:

def trapezium(f,n,a,b):
    h=(b-a)/float(n)

    area = (0.5)*h
    sum_y = (f(0)+f(b))

    i=a
    while i<b:
        print i
        sum_y += 2*f(i)
        i += h

    area *= sum_y

    return area

def f(x):
    return x ** 2

print trapezium(f, 10000, 0, 5)


texts: PHP code to make a WHOIS request and return the received data

texts:
I have written some PHP to make WHOIS queries and return the retrieved WHOIS record.

The code is an excerpt from a much larger program used for monitoring domain name expiry. It's a command-line program designed to be run in a shell such as Bash or PowerShell, and has no web services involved.

Firstly, there is a function to identify the first-level TLD for the domain:

//Return the first-level TLD for a domain
function getTld($domain) {
    //If domain contains dot, find first-level TLD and return it
    if(strpos($domain, ".")) {
        return(pathinfo($domain, PATHINFO_EXTENSION));
    //If domain doesn't contain a dot, just return domain as-is
    } else {
        return($domain);
    }
}

Then, the first-level TLD is prepended to .whois-servers.net, and a WHOIS lookup is made to it over TCP port 43:

//Return raw WHOIS data for domain
function whois($domain) {
    $whoisServer = getTld($domain) . ".whois-servers.net";
    set_error_handler("whoisWarningHandler", E_WARNING);
    $whois = fsockopen($whoisServer, 43);
    restore_error_handler();
    stream_set_timeout($whois, 3);
    stream_set_blocking($whois, false);
    fwrite($whois, $domain . "\r\n");
    $read = [$whois]; $retries = 1; $null = null;
    while(stream_select($read, $null, $null, 5) === false) {
        if($retries++ >= 5) {
            return(0);
        }
        print("Retrying... (attempt " . $retries . ")");
        sleep(1);
    }
    sleep(1);
    return(filter_var(fread($whois, 65535), FILTER_DEFAULT, FILTER_FLAG_STRIP_HIGH));
}

Finally, there is a custom warning handler to terminate the program if a connection to the WHOIS server cannot be established:

//Custom warning handler for WHOIS fsock/stream
function whoisWarningHandler($errno, $errstr) {
    print("An error occurred while connecting to the WHOIS server.\n\nError output:\n\n" . $errstr . "\n");
    exit(2);
}

The code may then be called using e.g. print(whois("example.com"));, which would print the WHOIS record for example.com.

Please could anyone advise as to whether best practise for code quality, efficiency and security has been followed, and any recommended adjustments/improvements that could be made?


texts:
How to refactor this go code to make it more easy to understand and to maintain?
It is email sender worker-pool skeleton.
To understand the working-pool logic I coded it without real email client and database code.
To simulate the read from database, I used ints, taking them in random groups (0..6 items each) with random sleep times.
Instead of sending real emails, Just printing with random sleeps.
If I add real email client code into it, it will become more complex.
Especially, how to split the code in the main function into smaller functions?
// main.go
package main

import (
    "fmt"
    "math/rand"
    "os"
    "os/signal"
    "strconv"
    "sync"
    "syscall"
    "time"
)

// Msg is an email message
type Msg struct {
    From    string
    To      string
    Subject string
    Body    string
}

var r = make(chan int, 100)

func main() {
    fmt.Println("Begin")

    q := make(chan Msg)
    sigs := make(chan os.Signal)
    stop := make(chan bool)

    signal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM)
    go func() {
        sig := <-sigs
        fmt.Println(sig)
        stop <- true
    }()

    var wg sync.WaitGroup
    for i := 0; i < 4; i++ {
        wg.Add(1)
        go func() {
            defer wg.Done()
            for m := range q {
                send(m)
            }
        }()
    }

    for i := 0; i < 100; i++ {
        r <- i
    }
    close(r)

    wg.Add(1)
    go func() {
        defer wg.Done()
        for {
            a, _ := read()
            for _, m := range a {
                q <- m
            }
            select {
            case <-stop:
                close(q)
                return
            case <-time.After(time.Millisecond):
            }
        }
    }()
    wg.Wait()
    fmt.Println("End")
}

func read() ([]Msg, error) {
    d := time.Duration(rand.Intn(400)) * time.Millisecond
    time.Sleep(d)
    a := []Msg{}
    c := rand.Intn(6)
    for i := 0; i < c; i++ {
        n := <-r
        m := Msg{"support@example.com", "user" + strconv.Itoa(n) + "@example.com", strconv.Itoa(n), "Test Body"}
        a = append(a, m)
    }
    for _, m := range a {
        fmt.Print(m.Subject, " ")
    }
    fmt.Println("read in", d)
    return a, nil
}

func send(m Msg) {
    d := time.Duration(rand.Intn(700)) * time.Millisecond
    time.Sleep(d)
    fmt.Println(m.Subject, "sent in", d)
}

Thanks


texts: Randomly generate set of size M from array of size N

texts:
The following algorithm attempts to randomly generate a set of size M from an array of size N. It is not based on Knuth Fisher Yates shuffle, but could someone verify its correctness?

import random

def random_m(arr, m):
    if len(arr) <= m:
        return arr

    for i in range(m):
        rand = random.randint(i, len(arr)-1)
        arr[i], arr[rand] = arr[rand], arr[i]

    return arr[:m]

if __name__ == "__main__":
    print random_m([1,2,3,4,5,6,7], 5)

The above runs in\$\ O(m)\$ where as the method based on Knuth Fisher Yates runs in \$\ O(n)\$.


texts:
I'm currently writing a small game, needing some advice for things I could do better on this resource management system. Speed is not crucial, and I have no memory budget.

The goal is to load and store resources so they can be reused and accessed with a string. That way, all resources are loaded at once, and can be reused by this singleton from anywhere else in the code. This system currently works, I'm just looking for ways to improve it or better leverage STL's features.

The Resource class

class Resource
{
public:
    Resource();
    virtual ~Resource();

    virtual void loadResource() = 0;
    virtual void unloadResource() = 0;

    void setResourceId(unsigned id);
    unsigned getResourceId() const;

    void setResourcePath(const std::string& path);
    std::string getResourcePath() const;

protected:
    unsigned mResourceId;
    std::string mResourcePath;

};

It's a simple base class with getters and setters, along with pure virtual loadResource() and unloadResource() functions that each derivative will override.

The ResourceManager class

class ResourceManager : public Singleton<ResourceManager>
{
public:
    ResourceManager();
    virtual ~ResourceManager();

    void addResource(Resource* resource, const std::string& name, const std::string& path);

    template <typename T>
    T* getResource(const std::string& name) {
        return dynamic_cast<T*>(mResources.find(name)->second);
    }

    static ResourceManager& getInstance();
    static ResourceManager* getInstancePtr();

private:
    std::map<std::string, Resource*> mResources;

};

The addResource implementation

void ResourceManager::addResource(Resource* resource, const std::string& name, const std::string& path)
{
    resource->setResourcePath(path);
    resource->setResourceId(mResources.size());
    resource->loadResource();

    mResources.insert(std::pair<std::string, Resource*>(name, resource));
}

The unloadResource function is called for every Resource in ResourceManager's destructor.

Usage example: loading the resource (with a hypothetical Texture class)

mResourceManager->addResource(new Texture, "test", "Resources/test.png");

Usage example: accessing the resource

mResourceManager->getResource<Texture>("test");

Like I said earlier, speed/memory isn't crucial, so all solutions are welcome.


texts: A recursive algorithm to find the number of distinct quantities of money from a pile of coins

texts:
Problem: find the number of distinct quantities of money that a pile of coins can make.

The vector coins contains the values of the coins, and the corresponding vector quantity contains the number of coin there are (let's say coins = {1} and quantity = {5}, this means I have 5 pennies).

Although I have solved this problem, I would like to make it more time efficient. Could someone give me some pointers?

Miscellaneous info: the variable ctq stands for "coins to quantity". I solved this by systematically iterating through all possible combinations of coins and putting their sum into a set. There has to be a better way to solve this problem, because this problem is supposed to be a dynamic programming question and I solved this problem without any knowledge of what that's supposed to be.

#include<iostream>
#include<vector>
#include<map>
#include<set>

int money(std::map<int, int> x)
{
    int sum=0;
    for(auto it=x.begin(); it!=x.end(); ++it)
    {
        sum+=it->first*it->second;
    }
    return sum;
}

int rec
(
    std::set<int> &sums,
    std::map<int, int> ctq,
    std::vector<int> coins,
    std::vector<int> quantity,
    int m
)
{
    for(int k=quantity[m]; k>=0; k--)
    {
        ctq[coins[m]] = k;
        sums.insert(money(ctq));
        if(m != 0)
        {
            rec(sums, ctq, coins, quantity, m-1);
        }
    }
    return sums.size()-1;
}

int possibleSums(std::vector<int> coins, std::vector<int> quantity)
{
    std::map<int, int> ctq;
    for(std::size_t i=0; i<coins.size(); i++)
    {
        if(ctq.find(coins[i]) == ctq.end())
        {
            ctq.insert(std::make_pair(coins[i], quantity[i]));
        }
        else
        {
            ctq[coins[i]] += quantity[i];
        }
    }

    std::vector<int> n_coins, n_quantity;
    for(auto it = ctq.begin(); it != ctq.end(); ++it)
    {
        n_coins.push_back(it->first);
        n_quantity.push_back(it->second);
    }

    std::set<int> sums;
    return rec(sums, ctq, n_coins, n_quantity, n_coins.size()-1);
}

int main()
{
    std::vector<int> coins = {10, 50, 100, 200};
    std::vector<int> quantity = {511, 22, 30, 50};
    std::cout << possibleSums(coins, quantity) << "\n";
    return 0;
}


texts:
I'm learning Python by implementing commonly used data structures. My primary language is Java, thus would like to know if I'm being Pythonic enough. Any means to better up will be appreciated.

class Node:
    def __init__(self, value=None, next=None):
        self.value = value
        self.next = next

from node import Node

class Stack:
    def __init__(self):
        self.top = None
        self.size = 0

    def push(self, item):
        curr = Node(item)
        self.size += 1
        if self.top is None:
            self.top = curr
        else:
            curr.next = self.top
            self.top = curr

    def peek(self):
        return self.top.value

    def pop(self):
        if self.top is None:
            raise Exception("Nothing to pop.")
        curr = self.top
        self.top = self.top.next
        self.size -= 1
        return curr

    def __sizeof__(self):
        return self.size

    def is_empty(self):
        return self.size == 0;

    def __str__(self):
        curr = self.top
        while curr:
            print(curr.value, end=' ')
            curr = curr.next


texts:
I’m still relatively new to the TDD scene. I’m writing a Rails app, and some duplication immediately sticks out at me in my first model spec. How else can I approach this?

require 'spec_helper'

describe TimeEntry do

  describe "without a project" do
    let(:entry) { FactoryGirl.build :time_entry }
    it "should not be valid" do
      entry.project = nil
      expect(entry).to_not be_valid
    end
  end

  describe "without a user" do
    let(:entry) { FactoryGirl.build :time_entry }
    it "should not be valid" do
      entry.user = nil
      expect(entry).to_not be_valid
    end
  end

end


texts: Query for combining two SELECTs to get active users and 1 inactive user

texts:
What this query does:

Gets multiple users with the first select in the union; those are the active users.
But when a user is not in that list, but there is a @userid, it should get that user as well and set active to 0 there; that is what the second select does.
If a user is in the first select, and in the second select, the second one should not be in the resultset; that is what the group by with the max is for.

Is there a more efficient way to write this query?

SELECT pk_userid,
       username,
       CAST(MAX(active) AS BIT) AS active
FROM   (SELECT     pk_userid,
                   username,
                   1 AS active
        FROM       dbo.tbluser u
        INNER JOIN tblCustomer c ON u.pk_userid = c.fk_userid
        WHERE      ( c.fk_projectid = @projectid
                 AND c.fk_orderid = @orderid )
        UNION
        SELECT pk_userid,
               username AS username,
               0        AS active
        FROM   dbo.tbluser u
        WHERE  pk_userid = @userid) a
GROUP  BY pk_userid,
          username
ORDER  BY username


texts: Check which numbers satisfy the condition [A*B*C = A! + B! + C!]

texts:
#include <iostream>
#include <cmath>
using namespace std;
int s = 1; //Serial No.

Should I use recursion for the factorials function?

int Factorial(int n)
{
    int k=1;
    for(int i=1;i<=n;++i)
    {
        k=k*i;
    }
    return k;
}

How I can go about doing this in a single for loop instead of the 3 while loops?

int main()
{
    int a = 1;
    int b = 1;
    int c = 1;
    int Fact1;
    int Fact2;
    int Fact3;
    while (a < 11)
    {
        Fact1 = Factorial(a);
        while (b < 11)
        {
            Fact2 = Factorial(b);
            while (c < 11)
            {
                Fact3 = Factorial(c);
                cout << s << " : ";
                int LHS = Fact1 + Fact2 + Fact3;
                if (LHS == a * b * c)
                {
                    cout << "Pass:" <<"    "<< a << " & " << b << " & " << c << endl;
                }
                else
                {
                    cout << "Fail" /*<<"   "<< Fact1 <<"   "<< Fact2 <<"   "<<Fact3*/<<endl;
                }
                    c++;
                    s++;
            }
            c = 1;
            b++;
        }
        b = 1;
        a++;
    }
    return 0;
}

Also I would love some variable naming tips.


texts: Create URL using data obtained from filters

texts:
Unfortunately there is no URL where you can see the code working. I hope you all can figure out what the code does simply by looking at it.

GitHub

var FilteredNav = {
      wrapper: $(".dept-filters")
      , init: function() {
        FilteredNav.changeUrl();
        FilteredNav.createUrl();
      }
      , createUrl: function() {
        var url = null
          , urlItems = null;

        $.each(FilteredNav.wrapper, function() {
          // clean it all up before creating the url
          urlItems = [];

          var self = $(this)
            , checkedInput = self.find('input[type="checkbox"]:checked')
            , submitButton = self.find('.refinar-btn');

          // select only the relevant items
          $.each(checkedInput, function(i, item) {
            urlItems.push($(item).attr("rel"));
          });

          if (checkedInput.length) {
            // create the url
            url = document.location.protocol
            + "//"
            + document.location.host
            + "/"
            + self.attr("data-dept")
            + "/?"
            + urlItems.join("&");

            // add new url as href of 'refine' button
            submitButton.removeClass("hide").attr("href", url);
          } else {
            submitButton.addClass("hide");
          }
        });
      }
      , changeUrl: function() {
        FilteredNav.wrapper.find('input[type="checkbox"]').bind("change", FilteredNav.createUrl);
      }
    };

    // uncomment this line when testing on the console
    // FilteredNav.init();

    // comment this line when testing on the console
    $(document).ready(function() {
      FilteredNav.init();
    });


texts: Using descriptors with instance variables to store a human's age

texts:
I am studying descriptors. They work with class varibles out of the box, but I want them to operate on instance variables too, so I did this:

class NumberDescriptor(object):
    def __init__(self,name):
        self.name = name

    def __set__(self, instance, value):
        if not isinstance(value, int):
            raise ValueError("%s is not a number." % value)
        else:
            setattr(instance, self.name, value)

    def __get__(self, instance, owner):
        return getattr(instance, self.name)

class Human(object):
    age = NumberDescriptor("_age")

    def __init__(self,age):
        self.age = age

a = Human(12)
print a.age
b = Human("osman")
print b.age

Is this the right way to go about this?


texts:
In my code I have a base type which is OnlinePaymentTransaction:

public abstract class OnlinePaymentTransaction
{
     public abstract void Complete( PaymentGatewayCallbackArgs args );
}

The problem I am having is that each class that inherits from this base class require different dependency's in the complete method. Currently I have just added the dependency's as extra parameters to the complete method which doesn't seem right. For example my base class is now like this.

public abstract class OnlinePaymentTransaction
{
     public abstract void Complete( Dependency1 dep1, Dependency2 dep2, PaymentGatewayCallbackArgs args );
}

I cannot inject the dependency's in the constructor as the OnlinePaymentTransactions are retrieved from using nhibernate.

What would you recommend because I don't like using ServiceLocator as it hides the dependency and also makes it harder to test. An suggestions would be greatly appreciated.


texts: Need reviews for impacts of dirty bug fix

texts:
I was having a hard time with bug logstash#665. Hope they will fix it some day, but sparc/solaris support is probably not on top of their priority list. For further reference, original error is:

NotImplementedError: stat.st_dev unsupported or native support failed to load dev_major at org/jruby/RubyFileStat.java:190
_discover_file at /tmp/aaaa/logstash-1.4.1.dev/vendor/bundle/jruby/1.9/gems/filewatch-0.5.1/lib/filewatch/watch.rb:140

After digging a lot I found out that the problem here is the usage of a native library which is not correclty retrieved on Solaris. So when ruby fails, it is trying a fallback to java, which fails as well. Now I have retrieved the original watch.rb source file and isolated the problematic function:

private
def _discover_file(path, initial=false)
  globbed_dirs = Dir.glob(path)
  @logger.debug("_discover_file_glob: #{path}: glob is: #{globbed_dirs}")
  if globbed_dirs.empty? && File.file?(path)
    globbed_dirs = [path]
    @logger.debug("_discover_file_glob: #{path}: glob is: #{globbed_dirs} because glob did not work")
  end
  globbed_dirs.each do |file|
    next if @files.member?(file)
    next unless File.file?(file)

    @logger.debug("_discover_file: #{path}: new: #{file} (exclude is #{@exclude.inspect})")

    skip = false
    @exclude.each do |pattern|
      if File.fnmatch?(pattern, File.basename(file))
        @logger.debug("_discover_file: #{file}: skipping because it " +
                      "matches exclude #{pattern}")
        skip = true
        break
      end
    end
    next if skip

    stat = File::Stat.new(file)
    @files[file] = {
      :size => 0,
      :inode => [stat.ino, stat.dev_major, stat.dev_minor],
      :create_sent => false,
    }
    if initial
      @files[file][:initial] = true
    end
  end
end # def _discover_file

More precisely, the bug was happening there:

    stat = File::Stat.new(file)
    @files[file] = {
      :size => 0,
      :inode => [stat.ino, stat.dev_major, stat.dev_minor],
      :create_sent => false,
    }

So I a tried to understand what those two lines do and how to work them around to somehow have something which works. For reference, documentation says:

  dev_major() public

  Returns the major part of File_Stat#dev or nil.

After some experimentation, I concluded that since this function can return nil, I could just replace the call of the function by nil like this:

stat = File::Stat.new(file)
@files[file] = {
  :size => 0,
  :inode => [stat.ino, nil, nil],
  :create_sent => false,
}

Just replaced _stat.dev_major_ and _stat.dev_minor_ by nil, launched the program, and it worked. Now I did not test a lot but everything seems to work fine.

So I need your reviews for that last snippet of code which is of my own: The program seems to be bearing with it, but is it really safe to do this?


texts: Optimize this Scheme-written chess engine module

texts:
I'd like to know how to optimize this by shadowing symbols 'lo and 'hi inside nested function f. I guess CPS conversion would solve this but how?

;; chess engine - early development

;; Alist: (cons 'piece xy-coordinates)
(define whites) (define blacks)

(begin
  (define setup
    (let ([lo `(p0 p1 p2 p3 p4 p5 p6 p7)]
            [hi `(r0 n0 b0 q k b1 n1 r1)])
      (define f
        (let ([xs (iota 8)])
          (lambda (ls y)
            (map (lambda (i x) (cons i (cons x y))) ls xs))))
      (lambda (l h) (concatenate (f lo l) (f hi h)))))
  (set! whites (setup 1 0)) (set! blacks (setup 6 7)))


texts:
I want to store WGS84-coordinates in two integers for latitude and longitude instead of floats to get a higher precision than with floats.

Here's my code:

struct Coordinate
{
    private int latitude;
    private int longitude;

    const double latMin = -90.0f;
    const double latMax = 90.0f;
    const double lngMin = -180.0f;
    const double lngMax = 180.0f;

    public Coordinate(double latitude, double longitude)
    {
        this.latitude = mapDoubleToInt(latitude, latMin, latMax);
        this.longitude = mapDoubleToInt(longitude, lngMin, lngMax);
    }

    public double Latitude { get { return mapIntToDouble(latitude, latMin, latMax); } }
    public double Longitude { get { return mapIntToDouble(longitude, lngMin, lngMax); } }

    private static int mapDoubleToInt(double value, double min, double max)
    {
        return (int)(((long)int.MaxValue - int.MinValue) * (value - min) / (max - min) + int.MinValue);
    }

    private static double mapIntToDouble(int value, double min, double max)
    {
        return ((double)value - int.MinValue) / ((long)int.MaxValue - int.MinValue) * (max - min) + min;
    }
}

I'm not sure if there is a better to convert the data. There are a lot of casts and arithmetic operations in it -- any way to do this more elegantly?


texts:
I am trying to learn Clojure for some time. In my experience, it has been rather too easy to produce write-only code.

Here is a solution to a simple problem with very little essential complexity. Input and output formats are extremely simple, too. Which means all complexity in it must be accidental. How to improve its legibility, intelligibility?

Is the decomposition of the problem into functions all right?

Also other specific problems:

How to input/output numbers? Is there any benefit to use read-string instead of Double/parseDouble? How to format floating point numbers to fixed precision without messing with the default locale?
How to avoid the explicit loop/recur, which is currently a translation of a while loop?
Are there definitions that should/shouldn't have bee private/dynamic?

  Problem

  You start with 0 cookies. You gain cookies at a rate
  of 2 cookies per second [...]. Any time you
  have at least C cookies, you can buy a cookie farm. Every time you buy
  a cookie farm, it costs you C cookies and gives you an extra F cookies
  per second.

  Once you have X cookies that you haven't spent on farms, you win!
  Figure out how long it will take you to win if you use the best
  possible strategy.

(ns cookie-clicker
  (:use [clojure.string :only [split]])
  (:require [clojure.java.io :as io]
            [clojure.test :refer :all]))

;;See http://code.google.com/codejam/contest/2974486/dashboard#s=p1

(defn parse-double [s] (java.lang.Double/parseDouble s))

(defn parse-row [line]
  (map parse-double (split line #"\s+")))

(defn parse-test-cases [rdr]
  (->> rdr
    line-seq
    rest
    (map parse-row)))

(def initial-rate 2.0)

(defn min-time [c f x]
  (loop [n 0 ; no of factories used
         tc 0 ; time cost of factories built
         r initial-rate ; cookie production rate
         t (/ x r)] ; total time
    (let [n2 (inc n)
          tc2 (+ tc (/ c r))
          r2 (+ r f)
          t2 (+ tc2 (/ x r2))]
      (if (> t2 t)
        t
        (recur n2 tc2 r2 t2)))))

(java.util.Locale/setDefault (java.util.Locale/US))

(defn ans [n t]
  (str "Case #" n ": " (format "%.7f" t)))

(defn answers [test-cases]
  (map #(ans %1 (apply min-time %2))
       (rest (range))
       test-cases))

(defn spit-answers [in-file]
  (with-open [rdr (io/reader in-file)]
    (doseq [answer (answers (parse-test-cases rdr))]
      (println answer))))

(defn solve [in-file out-file]
  (with-open [w (io/writer out-file :append false)]
    (binding [*out* w]
      (spit-answers in-file))))

(def ^:dynamic *tolerance* 1e-6)

(defn- within-tolerance [expected actual]
  (< (java.lang.Math/abs (- expected actual))
     *tolerance*))

(deftest case-3
    (is (within-tolerance
          63.9680013
          (min-time 30.50000 3.14159 1999.19990))))

(defn -main []
  (solve "resources/cookie_clicker/B-large-practice.in"
         "resources/cookie_clicker/B-large-practice.out"))


texts:
I've implemented a quick and dirty repository to save and insert users to a MongoDB. As you can see, it just inserts one and finds one. Not a rocket.

The thing is I don't really know what are the best practices when implementing a repository layer, how to really arquitect this, etc...

Furthermore, even if it sounds too simple, I'm not sure which variables should be instance properties or not (for example, the database, or the client). Assumed those where convenient, but I'm not sure on the choice.

Any tips are welcome :)

User.kt

data class User (val chatId: String, val username: String, val email: String)

BaseRepository.kt

import com.mongodb.MongoClient
import com.mongodb.MongoClientURI
import com.mongodb.client.MongoDatabase

abstract class BaseRepository<Entity>(databaseUri: String) {
    protected var database: MongoDatabase? = null
    protected var mongoClient: MongoClient? = null

    init {
        val connectionString = MongoClientURI(databaseUri)
        mongoClient = MongoClient(connectionString)
        database = mongoClient?.getDatabase("paybotDB")
    }

    abstract fun insertOne(e: Entity);

    abstract fun findOne(username: String) : Entity;
}

UserRepository.kt

import org.bson.Document
import org.jgmanzano.paybot.entities.User

class UserRepository(databaseUri: String) : BaseRepository<User>(databaseUri) {

    override fun insertOne(user: User){
        val document = Document("username", user.username)
                .append("chatId", user.chatId)
                .append("email", user.email)

        database?.getCollection("users")?.insertOne(document)
    }

    override fun findOne(username: String): User {
        val collection = database?.getCollection("users")
        val userDocument =  collection?.find(Document("username", username))?.first()

        return User(
                userDocument?.get("chatId") as String,
                userDocument?.get("username") as String,
                userDocument?.get("email") as String
        )
    }
}


texts: Wrapper function that returns cached value from WinAPI call

texts:
I am writing myself a little wrapper and I decided to cache values that shouldn't change (often or at all) for returning to the user, I'm coming from the premise that the WinAPI call is more expensive than returning my cached values, which I'm not sure if is true (or much more expensive to the point where it's worth it).
Here is my function:
const SYSTEM_INFO& getSystemInfo(const bool reCache)
    {
        static SYSTEM_INFO nativeSystemInfo;
        static bool cached_nativeSystemInfo{ false };

        if (!cached_nativeSystemInfo || reCache)
        {
            GetNativeSystemInfo(&nativeSystemInfo);
            cached_nativeSystemInfo = true;
        }

        return nativeSystemInfo;
    }

After some research on GetNativeSystemInfo and SYSTEM_INFO in general, I've seen that under normal circunstances the return structure should never change, but it is not impossible for it to happen. That is why I came up with the reCache function parameter.
Would you understand what the reCache argument does even without documentation? Is this actually efficient? Would it be fit for it to be inlined?


texts: Computing a list of divisors of a number

texts:
I developed the following Python functions when solving a few Project Euler problems, and since I'm not that familiar with Python, I'm curious at how I could improve them.

The code consists of a data holder class, and a few functions.

Option class:

This object stores data for a combination option. It has two data members:

value: the value of the option
count: how many times this option can be chosen

class Option:
    def __init__(self, value, count):
        self.value = value
        self.count = count

Get Prime Factorization:

This function calculates a number's prime factorization. It returns the factorization as a list of Options where the option's value is the prime and it's count is the power.

def getPrimeFactorization(n):
    f = []

    nth = 0

    while n > 1:
        prime = nthPrime(nth)

        if n % prime == 0:
            f.append(Option(prime, 1))

            n = n // prime

            while n % prime == 0:
                f[-1].count += 1

                n = n // prime

        nth += 1

    return f

Get Combinations:

To calculate the combinations, I use getCombinationsIncrement to iterate through each possible combination. The index is the index of the current option, options is the list of Options, and chosen is the number of times the Option will be chosen.

def getCombinationsIncrement(index, options, chosen):
    if index >= len(options):
        return False
    else:
        chosen[index] += 1

    if chosen[index] > options[index].count:
        chosen[index] = 0
        return getCombinationsIncrement(index + 1, options, chosen)
    else:
        return True

The options parameter is a list of options, combine is the function used to combine options, base is the base amount to combine with other values (it's similar to reduce if your familiar with JavaScript).

def getCombinations(options, combine, base):
    combos = [base]
    chosen = [0] * len(options)

    while getCombinationsIncrement(0, options, chosen):
        combos.append(base)

        for i in range(len(options)):
            for _ in range(chosen[i]):
                combos[-1] = combine(combos[-1], options[i].value)

    combos.sort()

    return combos

Get Divisors

Using the functions above it's easy to calculate all the divisors of a number.

def multiply(x, y):
    return x * y

def getDivisors(n):
    return getCombinations(getPrimeFactorization(n), multiply, 1)

My primary concern is with the getCombinationsIncrement function. I'd like it to be scoped only into the getCombinations function, and I don't particularly like having to make a class to fix that. It also might not be the best way to go about creating the combinations.


texts: How to use smart pointers with SDL2 (SDL_RWops)?

texts:
I want to write read savefile function with smart pointers and SDL2. I have little expirience with smart pointers and just want to ask is my code good, correct and no memory leaks.
this is my code:
std::shared_ptr<SDL_RWops> saveFile;

--
int GameEngine::ReadSave() {

        int Highlevel;

        //Open file for reading in binary
        saveFile = std::shared_ptr<SDL_RWops>(SDL_RWFromFile( "data/save.txt", "r" ), SDL_RWclose);

        //File does not exist
        if( saveFile.get()  == NULL ){
                printf( "Warning: Unable to open file! SDL Error: %s\n", SDL_GetError() );

                Highlevel = 0;

                //Create file for writing
                saveFile = std::shared_ptr<SDL_RWops>(SDL_RWFromFile( "data/save.txt", "w+" ), SDL_RWclose);

                if( saveFile.get() != NULL ){
                        printf( "New save file created!\n" );

                        //Initialize data
                        SDL_RWwrite( saveFile.get(), &Highlevel, sizeof(int), 1 );
                }
                else {
                        printf( "Error: Unable to create savefile! SDL Error: %s\n", SDL_GetError() );
                }
        }
        else{
                //Load data
                printf( "Reading save file...!\n" );

                SDL_RWread( saveFile.get(), &Highlevel, sizeof(int), 1 );
        }

        return Highlevel;
}


texts: First jQuery Plugin, Would like a code review

texts:
I created my first jQuery plugin over this weekend. I would like a code review so that I can improve my code in the future and learn from any mistakes I make. Any tips for Github would also be greatly appreciated since I am also new to GitHub :).

Demo: https://rawgithub.com/Shivambh28/ezToggle/master/demo.html

GitHub: https://github.com/Shivambh28/ezToggle

Plugin code:

(function($){
    $.fn.ezToggle = function(options) {
        var defaults = {
            selector: '.selector',
            speed : 200
        }
        defaults.minHeight = $(defaults.selector).outerHeight(true);
        var options =  $.extend(defaults, options);
        return this.each(function() {
            var o    = options,
                yDiv = $(this),
                oHei = $(yDiv).height();
            $(yDiv).not('.opened').addClass('closed');
            $('.closed').height(defaults.minHeight);
            $('.opened').height(oHei);
            $(defaults.selector).click(function() {
                if ($(this).closest(yDiv).hasClass('closed') ) {
                    $('.opened').removeClass('opened').addClass('closed').animate({height:defaults.minHeight}, defaults.speed);
                    $(this).closest(yDiv).removeClass('closed').addClass('opened').animate({height:oHei}, defaults.speed);
                } else if ( $('.opened').length == 1 ) {
                    $(this).closest(yDiv).removeClass('opened').addClass('closed').animate({height:defaults.minHeight}, defaults.speed);
                }
            });
        });
    };
})(jQuery);


texts:
I have an assignment to create a function that reverses the letters of each word in a string individually. I feel like this should be a rather simple task. I did figure out a solution, although I feel like it uses too many variables as a sort of hack method. Any suggestions on how to make it more efficient/shorter?

#include<iostream>
#include<conio.h>
#include<string.h>

using namespace std;

void rev(char str[80])
{
char t;
int l = 0, n = strlen(str), k = 0;

for (int i = 0; i <= n; i++)
{
    if (str[i] == ' ' || str[i] == '\0')
    {
        for (int j = i - 1; j > (k + i - 1) / 2; l++, j--)
        {
            t = str[j];
            str[j] = str[l];
            str[l] = t;
        }
        k = i + 1;
        l = k;
    }
}

}

void main()
{
    char str[80];
    cout << "Please enter a string : ";
    cin.getline(str, 80);
    cout << "The original string is : " << str << "\n";
    rev(str);
    cout << "The new string is : " << str << "\n";
    system("pause");
}


texts: Pandas/Numpy statistical odds ratio test

texts:
I'm looking for a faster way to do odds ratio tests on a large dataset. I have about 1200 variables (see var_col) I want to test against each other for mutual exclusion/ co-occurrence. An odds ratio test is defined as (a * d) / (b * c)), where a, b c,d are number of samples with (a) altered in neither site x & y  (b) altered in site x, not in y (c) altered in y, not in x (d) altered in both. I'd also like to calculate the fisher exact test to determine statistical significance. The scipy function fisher_exact can calculate both of these (see below).

#here's a sample of my original dataframe
sample_id_no  var_col
       0    258.0
       1    -24.0
       2   -150.0
       3    149.0
       4    108.0
       5   -126.0
       6    -83.0
       7      2.0
       8   -177.0
       9   -171.0
      10     -7.0
      11   -377.0
      12   -272.0
      13     66.0
      14    -13.0
      15     -7.0
      16      0.0
      17    189.0
      18      7.0
      13    -21.0
      19     80.0
      20    -14.0
      21    -76.0
       3     83.0
      22   -182.0

import pandas as pd
import numpy as np
from scipy.stats import fisher_exact
import itertools

#create a dataframe with each possible pair of variable
var_pairs = pd.DataFrame(list(itertools.combinations(df.var_col.unique(),2) )).rename(columns = {0:'alpha_site', 1: 'beta_site'})

#create a cross-tab with samples and vars
sample_table = pd.crosstab(df.sample_id_no, df.var_col)

odds_ratio_results = var_pairs.apply(getOddsRatio, axis=1, args = (sample_table,))

#where the function getOddsRatio is defined as:
def getOddsRatio(pairs, sample_table):

    alpha_site, beta_site = pairs
    oddsratio, pvalue = fisher_exact(pd.crosstab(sample_table[alpha_site] > 0, sample_table[beta_site] > 0))
    return ([oddsratio, pvalue])

This code runs very slow, especially when used on large datasets. In my actual dataset, I have around 700k variable pairs. Since the getOddsRatio() function is applied to each pair individually, it is definitely the main source of the slowness. Is there a more efficient solution?


texts: C++: Hiding class implementation detail generic

texts:
It always bugged me that you would have to write your private class members inside the header files in C++. This means that everytime you change you implementation, client code has to be rebuild.

I found thise site which describes how to hide implementation detail in C++: http://www.octopull.demon.co.uk/c++/implementation_hiding.html

However I also wanted the code to be generic, so that I didn't have to rewrite the same code for each and every class I create. Here is what I got:

#define TL_UTILS_IMPL_DECL(member) \
    private: \
        class impl; \
        impl* member;

#define TL_UTILS_IMPL_START(t_class, parent) \
    class t_class::impl \
    { \
        public: \
            t_class* parent; \
            impl(t_class* self) \
                : parent(self) \
            {}

#define TL_UTILS_IMPL_END() \
    };

#define TL_UTILS_IMPL_INIT(member) \
    member = new impl(this);

#define TL_UTILS_IMPL_TERM(member) \
    delete member;

#define TL_UTILS_IMPL_PREFIX(t_class) \
    t_class::impl::

Example usage:

// Header file:
    class foo
    {
            TL_UTILS_IMPL_DECL(m)

        public:
            foo();
            ~foo();
    };

// Source file:
    TL_UTILS_IMPL_START(foo, p)
        void bar();
    TL_UTILS_IMPL_END()

    foo::foo()
    {
        TL_UTILS_IMPL_INIT(m)

        // from here on we can use the private
        // data and methods stored in m
        m->bar();
    }

    foo::~for()
    {
        TL_UTILS_IMPL_TERM(m)
    }

    void TL_UTILS_IMPL_PREFIX(foo) bar()
    {
        // do something useful
        // use p as a pointer to the parent class instance
    }

I always hear that preprocessor macros are dirty and should not be used in C++, and I agree to some degree. However I could not realize what I wanted using templates.

So what do you think?

Is the use of preprocessor macros justified here?
Is the code safe?
Any improvements you can think of?


texts:
I've completed the "Sequence Counter" level of TIS-100, but this is horrendously inefficient.  My cycle counts are at about twice the minimum possible according to the charts:

I'm not really as concerned about the other metrics.

I struggled to figure this one out.  And there's definitely bits of my code which I know look suspicious, but I don't feel strong enough with the language yet to really spot how to make this execute fewer instructions.

Here's the problem description:

SEQUENCES ARE ZERO TERMINATED
READ A SEQUENCE FROM IN
WRITE THE SUM TO OUT.S
WRITE THE LENGTH TO OUT.L

Most of my code are in three nodes:

TOP LEFT (IN)

START:
 MOV UP, ACC
 MOV ACC, DOWN
 MOV ACC, DOWN

JNZ SEQ
 MOV 0, RIGHT
 MOV 0, RIGHT
 JMP START

SEQ:
 MOV 1, RIGHT
 MOV 1, RIGHT

TOP RIGHT

START:
 ADD LEFT
 SAV
 MOV 0, ACC
 MOV LEFT, ACC
 JEZ DONE
 SWP
 JMP START

DONE:
 SWP
 MOV ACC, DOWN
 MOV 0, ACC

MIDDLE LEFT:

START:
 ADD UP
 SAV
 MOV 0, ACC
 MOV UP, ACC
 JEZ DONE
 SWP
 JMP START

DONE:
 SWP
 MOV ACC, DOWN
 MOV 0, ACC

MIDDLE RIGHT:

MOV UP, DOWN

BOTTOM LEFT (OUT.S)

MOV UP, DOWN

BOTTOM RIGHT (OUT.L)

MOV UP, DOWN

As I said, this works, but it's horribly inefficient.  Cycle count is up to 485... but looks like it could be under 250.

Also, any tips on making this code more readable while still staying within the extreme character limits would be greatly appreciated.


texts:
GitHub

There need to be a software design supporting gradual migration from one payment system (E-xact) to another (Stripe). Credit cards data are stored outside, so I would like to use both systems in parallel for a while to do not make all users to re-enter credit card data.

Here is what I have at the moment in the domain core:

public interface IMainPaymentAdapter : IPaymentAdapter
{
}

public interface IPaymentAdapter : IPaymentService
{
}

public interface IPaymentGateway : IPaymentService
{
}

public interface IPaymentService
{
    Task<BillingId> RegisterAsync(CreditCard card);
    Task ChargeAsync(BillingId id, decimal amount);
}

The idea is that IPaymentService defines API shape, IPaymentAdaptor is about to be implemented for each payment system in use, IPaymentGateway dispatches calls to the right adaptor based on a BillingId and is supposed to be injected into the consuming code:

public abstract class BillingId
{
    public static BillingId Parse(string text)
    {
        var parts = text.Split('/');
        return (BillingId)Activator.CreateInstance(
            typeof(BillingId<>).MakeGenericType(Type.GetType(parts[0])),
            parts[1]);
    }

    protected BillingId(string value) => Value = value;
    public string Value { get; }
    public abstract Type Adapter { get; }
    public override string ToString() =>
        $"{Adapter.AssemblyQualifiedName}/{Value}";
}

public class BillingId<TAdapter> : BillingId
    where TAdapter : IPaymentAdapter
{
    public BillingId(string value) : base(value) { }
    public override Type Adapter => typeof(TAdapter);
}

My gateway looks like this – note that card registration call is always dispatched to the current IMainPaymentAdaptor implementation, while everything else goes to the adaptor that provided the billing id originally:

[Service]
public class PaymentGateway : IPaymentGateway
{
    public PaymentGateway(IServiceProvider provider) => Provider = provider;
    IServiceProvider Provider { get; }

    public async Task<BillingId> RegisterAsync(CreditCard card) =>
        await Adapter().RegisterAsync(card);

    public async Task ChargeAsync(BillingId id, decimal amount) =>
        await Adapter(id).ChargeAsync(id, amount);

    IPaymentAdapter Adapter() => Adapter(typeof(IMainPaymentAdapter));
    IPaymentAdapter Adapter(BillingId id) => Adapter(id.Adapter);
    IPaymentAdapter Adapter(Type type) =>
        (IPaymentAdapter)Provider.GetService(type);
}

Here is what I have in a Stripe adapter assembly:

public interface IStripeAdapter : IMainPaymentAdapter
{
}

[Service]
public class StripeAdapter : IStripeAdapter
{
    StripeClient Client { get; } = new StripeClient();

    public async Task<BillingId> RegisterAsync(CreditCard card) =>
        new BillingId<IStripeAdapter>(await Client.RegisterAsync(card));

    public async Task ChargeAsync(BillingId id, decimal amount) =>
        await Client.Charge(id.Value, amount);
}

Note that E-xact adapter (a decommissioning one) should be based on IPaymentAdaptor, not the IMainPaymentAdapter:

public interface IEXactAdapter : IPaymentAdapter
{
}

What would you say about this design approach? Does it look clean enough?


texts: Insert sort not working for large arrays

texts:
I've written an insert sort and for my assignment I must be able to sort an array of size 107. I've tested this sort with smaller arrays and it always sorts it correctly (up to size 105). If I make the array any bigger and try to output the sorted array nothing happens (I've waited 15 minutes just in case it was just talking long).

I was wondering if anybody had any information on how to fix this.  Maybe my code is just wrong or maybe I should be using something different.

This is the code for my sort. I've shuffled different sized arrays and it always gave the sorted array correctly though as stated before once an array was bigger than 105 nothing would happen!

public static void insertSort(int[] arr){

        int x, y;
        for(y=1; y< arr.length; y++) {
            int temp = arr[y];
            x = y;
            while(x>0 && arr[x-1] >= temp){
                arr[x] = arr[x-1];
                --x;
            }
            arr[x] = temp;
        }
}