texts: Ruby on rails with active record perfomance

texts:
I've got relation in my database as following :

Customer has many Orders
Order has many Parts
Order has many Upc

So my requirement is to copy all orders from one customer and attach or copy those orders (with their dependencies including parts and upcs) to another customer. With originals customers orders to be left in-tacked, so I'd basically clone orders and dependencies from customer a to customer b

Here is what I got so far, but its kinda slow (slowest first):

I'd iterate trough customers orders first and then I'd call copy_order1 method to copy order and dependencies to another customer. here is copy_order1 (which is in class Customer):

def copy_order1(source_order)
        order_attributes = source_order.attributes.merge({:customer_id => self.customer_id})
        ['id', 'deleted_at'].each{|k| order_attributes.delete k}
        ord = Order.create(order_attributes)

        source_order.parts.each do |part|
            part_attributes = part.attributes.merge({:order_id => ord.id})
            ['id', 'deleted_at'].each{|k| part_attributes.delete k}

            Part.create(part_attributes)

        end

        source_order.upcs.each do |upc|
            upc_attributes = upc.attributes.merge({:order_id => ord.id})
            ['id', 'deleted_at'].each{|k| upc_attributes.delete k}

            Upc.create(upc_attributes)

        end

        return ord
      end

And there I made slightly faster method called copy_order2 :

def copy2(destination_customer)

    ActiveRecord::Base.transaction do
      Order.includes(:customer, :part, :upc).where(:customer_id => self.id).find_in_batches(:batch_size => 50) do |batch|
        batch.each do |order|
          new_order = order.dup
          new_order.parts << order.parts.each {|part| tmp = part.dup; tmp.id = tmp.order_id = nil; tmp}
          new_order.upcs    << order.upcs.each    {|upcs| tmp = upc.dup; tmp.id = tmp.order_id = nil; tmp}

          destination_customer.orders << new_ordert
        end

        # Save one batch
        destination_customer.save!
      end
    end
  end

Can anyone suggest performance friendly way to do this from your own experience? How would you approach this issue if you had one?


texts: Project Euler #5 (Smallest multiple) in Swift

texts:
I found this one a little bit easier than the previous problems, but I was already familiar with the GCD/LCM formulas.

import Foundation

func printTimeElapsedWhenRunningCode(title:String, operation:()->()) {
    let startTime = CFAbsoluteTimeGetCurrent()
    operation()
    let timeElapsed = CFAbsoluteTimeGetCurrent() - startTime
    println("Time elapsed for \(title): \(timeElapsed) s")
}

func greatestCommonDenominator(a: Int, b: Int) -> Int {
    return b == 0 ? a : greatestCommonDenominator(b, a % b)
}

func leastCommonMultiple(a: Int, b: Int) -> Int {
    return a * (b / greatestCommonDenominator(a, b))
}

func leastCommonMultiple(input: [Int]) -> Int {
    var result: Int = input[0]
    for value in input {
        result = leastCommonMultiple(result, value)
    }
    return result
}

func solution5() {
    let firstTwentyInts: [Int] = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]
    let answer: Int = leastCommonMultiple(firstTwentyInts)

    println(String(answer))
}

printTimeElapsedWhenRunningCode("Least Common Multiple", solution5)

And for the record, I know that solution5() is ugly as a function, but for the purposes of this review, you should think of that more like you might think of main in another programming language.  Ultimately, I've only packaged those lines of code into a function so I can throw it in printTimeElapsedWhenRunningCode() which is a nice way to time my solutions.

This particular solution consistently runs in under 0.001 seconds (some times as low as 0.0004 seconds) for me.


texts:
I implemented a Vigenere cipher that preserves case and can also decrypt if you pass the -d argument. Usage is ./vigenere <plaintext|ciphertext> key [-d] and it works fine but I think there are probably some things I could do better. So, just looking for critique.
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>

#define ENCRYPT 1
#define DECRYPT -1

int mod(int x, int n)
{
    return (x % n + n) % n;
}

char *vigenere(char *input, char *keystream, int mode)
{
    if (strlen(keystream) != strlen(input))
        return NULL;

    int output_len = strlen(input), offset = 'a', wasupper = 0;
    char *output = malloc(output_len);

    for (int i = 0; i < output_len; ++i)
    {
        if (isupper(input[i]))
        {
            input[i] = tolower(input[i]);
            wasupper = 1;
        }
        else
            wasupper = 0;

        output[i] = mod((input[i] - offset) + (keystream[i] - offset) * mode, 26) + offset;

        if (wasupper)
            output[i] = toupper(output[i]);
    }

    return output;
}

char *gen_keystream(char *key, int keystream_len)
{
    int key_len = strlen(key), j = 0;
    char *keystream = malloc(keystream_len);

    for (int i = 0; i < keystream_len; j = ++i % key_len)
        keystream[i] = key[j];

    return keystream;
}

int main(int argc, char **argv)
{
    if (argc < 3)
        return EXIT_FAILURE;

    int mode = ENCRYPT;

    if (argc > 3 && strcmp(argv[3], "-d") == 0)
        mode = DECRYPT;

    int keystream_len = strlen(argv[1]);
    char *keystream = gen_keystream(argv[2], keystream_len);
    char *result = vigenere(argv[1], keystream, mode);

    printf("%s\n", result);

    free(keystream);
    free(result);

    return EXIT_SUCCESS;
}


texts: Merge into an object from two different API calls

texts:
I'm working on an app to compare SDKS (their churn and acquisiton rates). I have created an API with two separate endpoints.
The first, compares one sdk to ther other and spits out that data for each sdk.
The second, simply gets general information about a single sdk.
I'm merging these objects into one, so that all information regarding a single SDK can be found.
Problems I previously had, and might still come up (hopefully fixed by now): When setting the object at the end with setAllSdksInfo(objCopy) there was a problem in which it would not set it ok.
I'm also getting an ESLint warning which states "Function declared in a loop contains unsafe references to variable(s) 'objCopy', 'objCopy', 'objCopy', 'objCopy', 'objCopy', 'objCopy', 'objCopy'" but that doesn't seem to be causing any problems.
import React, { useEffect } from "react";
import MatrixSquare from "./MatrixSquare";

function Matrix({ selectedSdks, allSdksInfo, setAllSdksInfo, showMatrix, setShowMatrix }) {

  useEffect(() => {
    (async () => {
      const selectedSdksKeys = Object.keys(selectedSdks);
      if (!selectedSdksKeys.length) return;

      setShowMatrix(false);

      let comparedCount = 0;

      const notComparedKeys = [];

      selectedSdksKeys.forEach((key, i) => {
        for (let j = i + 1; j < selectedSdksKeys.length; j++) {
          if ( allSdksInfo?.[key]?.["churned_to"]?.hasOwnProperty( selectedSdksKeys[j])) {
            comparedCount += 1;
            if (comparedCount === 3) {
              setShowMatrix(true);
            }
          } else {
            notComparedKeys.push([key, selectedSdksKeys[j]]);
          }
        }
      });

      let objCopy = Object.assign({}, allSdksInfo);

      for (let i = 0; i < notComparedKeys.length; i++) {
        await fetch( `/api/sdk/churn?sdk1_id=${notComparedKeys[i][0]}&sdk2_id=${notComparedKeys[i][1]}`)
          .then((res) => res.json())
          .then((res) => {
            const copyPreviousObj = Object.assign({}, objCopy);
            objCopy = { ...objCopy, ...res };
            const resKeys = Object.keys(res);

            resKeys.forEach((key) => {
              const new_churned_to = objCopy[key]["churned_to"];
              const new_acquired_from = objCopy[key]["acquired_from"];

              if (copyPreviousObj[key]) {
                objCopy[key]["churned_to"] = {
                  ...new_churned_to,
                  ...copyPreviousObj[key]["churned_to"],
                };
                objCopy[key]["acquired_from"] = {
                  ...new_acquired_from,
                  ...copyPreviousObj[key]["acquired_from"],
                };
              }
            });
          });
      }

      selectedSdksKeys.forEach(async (id, i) => {
        if (allSdksInfo[id]?.["num_installed_apps"]) return;
        const res = await fetch(`/api/sdk/general_info?sdk_id=${id}`);
        const data = await res.json();
        objCopy[id]["num_installed_apps"] = data["num_installed_apps"];
        objCopy[id]["acquired_total"] = data["acquired_total"];
        objCopy[id]["churned_total"] = data["churned_total"];
      });

      setAllSdksInfo(objCopy);
      setShowMatrix(true);
    })();
  }, [selectedSdks]);


texts: A simple Ansible playbook that powers on a server

texts:
This is an ansible playbook that I use for powering on one of my home servers in a rack, that I just turn on when needed. It checks for the switch power, management (bmc) network, powers the server on, then waits for the SSH port to become available.

The playbook;

#!/usr/bin/ansible-playbook
---
- hosts: localhost
  connection: local
  gather_facts: no
  vars_prompt:
  - name: "PASSWORD"
    prompt: "Password for superone IPMI?"
    private: yes
  tasks:
  - name: switch
    wait_for:
      host: 192.168.66.4
      port: 80
      timeout: 10
  - name: superone-bmc network
    wait_for:
      host: 192.168.66.7
      port: 80
  - name: superone-bmc power
    ipmi_power:
      name: 192.168.66.7
      user: ADMIN
      password: "{{ PASSWORD }}"
      state: on
  - name: superone ping
    wait_for:
      host: 192.168.66.10
      port: 22

I'm looking for your guidance to optimize around the following issues I see in this playbook;

1st concern: "Localhost" referenced when I run it. This is because the ansible connection is local, and I'm not specifying any ansible hosts, but it means these status messages are of absolutely no use;

PLAY [localhost] ****...

TASK [switch] ****...
ok: [localhost]

TASK [server-bmc interface] ****...
ok: [localhost]

2nd concern; If the server is already on (the final ping to 192.168.66.10 succeeds), I've just run a bunch of tasks that were unnecessary. I almost want to run the tasks in reverse, see what fails, then start from there.

This isn't a worry for this short script, but as I'm learning Ansible and writing more complex playbooks, I don't want to waste time with tasks that are unnecessary.

3rd concern: Is anything I'm doing not very Ansible-like, does anything go against Ansible best practices?


texts: Prime generator SPOJ problem in Python 3

texts:
I am trying to solve an SPOJ problem: print all prime numbers in a given range (as large as \$10^9\$). I have used the Sieve of Eratosthenes algorithm. But it is still slow when input is in range of \$10^4\$.

import math
no_of_cases = int(input())

for i in range(no_of_cases):
    x = input().split(" ")
    a = int(x[0])
    b = int(x[1])
    lis = set([p*i for p in range(2,b+1) for i in range(2,b+1)])

    print (sorted(set(range(a,b+1))- lis))

I have already asked a similar question over here.


texts:
I have a class that is used to basically store samples from data being read from a system. Within that class is a property that I use to store the date and time of that sample:

public class ReadingValue
{
    public DateTime DateTimeOfReading { get; set; }
    public float Reading { get; set; }
}

I need to sort a list of ReadingValue based on the DateTimeOfReading property.

This is what I've come up with:

public IEnumerable<ReadingValue> Hourly(IList<ReadingValue> readings)
{
    var sortedReadings = readings.OrderBy(x => x.DateTimeOfReading.TimeOfDay)
        .OrderBy(x => x.DateTimeOfReading.Date)
        .OrderBy(x => x.DateTimeOfReading.Year);

    return sortedReadings;
}

The code seems to work, when I pass in a list of ReadingValue's it returns the list in sorted order. Is there anything I've overlooked or should do differently? I know time and date programming can be a tricky topic with things like timezones, daylight savings etc. but sorting dates and times shouldn't involve any of that, I don't think.


texts:
This is a program to sort three inputted integers in order, from least to greatest. I would like to have it reviewed.

#include <iostream>

void Sort(int &a, int &b, int &c){
    if(a>b){
        int tmp = a;
        a = b;
        b = tmp;
    }
    if(a>c){
        int tmp = a;
        a=c;
        c = tmp;
    }
    if(b>c){
        int tmp = b;
        b=c;
        c=tmp;
    }
    return;
}

int main(){
    std::cout << "Enter three integers: " << std::endl;
    int num1;
    int num2;
    int num3;
    std::cin >> num1 >> num2 >> num3;

    int output1 = num1;
    int output2 = num2;
    int output3 = num3;

    Sort(output1,output2,output3);

    std::cout << num1 << " " << num2 << " " << num3 << " "
         << " in sorted order: ";
    std::cout << output1 << " " << output2 << " " << output3 << std::endl;

    return 0;
}


texts: Static Methods for Dealing with Conversions from and to UTC

texts:
I asked this question over at stackoverflow but was told it may be better suited here.

So I absolutely want to store DateTimeOffset objects in UTC format. To achieve the correct conversions, I've created my own methods to deal with the conversions.

/// String representation of the specified time zone.
        private const String LOCAL_TIME_ZONE_STRING_REPRESENTATION = "GMT Standard Time";
        /// TimeZoneInfo representation of the specified time zone.
        private static TimeZoneInfo LOCAL_TIME_ZONE = TimeZoneInfo.FindSystemTimeZoneById(LOCAL_TIME_ZONE_STRING_REPRESENTATION);

        /// With a given DateTime, passed DateTime is assumed it has been parsed and shares the same time zone as TimeZoneInfo LOCAL_TIME_ZONE.
        /// <param name="dateAndTime">DateTime in TimeZoneInfo LOCAL_TIME_ZONE.</param>
        /// <returns>UTC DateTime.</returns>
        public static DateTime ConvertToUtcDateTime(DateTime dateAndTime)
        {
            return TimeZoneInfo.ConvertTime(dateAndTime, LOCAL_TIME_ZONE).ToUniversalTime();
        }
        /// With a given DateTime, the DateTime is assumed to be a UTC time. It will then return a DateTime converted to TimeZoneInfo LOCAL_TIME_ZONE.
        /// <param name="dateAndTime">DateTime that is in UTC.</param>
        /// <returns>Converted to TimeZoneInfo LOCAL_TIME_ZONE DateTime.</returns>
        public static DateTime ConvertToLocalDateTime(DateTime dateAndTime)
        {
            return TimeZoneInfo.ConvertTimeFromUtc(dateAndTime, LOCAL_TIME_ZONE);
        }

Using the String constant LOCAL_TIME_ZONE_STRING_REPRESENTATION, any user who wishes to compile the code can specify which time zone they want the code to run in, rather than it try to use Window's local time zone.

Then the two above methods can be used to make a conversion between between the two:

private static void Main()
        {
            //Parse a date and time. It is to be assumed this parsed date and time is in the same time zone
            // as LOCAL_TIME_ZONE.
            DateTimeOffset dateTime = ConvertToUtcDateTime(new DateTime(2019,6,1,15,30,0));

            //Assuming we have retrieved a date and time that is in UTC time, we can now convert it
            // to the same time zone as LOCAL_TIME_ZONE.
            DateTime convertedFromUTC = ConvertToLocalDateTime(dateTime.DateTime);
}

The system would be able to parse DateTime's that have no time zone associated with them regardless where they would've came from, and convert them into UTC time assuming that DateTime came from the same TimeZone as LOCAL_TIME_ZONE. The only time where we would need to convert retrieved UTC DateTimes back into the same time zone as LOCAL_TIME_ZONE would be when we are visually displaying it to a user. All TimeSpan calculations etc, would use the UTC DateTimeOffset.

This seems to work as intended, and I can change LOCAL_TIME_ZONE_STRING_REPRESENTATION to any time zone I want, and using the methods I created, the system uses that time zone instead of Window's local time zone.

This would be particularly useful for me as the server hosting an application may be in a different time zone and have a different culture, but its intended users could be for a totally different time zone.

Am I making too much work for myself, or would this be a reasonable way to implement what I need?


texts:
I have an alternative algorithm to the same problem as Finding missing items in an int list.

My implementation includes optional min and max bounds to selectively fill in the list.

The linked implementation is much simpler.

My Questions are:

How do our two algorithms compare, efficiency wise?
Besides the algorithm linked, are there more efficient algorithms?
Did I identify and does my algorithm work for the edge cases?

I tried not to use min and max because I heard that they are \$\mathcal{O}(n)\$.

However, I used the .index method for lists. I am not sure how efficient .index is. I would think that it would be \$\mathcal{O}(\log n)\$ for a sorted but I am not sure if or how the .index function would know that a given list is sorted.

Additionally, I used exceptions, which do give a performance penalty.

7 Cases

One missing number - Normal
Multiple Missing Numbers - Normal
No missing numbers - Normal
Repeats - Normal
Array too small - Case for empty array: returns an array of the numbers from min_val to max_val inclusive
Missing numbers at end - Filled in based on the min and max number
Numbers out of range - Ignored those which were out of range

from bisect import bisect_left

def find_missing(int_array, min_val = False, max_val = False):

"""Doctest

>>> find_missing([1,2,3,5,6,7], 1, 7)

[4]
>>> find_missing([2,3,6,4,8], 2, 8)

[5, 7]
>>> find_missing([1,2,3,4], 1, 4)

[]
>>> find_missing([11,1,1,2,3,2,3,2,3,2,4,5,6,7,8,9],1,11)

[10]
>>> find_missing([-1,0,1,3,7,20], -1, 7)

[2, 4, 5, 6]

>>> find_missing([-2,0,3], -5, 2)

[-5, -4, -3, -1, 1, 2]

>>> find_missing([2],4,5)

[4, 5]

>>> find_missing([3,5,6,7,8], -3, 5)

[-3, -2, -1, 0, 1, 2, 4]

>>> find_missing([1,2,4])

[3]

"""
if len(int_array) == 0:
    return list(range(min_val, max_val+1))

int_array = sorted(int_array)
first_in_int_array = int_array[0]
last_in_int_array = int_array[len(int_array)-1]

if not min_val:
    min_val = first_in_int_array

if not max_val:
    max_val = last_in_int_array
result = []

#Checking to see if the min & max values currently exist
#If they do not then add them to the resultant array as they are missing numbers
if min_val < first_in_int_array:
    int_array.insert(0, min_val)
    result.append(min_val)

if max_val > last_in_int_array:
    int_array.insert(len(int_array), max_val)
    result.append(max_val)

#Dealing with case where max_val < last_in_int_array but not in array
#Example: max_val = 2 int_array = [1,3]
#Also dealing with the analogous case for min_val and first_in_int_array
#Deal with this using exceptions
try:
    min_pos = int_array.index(min_val)

except Exception as e:
    result.append(min_val)
    min_pos = bisect_left(int_array, min_val)
    int_array.insert(min_pos, min_val)

try:
    max_pos = int_array.index(max_val)
except Exception as e:
    result.append(max_val)
    max_pos = bisect_left(int_array, max_val)
    int_array.insert(max_pos, max_val)

for i in range(min_pos,max_pos):
    difference = int_array[i+1] - int_array[i]
    if difference != 1 and difference != 0:
        result += range(int_array[i]+1,int_array[i+1])

result.sort()
return result


texts: Improving F# conditional assignment with match expression

texts:
In my code I declared a dictionary to store various counters

let counters = Dictionary<Type, int>()

Later, I need to generate several labels using these counters, like this:

First type a label is generated for a given type, it should consist of the type name itself:
"MyType"
Subsequent label should be the type name, appended with the number of times a label was previously generated for that type, in parentheses:
"MyType (2)"

Here's how I'm accomplishing this now:

let t : Type = ...

let label =
    if (counters.ContainsKey(t)) then
        counters.[t] <- counter.[t] + 1
        sprintf "%s (%i)" t.Name counters.[t]
    else
        counters.Add(t, 1)
        t.Name

This is exactly how I would write it if I had to use C# (with the exception of the in-line if / else), but after I wrote it F#, it seems clumsy and a little messy. I suspect there is a much more elegant, idiomatic way of writing this in F#. Perhaps using a match expression?


texts: Project Euler #14 (Longest Collatz sequence)

texts:
A Collatz sequence for a given positive integer \$n\$ is to take half of \$n\$ if even and \$3n+1\$ if \$n\$ is odd; repeat until the value goes to \$1\$.  The question is which number from 1 to 1,000,000 has the longest Collatz sequence?

The Collatz sequence for \$n=13\$ from Project Euler #14:

  13 → 40 → 20 → 10 → 5 → 16 → 8 → 4 → 2 → 1

I wrote this code with lists, but the program never seemed to come to an end. I rewrote it with arrays, and it's still the same. Starting from 10, increasing the number 10 times seems to increase the program run time by roughly 100 times, and at this rate it will take about 15 days for it to complete.

The algorithm is to take a number, generate its Collatz sequence, and eliminate all the even multiples of the numbers from the sequence.

import numpy as np

p = 1000000    #maximum number that the code works up to
collatz_array = np.zeros([3, p-2], dtype='int64')

for i in range(2, p):
    i = int(i)
    collatz_array[0][i-2] = collatz_array[1][i-2] = i  #1st row and 2nd row are populated with natural numbers from 2 to p

for i in collatz_array[0]: #the numbers in the first row of the array can be zeroed if they are done with, while the second row is used as a reference
    if i != 0:
        k = i    #for i to remain unchanged
        count = 1
        sequence = []    #list to store the complete collatz sequence
        sequence.append(k)
        while k > 1:
            if k % 2 == 0:
                count += 1
                k = k//2
                sequence.append(k)
            else:
                count += 1
                k = int((3*k)+1)
                sequence.append(k)
        c = 0
        for q in sequence:                           #q is an element in the sequence
            if q in collatz_array[0]:
                q = int(q)
                collatz_array[2][q-2] = count - c    #the length of the collatz sequence of a number is stored in the third row
                                                     #as the sequence progresses, the count is decreased with 'c'
                w = q                                #for q to remain unchanged
                for e in range(1, p//q):             #loop is run for about the number of even multiples of q
                    w *= 2                           #the next even multiple
                    if w in collatz_array[0]:
                        collatz_array[2][w-2] = collatz_array[2][i-2] + e    #the length of the sequence increases by 1, for an even multiple
                        collatz_array[0][w-2] = 0
                collatz_array[0][q-2] = 0
            c += 1

max_value, max_count = 0, 0
for i in range(2, p):
    if max_count < collatz_array[2][i-2]:
        max_count = collatz_array[2][i-2]
        max_value = collatz_array[1][i-2]

print("Number with longest collatz sequence: ", max_value)

Example: i = 13, sequence = [13, 40, 20, 10, 5, 16, 8, 4, 2, 1], count = 10 for 13 and decreases by 1 for the next number,  w = 13 and it's even multiples 26, 52, 104 and so on are eliminated from collatz_array[0] with their counts increased by 1.

This is the best algorithm I have been able to think of, that seems to work. Is it possible to start from 2 and go up? I can't think of a complete algorithm to do that.

(P.S. I know there are other similar questions, which I haven't gone through and might do after solving the problem myself, but I only want to optimize my code.)


texts: Reverse string in JavaScript without using reverse()

texts:
I have to reverse a string in JavaScript and cannot use the built in reverse() function. It does not seem efficient to have to create two arrays but is there a better way?

function reverseString(str) {
  newarr = str.split("");
  result = [];
  x = newarr.length;
  for (i = x; i > -1; i--) {
    result.push(newarr[i]);
  }
  str = result.join("");
  return str;
}

reverseString("hello");


texts:
For each ID found in Column A in the XLS file, run a query to
  retrieve and save a customer.

"Customers" table in db.accdb Access file
+----+-----------------+
| ID |    Customer     |
+----+-----------------+
|  1 | Thomas Moody    |
|  2 | Natalie Laguna  |
|  3 | James Robinson  |
+----+-----------------+

.xlsx Excel worksheet
+----------+
| Column A |
+----------+
|        1 |
|        2 |
|        3 |
+----------+

Solution:

Should I use Singleton pattern to persist connection lifetime?
I'm sure it's better to retrieve all customers at once but what's next? How do I retrieve customers that easily?

Option Explicit

Private pDb As ADODB.Connection
Private pDbCmd As ADODB.Command
Private pDbRecordset As ADODB.Recordset

Private Sub Main()

    ' Assuming I've already read values from column into an array
    Dim customerIDs(1 To 3, 1 To 1) As Long
    Let customerIDs(1, 1) = 1
    Let customerIDs(2, 1) = 2
    Let customerIDs(3, 1) = 3

    Dim i As Long
    Dim customerID As Long
    Dim customer As String

    ' For each ID run a query, retrieve and display a customer name
    For i = 1 To UBound(customerIDs, 1)
        Let customerID = customerIDs(i, 1)
        Let customer = GetCustomer(customerID)

        Debug.Print customer
    Next i

    Call CloseConnection

End Sub

Private Function QueryDB(sqlQuery As String) As String

    ' Singleton
    If (pDb Is Nothing) Then
        Call OpenConnection
    End If

    Call ExecuteCmd(sqlQuery)
    Let QueryDB = ReadRecord

End Function

Private Function GetCustomer(ID As Long) As String

    ' Prepare SQL query
    Dim sqlQuery As String
    Let sqlQuery = "SELECT Customer FROM Customers WHERE Customers.ID = " & ID

    ' Return
    Let GetCustomer = QueryDB(sqlQuery)

End Function

Private Sub OpenConnection()

    Set pDb = New ADODB.Connection
    Set pDbCmd = New ADODB.Command
    Set pDbRecordset = New ADODB.Recordset

    Dim dataSource As String
    Let dataSource = ThisWorkbook.Path & "\db.accdb"

    Dim connectionString As String
    Let connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & dataSource & ";Persist Security Info=False;"

    Call pDb.Open(connectionString)
    Let pDbCmd.ActiveConnection = pDb

End Sub

Private Sub ExecuteCmd(sqlQuery As String)

    pDbCmd.CommandText = sqlQuery
    pDbCmd.CommandType = adCmdText

    Set pDbRecordset = pDbCmd.Execute

End Sub

Private Function ReadRecord() As String

    Do While Not (pDbRecordset.EOF)
        Let ReadRecord = pDbRecordset.Fields("Customer").value
        Call pDbRecordset.MoveNext
    Loop

End Function

Private Sub CloseConnection()

    Call pDb.Close

    Set pDbRecordset = Nothing
    Set pDbCmd = Nothing
    Set pDb = Nothing

End Sub


texts:
I'm posting a solution for LeetCode's "String to Integer (atoi)". If you'd like to review, please do. Thank you!
Problem

Implement atoi which converts a string to an integer. The function first discards as many whitespace characters as necessary until the first non-whitespace character is found. Then, starting from this character takes an optional initial plus or minus sign followed by as many numerical digits as possible, and interprets them as a numerical value. The string can contain additional characters after those that form the integral number, which are ignored and have no effect on the behavior of this function. If the first sequence of non-whitespace characters in str is not a valid integral number, or if no such sequence exists because either str is empty or it contains only whitespace characters, no conversion is performed. If no valid conversion could be performed, a zero value is returned.

Note:

Only the space character ' ' is considered a whitespace character.
Assume we are dealing with an environment that could only store integers within the 32-bit signed integer range: [−231,  231 − 1]. If the numerical value is out of the range of representable values, 231 − 1 or −231 is returned.

Example 1:
Input: str = "42"
Output: 42

Example 2:
Input: str = "   -42"
Output: -42
Explanation: The first non-whitespace character is '-', which is the minus sign. Then take as many numerical digits as possible, which gets 42.

Example 3:
Input: str = "4193 with words"
Output: 4193
Explanation: Conversion stops at digit '3' as the next character is not a numerical digit.

Example 4:
Input: str = "words and 987"
Output: 0
Explanation: The first non-whitespace character is 'w', which is not a numerical digit or a +/- sign. Therefore no valid conversion could be performed.

Example 5:
Input: str = "-91283472332"
Output: -2147483648
Explanation: The number "-91283472332" is out of the range of a 32-bit signed integer. Thefore INT_MIN (−231) is returned.

Code
from typing import List
import collections
import itertools
import functools
import math
import string
import random
import bisect
import re
import operator
import heapq
import queue

from queue import PriorityQueue
from itertools import combinations, permutations
from functools import lru_cache
from collections import defaultdict
from collections import OrderedDict
from collections import deque
from collections import Counter

class Solution:
    def myAtoi(self, s):
        s = re.findall(r'^\s*[+-]?\d+', s)
        try:
            MAX, MIN = 2147483647, -2147483648
            res = int(''.join(s))
            if res > MAX:
                return MAX
            if res < MIN:
                return MIN
            return res
        except:
            return 0

if __name__ == "__main__":
    print(Solution().myAtoi("   -42"))

References:

LeetCode 8. String to Integer (atoi)

Leetcode atoi (string to integer)


texts:
This is a start on a multi-threaded game loop and I just wish to confirm my code is going in the correct direction, and if not, if there is any way it can be improved. I have good experience in game development and C++ in general, but limited experience when it comes to multi-threaded environments.

#include <iostream>
#include <string>
#include <thread>
#include <mutex>
#include <memory>
#include <chrono>

class Test
{
public:
    Test()
    {
        std::cout << "Test starting" << std::endl;
        start();
    }
    ~Test()
    {
        stop();
        std::cout << "Test finished" << std::endl;
    }
    inline void quit()
    {
        running = false;
    }
private:
    void start()
    {
        renderThread = std::unique_ptr<std::thread>(new std::thread(&Test::renderFunc, this));
        updateThread = std::unique_ptr<std::thread>(new std::thread(&Test::updateFunc, this));
        std::cout << "Threads Created" << std::endl;
        running = true;
    }
    void stop()
    {
        renderThread->join();
        updateThread->join();
        std::cout << "Threads joined" << std::endl;
    }

    void updateFunc()
    {
        while(running)
        {
            mutex.lock();
            std::cout << "update" << std::endl;
            mutex.unlock();
        }
    }

    void renderFunc()
    {
        while(running)
        {
            mutex.lock();
            std::cout << "render" << std::endl;
            mutex.unlock();
        }
    }

    volatile bool running;
    std::mutex mutex;
    std::unique_ptr<std::thread> renderThread;
    std::unique_ptr<std::thread> updateThread;
};

int main(int argc, char* argv[])
{
    std::unique_ptr<Test> test = std::unique_ptr<Test>(new Test());

    typedef std::chrono::high_resolution_clock Clock;
    typedef std::chrono::seconds Seconds;

    Clock::time_point t0, t1;
    Seconds seconds;

    t0 = Clock::now();
    do
    {
        t1 = Clock::now();
        seconds = std::chrono::duration_cast<Seconds>(t1 - t0);
    }while(seconds.count() <= 15);

    test->quit();

    return 0;
}

(The timer code is just there for testing the threaded code.)


texts: Return IEnumerable from a private method; use Dictionary or anon. type?

texts:
Is it okay to return IEnumerable<KeyValuePair<string, string>> from a private method instead of returning a read-only dictionary? This allows for shorter/simpler code.

Note: In the below code, PropertyDictionary is a static property that returns an IReadOnlyDictionary<string, PropertyInfo> that was created through reflecting over the MyClass class looking for public, non-static, string-returning properties bearing a particular attribute. Also, the instance method that calls GetPropertyValues does some formatting, immediately changing the result into an IEnumerable<string>, so the dictionary aspect isn't needed for long.

private static IEnumerable<KeyValuePair<string, string>> GetPropertyValues(MyClass myClass) {
   return
      PropertyDictionary.ToDictionary(
         kvp => kvp.Key,
         kvp => (string) kvp.Value.GetValue(myClass, null)
      )
      .Where(kvp => !string.IsNullOrEmpty(kvp.Value));
}

vs.

private static IReadOnlyDictionary<string, string> GetPropertyValues(MyClass myClass) {
   return
      new ReadOnlyDictionary(
         PropertyDictionary.ToDictionary(
            kvp => kvp.Key,
            kvp => (string) kvp.Value.GetValue(myClass, null)
         )
         .Where(kvp => !string.IsNullOrEmpty(kvp.Value))
         .ToDictionary(kvp => kvp.Key, kvp => kvp.Value)
      );
}

This converts to a dictionary twice. I wish there were a way to do Where and Select at the same time! Perhaps there is a better way. Can you suggest one?

Also, should I use an anonymous type instead of a dictionary for the intermediate step?

private static IEnumerable<KeyValuePair<string, string>> GetPropertyValues(MyClass myClass) {
   return
      PropertyDictionary.Select(
         kvp => new {
            key = kvp.Key,
            value = (string) kvp.Value.GetValue(myClass, null)
         }
      )
      .Where(o => !string.IsNullOrEmpty(o.Value));
    // But now this isn't returning a Dictionary, but an anonymous object,
    // so this isn't going to work
}

and

private static IReadOnlyDictionary<string, string> GetPropertyValues(MyClass myClass) {
   return
      new ReadOnlyDictionary(
         PropertyDictionary.Select(
            kvp => new {
               key = kvp.Key,
               value = (string) kvp.Value.GetValue(myClass, null)
            }
         )
         .Where(o => !string.IsNullOrEmpty(o.value))
         .ToDictionary(o => o.key, o => o.value)
      );
}

Are either of these substantially superior?

Of course, all comments to improve quality are welcome.

A peripheral note on the Reflection shown here

Please stay focused on the requested aspects of the code review. For informational purposes: there are a number of properties in MyClass that have a special label accompanying them. This code is expected to be changed over time with new properties being added. Instead of the labels being associated with each property via a list or procedurally, and being far away in the code from the properties themselves, it seems best to me that each property simply be annotated via an attribute (right next to the property!) stating the property's key for serialization. Getting that attribute takes reflection. The PropertyInfo collection is materialized only once, and then used repeatedly at serialization time. If there is a performance problem, which I don't anticipate, I will use Reflection.Emit to solve it, because I think the value of the label-bearing attribute is high and leads to better and easier to maintain code.


texts: Nesting for loops to find matches in different tables

texts:
I'm not sure if I'm even approaching this correctly (still very much learning), but this is what I'm attempting to accomplish:
My script gets an array from a column (tab names of the sheet) and then calls another function to copy those tabs (this part works fine).  What I'm attempting to add is a separate list of properties that I want to assign to each copied sheet (visibility, color, etc.)  This secondary list is on another tab, so my thought was that within my first loop (that determines which tabs to copy), I would have a nested loop that would find the match to the tab name and then bring those variables in to be associated with the sheet name.
My secondary for loop works, but it seems counter intuitive or somewhat redundant.  It feels like a lot of wasted effort to loop through the "properties array" for every loop, but maybe it is necessary.
function getSheetArray(ui, ss, settingsSheet, updateID, latestVersion, versionRangeName, updateSheet, updateSheetsSheet, sheetsToUpdateRangeName, updateSheetsVals) {
  var updateSheetsLength = updateSheetsVals.filter(String).length;
  if (updateSheetsLength == null) {
    return
  }
  var sheetDataRange = updateSheetsSheet.getRange(2, 1, updateSheetsLength, 1);
  const sheetData = sheetDataRange.getValues();

  var updateSheet = SpreadsheetApp.openById(updateID);
  var tabSheet = updateSheet.getSheetByName("tabDefinitions");
  var tabDataRange = tabSheet.getRange(2, 1, tabSheet.getMaxRows() - 1, tabSheet.getMaxColumns());
  const tabData = tabDataRange.getValues();
  var tabProps = [];
  for (var i = 0; i < sheetData.length; i++) {
    var sheetName = sheetData[i];

    for (var j = 0; j < tabData.length; j++) {
      if (sheetName == tabData[j][0]) {
        var tabProps = [
          tabName = tabData[j][0],
          tabVisibility = tabData[j][3],
          tabUpdVisibility = tabData[j][4],
          tabClearData = tabData[j][5],
          tabFormat = tabData[j][6],
          tabPosition = tabData[j][7],
          tabColor = tabData[j][8]
        ];
      }
    }
    console.log("tabProps = ", tabProps);
    console.log("tabName = " + tabName);
  }
}


texts: Transferring large amounts of data in web editor

texts:
I am making a web editor for fun and I was told that the way I was doing it (using PHP) would be a bad way. I also thought about it while I was making it, and in massive sums of data transfer it would be a bad idea to do it this way. I can't think of another way to do it and was looking for someone to help me improve it, by that I mean my save method I am using.

Editor:

    <title>Web Editor</title>
    <link href="controller.css" rel="stylesheet" />

File:

C:\hello.html

JS:

function save() {
  var dir = document.getElementById("file").innerHTML;
  var data = document.getElementById("editPad").innerHTML;
  window.location = "save.php?dir=" + encodeURIComponent(dir) + "&data=" + encodeURIComponent(data);
}

PHP:

<?php
    $dir = $_GET['dir'];
    $data = $_GET['data'];
    $lookFor = array("&lt;", "&gt;","
","<%2Fdiv>","
","
");
    $replaceWith = array("<", ">", "", "", "","");
    $newData = str_replace($lookFor,$replaceWith,$data);

    $f = fopen(urldecode($dir),"w");
    fwrite($f,urldecode($newData));
    fclose($f);
?>

All of it is just a work in progress and I need more done. But for right now, is there a better way for me to save the file with massive sums of data being transferred?


texts: Find combination of sets which sum up to a specified result

texts:
Example input :

  A) 1, 2

  B) 2, 8

  C) 7, 8

  Required Result : 8, 10

The output from the program with this input should be A + C.

Few notes :

We can only combine 2 sets.
There must always be exactly one pair (or a single set) which sums up to the specified result.
Input will always be in this format x,y.

Set

internal class Set
{
    protected bool Equals(Set other)
    {
        return Number01 == other.Number01 && Number02 == other.Number02;
    }

    public override bool Equals(object obj)
    {
        if (ReferenceEquals(null, obj)) return false;
        if (ReferenceEquals(this, obj)) return true;
        if (obj.GetType() != this.GetType()) return false;
        return Equals((Set) obj);
    }

    public override int GetHashCode()
    {
        unchecked
        {
            return (Number01*397) ^ Number02;
        }
    }

    public int Number01 { get; }
    public int Number02 { get; }

    public Set(int number01, int number02)
    {
        Number01 = number01;
        Number02 = number02;
    }

    public static Set operator +(Set set1, Set set2)
    {
        return new Set(set1.Number01 + set2.Number01, set1.Number02 + set2.Number02);
    }
}

Static void Main

    static void Main(string[] args)
    {
        Console.Write("Length : ");
        int inputLength = int.Parse(Console.ReadLine());
        string[] inputSets = new string[inputLength];
        Set[] sets = new Set[inputLength];

        for (int i = 0; i < inputLength; i++)
        {
            Console.Write($"Enter set #{i + 1} : ");
            inputSets[i] = Console.ReadLine();
        }

        Console.Write("Enter the expected result : ");
        string[] answer = Console.ReadLine().Split(',');
        Set requiredResult = new Set(int.Parse(answer[0]), int.Parse(answer[1]));

        for (int i = 0; i < inputSets.Length; i++)
        {
            string[] numbersFromSet = inputSets[i].Split(',');
            sets[i] = new Set(int.Parse(numbersFromSet[0]), int.Parse(numbersFromSet[1]));
        }

        foreach (Set set in sets)
        {
            if (Equals(set, requiredResult))
            {
                Console.WriteLine("First set : " + set.Number01 + " " + set.Number02);
                Console.WriteLine("Result : " + requiredResult.Number01 + " " + requiredResult.Number02);
                Console.ReadKey();
                return;
            }
        }

        for (int i = 0; i < sets.Length; i++)
        {
            for (int j = i + 1; j < sets.Length; j++)
            {
                if (Equals(sets[i] + sets[j], requiredResult))
                {
                    Console.WriteLine("First set : " + sets[i].Number01 + " " + sets[i].Number02);
                    Console.WriteLine("Second set : " + sets[j].Number01 + " " + sets[j].Number02);
                    Console.WriteLine("Result : " + requiredResult.Number01 + " " + requiredResult.Number02);
                    Console.ReadKey();
                    return;
                }
            }
        }
        Console.ReadKey();
    }


texts:
Suppose there is a number N which can be divided into two positive non zero numbers X and Y i.e N = X + Y. There will be N/2 pairs of (X,Y).

I want to find the largest LCM(Least common multiple) of X & Y

  Example
  5 = (1 + 4) and 5 = (2 + 3)
  Since LCM(1,4) = 4 < LCM(2,3) = 6 the largest LCM will be LCM(2,3) = 6.

CODE

#include <stdio.h>
int lcm(int, int);
int main(void)
{
     int counter = 0;
     int lowerBound = 0, upperBound, input, result; // input is the n
     printf("input = ");
     scanf("%d",&input);
     int max = -1;
     upperBound = input; // at first upperBound will be the input
     for(counter=0; counter < input/2; counter++) // we will iterate till the input/2 terms
     {
         lowerBound++;
         upperBound--;

         // in every iteration we will compute the lcm of lowerBound and upperBound
         // so 1st iteration : compute lcm(1, n-1)
         // 2nd iteration    : compute lcm(2, n-2)
         // 3rd iteration    : compute lcm(3, n-3)
         // .......after ((n/2)-1)th iteration.....
         // if n is even     : compute lcm(n/2, n/2)
         // if n is odd      : compute lcm((n/2)-1, n/2)

         result = lcm(lowerBound,upperBound); // store the result

         if(result >= max) // if result is maximum update the maximum
         {
             max = result;
         }
     }

     printf("output = %d",max);
    return 0;
}

int lcm(int x, int y)
{
    int n1 = x, n2 = y;
    while(n1 != n2)
    {
        if(n1 > n2)
           n1 = n1 - n2;
        else
        n2 = n2 - n1;
    }
  return((x*y) / n1);
}

OUTPUT 1

input = 10
output = 21

OUTPUT 2

input = 11
output = 30

UPDATE 1

After Aseem Bansal's answer I try to find a more optimize way to solve the problem and i came up with this code

#include<stdio.h>
int main(void)
{
    int input, result = 0;
    printf("Enter the input = ");
    scanf("%d",&input);

    while(input <= 0) // if input is negative ask again
    {
        printf("Enter a positive non zero number :");
        scanf("%d",&input);
    }

    int middle = (input/2);
    if(input%2 != 0) // if the input is an odd number
    {
        result = (middle * (middle+1));
    }

    else // if input is an even number
    {
        result = middle%2 == 0 ? ((middle-1) * (middle+1))
                               : ((middle-2) * (middle+2));
    }

    printf("result = %d",result);
    return 0;
}

OUTPUT 1

Enter the input = 13
result = 42

OUTPUT 2

Enter the input = 12
result = 35

OUTPUT 3

Enter the input = 10
result = 21

EXPLANATION

As for any odd number the middle and middle+1 are highest coprime numbers, so the GCD will be 1. Therefore LCM will be product of middle and middle+1.

But for any even number the LCM of middle and middle+1 is 1. So we need to find the nearest coprime numbers. If middle is even then the nearest coprime numbers are middle-1 and middle+1 otherwise the nearest coprime numbers are middle-2 and middle+2. The product will be the result.

NOTE

here middle is floor of (middle).

Can it be more optimized? Any review is welcome.


texts: A collection of tasks and their CancellationTokens

texts:
I have a task wrapper which stores tasks, their CancellationTokens and of course their names (botName). botName is important, because when I want to stop a bot/cancel task, I will have to find it in the collection.

I wonder if there is a better collection to do that, because it looks ugly, especially the CancellationToken cancellation logic.

public class BotWrapper
{
    private readonly static ConcurrentDictionary<string, Tuple<Task, CancellationTokenSource>> _bots = new ConcurrentDictionary<string, Tuple<Task, CancellationTokenSource>>();

    public void Start(string botName, string symbol, KlineInterval interval, StrategyBase strategy)
    {
        CancellationTokenSource cts = new CancellationTokenSource();

        Task task = Task.Run(() => strategy.Start(symbol, interval, cts.Token), cts.Token);

        _bots.TryAdd(botName, new Tuple<Task, CancellationTokenSource>(task, cts));
    }

    public void Stop(string botName)
    {
        foreach (var bot in _bots)
        {
            if (bot.Key.Contains(botName))
            {
                CancellationTokenSource cts = bot.Value.Item2;
                cts.Cancel();

                Thread.Sleep(2500);

                cts.Dispose(); // unmanaged

                _bots.TryRemove(botName, out _);
            }
        }
    }
}

By the way StrategyBase.Start is nothing specific:

public virtual void Start(string symbol, KlineInterval interval, CancellationToken token)
{
    ... logic

    ... and at some point

    if (token.IsCancellationRequested)
    {
        try
        {
            token.ThrowIfCancellationRequested();
        }
        catch (OperationCanceledException)
        {
            SocketClient.UnsubscribeAll();
            Console.WriteLine("Task canceled.");
        }
    }
}
```


texts:
My program 'Monkey', written in Go, can take a file like this:

+ 9 13
/ 10 2

And prints the output (in the case for the 'file' above, '22' and '5'.)
Variables can also be declared to an expression. In this 'file':

* 5 4 : a
+ a 2 : a

The variable a ends up as 22, because at first we assign it to 5 * 4 (20), and then add 2 (22).

Here's the source for the program, and here it is with syntax highlighting.

package main

import (
    "bufio"
    "fmt"
    "os"
    "strings"
    "strconv"
)

// error management
func check(e error) {
    if e != nil {
        panic(e)
    }
}

func openfile(filename string) (lines []string) {
    // safely open file
    source, err := os.Open(filename)
    check(err)

    scanner := bufio.NewScanner(source)
    // equivalent to a while loop
    for scanner.Scan() {
        lines = append(lines, scanner.Text())
    }

    return
}

var variables map[string]float32

// determine whether a token is a variable reference or
// an integer literal, and return it.
func getvalue(item string) float32 {
    // if item is number
    if num, err := strconv.Atoi(item); err == nil {
        return float32(num)
    }
    return variables[item]
}

func operate(operands []string, op string) float32 {
    var result float32 = 0
    // o = index in operands[]
    for o := 0; o < len(operands); o++ {
        if op == "+" {
            if o == 0 {
                result = getvalue(operands[0])
            } else {
                result += getvalue(operands[o])
            }
        } else if op == "-" {
            if o == 0 {
                result = getvalue(operands[0])
            } else {
                result -= getvalue(operands[o])
            }
        } else if op == "*" {
            if o == 0 {
                result = getvalue(operands[0])
            } else {
                result *= getvalue(operands[o])
            }
        } else if op == "/" {
            if o == 0 {
                result = getvalue(operands[0])
            } else {
                result /= getvalue(operands[o])
            }
        } else {
            return 0.0
        }
    }
    return result
}

var x, y int64 // these will be assigned to function params
var xerr, yerr error
func main() {
    variables = make(map[string]float32)
    lines := openfile(os.Args[1])
    for lineNumber, line := range lines {
        words := strings.Split(line, " ")
        operands := 0 // count of numbers that the operation will be applied to
        for _, word := range words {
            if _, err := strconv.Atoi(word); err == nil {
                operands += 1
            }
        }
        // line needs to end in ';' or ': varName' to be correct
        if len(words) >= operands + 2 {
            if words[operands + 1] == ";" {
                fmt.Println(operate(words[1:operands+1], words[0]))
            } else if words[operands + 1] == ":" {
                fmt.Println("var", words[operands + 2], "=", operate(words[1:operands+1], words[0]))
                variables[words[operands + 2]] = operate(words[1:operands+1], words[0])
            }
        } else if len(words) < 0 && len(words) < operands + 2 {
            fmt.Println("error: not enough arguments at line", lineNumber)
        }
    }
}


texts:
I am trying to solve a Hackerrank problem Sherlock and Anagrams. I think my code is valid but somehow times out for some of the test cases. Any tips on how to improve its performance? Critique unrelated to performance is welcome as well!
Here is my main method which gets a string as an input and returns an integer that represents the number of pairs of substrings of the string that are anagrams of each other:
function sherlockAndAnagrams(s) {

    let substrings = [];
    let pairs = [];

    // get all substrings
    for (let i = 0; i < s.length+1; i++) {
        for (let j = i+1; j < s.length+1; j++) {
            substrings.push(s.substring(i, j));
        }
    }

    // sort substrings so they can be compared using ===
    substrings = substrings.map(sub => [...sub].sort().join(""));

    // count them by comparing each with each skipping the ones with different length
    return substrings.reduce((counter, sub, index, arr) => {
        return counter += arr.reduce((acc, item, jndex) => {
            if (sub.length === item.length && sub === item && index !== jndex) {
                let uid = [index, jndex].sort().join("");
                if (!pairs.includes(uid)) {
                    acc++;
                    pairs.push(uid);
                }
            }
            return acc;
        }, 0);
    }, 0);
}

Here is a shortened version of the problem description as additional context:

Two strings are anagrams of each other if the letters of one string can be rearranged to form the other string. Given a string, find the number of pairs of substrings of the string that are anagrams of each other.
sherlockAndAnagrams has the following parameter: s: a string
It must return an integer that represents the number of anagrammatic pairs of substrings in s. For each query, return the number of unordered anagrammatic pairs.


texts:
I currently am making a small application where a user will enter their ID which needs to be in a certain format.  When entered in the wrong format, different output errors are produced.

I currently output errors like this:

public void errorLogger(string error)
        {
            errors += error + Environment.NewLine + "
";
        }

I have read that using += is not a great operator to use. Alternatively I have thought this may be better:

public void errorLogger(string key, string err)
        {
            if(!String.IsNullOrEmpty(err))
            output.Add(key, err);
        }

but then I basically do the same thing later:

    string keys = "";
    foreach (KeyValuePair<string, string> entry in core.errorLogger())
    {
        keys += entry.Key + ":       " + entry.Value + "
";
    }

Is there a cleaner way to output errors?  The output is injected under the submit button into:

errorSpan.InnerHtml = (keys);

This is what I ended up using going off of Charles' response to AWinkle

public void logError(string err, string desc)
                {
                    if(!String.IsNullOrEmpty(desc))
                        errors.AppendFormat("{0,10}:&nbsp;{1}
", err, desc);
                }
public string getErrors()
            {
                return errors.ToString();
            }

Then :

errorspan.InnerHtml = (core.getErrors());


texts:
Following snippet reads CSV Line count using BinaryReader.

Currently it checks \r and \n for line delimiters.

        private static int GetLineCount(string fileName)
        {
            BinaryReader reader = new BinaryReader(File.OpenRead(fileName));
            int lineCount = 0;

            char lastChar = reader.ReadChar();
            char newChar = new char();

            do
            {
                newChar = reader.ReadChar();
                if (lastChar == '\r' && newChar == '\n')
                {
                    lineCount++;
                }
                lastChar = newChar;
            } while (reader.PeekChar() != -1);
            return lineCount;
        }

I want to use Environment.NewLine string and make it work on windows\unix.

I want to refactor above to find word occurance and then match for the word Environment.NewLine. The issue is that I am not able to refactor following for word (more specifically change lastChar , newChar into Array.

                do
                {
                    newChar = reader.ReadChar();
                    if (lastChar == '\r' && newChar == '\n')
                    {
                        lineCount++;
                    }
                    lastChar = newChar;
                } while (reader.PeekChar() != -1);


texts: Creating an IUserSession that is used throughout my code

texts:
I need a bit of help on if I have coded this class correctly.

I want to handle the setting of client cookie/client store.

public class UserSession : IUserSession
{

    private readonly IReadOnlySession _repo;
    public UserSession(IReadOnlySession repo)
    {
        _repo = repo;
    }

    private string _loginId;
    public string LoginID
    {
        get { return HttpContext.Current.User.Identity.Name; }
        set { _loginId = value; }
    }

    private string _companyIdentifier;
    public string CompanyIdentifier
    {
        get { return AuthenticateCookie.GetCompanyIdentifierFromTicket(LoginID); }
        set { _companyIdentifier = value; }
    }

    /// <summary>
    /// when the client store is set, this means the user has been changed
    /// </summary>
    /// <param name="loginId"></param>
    /// <param name="identifier"></param>
    public void SetClientStore(string loginId, string identifier)
    {
        MyProfile = null;
        AuthenticateCookie.AddDetailsToCookie(loginId, identifier);

        LoginID = loginId;
        CompanyIdentifier = identifier;
    }

    public void Logout()
    {
        // we could throw an exception here?
        MyProfile = null;
        HttpContext.Current.User = null;
        FormsAuthentication.SignOut();
        //clear cookie values too?

    }

    private UserProfile _myprofile;
    public UserProfile MyProfile
    {
        get { return SetupProfile(); }
        private set { _myprofile = value; }
    }

    private UserProfile SetupProfile()
    {
        if (_myprofile == null)
        {
            if (string.IsNullOrEmpty(LoginID) || string.IsNullOrEmpty(CompanyIdentifier))
            {
                Logout();
                return null;
            }

            //call repo to get object...

            _myprofile = _repo.All<User>()
                .Where(x => x.Login == LoginID)
                .Join(_repo.All<Profile>().Where(x => x.IsActive),
                      x => x.UserID, y => y.UserID,
                      (x, y) =>
                          new
                            {
                                x.UserID, y.CompanyID, y.RoleID,
                            })
                .Join(_repo.All<Company>()
                        .Where(x => x.IsActive && x.Identifier == CompanyIdentifier),
                    x => x.CompanyID, y => y.CompanyID,
                    (x, y) =>
                        new
                          {
                              x.UserID, y.CompanyID, x.RoleID, x.IsSurveyor,
                              CompanyFriendlyName = y.Name,
                              CompanyType = y.Type
                          })
                .Join(_repo.All<Role>(), x => x.RoleID, y => y.RoleID,
                      (x, y) =>
                          new
                            {
                                x.UserID, x.CompanyID, y.RoleName, x.CompanyFriendlyName, x.CompanyType
                            })
                .Join(_repo.All<Subscription>(),
                      x => x.CompanyID, y => y.CompanyID,
                      (x, y) =>
                      new UserProfile
                          {
                              UserID = x.UserID,
                              CompanyID = x.CompanyID,
                              Role = x.RoleName.Convert<RoleName>(),
                              CompanyFriendlyName = x.CompanyFriendlyName,
                              LoginID = LoginID,
                              Identifier = CompanyIdentifier,
                              PricePlan = y.Name.Convert<PricePlanType>(),
                              CompanyType = x.CompanyType.Convert<CompanyType>()
                          })
                .SingleOrDefault();

            if (_myprofile == null)
                Logout();
        }

        return _myprofile;
    }
}


texts:
I have a Ruby program which should solve the following problem:

  Consider the divisors of 30: 1,2,3,5,6,10,15,30. It can be seen that
  for every divisor d of 30, d+30/d is prime.

  Find the sum of all positive integers n not exceeding 100 000 000 such
  that for every divisor d of n, d+n/d is prime.

require 'prime'

class Integer
    def factors # returns an array of all factors of self
        return (1..self).collect { |n| n if ((self/n) * n) == self }.compact
    end
end

puts "Started at #{Time.now}."
counter = 0

1.upto(100000000) do |n|
    factors = n.factors
    counter += n if factors.all? { |d| ( (d+n) / d ).is_a? Prime }
end

p counter
puts "Ended at #{Time.now}."

Problem is, while the code runs, it takes so long (not finished after several hours) that I can't actually test if I get the right answer. Is there any way to make the code more efficient so that it completes in a shorter amount of time? The problem is question #357 of Project Euler. All Euler problems should take less than one minute to solve if an efficient algorithm is being used.


texts:
I am getting data from JSON and then create rows of it:

        $.each(data.GetwebMethodResult, function (index, item) {
        $("#TableABC").append(FunABC(item.aID, item.b, item.c, item.d, item.e, item.f));
        });

function FunABC(a, b, c, d, e, f) {
    var row =
        "
" +
        "
" +
        "       " +
        "
" + a + "
" +
        "       	" +
        "
" +
        "
";

    return row;
}

Is there any better way of doing it?


texts:
I have the following oops code, I am also monitoring user activity to see if it is idle for more than 5 seconds. I am very new to oops, so just want to understand if there are better way to implement it.

#!/usr/bin/python

import Tkinter
import time

class simpleapp_tk(Tkinter.Tk):
    def __init__(self,parent):
        Tkinter.Tk.__init__(self,parent)
        self.parent = parent
        self.running = None
        self.initialize()

    def initialize(self):
        self.grid()

        self.entryVariable = Tkinter.StringVar()
        self.entry = Tkinter.Entry(self,textvariable=self.entryVariable)
        self.entry.grid(column=0,row=0,sticky='EW')
        self.entry.bind("<Return>", self.OnPressEnter)
        self.entryVariable.set(u"Enter text here.")

        button = Tkinter.Button(self,text=u"Click me !",
                                command=self.OnButtonClick)
        button.grid(column=1,row=0)

        self.labelVariable = Tkinter.StringVar()
        label = Tkinter.Label(self,textvariable=self.labelVariable,
                              anchor="w",fg="white",bg="blue")
        label.grid(column=0,row=1,columnspan=2,sticky='EW')
        self.labelVariable.set(u"Hello !")

        self.grid_columnconfigure(0,weight=1)
        self.resizable(True,False)
        self.update()
        self.geometry(self.geometry())
        self.entry.focus_set()
        self.entry.selection_range(0, Tkinter.END)
        self.after(1000, self.tick)
        self.eventbind()

    def OnButtonClick(self):
        self.labelVariable.set( self.entryVariable.get()+" (You clicked the button)" )
        self.entry.focus_set()
        self.entry.selection_range(0, Tkinter.END)

    def OnPressEnter(self,event):
        self.labelVariable.set( self.entryVariable.get()+" (You pressed ENTER)" )
        self.entry.focus_set()
        self.entry.selection_range(0, Tkinter.END)

    def reset(self, *ignore):
        self.running = None

    def tick(self, *ignore):
        if not self.running:
            self.running = time.time()
        elif time.time() - self.running > 5:
            print 'I waited 5 seconds...'
            self.running = None
        self.after(1000,self.tick)

    def eventbind(self):
        self.bind('<Key>',self.reset)
        self.bind('<Button-1>',self.reset)

if __name__ == "__main__":
    app = simpleapp_tk(None)
    app.title('my application')
    app.mainloop()


texts:
I would like to know if this is being done correctly.

using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.Text;

public class InnerJoinTables
{

    public List<InnerJoinTable> Items = new List<InnerJoinTable>();

}

public class InnerJoinTable
{
    public int ID { get; set; }
    public string RightTable { get; set; }
    public string LeftTable { get; set; }

    public InnerJoinTable(int ID, string RightTable, string LeftTable)
    {
        this.ID = ID;
        this.RightTable = RightTable;
        this.LeftTable = LeftTable;
    }
}

Calling code:

InnerJoinTables m = new InnerJoinTables();

m.Items.Add(new InnerJoinTable(1, "A", "B"));


texts:
I am trying to calculate a customized concordance index for survival analysis. Below is my code. It runs well for small input dataframe but extremely slow on a dataframe with one million rows (>30min).

import pandas as pd

def c_index1(y_pred, events, times):
    df = pd.DataFrame(data={'proba':y_pred, 'event':events, 'time':times})
    n_total_correct = 0
    n_total_comparable = 0
    df = df.sort_values(by=['time'])
    for i, row in df.iterrows():
        if row['event'] == 1:
            comparable_rows = df[(df['event'] == 0) & (df['time'] > row['time'])]
            n_correct_rows = len(comparable_rows[comparable_rows['proba'] < row['proba']])
            n_total_correct += n_correct_rows
            n_total_comparable += len(comparable_rows)

    return n_total_correct / n_total_comparable if n_total_comparable else None

c = c_index([0.1, 0.3, 0.67, 0.45, 0.56], [1.0,0.0,1.0,0.0,1.0], [3.1,4.5,6.7,5.2,3.4])
print(c) # print 0.5

For each row （in case it matters...）:

If the event of the row is 1: retrieve all comparable rows whose

index is larger (avoid duplicate calculation),
event is 0, and
time is larger than the time of the current row. Out of the comparable rows, the rows whose probability is less than the current row are correct predictions.

I guess it is slow because of the for loop. How should I speed up it?


texts:
Just needed a quick way to convert an elementtree element to a dict. I don't care if attributes/elements clash in name, nor namespaces. The XML files are small enough. If an element has multiple children which have the same name, create a list out of them:

def elementtree_to_dict(element):
    d = dict()
    if hasattr(element, 'text') and  element.text is not None:
        d['text'] = element.text

    d.update(element.items()) # element's attributes

    for c in list(element): # element's children
        if c.tag not in d:
            d[c.tag] = elementtree_to_dict(c)
        # an element with the same tag was already in the dict
        else:
            # if it's not a list already, convert it to a list and append
            if not isinstance(d[c.tag], list):
                d[c.tag] = [d[c.tag], elementtree_to_dict(c)]
           # append to the list
            else:
                d[c.tag].append(elementtree_to_dict(c))
    return d

Thoughts? I'm particularly un-fond of the not instance part of the last if.


texts:
Team, My code: works and does the job. delete partition by unmounting paths if it is not root and is present in defined list in vars.
caveat: I have observed that at times some devices are left unmounted and when I rerun task they then get deleted. not sure what is the issue.
steps:

loops through all devices that are in vars
checks if they exists on node via lsblk command
based on result of each item[device from list], task runs an include_task, which
then performs deletion [ unmount, delete
partition steps]

Is there any standard approaches that I could use in each task of mine? like instead of using shell module, can I just do it using ansible_device and compare it with list of devices I have in var and then if there is match proceed to deletion? if yes, I am not sure how to do that comparison. anything else, let know please. thanks. am new please give me exact code example of pointing to better approaches. appreciate it.
vars.yml
local_volume_mount_root_directory: /local-volumes
nvme_extn: "p"
loop_device: "loop"
device_prefix: /dev/
devices_list: ["/dev/sdd", "/dev/nvme1n1"]
device_part_number: 1
device_storage_class: ssd-wkr

tasks
- name: "Check if all inventory defined devices exists on node"
  shell: "lsblk -p -l | grep {{ item }}"
  register: inv_device_exists
  ignore_errors: yes
  with_items: "{{ devices_list }}"
  tags: inv_device_deletion

- name: "Run include_tasks if each inventory device exists on node"
  include_tasks:
    file: delete_devices.yml
    apply:
      tags: inv_device_deletion
  when: item.stdout != ""
  with_items: "{{ inv_device_exists.results }}"
  tags: inv_device_deletion

below: check to assure each device is not ROOT then check what type is it with regex, then enters block to delete it.
delete_devices.yml
- name: "Check if all inventory defined devices are mounted on ROOT /"
  shell: lsblk -l -p | grep -w "{{ item.item }}" | grep -w /
  register: is_device_root
  failed_when:
    - is_device_root.rc == 0
  ignore_errors: no

- name: block to delete Type SD
  block:
    - name: Get device UUID
      command: blkid -s UUID -o value "{{ item.item }}{{ device_part_number }}"
      register: uuid_sd
      ignore_errors: yes

    - name: un-mount devices sd
      mount:
        path: "{{ volume_mount_root_directory }}/{{ device_storage_class }}/{{ uuid_sd.stdout }}"
        state: unmounted
      ignore_errors: yes
      when: uuid_sd.stdout != ""

    - name: Delete partitions "{{ item.item }}"
      parted:
        device: "{{ item.item }}"
        number: "{{ device_part_number }}"
        state: absent
  when: item.item is regex("sd\w+")

- name: block to delete Type NVME
  block:
    - name: Get NVME device UUID
      command: blkid -s UUID -o value "{{ item.item }}{{ nvme_extn }}{{ device_part_number }}"
      register: uuid_nvme
      ignore_errors: yes

    - name: un-mount devices nvme
      mount:
        path: "{{ volume_mount_root_directory }}/{{ device_storage_class }}/{{ uuid_nvme.stdout }}"
        state: unmounted
      ignore_errors: yes
      when: uuid_nvme.stdout != ""

    - name: Delete partitions "{{ item.item }}"
      parted:
        device: "{{ item.item }}"
        number: "{{ device_part_number }}"
        state: absent
  when: item.item is regex("nvme\w+")
```


texts:
I solved the problem but for two test cases, it's giving me timeout error. It's taking longer than 2 seconds on their servers. I tried using <ctime> to calculate the run time of the program and on my system, it's taking between 1.3-1.6 seconds. It's only giving me error for TestCases #9 and #10.

The question is to find the largest N-digit "decent" number, where a decent number consists only of the digits '3' and '5', and the number of threes is divisible by 5, and the number of fives is divisible by 3.

#include <iostream>
#include <string>

std::string decent_number(int, std::string);

int main() {
  clock_t start = clock();
  int numOfCases;

  std::cin >> numOfCases;
  int n;
  for (int i = 0; i < numOfCases; ++i) {
    std::string dn("-1");
    std::cin >> n;
    for (int j = n; j >= 0; --j) {
      if (j % 3 == 0 && (n-j) % 5 == 0) {
        dn = decent_number(j, "5");
        dn += decent_number(n-j, "3");
        break;
      }
    }
    std::cout << dn << std::endl;
  }
  clock_t ends = clock();
  std::cout << "Time: " << static_cast<double>(ends - start)/ CLOCKS_PER_SEC
            << std::endl;
  return 0;
}

std::string decent_number(int repeatNum, std::string num) {
  std::string dn;
  for (int i = 0; i < repeatNum; ++i)
    dn = dn + num;
  return dn;
}

The code is simple, I check for the number of 3s and 5s which make the number and call a string builder function which builds the string.


texts:
Is there a smarter way to do the following without the $result variable and without the if-statements?

    ...
    $description = BIG ARRAY
    $result = array('error' => '', 'amounts' => array(5, 10, 25, 50));
    if (isset($description['error'])) $result['error'] = $description['error'];
    if (isset($description['amounts'])) $result['amounts'] = $description['amounts'];

    return $result;


texts:
This video should explain how the game works, but in simple form, it's a game where you enter a number between 1 and 3, This number is than removed from 12, in doing so the computer will then pick a number between 1-3 based on what number you have picked, if you choose to remove 1 marble it should say that it has removed 3 marbles. This works because there are 3 lots of 4 in 12. And the maths tells it to remove what number you have chosen from 4. Because there are 3 lots of 4, you can never win, which is the whole point of the game.

Is there any way I could improve on the code?

 import java.util.Scanner;

    public class Main {

        public static int input;
        public static int marble = 12;
        public static int comFirst = (int) (Math.random() * 3 + 1);

        @SuppressWarnings("resource")
        public static void main(String[] args) throws InterruptedException {

            System.out.println("There Are 12 Marbles, You Can Only Remove Up To 3 Marbles At A Time");
            System.out.println("Your Goal Is To Remove The Last Marble, Marble 1");
            System.out.println("To Remove A Marble Either Enter 1, 2 or 3");
            System.out.println("");

            while (true) {

                if (marble == 1) {
                    System.out.println("There Is " + marble + " Marble Remaining");
                } else {
                    System.out.println("There Are " + marble + " Marbles Remaining");
                }

                Scanner scanInput = new Scanner(System.in);
                input = scanInput.nextInt();

                if (input > 3 || input < 1) {
                    System.out.println("You Can Only Remove 3 Marbles At A Time");
                } else {

                    marble = marble - input;

                    Thread.sleep(250);
                    int cpuAnswer = 4 - input;
                    if (cpuAnswer == 1) {
                        System.out.println("The Computer Has Removed " + cpuAnswer + " Marble");
                    } else {
                        System.out.println("The Computer Has Removed " + cpuAnswer + " Marbles");
                    }
                    if (marble - cpuAnswer == 0) {
                        System.out.println("There Are No Marbles Remaining, The Computer Has Won!!");
                        System.out.println("The Computer Has Won");
                        return;
                    }
                    if (marble - input == 0) {
                        System.out.println("There Are No Marbles Remaining, You Have Won!!");
                        return;
                    }
                    marble = marble - cpuAnswer;

                }
            }
        }

    }


texts: Cycle through an array of available colors repeatedly

texts:
I have an array of colors for my app to choose from. My goal was to have the app cycle through the array of colors, apply it to my object, and reset to the beginning once each color has been used. This is simple enough to implement, but I am looking to see if it's possible to clean it up slightly. The one complication I have is that I am trying to prevent duplicate colors.

E.g. If I choose to use the size of the array of the object that has the color affected - when an item (or multiple) is deleted and a new one is added, it might have a duplicate color as the previous card leading to a visual design that I don't want.

To prevent this I decided to make a new counter variable that counts each time a new card is created, regardless of deletions. I feel like there might be a more elegant solution that I am not thinking of so any feedback or alternative approaches would be very appreciated!

All of the necessary code can be seen here:

class BrowseHabitsActivity : Activity() {
    private lateinit var recyclerView: RecyclerView
    private lateinit var addHabitButton: FloatingActionButton
    private val habits: ArrayList<Habit> = Habit.createHabitList(25)

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_browse_habits)

        recyclerView = findViewById(R.id.rvHabits)
        recyclerView.layoutManager = LinearLayoutManager(this)
        recyclerView.adapter = BrowseHabitsAdapter(habits)

        var cardCount = 0

        addHabitButton = findViewById(R.id.addHabitButton)
        addHabitButton.setOnClickListener {
                habits.add(Habit("New Habit", 1234, chooseCardColor(cardCount++)))
                (recyclerView.adapter as BrowseHabitsAdapter).notifyItemInserted(habits.size)
        }
    }

    private fun chooseCardColor(cardCount: Int): Int {
        val colors = resources.getIntArray(R.array.cardColors)
        return colors[cardCount % colors.size]
    }
}```


texts: Producing a Pandas Data Frame from Long to Wide format Efficiently


texts: How to create associative hashs in Ruby (on Rails) dynamicly

texts:
I am developing a webapp with Ruby on Rails to expand the features of mite (online time-tracking app) with the help of the offical mite API. Unfortuanaly, the API can't return all projects by a specific customer id. Because of that, i am developing a workaround.

At first, i get all customers and save them in a hash. Then i iterate throug all projects and save each project object to a hash inside the customer hash.

My code looks like this:

def index
  # Mite authentication
  Mite.account = '...'
  Mite.authenticate('...','...')

  # get all customers from Mite
  @customers = Hash.new
  Mite::Customer.all.each do |customer|
    @customers[customer.id] = {:name => customer.name, :projects => Hash.new}
  end

  # get all projects from Mite
  Mite::Project.all.each do |project|
    @customers[project.customer_id][:projects] = {:project => project}
  end
end

Unfortuanaly, only the last project is saved in the ":projects" hash. But why? Adding customers works with this method too. In general, is this "the ruby way"? I'm very new to it :)


texts:
I need to write a custom reducer utility. It should take a dictionary of reducers and a publish subject to return a state, with a dispatch method to dispatch actions and notify the publish subject.

It should be 100% type-checked with TypeScript, compatible with strict compiler options, and should only use type-inference when applicable.

Link in the TypeScript Playground to see the types.

Implementation

type Action<T = string, S extends {} = any> = S & {
    type: T
}

type Reducer<S = any, A extends Action = Action> = (state: S | undefined, action: A) => S

interface Reducers<S = any, A extends Action = Action> {
    [key: string]: Reducer<S, A>
}

type ReducerState<R> = R extends Reducer<infer S, any>
    ? S
    : never

type ReducersActions<R extends Reducers> = {
    [K in keyof R]: R[K] extends Reducer<any, infer A>
        ? A
        : never
}[keyof R]

type StoresState<R extends Reducers> = {
    [K in keyof R]: ReducerState<R[K]>
}
type Stores<R extends Reducers> = StoresState<R> & {
    dispatch(action: ReducersActions<R>): void
}

interface Subject<T> {
    next(object: T): void
}

function createReducer<T extends Reducers>(
    reducers: T,
    publish: Subject<Stores<T>>
): Stores<T> {
    const state: Partial<Stores<T>> = {}

    state.dispatch = function dispatch(action) {
        Object
            .keys(reducers)
            .forEach(key =>
                state[key] = reducers[key](state[key], action)
            )

        publish.next(state as Stores<T>)
    }
    state.dispatch({type: ''} as Action)

    return state as Stores<T>
}

Test code

namespace Actions {
    export type AddTodo = Action<'add-todo', {todo: string}>
    export type RemoveTodo = Action<'remove-todo', {index: number}>
    export type Todos =
        | AddTodo
        | RemoveTodo

    export type ChangeInput = Action<'change-input', {input: string}>

    export type All =
        | Todos
        | ChangeInput
}

function todos(todos: string[] = [], action: Actions.Todos) {
    switch(action.type) {
        case 'add-todo':
            return [...todos, action.todo]
        case 'remove-todo':
            return todos.filter((_, i) => i === action.index)
    }

    return todos
}

function input(input: string = '', action: Actions.ChangeInput) {
    switch(action.type) {
        case 'change-input':
            return action.input
    }

    return input
}
const state = createReducer({todos, input}, {
    next: ({todos, input}) => console.log('state', {todos, input})
})

state.dispatch({
    type: 'change-input',
    input: 'do something'
})

state.dispatch({
    type: 'add-todo',
    todo: state.input
})

Can it be simplified? (e.g. less use of generics, get rid of TypeScript 2.8+ requirement for infer, etc..)
Can I prevent reducers in the  createReducer function from having a dispatch property?
Do you have any other suggestions/improvements?


texts: Finding the rod pieces in the rod cut issue

texts:
I have been reading the chapter 15 of "Introduction to Algorithms" (3rd edition) by Cormen, etc. The chapter 15 is about dynamic programming, and the first example they show us is the "rod cut problem".

Now, I have spent some time trying to understand it, but mostly trying to understand the pseudocode, and why it really works. I think dynamic programming is probably the most difficult design technique to put in practice that I have seen so far. The ideas are quite easy, but applying them is quite a nightmare, at least for me. You can choose between memoisation or a bottom-up approach, but you need to have a clear and deep understanding of the problem, and usually this requires quite a lot of time, but if you are in an exam...

From now on, I will assume that you know what the rod cut problem is.

Now, I wanted to create, based on a pseudocode from the book, an algorithm for the rod cutting problem that actually returns a list of the indices where we can find the small pieces that we have used to maximise the total price.

I have used Python, which simplifies quite a lot the process of writing programs, in general.

The following is the algorithm that I came up with (which is really similar to the pseudo code that the authors provide to find the maximum revenue for a rod of a certain length, but that algorithm does not calculate and returns which smaller pieces maximise the revenue):

def extended_bottom_up_rod_cut(prices, n):
    revenues = [-sys.maxsize] * (n + 1)

    s = [[]] * (n + 1)

    revenues[0] = 0
    s[0] = [0]

    for i in range(1, n + 1):

        max_revenue = -sys.maxsize  # a big small number

        for j in range(1, i + 1):

            # Note that j + (i - j) = i.
            # What does this mean, or why should this fact be useful?
            # Note that at each iteration of the outer loop,
            # we are trying to find the max_revenue for a rod of length i
            # (and we want also to find which items we are including to obtain that max_revenue).
            # To obtain a rod of size i, we need at least 2 other smaller rods,
            # unless we do not cut the rod.
            # Now, to obtain a rod of length i,
            # we need to put together a rod of length j < i and a rod of length i - j < j,
            # because j + (i - j) = i, as we stated at the beginning.
            if max_revenue < prices[j] + revenues[i - j]:

                max_revenue = prices[j] + revenues[i - j]

                if prices[i - j] != 0:
                    s[i] = [j, i - j]  # Indices of prices such that price[j] + price[i - j] = max_revenue of i
                else:
                    s[i] = [j]

        revenues[i] = max_revenue

    return revenues, s

First of all, is the algorithm correct?

Apparently, it seems that it returns the right answer, but I am a bit confused:
as the size of the rod increases, we are always going to just use at most 2 small pieces, and no more than that, but why such an algorithm should give the right answer? Why using 3 or more pieces would not give the right answer?


texts:
I have the following simple program which calculates and returns the nearest power of 2 of a given number. Because I use increments and decrements to find the closest power, this takes a very long time when working with higher numbers. Is there any way to reduce the run time of the program when working with larger numbers?

puts "Enter the value of n:"
n = gets.chomp.to_i

def ispow2(n)
    n & (n - 1) == 0
end

if ispow2(n)
    puts "#{n} is the closest power of 2 to #{n}."
    exit
end

x = n
y = n

until ispow2(x)
    x += 1
    ispow2(x)
end

until ispow2(y)
    y -= 1
    ispow2(y)
end

if (n - y) == (x - n)
    puts "#{x} and #{y} are the closest powers of 2 to #{n}."
else if (n - y) < (x - n)
    puts "#{y} is the closest power of 2 to #{n}."
else
    puts "#{x} is the closest power of 2 to #{n}."
end


texts: clean approach to decorator that takes optional keyword arguments

texts:
I write decorators a lot in my work. Sometimes you need to write "decorator that takes arguments", it usually turns out to be something like this:

def decorator(**kwargs):

    def _decorator(func):

        @wraps(func)
        def decorated(*func_args, **func_kwargs):
            # do something with kwargs here
            return func(*func_args, **func_kwargs)

        return decorated

    return _decorator

but in this case you'll always have to use your decorator like so:

@decorator()  # if you forget () here you'll get an exception
def myfunc():
    pass

So I come up with this snippet, IMO this is nicer to read/write and understand:

from functools import wraps, partial

def decorator(func=None, **kwargs):
    if func:

        @wraps(func)
        def decorated(*func_args, **func_kwargs):

            if kwargs.get("sayhi"):
                print("hi")

            return func(*func_args, **func_kwargs)

        return decorated

    else:
        return partial(decorator, **kwargs)

@decorator
def hello(name):
    print(f"hello {name}")

@decorator(sayhi=True)
def bye(name):
    print(f"bye {name}")

hello("rabbit")
# "hello rabbit"

bye("rabbit")
# hi
# bye rabbit


texts:
Fiddle: http://jsfiddle.net/fhBd5/

So the above is working but I'm having trouble trying to come up with a clean and concise way to do some type of loop on the if or statements.

Any help is very much appreciated!

var checkPositionOnLoad = function (e) {
        var currentPos = 0;
        var listItem = document.getElement('li.current');
        var currentSelected = $('list').getChildren('li').indexOf(listItem) + 1;

        if (currentSelected <= 3) {
            return false;
        }
        if(currentSelected==4||currentSelected==5||currentSelected==6){
            currentPos = -300 * 1;
            $('list').setStyle('left', currentPos);
        }
        else if(currentSelected== 7||currentSelected==8||currentSelected==9){
            currentPos = -300 * 2;
            $('list').setStyle('left', currentPos);
        }
        else if(currentSelected==10||currentSelected==11||currentSelected==12){
            currentPos = -300 * 3;
            $('list').setStyle('left', currentPos);
        }
        else if(currentSelected==13||currentSelected==14||currentSelected==15){
            currentPos = -300 * 4;
            $('list').setStyle('left', currentPos);
        };

    };


texts: Sort an array of strings using bubble sort

texts:
I have this following code to sort an array of strings order by ASCII value (alphabetically) using bubble sort.

#include <stdio.h>
#include <string.h>
int main(){
    char txt1[201][10], temp[201];
    for(int i=0; i < 10; i++){
        if(i){scanf("%c", txt1[i]);}
        scanf("%[^\n]s", txt1[i]);
    }

    for(int i=0; i<9; i++){
        for(int j=i+1; j<10; j++){
            if(strcmp(txt1[i], txt1[j]) > 0){
                strcpy(temp, txt1[i]);
                strcpy(txt1[i], txt1[j]);
                strcpy(txt1[j], temp);
            }
        }
    }
    for(int i=0; i < 10; i++){
        printf("%s\n", txt1[i]);
    }
}

Sample

> Input
Bravo
Charlie
Foxtrot
Alpha
Golf
Delta
Echo
Hotel
India
Juliet

> Output
Alpha
Bravo
Charlie
Delta
Echo
Foxtrot
Golf
Hotel
India
Juliet

But I have a concern at line 6-7 (In the first for loop). I need to input value with space so I used %[^\n]s (to receive a string with space) and %c (to receive space between each input).

Will it produce any problem when sorting if using this method on inputting the value?


texts: POSIX shell function to "dump" all given arguments

texts:
My today's idea was to create a POSIX shell function to dump all given arguments, typical use would be to call it from a fucntion, where you already know some arguments are not well set (empty; not integer) and this way you can inspect all given arguments in one go. It reminds me of a PHP var_dump function. :) Would anyone be able to find weak spots in there, all input is welcome.

#!/bin/sh

dump_arguments ()
# string function - prints arguments (position and content)
# indicates empty arguments and integer numbers
{
    printf '%b' "dump_arguments()\\n----------------\\n$# arguments are being inspected"
    [ $# -gt 0 ] && { printf ':\n'; i=1; } || printf '.\n'
    while [ $# -gt 0 ]; do
        printf '%s' "[$i]: '$1'"
        [ -z "$1" ] && printf ' (empty)'
        [ "$1" -eq "$1" ] 2> /dev/null && printf ' (integer)'
        printf '\n'
        shift 1
        i=$((i+1))
    done
} >&2

# inside some function you would call it like this
dump_arguments "$@"

# but to only try it out, you can call it directly
dump_arguments '1' '' 5


texts:
Recently, I started reading image processing via opencv library in python.

I create a minio object storage and upload some photos into it. After that, I wrote a program which reads every image in each bucket in minio and watermark it with a simple logo. I read each image with imread and finally (after inserting a watermark), save it with imwrite (on the same image).

But when testing my code, I saw that for each image it took about 0.4 seconds. Since I want to do this simple operation for a lot of images, this time is not acceptable.

Here is a part of my simple code:

import cv2
import numpy as np

logo_img = cv2.imread('logo.png', cv2.IMREAD_UNCHANGED)

scl = 50
w = int(logo_img.shape[1] * scl / 100)
h = int(logo_img.shape[0] * scl / 100)
dim = (w, h)
logo = cv2.resize(logo_img, dim, interpolation=cv2.INTER_AREA)
logo_height, logo_width = logo.shape[:2]

def watermark_image(image_name):
    image = cv2.imread(image_name)
    image_height, image_width = image.shape[:2]
    image = np.dstack([image, np.ones((image_height, image_width), dtype="uint8") * 255])
    # Blend
    ovr = np.zeros((image_height, image_width, 4), dtype="uint8")

    x_pos = int(random() * (image_height - 10 - logo_width))
    y_pos = int(random() * (image_width - 10 - logo_height))

    ovr[x_pos:x_pos + logo_height, y_pos:y_pos + logo_width] = logo
    image = cv2.addWeighted(ovr, 0.6, image, 1.0, 0, image)
    cv2.imwrite(image_name, image)

import time
start = time.time()
for bucket in buckets:
    objects = minioClient.list_objects(bucket.name, prefix=None, recursive=True)
    for current_object in objects:
        watermark_image('./test/' + current_object.object_name)

end = time.time()

print(end - start)

How can I improve my code and optimize it in order to need less runtime?

Suppose that I have a object storage which contains a lot of image. Actually I want to prepare an API, for people to request a watermark for every image and then I want to show them requested image after watermarking it online.


texts:
The purpose of the program is to add 2 sides of an array starting from the bottom and top of both ends and to find the lowest difference at equal decrements of iteration. The program functions but it's slow.

int solution(vector<int> &A) {
    int n = A.size();
    int i, j, rsum, lsum, difference;
    int currentmindifference = 1000;

    for(i = 0; i < n; i++)
    {
        lsum = 0;
        rsum = 0;
        for(j = 0; j <= i; j++) lsum += A[j];
        for(j = i + 1; j < n; j++) rsum += A[j];
        difference = abs (lsum - rsum);
        if (difference < currentmindifference) currentmindifference = difference;
    }

    return currentmindifference;
}


texts:
Help me review this code:

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

template <typename T>
class auto_ptr
{
public:
    explicit auto_ptr(T* p = NULL):m_p(p){}
    auto_ptr(auto_ptr& other);
    auto_ptr& operator=(auto_ptr& other);
    T* get() const { return m_p; }
    void reset(T* p = NULL);
    T& operator * (){ return *m_p; }
    T* operator -> (){ return m_p; }
    ~auto_ptr()
    {
        if(m_p)
            delete m_p;
        m_p = NULL;
    }
private:
    T* m_p;
    T* release();
};

int main()
{
    auto_ptr<int> p(new int(3));
    cout<<*p<<endl;

    int *b = new int(6);
    p.reset(b);
    cout<<*p.get()<<endl;

    auto_ptr<int> p1(new int(10));
    p = p1;
    cout<<*p<<endl;
    assert(NULL == p1.get());

    auto_ptr<int> p2(new int(100));
    auto_ptr<int>p3(p2);
    cout<<*p3<<endl;
    assert(NULL == p2.get());
}

template <typename T>
T* auto_ptr<T>::release()
{
    T* temp = this->m_p;
    this->m_p = NULL;
    return temp;
}

template <typename T>
auto_ptr<T>::auto_ptr(auto_ptr& other)
{
    m_p = other.release();
}

template <typename T>
auto_ptr<T>& auto_ptr<T>::operator=(auto_ptr& other)
{
    if(this == &other)
        return *this;
    delete m_p;
    m_p = other.release();
    return *this;
}

template <typename T>
void auto_ptr<T>::reset(T* p)
{
    if(m_p != p)
    {
        delete m_p;
        m_p = p;
    }
}


texts: Priority checker for infix-to-postfix converter

texts:
I am trying to implement an infix to postfix conversion program using stacks.  I have actually have done it successfully, but I'm uncertain about the complexity of the logic that I used for the priority checking.

int hasLowerPriority(char ch,char ch2)
{
    int num=0,num2=0;
    if(ch=='+'||ch=='-')
        num=1;
    if(ch=='*'||ch=='/')
        num=2;
    if(ch2=='+'||ch2=='-')
        num2=1;
    if(ch2=='*'||ch2=='/')
        num2=2;
    if(num<num2)
        return 1;
    else
        return 0;
}

To keep it simple I am using four basic operators only. I am looking for optimized code for the same operation. Can I reduce its complexity?


texts:
Controller class

namespace App\Http\Controllers\Website\SportsType;
use App\Classes\Contract\SportsType\ISportsType;
use \App\Http\Requests\SportsType\SportsTypeRequest as SportsTypeRequest;
class SportsTypeController extends \App\Http\Controllers\BaseController
{
    private $AllSportsTypes = "SportsTypes";
    private $sportstype;

    public function __construct(ISportsType $_sportstype) {
        $this->sportstype = $_sportstype;
        parent::__construct();
    }

    public function index() {
        $SportsTypes = $this->sportstype->All();
        return view('SportsType.List')->with('SportsTypes', $SportsTypes);
    }

    public function create() {
        return view('SportsType.Create');
    }

    public function edit($SportsTypeID) {

        $SportsType = $this->sportstype->Get($SportsTypeID);
        return view('SportsType.Edit', array('SportsType' => $SportsType));
    }

    public function save(SportsTypeRequest $request) {
        $data = [
            'SportsType'    =>  $request['SportsType'],
            'SportsTypeID'  =>  $request['SportsTypeID'],
        ];
        $result = $this->sportstype->Save($data);
        return redirect()->route($this->AllSportsTypes);
    }
}

Business logic class

namespace App\Classes\BusinessLogic\SportsType;
use App\Classes\DatabaseLayer\SportsType\SportsTypeDb;
use App\Classes\Contract\SportsType\ISportsType;

class SportsTypeBL implements ISportsType {

    public function All() {
        $SportsTypes = (new SportsTypeDb())->All();
        return $SportsTypes;
    }

    public function Get($SportsTypeID) {
        $SportsType = (new SportsTypeDb())->Get($SportsTypeID);
        if($SportsType == null) {
            \App::abort(404);
            return;
        }
        return $SportsType;
    }

    public function Save($data) {
        return (new SportsTypeDb())->Save($data);
    }
}

Database class

namespace App\Classes\DatabaseLayer\SportsType;

class SportsTypeDb {

    public function All() {
        $SportsTypes = \App\Models\SportsType\SportsTypeModel::all();
        return $SportsTypes;
    }

    public function Get($SportsTypeID) {
        $SportsType = \App\Models\SportsType\SportsTypeModel
                ::where('SportsTypeID', $SportsTypeID)
                ->first();
        return $SportsType;
    }

    public function Save($data) {
        if($data["SportsTypeID"] == 0) {
            $SportsType = new \App\Models\SportsType\SportsTypeModel();
        }
        else {
            $SportsType = $this->Get($data["SportsTypeID"]);
        }

        $SportsType->SportsType     = $data["SportsType"];
        $SportsType->save();
        return true;
    }
}

Which class should have code for caching?
Am I writing bad or very bad code? Can you please suggest good ways to improve it?


texts:
I would like some advice to shorten down this snippet, give it more efficient flow and look. Review should focus on keeping it as a compact single method (except the two public props). The DataType and MeasureStatus is an enum. Readability is of course more important than compactness.

....
/// <summary>
/// Helper that hold methods for evaluate and calculate data
/// that will be serialized/deserialized in Serializer/SerializerBase.
/// Please don't put serializing routines in here and also understand
/// that some decisions here are based on protocol specifikations.
/// </summary>
....
public Unit MeasureType { get; set; }
public ModeType Aggregate { get; set; }
.....

public Tuple<DataType, byte> EvaluateDataType(double value, MeasureStatus? status = null)
{
    int quantityOfDecimals = 0;
    DataType dataType = DataType.MISSING_LONG;
    byte nibbled = 0;
    bool statusIsMissing = false;

    if (status != null)
        if (status == MeasureStatus.Missing)
            statusIsMissing = true;

    quantityOfDecimals =
      (this.MeasureType == Unit.kWh || this.MeasureType == Unit.ºC) ? 1 : 2;

    // Qty decimals affect limit size  of 'value'
    if (quantityOfDecimals == 1)
    {
        if (value < 3276 && value > -3276)
            if (!statusIsMissing)
                dataType = DataType.SHORT_1DEC;
            else
                dataType = DataType.MISSING_SHORT;
        else
            if (!statusIsMissing)
                dataType = DataType.LONG_1DEC;
            else
                dataType = DataType.MISSING_LONG;
    }

    // Qty decimals affect limit size  of 'value'
    if (quantityOfDecimals == 2)
    {
        if (value < 327 && value > -327)
            if (!statusIsMissing)
                dataType = DataType.SHORT_2DEC;
            else
                dataType = DataType.MISSING_SHORT;
        else
            if (!statusIsMissing)
                dataType = DataType.LONG_2DEC;
            else
                dataType = DataType.MISSING_LONG;
    }

    nibbled = (byte)(Aggregate | dataType);
    return new Tuple<DataType, byte>(dataType, nibbled);
}