texts: Calculating and displaying number statistics

texts:
I'm writing a program which takes individual int inputs from the user and then outputs some details on the numbers (average, min, max and how many).
Input.readInt() is a method I made which simply reads an integer from the command line and returns it.

There are a few things I'd like to improve - for the average the float does not seem to work, it only holds prints out value to nearest integer. I'd also like to format this to always display 2 decimal places.
Is there any way to dynamically assign the size of the array? So I could enter more than 10 values?

I'm looking for advice on more efficient methods (both speed and code length), and any other general advice which could help me learn.

public class NumberStats {

    public static void main(String[] args) {
        int[] input = new int[10];
        int i;
        int total = 0;
        int min = 0;
        int max = 0;
        double average = 0;
        int count = 0;

        while (true) { // READ INPUTS
            System.out.print("Please enter a number: ");
            input[count] = Input.readInt();

            if (input[count] == 0) {
                break;
            } else if (input[count] < 0) {
                System.err.println("Error: " + input[count]
                        + " is not valid, exiting.\n");
                break;
            } else if (input[count] > 100) {
                System.out
                        .println("Warning: "
                                + input[count]
                                + " is not valid and will be excluded from final statistics.");
            }

            if (input[count] <= 100) { // IF INPUT VALID
                if (count == 0) {
                    min = input[count];
                    max = input[count];
                } else if (input[count] < min) {
                    min = input[count];
                } else if (input[count] > max) {
                    max = input[count];
                }
                count++;
                System.out.println("#" + count + ": " + input[count - 1]);
            }

        }
        if (count != 0) {
            for (i = 0; i < input.length; i++) { // CALCULATE SUM
                total += input[i];
            }
            average = total / count; // CALCULATE AVERAGE

            System.out.println("Total: " + total);
            System.out.println("Count: " + count);
            System.out.println("Min: " + min);
            System.out.println("Max: " + max);
            System.out.println("Average: " + average);
        } else {
            System.out.println("No valid input");
        }
    }
}


texts:
I've been agonizing over this for an hour or two. I require a bidirectional dictionary that was thread safe. From what I understand about dictionaries, they're thread safe when being read from, but no so much when being written to. I've tried to write this code snippet to my understanding of correct, but a review would be excellent if possible.

class ConcurrentBidirectionalDictionary<TKey,UKey>
{
    private Dictionary<TKey, UKey> BackingDictionary;

    public ConcurrentBidirectionalDictionary()
    {
        BackingDictionary = new Dictionary<TKey, UKey>();
    }

    //Adding to dictionaries is not thread-safe ergo, lock when adding
    private readonly object _SyncLock = new object();
    public void Add(TKey item1, UKey item2)
    {
        if (!BackingDictionary.ContainsKey(item1) && !BackingDictionary.ContainsValue(item2))
        {
            lock (_SyncLock)
            {
                if (!BackingDictionary.ContainsKey(item1) && !BackingDictionary.ContainsValue(item2))
                {
                    BackingDictionary.Add(item1, item2);
                }
                else
                {
                    ThrowNewDuplicateKeyException(item1, item2);
                }
            }
        }
        else
        {
            ThrowNewDuplicateKeyException(item1, item2);
        }
    }

    private void ThrowNewDuplicateKeyException(TKey item1, UKey item2)
    {
        if (BackingDictionary.ContainsKey(item1) && BackingDictionary.ContainsValue(item2))
        {
            throw new ArgumentException("Duplicate Keys not allowed", "item1, item 2", null);
        }
        else if (BackingDictionary.ContainsKey(item1))
        {
            throw new ArgumentException("Duplicate Keys not allowed", "item1", null);
        }
        else if (BackingDictionary.ContainsValue(item2))
        {
            throw new ArgumentException("Duplicate Keys not allowed", "item 2", null);
        }
    }

    //Reading is thread safe, no lock needed
    public TKey GetFromUKey(UKey UKey)
    {
        var Record = BackingDictionary.FirstOrDefault(x => EqualityComparer<UKey>.Default.Equals(x.Value, UKey));
        if (Record.Equals(default(KeyValuePair<TKey,UKey>)))
        {
            throw new IndexOutOfRangeException($"Unable to find UKey {UKey}");
        }
        return Record.Key;
    }

    public UKey GetFromTKey(TKey TKey)
    {
        return BackingDictionary[TKey];
    }
}


texts: Testing whether a matrix contains a submatrix

texts:
As part 2 of my other question concerning this long running project I've been inquiring about on CR, I reimplemented my generic function for determining if an array of arrays is a sub-array or submatrix of a larger array of arrays.
I'm looking for advice on better implementation, ways to improve code clarity, advice on best practices and anything else that might be useful. This is my new implementation:

namespace MathAlgorithms

module ArrayFunctions =
    // Generic because it makes testing easier, yay math
    let IsSubMatrix (smallArray:'a[][]) (largeArray:'a[][]) (startCoordinate:(int * int)) =
        let searchHeight , searchWidth = smallArray.Length - 1 , smallArray.[0].Length - 1
        let startHeight  , startWidth  = startCoordinate

        try
            let WidthLoop heightIndex =
                let rec WidthLoopRec heightIndex widthIndex =
                    let largeValue = largeArray.[startHeight + heightIndex].[startWidth + widthIndex]
                    let smallValue = smallArray.[heightIndex].[widthIndex]

                    match ( smallValue = largeValue , widthIndex < searchWidth ) with
                    | ( true  , true  ) -> WidthLoopRec heightIndex (widthIndex + 1)
                    | ( true  , false ) -> true
                    | ( false , _     ) -> false
                WidthLoopRec heightIndex 0

            let HeightLoop () =
                let rec HeightLoopRec heightIndex =
                    let isMatch = WidthLoop heightIndex

                    match ( isMatch , heightIndex < searchHeight) with
                    | ( true  , true  ) -> HeightLoopRec ( heightIndex + 1 )
                    | ( true  , false ) -> true
                    | ( false , _     ) -> false
                HeightLoopRec 0

            HeightLoop ()

        with // Not really sure what I want to do with error handling atm
            | :? System.ArgumentOutOfRangeException -> false
            | :? System.ArgumentNullException       -> false
            | :? System.ArgumentException           -> false

I ran this code through my tests, and it's functionally the same as the old while-do version which I'm including for comparison's sake:

namespace MathAlgorithms

module ArrayFunctions =
    // Generic because it makes testing easier, yay math
    let SearchSubset (tSmallArray:'a[][]) (tLargeArray:'a[][]) (pCoordinate:(int * int)) =
        let tSmallHeight = tSmallArray.Length
        let tSmallWidth = tSmallArray.[0].Length

        let tHeightIndex = fst pCoordinate
        let tWidthIndex = snd pCoordinate
        let mutable tSmallHeightIndex = 0
        let mutable tSmallWidthIndex = 0
        let mutable tMatch = true

        try
            while ( tSmallHeightIndex < tSmallHeight - 1 ) && tMatch do
                while ( tSmallWidthIndex < tSmallWidth - 1 ) && tMatch do
                    let tLargeCurrentValue = tLargeArray.[tHeightIndex + tSmallHeightIndex].[tWidthIndex + tSmallWidthIndex]
                    let tSmallCurrentValue = tSmallArray.[tSmallHeightIndex].[tSmallWidthIndex]

                    if tSmallCurrentValue = tLargeCurrentValue then
                        tSmallWidthIndex <- tSmallWidthIndex + 1
                    else
                        tMatch <- false

                tSmallWidthIndex  <- 0
                tSmallHeightIndex <- tSmallHeightIndex + 1

            tMatch
        with
            | _ -> false

Github for further info:
https://github.com/Kenneth-Posey/LearningFsharp/tree/master/FsharpTutorial/YeFsharpLibrary
The use of the function is in the module FsharpImaging.fs, it's tested by UnitTest.fs and it's located in ArrayFunctions.fs.


texts: Is there a more optimized way for this MySql Query

texts:
with below query i'm getting the results that i want but it's quite slow taking nearly 0.2 seconds (on an i5 machine). Is there a more optimized way to get the same results.

Basically this query fetches the last 20 rows in the table and shows only one row per yzr.name and orders by yzr.favorite_count

SELECT      gzt.name AS gazete,
            yz.*,
            yzr.name,
            yzr.gazete_id,
            yzr.yazar_image_link,
            yzr.favorite_count,
            DATE_FORMAT(tarih,'%d.%m.%Y') As formatted_tarih

FROM        yazar AS yzr

INNER JOIN  yazi   yz  ON yzr.id=yz.yazar_id
INNER JOIN  gazete gzt ON yzr.gazete_id = gzt.id

GROUP By    yzr.name
ORDER BY    yzr.favorite_count DESC

LIMIT 20 OFFSET 0


texts: Check whether a permutation with one fixed point can be rotated into one with two fixed points

texts:
A friend gave me the following riddle:

  Given n people with n distinct names, you place n names tags on a round table with n seats. If the n people now sit at those seats randomly such that exactly one person sits correctly (in the seat with the correct name tag with their name one it), can we rotate the table such that (at least) two people sit correctly?

For odd n this is false, which you can see by considering by placing the name tags 1, ..., n in order and seating the people as 1, n, n - 1, ... 2. I haven't been able that this true for even n so I wanted to try out small even n with a python script.

I wrote the following code. Unfortunately, it is very slow (n = 10 takes about 25 seconds, but n = 12 takes nearly 11 minutes!) so I am searching for libraries which can speed up the things I implemented from scratch or maybe a method which speeds things up.

I have 4 methods:

perms(n), which gives me all permutations of 0, ..., n- 1 which have one fixed point,
fixtest(L,m), which tests if the permutation L has m fixed points,
rot(L), which rotates the permutation L, i.e. [1,2,3] becomes [2,3,1] and
test(n) which, for a given n generates all permutations of 0, ..., n- 1 which have one fixed point with perms(n) and then for each one, performs all rotations and for every rotation checks the number of fixed points and writes them in a list C. If C only contains ones, we have found a counterexample to the riddle above.

My code looks like this

from itertools import permutations
from collections import deque

# find all permutations of [n] with 1 fixed point
def perms(n):
    P = (perm for perm in permutations(range(n)))
    D = []                        # D will contain the 'right' permutations (those with one fixed point)
    for perm in P:                # count fixed points (counter c)
        c = 0
        for idx, k in enumerate(perm):
            if idx == k:
                c +=1
        if c == 1:
            D.append(perm)
    return D

 # tests if a sequence L has m fixed points
def fixtest(L,m):
    L = list(L)
    c = 0
    for idx, k in enumerate(L):
        if idx == k:
            c +=1
    if c == m:
        return True
    else:
        return False

# rotates the list L
def rot(L):
    L = deque(L)
    a = L.pop()
    L.appendleft(a)
    return list(L)

def test(n):
    for f in perms(n):
        k = 0
        C = []
        f_real = list(f)
        while k < n - 1:
            f = rot(f)
            C.append(fixtest(f,1))
            k +=1
        if all(x == True for x in C):
            return n, 'Counterexample found:', f_real
    return n, 'no counterexamples found'


texts: Designing object oriented clean code structure with spring services

texts:
I'm writing spring app for storing and manipulating recipes. I wrote ShoppingList service which generates, based on UUIDs of recipes, shopping list. This is my current model for which i wrote tests and works as intended.
Service uses another service called IngredientConverter which converts to response models. Now i wanted to move some dependency to ShoppingList as this function is jealous of functions, but approached a problem. How can a this class use IngredientConverter service without ugly passing it to ShoppingList function? Are there any tips you could give my code and structure planning?
@Service
@AllArgsConstructor
public class ShoppingListService {

    private final RecipeService recipeService;
    private final IngredientConverter ingredientConverter;

    public ShoppingList generateShoppingList(List<UUID> uuidsOfRecipes) {
        List<Recipe> recipes = recipeService.getAllByIDIn(uuidsOfRecipes);
        ShoppingList shoppingList = ShoppingList.empty();

        Map<Ingredient, Integer> ingredients = new HashMap<>();

        recipes.forEach(recipe ->
                recipe.getIngredients().forEach(
                        ingredientQuantity ->
                                ingredients.compute(
                                        ingredientQuantity.getIngredient(),
                                        (key, value) ->
                                                value == null ?
                                                        ingredientQuantity.getAmount() :
                                                        value + ingredientQuantity.getAmount())));

        ingredients.keySet().forEach(
                ingredient ->
                        shoppingList.getIngredients().add(
                                ingredientConverter.convertWithAmount(
                                        ingredient.getName(),
                                        ingredients.get(ingredient),
                                        ingredient.getUnit())
                        )

        );

        return shoppingList;
    }

}

@Data
@AllArgsConstructor
public class ShoppingList {

    private final List<IngredientQuantity> ingredients;

    public static ShoppingList of(List<IngredientQuantity> ingredients) {
        return new ShoppingList(ingredients);
    }

    public static ShoppingList empty(){
        return ShoppingList.of(new ArrayList<>());
    }

}

@Service
public class IngredientConverter {

 public IngredientQuantity convertWithAmount(String name, int amount, Unit unit) {
        return IngredientQuantity.builder()
                .amount(amount)
                .ingredient(convert(name, unit))
                .build();
    }
}

@Data
@Entity
@SuperBuilder
@NoArgsConstructor
@AllArgsConstructor
@EqualsAndHashCode(callSuper = true)
public class IngredientQuantity extends IdentifiableEntity {

    private int amount;
    @ManyToOne
    private Ingredient ingredient;
}

@Data
@Getter
@Entity
@SuperBuilder
@NoArgsConstructor
@AllArgsConstructor
@EqualsAndHashCode(callSuper = false)
public class Ingredient extends IdentifiableEntity {

    private String name;
    @Enumerated(EnumType.STRING)
    private Unit unit;
}

@Getter
@NoArgsConstructor
@SuperBuilder
@MappedSuperclass
public class IdentifiableEntity {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private UUID ID;
}
```


texts: Generating two .csv files from named parameters

texts:
I wrote Clojure code which takes named params and has to generate 2 .csv files as output.

Please review it.

(ns my_cli_clojure.core
  (:gen-class :main true))

(require '[clojure.data.csv :as csv]
     '[clojure.java.io :as io]
     '[me.raynes.fs :as fs]
     '[clojure.tools.cli :refer [cli] :as c])

(defn write_csv_data [& {:keys [data outfile]
                     :or {data ""
                          outfile ""}}]
  (csv/write-csv outfile
                data))

(defn -main
  [& args]
    (let [[options args banner]
  (c/cli args
 ["-d" "-dome" "Dome Identifier" :default "dome1"]
 ["-p" "-principal" "Principal code" :default "kraft"]
 ["-o" "-output-directory" "Output file" :default "."]
 ["-h" "-help" "Show Help" :flag true :default false])]

(when (:help options)
  (println banner)
  (System/exit 0))

 (let [output_directory (:output-directory options)]
(if-not (fs/exists? output_directory)
  (fs/mkdirs output_directory))
(doseq [n (clojure.string/split (:dome options) #",")]
  (let [dome_identifier (first (clojure.string/split n #"-"))]
(with-open [out-file (io/writer (clojure.string/join "/" [output_directory
                                                                  (clojure.string/join "." [dome_identifier "csv"])]))]
(write_csv_data :data [["dome_identifier" "name"]
                       [dome_identifier (first (reverse     (clojure.string/split n #"-")))]] :outfile out-file))

(with-open [dome_principal_file (io/writer (clojure.string/join "/" [output_directory
                                                                           (clojure.string/join "." ["dome_principal" dome_identifier "csv"])]))]
 (write_csv_data :data [(clojure.string/split "dome_identifier principal_code currency_code active latitude longitude" #"\s")
                        [dome_identifier (:principal options) "" "t" "" ""]] :outfile dome_principal_file)))))))


texts: Fastest way to find dataframe indexes of column elements that exist as lists

texts:
I asked this question here: https://stackoverflow.com/q/55640147/5202255 and was told to post on this forum. I would like to know whether my solution can be improved or if there is another approach to the problem. Any help is really appreciated!

I have a pandas dataframe in which the column values exist as lists. Each list has several elements and one element can exist in several rows. An example dataframe is:

X = pd.DataFrame([(1,['a','b','c']),(2,['a','b']),(3,['c','d'])],columns=['A','B'])

X =
 A          B
0  1  [a, b, c]
1  2  [a, b]
2  3     [c, d]

I want to find all the rows, i.e. dataframe indexes, corresponding to elements in the lists, and create a dictionary out of it. Disregard column A here, as column B is the one of interest! So element 'a' occurs in index 0,1, which gives {'a':[0,1]}. The solution for this example dataframe is:

Y = {'a':[0,1],'b':[0,1],'c':[0,2],'d':[2]}

I have written a code that works fine, and I can get a result. My problem is more to do with the speed of computation. My actual dataframe has about 350,000 rows and the lists in the column 'B' can contain up to 1,000 elements. But at present the code is running for several hours! I was wondering whether my solution is very inefficient.
Any help with a faster more efficient way will be really appreciated!
Here is my solution code:

import itertools
import pandas as pd
X = pd.DataFrame([(1,['a','b','c']),(2,['a','b']),(3,['c','d'])],columns=['A','B'])
B_dict = []
for idx,val in X.iterrows():
    B = val['B']
    B_dict.append(dict(zip(B,[[idx]]*len(B))))
    B_dict = [{k: list(itertools.chain.from_iterable(list(filter(None.__ne__, [d.get(k) for d in B_dict])))) for k in set().union(*B_dict)}]

print ('Result:',B_dict[0])

Output

Result: {'d': [2], 'c': [0, 2], 'b': [0, 1], 'a': [0, 1]}

The code for the final line in the for loop was borrowed from here https://stackoverflow.com/questions/45649141/combine-values-of-same-keys-in-a-list-of-dicts, and https://stackoverflow.com/questions/16096754/remove-none-value-from-a-list-without-removing-the-0-value


texts:
I have recently been refactoring some code in an effort to improve the exception handling, particularly to aid in improving the level of information given to developers during development. However I am worried that I have started down the wrong path.
For example we were getting complaints that the following code threw an exception with the message: Sequence contains no elements when a database does not contain a record with the supplied ID.
public Record GetRecord(string id)
{
    _dbContext.Records.First(r => r.Id == id);
}

After refactoring the code, it now throws an exception whose message is No record found with id: {0}.
public Record GetRecord(string id)
{
    try
    {
        _dbContext.Records.First(r => r.Id == id);
    }
    catch(InvalidOperationException ex)
    {
        throw new ApplicationException(string.Format("No record found with id: {0}". id), ex);
    }
}

I can understand that this error message might be clearer, as we now know that no record was found. However, using this logic, where should we stop? Surely the below would also be an 'improvement'
public Record GetRecord(string id)
{
    try
    {
        _dbContext.Records.First(r => r.Id == id);
    }
    catch(InvalidOperationException ex)
    {
        throw new ApplicationException(string.Format("No record found with id: {0}".
    }
    catch(SqlException ex)
    {
        throw new ApplicationException("An error occurred while processing the record"), ex);
    }
}

I would consider it bad practice to wrap exceptions like this, however I am willing to be proved wrong. Is there any reason why this would be desirable? Where should the line be drawn?
Microsoft provide the following advice

Consider wrapping specific exceptions thrown from a lower layer in a more appropriate exception, if the lower layer exception does not make sense in the context of the higher-layer operation.
This should be done rarely because it makes debugging more difficult. It is appropriate when you are certain that the lower layer is never the true source of the error.

However surely an exception can also be wrapped in a more appropriate exception?


texts:
I am trying to implement a custom ApiClient in Python, using requests.
The way it does authentication is by:

login(username, password) -> get back a token if valid, http error code if not
set the token in {'Authorization': token} header and use that header for all endpoints which need authentication

Can you check if the code looks OK, and if not what kind of changes would you recommend?

#!/usr/bin/env python

import requests
import json
import os
import sys

def read_file_contents(path):
    if os.path.exists(path):
        with open(path) as infile:
            return infile.read().strip()

class ApiClient():
    token = None
    api_url = 'http://10.0.1.194:1234'
    session = requests.Session()

    def __init__(self):
        self.token = self.load_token()

        if self.token:
            self.session.headers.update({'Authorization': self.token})
        else:
            # if no token, do login
            if not self.token:
                try:
                    self.login()
                except requests.HTTPError:
                    sys.exit('Username-password invalid')

    def load_token(self):
        return read_file_contents('token')

    def save_token(self, str):
        with open('token', 'w') as outfile:
            outfile.write(str)

    def login(self):
        email = '1@1.hu'
        password = 'passwd'

        headers = {'content-type': 'application/json'}
        payload = {
            'email': email,
            'password': password
        }
        r = requests.post(self.api_url + '/auth',
                          data=json.dumps(payload),
                          headers=headers)

        # raise exception if cannot login
        r.raise_for_status()

        # save token and update session
        self.token = r.json()['session']['token']
        self.save_token(self.token)
        self.session.headers.update({'Authorization': self.token})

    def test_auth(self):
        r = self.session.get(self.api_url + '/auth/is-authenticated')
        return r.ok

if __name__ == '__main__':
    api = ApiClient()
    print api.test_auth()


texts: Generating a data validation list and sorting it alphabetically

texts:
The following code clears 11 columns that contain lists that are used for data validation on another worksheet. This list is constantly changing due to records being added/removed from the source data. Basically I'm checking every value in a column, and if it meets all of my criteria I'm adding it to my data validation column (after making sure it doesn't already exist there).

Once I've populated my 11 columns, I sort each one alphabetically. This is the portion of my code that I don't like. While it doesn't explicitly select anything, I can see on my worksheet the last column that was sorted because it is selected.

What I'm wondering is if there's a better way to dynamically generate this list alphabetically without having to use .Sort - possibly populating an array and then sorting it alphabetically? I've never sorted an array in VBA, so I'm not sure 1. If it's even more efficient and 2. What is the best method to sort an array, if that's the approach I should take here?

Code:

Option Explicit
Sub PopulateAllDataValidationLists()

    Dim sht As Worksheet, sht2 As Worksheet
    Dim i As Long, listcol As Long

    Set sht = Worksheets("Sheet 1")
    Set sht2 = Worksheets("Data Validation")

        Application.ScreenUpdating = False

        sht2.Range("A2:K500").ClearContents

        For i = 1 To 11
            listcol = sht.Rows("1:1").Find(What:=sht2.Cells(1, i).Value, LookAt:=xlWhole).Column

            For j = 2 To sht.Cells(sht.Rows.Count, listcol).End(xlUp).Row
                If IsError(Application.Match(sht.Cells(j, listcol).Value, sht2.Range(ColumnLetter(i) & ":" & ColumnLetter(i)), 0)) And _
                sht.Cells(j, listcol).Value <> "" And _
                sht.Cells(j, listcol).Value <> "UNK" And _
                sht.Cells(j, listcol).Value <> "xxx" And _
                sht.Cells(j, listcol).Value <> "yyy" And _
                sht.Cells(j, listcol).Value <> "zzz" And _
                sht.Cells(j, listcol).Value <> "yxz" And _
                sht.Cells(j, listcol).Value <> "zyx" And _
                Len(sht.Cells(j, listcol).Value) <= 3 Then
                    sht2.Cells(sht2.Cells(sht2.Rows.Count, i).End(xlUp).Row + 1, i).Value = sht.Cells(j, listcol).Value
                End If
            Next j

        Next i

        'Sort all alphabetically
        For i = 1 To 11
            Worksheets("Data Validation").Sort.SortFields.Clear
            Worksheets("Data Validation").Sort.SortFields.Add Key:=Range(ColumnLetter(i) & "2"), SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal

            With Worksheets("Data Validation").Sort
                .SetRange Range(ColumnLetter(i) & "2:" & ColumnLetter(i) & sht2.Cells(sht2.Rows.Count, i).End(xlUp).Row)
                .Header = xlNo
                .MatchCase = False
                .Orientation = xlTopToBottom
                .SortMethod = xlPinYin
                .Apply
            End With
        Next i

        Application.ScreenUpdating = True

End Sub
Function ColumnLetter(colnum As Long) As String

    ColumnLetter = Split(Cells(1, colnum).Address, "$")(1)

End Function

An example of data in a column:


texts:
I've been rewriting parts of my own framework and eventually came back to where it all began, making traits more useful and implementing auto initializing traits and I am wondering if someone has a bright idea on how to implement it a bit cleaner.

The idea of this is simple, let traits have constructors that are called before the class __construct().

namespace myframework\traits{
  trait Construct{
    function __wakeup(){
      foreach(array_remove(__TRAIT__, ref(class_uses(self::class, false))) as $trait){
        $list[($v = \myframework::loader()->trait($trait))[0]][] = $v[1];
        # generates: $list[$priority][] = $callback
      }

      if(ksort($list)){
        foreach($list as $cb){
          foreach($cb as $fn){
            $fn->call($this);
          }
        }
      } else {
        # Something horrible happend, oh well can/does it ever fail?
      }
    }
  }

  trait DB{
    private $db;
  }

  # Register anon function to fire when trait gets loaded. Constructor.
  \myframework::loader()->trait('myframework\traits\DB', function(){
    $this->db = myframework\Database::getInstance();
  }, 0);

  # This function essentially makes:
  # $data['myframework\traits\DB'] = [0 => 0, 1 => callback]
  # where key index 0 is the load priority, which gets sorted.
}

I tried to trim the code as much as possible for simplicity, the array_remove() is a function returning the an updated array by removing a key from a generated array and ref() is just a wrapper function to allow array_remove() to be inlined.

Now lets assume the above code is autoloaded, making a new file and doing the following is now possible:

class someClass{
  use myframework\traits\Construct;
  use myframework\traits\DB;

  public function __construct(){
    // DRY concept, $this->db is already set.

    $stmt = $this->db->prepare("SELECT * FROM table");
  }
}

Now this is just a minor example, imagine if you add a trait Log adding a method log($msg) that will automatically log the message under the class name and with the auto initializer the object itself can determine where to log, for example the filesystem if the database failed to connect.

So my question mainly is, if there is a cleaner way to implement the anonymous function because it is currently registered by name instead of reference. Also since this is the core of the framework it needs to be efficient as possible because __wakeup() can be called for each object created using this system.

Also I'd like to have some input on what I could improve upon it.


texts: Should I be using a stored procedure for this function in my code behind?

texts:
We typically do our saves and deletes for our asp.net pages (SQL Server as back-end) in the code behind. I've seen some reference the idea of creating a stored procedure for this purpose. Is this the best approach or is what I'm doing practical enough? Any suggestions? Here's an example of the delete button function (first half is for triggers set up in SQL):

protected void DeleteClick(object sender, EventArgs e)
{
    cookie = Request.Cookies["pAuthCookie"];
    if (txtKey.Text == "")
    {
        string scriptstring = "alert('User Error - Must Select Fromn the LIST first.');";
        ScriptManager.RegisterStartupScript(Tab1, typeof(string), "alertscript", scriptstring, true);
        if (TabContainer1.ActiveTabIndex == 1)
            TabContainer1.ActiveTabIndex = 0;
        return;
    }
    else
    {
        String fprescript = txtKey.Text;
        string empno = cookie["thenum"].ToString();

        string sqlstring1 = "UPDATE prescriptions set empfk = @empfk WHERE prescriptpk = @prescriptpk";
        con.Open();
        SqlCommand cmd1 = new SqlCommand(sqlstring1, con);
        cmd1.Parameters.Add("@prescriptpk", SqlDbType.Int);
        cmd1.Parameters.Add("@empfk", SqlDbType.Int);
        cmd1.Parameters["@prescriptpk"].Value = Convert.ToInt32(fprescript);
        cmd1.Parameters["@empfk"].Value = empno.Trim();
        cmd1.ExecuteNonQuery();

        con.Close();
        string sqlstring = "DELETE FROM prescriptions WHERE prescriptpk = @prescriptpk";
        con.Open();
        SqlCommand cmd = new SqlCommand(sqlstring, con);
        cmd.Parameters.Add("@prescriptpk", SqlDbType.Int);
        cmd.Parameters["@prescriptpk"].Value = Convert.ToInt32(fprescript);
        cmd.ExecuteNonQuery();

        con.Close();
        clearoutdata();
        TabContainer1.ActiveTabIndex = 0;
        GridView1.DataBind();
    }
}


texts:
I have a table that holds a user's weight for specific days. In my weights_controller.rb index action I can show these weights - no problem. What I also want to show on the index is the user's current weight, his weight loss over time as well as the timeframe he achieved this weight loss.

Thus I created a weight_calculator.rb to do the needed calculations:

class WeightCalculator
  def initialize(profile, user)
     @profile = profile
     @user = user
  end

  def current_weight
    @current_weight = Weight.where(:user_id => @user.id).order(:day).last
  end

  def weight_loss
    @current_weight = Weight.where(:user_id => @user.id).order(:day).last
    @start_weight = Weight.where(:user_id => @user.id).order(:day).first
    @weight_loss = @current_weight.kilograms - @start_weight.kilograms
  end

  def timeframe
    @current_weight = Weight.where(:user_id => @user.id).order(:day).last
    @start_weight = Weight.where(:user_id => @user.id).order(:day).first
    @weight_loss_timeframe = @current_weight.day - @start_weight.day
    @weeks = @weight_loss_timeframe.to_i/7
  end
end

This is my weights_controller.rb index action:

  def index
    @weights = Weight.where(:user_id => current_user.id).order(day: :desc)
    @weight_loss = WeightCalculator.new(@profile, current_user).weight_loss
    @weeks = WeightCalculator.new(@profile, current_user).timeframe

    @result = {}
    Weight.where(:user_id => current_user.id).each do |weight|
      @result[weight.day] = weight.kilograms
    end

    @profile = Profile.where(:user_id => current_user.id)
  end

Everything works fine in this setup. However, there is clearly some repition in my weight_calculator.rb and I am asking myself what would be the best way to write this code to be DRY conform?


texts:
This is supposed to get a single value from the DB.

What should I consider next? How can I upgrade it?

public static String GetConnectionString()
        {
            return ConfigurationManager.ConnectionStrings["xxx"].ConnectionString;
        }

        public static String GetProviderName()
        {
            return ConfigurationManager.ConnectionStrings["xxx"].ProviderName;
        }

        private Object GetValue(string cmdTxt)
        {
            try
            {
                using (SqlConnection connection = new SqlConnection(GetConnectionString()))
                using (SqlCommand command = new SqlCommand(cmdTxt, connection))
                {
                    connection.Open();
                    return command.ExecuteScalar() ?? null;
                }
            }
            catch (Exception e)
            {
                try
                {
                    log.Error(string.Format("SELECT User: {0} Base: {3} SQL:{2} Error:{1}", (Session["UserData"] as UserData).id_user, e.Message, cmdTxt, Session["ClientBASE"].ToString()));
                }
                catch { log.Error(string.Format("SELECT User: {0} SQL:{2} Error:{1}", (Session["UserData"] as UserData).id_user, e.Message, cmdTxt)); }
                return null;
            }
        }

        public bool GetValueAsBoolean(string cmdTxt)
        {
            return Convert.ToBoolean(this.GetValue(cmdTxt) ?? false);
        }

        public string GetValueAsString(string cmdTxt)
        {
            return (this.GetValue(cmdTxt) ?? String.Empty).ToString();
        }

        public int GetValueAsInt(string cmdTxt)
        {
            return Convert.ToInt32(this.GetValue(cmdTxt) ?? 0);
        }

        public double GetValueAsDobule(string cmdTxt)
        {
            return Convert.ToDouble(this.GetValue(cmdTxt) ?? 0.0);
        }


texts:
I wrote this code in my .bashrc to remap ls to honor .hidden files. I'm pretty new to shell/bash scripting, so I feel like this is not the most performant way to handle this, and it has some limitations. I would appreciate any suggestions regarding performance improvements, limitation reduction, or common best practices for shell/bash scripting (or improving my post since I'm new to the StackExchange network).

# File names in .hidden files are ignored by ls
# NOTES: Not tolerant of empty lines (or lines with only whitespace) in the .hidden file(s)
#    If any argument doesn't begin with a '-', this assumes it's a file argument
#    If you pass multiple folders, it will essentially concatenate the .hidden files and ignore all files matching any of those names (so if you have a file name TEST in two folders, but only have TEST in the .hidden file of one folder, calling ls on both folders won't show either TEST file)
#    It does honor the -a flag
#    I don't know if there's a limit on total number of flags or total command length, but if there is, this may surpass it depending on the number of file names in the .hidden file
ls () {
    DEFAULT_ARGS="--color=auto" # Here, because I want colors (and you can't have a function and an alias with the same name)
    ALL=false
    A=0
    F=0
    I=0
    declare -a ARGS
    declare -a FILES
    declare -a IGNORE
    for a in $@
    do
        if [[ $a =~ ^-(a|[^-]+a) ]]; then # If the -a flag is present
            ALL=true
            break
        fi
        if [[ $a =~ ^[^-].* ]]; then # If the argument doesn't start with '-', add it to the Files array
            FILES[$F]=$a
            ((F++))
        else                 # Otherwise add it to the Args array
            ARGS[$A]=$a
            ((A++))
        fi
    done
    if $ALL; then
        command ls ${DEFAULT_ARGS} ${@}
        return
    else
        if [ ${#FILES[@]} -eq 0 ]; then # If no files/directories are present, explicitly add the implied .
            FILES[$F]="."
        fi
        for f in ${FILES[*]}
        do
            if [ -f "${f}/.hidden" ]; then # Read the .hidden file, if present, and generate the -I flags
                IGNORE[$I]=$(awk '{print "-I " $0}' "${f}/.hidden" | tr "\n" " ")
                ((I++))
            fi
        done
        command ls ${DEFAULT_ARGS} ${ARGS[*]} ${IGNORE[*]} ${FILES[*]}
        return
    fi
}

Note: A .hidden file is a file (named .hidden) containing a list of file names from the same directory that should be treated as if they begin with a '.'


texts: Object-oriented design implementation of an Elevator

texts:
I am a newbie when it comes to Object Oriented Programming and I have read a lot of online articles and lessons so I want to try it out on my own. I've written a console app in C# and tried implementing Object Oriented Design and SOLID Principles.

The console app checks if a person has an access to a certain floor. Also, The app is in its initial stage so right now the Elevator accomodates a single person.

Although the app works. any feedback,comments, and suggestions will be greatly appreciated especially in terms of SOLID principles or OOP Design.

here is the code below

class Program
{
    static void Main(string[] args)
    {
        Person maintenanceEmployee = new MaintenanceEmployee();
        Elevator elev = new Elevator(maintenanceEmployee);
        elev.GoToFloor(Floors.FourthFloor);

        Person guest = new Guest();
        Elevator elev2 = new Elevator(guest);
        elev2.GoToFloor(Floors.SecondFloor);

        Person empfromthirdfloor = new EmployeeFromThirdFloor();
        Elevator elev3 = new Elevator(empfromthirdfloor);
        elev2.GoToFloor(Floors.ThirdFloor);

        Console.ReadLine();
    }
}

public enum Floors
{
    FirstFloor = 1,
    SecondFloor = 2,
    ThirdFloor = 3,
    FourthFloor = 4,
    FifthFloor = 5
}

public class Elevator
{
    Person person;
    public Elevator(Person _person)
    {
        this.person = _person;
    }

    public void GoToFloor(Floors _floor)
    {
        if (person.HasAccess(_floor))
        {
            Console.WriteLine("Elevating to " + _floor.ToString());
        }
        else
        {
            Console.WriteLine("No Access to " + _floor.ToString());
        }
    }
}

public abstract class Person
{
    public Floors[] accessibleFloors;

    public bool HasAccess(Floors _floor)
    {
        foreach (Floors i in accessibleFloors)
        {
            if (_floor == i)
            {
                return true;
            }
        }
        return false;
    }

}

public class MaintenanceEmployee : Person
{
    public Floors[] _accessibleFloors = { Floors.FirstFloor, Floors.SecondFloor, Floors.ThirdFloor, Floors.FourthFloor, Floors.FifthFloor };

    public MaintenanceEmployee()
    {
        //Not sure if this is the best practice
        //Reason why I did it like this is because
        //I need to change the arrays of accessibleFloors
        //in the abstract class "Person" in order to run successfully
        base.accessibleFloors = _accessibleFloors;
    }
}

public class EmployeeFromThirdFloor : Person
{
    public Floors[] _accessibleFloors = { Floors.ThirdFloor };

    public EmployeeFromThirdFloor()
    {
        //Not sure if this is the best practice
        //Reason why I did it like this is because
        //I need to change the arrays of accessibleFloors
        //of the abstract class "Person" in order to run successfully
        base.accessibleFloors = _accessibleFloors;
    }
}

public class Guest : Person
{
    public Floors[] _accessibleFloors = { Floors.SecondFloor };

    public Guest()
    {
        //Not sure if this is the best practice
        //Reason why I did it like this is because
        //I need to change the arrays of accessibleFloors
        //of the abstract class "Person" in order to run successfully
        base.accessibleFloors = _accessibleFloors;
    }
}


texts: Rewrite method to decide the ShowLevel based on roles

texts:
I have different roles in my system.

HOD
Staff
Non staff

I am having a form at the front end and fields shall be visible to only users with specific roles.

The ShowInGui levels are like this:

Show to All
Show to staff/HOD
Show to HOD

Any other do not show

I am planning to write a method which will take the user role and decides the access.

Could this method be better written?

public boolean canBeShownInGUI(Role role, int showInGui) {
    if (showInGui == 1) {
        return true;
    } else if (showInGui == 2 && (role == Role.HOD || role == Role.STAFF)) {
        return true;
    } else if (showInGui == 3 && role == Role.HOD) {
        return true;
    } else
      return false;
   }


texts:
In the question of how to reverse a string in Java, a comment mentioned that combining Unicode code points need to be taken into account.

The below code works as intended for all test cases I tried. Probably there are some edge cases in other scripts and languages I do not know. I'd like to learn about these, as well as any coding style issues.

package de.roland_illig.strrev

import com.ibm.icu.lang.UCharacter
import org.assertj.core.api.Assertions.assertThat
import org.junit.jupiter.api.Test

/**
 * Returns the reversed string, keeping clusters of combining code points
 * (such as German umlauts or Arabic tashkīl) together.
 */
fun String.reverse(): String {

    fun isLamAlef(cluster: List<Int>, ch: Int) =
            cluster.isNotEmpty() && cluster.first() == 0x0644 && ch == 0x0627

    val clusters = mutableListOf<List<Int>>()
    val cluster = mutableListOf<Int>()

    this.codePoints().forEachOrdered { ch ->
        if (!(UCharacter.getCombiningClass(ch) != 0) && !isLamAlef(cluster, ch)) {
            if (cluster.isNotEmpty()) {
                clusters += cluster.toList()
                cluster.clear()
            }
        }
        cluster += ch
    }

    if (cluster.isNotEmpty()) {
        clusters += cluster.toList()
        cluster.clear()
    }

    return fromCodePoints(*clusters.reversed().flatten().toIntArray())
}

class StringReverseTest {

    @Test
    fun ascii() {
        assertThat("hello".reverse()).isEqualTo("olleh")
    }

    @Test
    fun surrogates() {
        val emoji = fromCodePoints(0x1F645)
        assertThat(emoji.reverse()).isEqualTo(emoji)
    }

    @Test
    fun combining() {
        val combinedUmlaut = fromCodePoints(0x0041, 0x0308)
        assertThat(combinedUmlaut.reverse()).isEqualTo(combinedUmlaut)
    }

    @Test
    fun arabic() {
        assertThat("أَهْلًا وَ سَهْلًا".reverse()).isEqualTo("لًاهْسَ وَ لًاهْأَ")
    }

    @Test
    fun combiningAtBeginning() {
        val combinedUmlaut = fromCodePoints(0x0308, 0x0041)
        assertThat(combinedUmlaut.reverse())
                .isEqualTo(fromCodePoints(0x0041, 0x0308))
    }
}

private fun fromCodePoints(vararg codePoints: Int): String =
        String(codePoints, 0, codePoints.size)

For completeness, here are the Gradle dependencies for build.gradle:

dependencies {
    compile "org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlin_version"
    compile group: 'com.ibm.icu', name: 'icu4j', version: '61.1'

    testCompile "org.jetbrains.kotlin:kotlin-test:$kotlin_version"
    testCompile "org.junit.jupiter:junit-jupiter-api:5.0.2"
    testCompile "org.assertj:assertj-core:3.9.0"
}


texts:
I've been doing bits and bobs with Python for a few years, but I've never took the time to get feedback on what's pythonic and what's not. In the interest of collaborating more with Python programmers, I'd like to make sure my code follows conventions and idioms that the majority of Pythonistas will recognize.

Please review my Kitchen Timer class for:

pythonic idioms and conventions
behavioural correctness (especially around multi-threading and timing precision)
portability
readability
maintainability
efficiency

Also, if the purpose of the class is unclear from its API and comments, please offer your suggestions for improvement there too.

from threading import Timer as TTimer
from time import time
from threading import Lock

class NotRunningError(Exception): pass
class AlreadyRunningError(Exception): pass

class KitchenTimer(object):
    '''
    Loosely models a clockwork kitchen timer with the following differences:
        You can start the timer with arbitrary duration (e.g. 1.2 seconds).
        The timer calls back a given function when time's up.
        Querying the time remaining has 0.1 second accuracy.
    '''

    running = "running"
    stopped = "stopped"
    timeup =  "timeup"

    def __init__(self):
        self.__stateLock = Lock()
        self.state = self.stopped
        self.__timeRemainingLock = Lock()
        self.timeRemaining = 0

    def start(self, duration=1, whenTimeup=None):
        if self.isRunning():
            raise AlreadyRunningError
        else:
            self.state = self.running
            self.timeRemaining = duration
            self._userWhenTimeup = whenTimeup
            self._startTime = self._now()
            self._timer = TTimer(duration, self._whenTimeup)
            self._timer.start()

    def stop(self):
        if self.isRunning():
            self._timer.cancel()
            self.state = self.stopped
            self.timeRemaining -= self._elapsedTime()
        else:
            raise NotRunningError()

    def isRunning(self):
        return self.state == self.running

    def isTimeup(self):
        if self.state == self.timeup:
            return True
        else:
            return False

    @property
    def state(self):
        with self.__stateLock:
            return self._state

    @state.setter
    def state(self, state):
        with self.__stateLock:
            self._state = state

    @property
    def timeRemaining(self):
        with self.__timeRemainingLock:
            if self.isRunning():
                self._timeRemaining -= self._elapsedTime()
            return round(self._timeRemaining, 1)

    @timeRemaining.setter
    def timeRemaining(self, timeRemaining):
        with self.__timeRemainingLock:
            self._timeRemaining = timeRemaining

    def _whenTimeup(self):
        self.state = self.timeup
        self.timeRemaining = 0
        if callable(self._userWhenTimeup):
            self._userWhenTimeup()

    def _now(self):
        return time()

    def _elapsedTime(self):
        return self._now() - self._startTime


texts: Read comma separated values and insert in SQL Server 2016 table using String_Split

texts:
I know that this question has been asked many times over many years and I have read every one of them but I wanted to get a modern solution since software has changed and String_Split has been introduced in SQL Server 2016.

I have a stored procedure that splits a comma-separated string and inserts the values into a table after it deletes the value if it is already there. The code works but sometimes I write code that is totally convoluted.

ALTER PROCEDURE [dbo].[Admin_Save_PMIDS]
    @MemberID INT,
    @PMIDList VARCHAR(MAX)
AS
BEGIN
    SELECT Split.a.value('.', 'VARCHAR(100)') AS PMID
    INTO #pmids
    FROM
        (SELECT
             CAST('<M>' + REPLACE(@PMIDList, ',', '</M><M>') + '</M>' AS XML) AS String) AS A
    CROSS APPLY
        String.nodes('/M') AS Split (a)

    DELETE FROM [dbo].[PublicationTable]
    WHERE (MemberID = @MemberID)
     AND  PMID IN (SELECT PMID FROM #pmids)

    INSERT INTO [dbo].[PublicationTable] (PersonID, PMID, MemberID)
        SELECT
            @MemberID, PMID, @MemberID
        FROM
            [#pmids]
        WHERE
            (LEN(PMID) > 0)

    DROP TABLE #pmids
END

As you can see I'm creating a temporary table and using an XML structure as a cross apply. The code works but since I'm doing a lot of updating in the application I figured I'd get some current opinions.


texts:
I have written a toy script to list all the git branches in cwd. I am interested in knowing how can I make this code more modular and flexible.
For example I would like to have features like:

List only local branches.
List only remote branches.
Etc.

const os = require('os');
const cp = require('child_process');

const REGEX_STAR = /^\*\s*/g;

const promiseExec = (cmd) =>
  new Promise((resolve, reject) => {
    cp.exec(cmd, (err, stdout, stderr) => {
      if (err) {
        return reject(err);
      }
      resolve(lines(`${stdout}`));
    });
  });

const lines = (str) =>
  str.trim().split(os.EOL).map((line) =>
    line.trim().replace(REGEX_STAR, '')
  );

const branches = () =>
  promiseExec('git branch -a')
    .then((res) => {
      console.log(res);
    });

branches();


texts: Finding the next higher digital permutation of a number

texts:
This is my solution for CodeEval challenge 44.

  You are writing out a list of numbers.Your list contains all numbers with exactly Di digits in its decimal representation which are equal to i, for each i between 1 and 9, inclusive. You are writing them out in ascending order. For example, you might be writing every number with two '1's and one '5'. Your list would begin 115, 151, 511, 1015, 1051. Given N, the last number you wrote, compute what the next number in the list will be. The number of 1s, 2s, ..., 9s is fixed but the number of 0s is arbitrary.

  INPUT SAMPLE:

  Your program should accept as its first argument a path to a filename. Each line in this file is one test case. Each test case will contain an integer n < 10^6. E.g.

115
842
8000

  OUTPUT SAMPLE:

  For each line of input, generate a line of output which is the next integer in the list. E.g.

151
2048
80000

The function followingInteger takes a number in its decimal representation and returns the next higher permutation of the digits of the number. If there isn't a larger permutation of the digits, a '0' may be added to the digits:

ghci> followingInteger "123"
"132"
ghci> followingInteger "10"
"100"

The entire program can be used like this:

./ch044_solution ch044_input

where ch044_input is a file containing one integer on each line.

The code:

import Data.List (partition, sort)
import System.Environment (getArgs)

followingInteger :: String -> String
followingInteger digits
  | isSortedDesc digits = lowestPermutation ('0' : digits)
  | otherwise           = nextHigherPermutation digits

isSortedDesc :: (Ord a) => [a] -> Bool
isSortedDesc xs = all (uncurry (>=)) $ zip xs (tail xs)

lowestPermutation :: String -> String
lowestPermutation digits = let (zeros, nonZeros) = partition (== '0') digits
                               (lowestNonZeroDigit:otherDigits) = sort nonZeros
                           in  lowestNonZeroDigit : zeros ++ otherDigits

nextHigherPermutation :: String -> String
nextHigherPermutation = snd . foldr foldFun (False, "")
  where foldFun d (True, digits)  = (True, d:digits)
        foldFun d (False, digits)
          | null biggerDigits = (False, d:digits)
          | otherwise         = (True, newTail)
          where (biggerDigits, smallerDigits) = partition (> d) digits
                (swapDigit:otherDigits) = sort biggerDigits
                newTail = swapDigit : sort smallerDigits ++ (d : otherDigits)

mapFileLines :: (String -> String) -> IO ()
mapFileLines f = do
    (fileName:_) <- getArgs
    contents <- readFile fileName
    mapM_ (putStrLn . f) $ lines contents

main = mapFileLines followingInteger

I'm pretty new to Haskell, so please criticize my code in every way possible!

I'm especially interested in ways to make the code more readable!


texts:
I've the following tables

Candidates
Id  Name  PicId
 1  Tom   NULL
 2  James 1
 3  Bob   NULL
 4  Manny 2

Attachments
Id  Name
 1  One.jpg
 2  Two.doc
 3  Three.rtf

The join table AttachmentCandidate
CandidateId  AttachmentId
    3             1
    3             2
    4             3

So from the above tables it shows that a candidate's 'PicId' is nullable & one candidate can have 0 or many attachments.

Now the query what I wish to create is the one which should return me Candidate's Name, PicId, & Attachment Name, but I don't want the candidates who neither have a PicId nor any Attachments.

I was able to achieve it with a subquery. Is there any better way it can be done??

SELECT r.cname,r.picId,r.attName FROM
(SELECT Candidates.Name as cname,
Candidates.PicId as picId,
Attachments.Name as attName
FROM Candidates LEFT JOIN AttachmentCandidate
ON Candidates.Id = AttachmentCandidate.CandidateId
LEFT JOIN Attachments
ON AttachmentCandidate.AttachmentId = Attachments.Id) as r
WHERE (r.picId IS NOT NULL OR r.attName IS NOT NULL)

Result
cname   picId  attName
James   1      NULL
Bob     NULL   One.jpg
Bob     NULL   Two.doc
Manny   3      Three.rtf

And the candidate 'Tom' not is present in the result since he doesn't have a picId nor any attachments


texts: Taxi fare calculator based on distance and time in a threshold

texts:
I would like to create a taxi fare calculator which will take as params in a threshold the following:
const threshold = [
  {
    id: 1,
    ord: 1,
    step_distance: 100,
    step_time: 120,
    step_price: 5,
    threshold: 100,
  },
  {
    id: 2,
    ord: 2,
    step_distance: 100,
    step_time: 120,
    step_price: 0.3,
    threshold: 10000,
  },
];

When the ride starts it will take ord: 1 and for every second that is elapsed or new value for distance received it will run a loop to check which of step_distance or step_time has been reached. Then it calculates how many steps are available based on threshold / step_distance. For example in first threshold there is only one step and in second are 100. Once in step one the time reached 120s or 100m it will add $5 for the fare_price, will reset the timer to 0 and will move second threshold. Here every time 100m is reached or 120s the loop will run for 100 times adding to fare_price, $0.3 for each step .
The way I've done it is working but I would like to know if there is a better version achieving this.
const [initialTime, setInitialTime] = useState(new Date());
  const [totalTime, setTotalTime] = useState(0);
  const [currentOrd, setCurrentOrd] = useState(1);
  const [currentStep, setCurrentStep] = useState(0);
  const [currentPrice, setPrice] = useState(0);
  const [routeTime, setRouteTime] = useState(0);

  const { distance, time, currentTimeAndDate } = useTracking(true);

  useEffect(() => {
    const currentDistance = distance * 100;
    const diff = Math.round(
      moment.duration(moment().diff(initialTime)).asSeconds()
    );
    const totalTime = Math.round(
      moment.duration(moment().diff(currentTimeAndDate)).asSeconds()
    );
    setRouteTime(diff);
    setTotalTime(totalTime);
    if (diff || currentDistance) {
      track(currentDistance, diff);
    }
    return () => {
      null;
    };
  }, [distance, time, currentTimeAndDate]);

  const track = (distance, time) => {
    const item = threshold.filter((item) => item.ord === currentOrd);

    if (item[0].ord === currentOrd) {
      const stepDistance = item[0].step_distance;
      const stepTime = item[0].step_time;
      const price = item[0].step_price;
      const thresholdDistance = item[0].threshold;

      // IF AVAILABLE JUST RUN
      if (distance >= stepDistance * currentStep || time >= stepTime) {
        if (thresholdDistance / stepDistance === currentStep) {
          console.log("IS MAXIMUM AVAILABLE");
        } else {
          setPrice(currentPrice + price);
          const currentOrder = currentStep + 1;
          setCurrentStep(currentOrder);
        }
        setInitialTime(new Date());
        if (thresholdDistance / stepDistance - currentStep <= 0) {
          const currentOrder = currentOrd + 1;
          setCurrentOrd(currentOrder);
          setCurrentStep(1);
        }
      } else {
        console.log("Current Distance:", distance);
        console.log("Current Time:", routeTime);
      }
    }
  };


texts:
This is my implementation of the bell() function to calculate the n-th bell number in C.

Along with it I made the factorial() and binomial() functions.

I have serious doubts about their efficiency, in particular whether my implementation of the factorial() function should be correctly optimized for tail-recursion, and whether it is possible to rewrite the bell() to be more efficient.

Let me know any critics about my code, and if I can rely on this implementation or maybe use different approaches.

#include <stdio.h>
#include <stdlib.h>
#include <stdint.h> // For uint64_t
#include <inttypes.h> // For PRIu64

#define factorial(n) fact(n, 1)

static inline uint64_t fact(uint8_t n, uint64_t inc);
static inline uint64_t binomial(uint8_t n, uint8_t k);
static inline uint64_t bell(uint8_t n);

int main(int argc, char **argv) {
    printf("Bell: %" PRIu64 ".\n", bell(21));

    return EXIT_SUCCESS;
}

// Tail recursion?
static inline uint64_t fact(uint8_t n, uint64_t inc) {
    return (n == 0) ? inc : fact(n - 1, inc * (uint64_t)n);
}

static inline uint64_t binomial(uint8_t n, uint8_t k) {
    return factorial(n) / (factorial(k) * factorial(n - k));
}

// can calculate up to bell(21)
static inline uint64_t bell(uint8_t n) {
    if (n == 0) {
        return 1;
    }

    uint8_t i;
    uint64_t sum = 0;

    n--;

    for (i = 0; i <= n; i++) {
        sum += binomial(n, i) * bell(i);
    }

    return sum;
}


texts: Exception handling and releasing of OracleDB connection

texts:
Before I start implementing several REST API service endpoints, I'd like to make sure that I'm not doing it totally wrong.

/**
 * GET /api/test
 * Test API example.
 */
export let getTest = (req: Request, res: Response, next: NextFunction) => {
    // const token = req.user.tokens.find((token: any) => token.kind === "facebook");
    const db = new Database();

    db.getConnection()
        .then(con => {
            con.execute('SELECT * FROM BTO_MDS.AlARMS', {}, { maxRows: 22000 })
                .then(result => {
                    con.release();
                    res.json({data: result.rows});
                })
                .catch(ex => {
                    con.release();
                    res.status(500).json({message: ex.message});
                });
        })
        .catch(ex => {
            res.status(500).json({message: ex.message});
        });

};

Is the connection always released properly, or have I forgotten something?
What seems a bit messy is that I need to release the connection two times, and that I have two catch'es, since I cannot release the connection in the second catch.

For completeness: Database is simply a wrapper that contains the connection string configuration and returns a reference to a new connection:

import * as oracledb from 'oracledb';
import { IConnectionPool } from 'oracledb';

const config = {
    user: 'user',
    password: 'pw',
    connectString: 'databaseNameFromTNSNames',
    poolMax: 16
};

export default class Database {
    private pool: IConnectionPool;
    constructor() {
    }

    public createPool(): void {
        oracledb.createPool(config).then(conpool => {
                this.pool = conpool;
                console.log('Connection Pool created!');
            },
            err => {
                console.log('Error creating pool!');
            });
    }

    public getConnection() {
        return oracledb.getConnection();
    }
}


texts:
I'm creating a simple function to verify whether or not a string is a palindrome, and must use stacks in solving it.

bool isPalindrome(string word) {
    // #1 determine length
    int n = word.size();

    // #3 make sure we have an even string
    if (n % 2 != 0)
        word.erase(0, 1);

    // #2 load the stack
    stack<char> s;
    for (int i = 0; i < n / 2; i++) {
        s.push(word[i]);
        word.erase(i, 1);
    }

    // #4 if our stack is empty, then return true
    if (s.empty())
        return true;

    // #5 compare the first & last letters for a valid palindrome
    /*if (s.top() == word[0]) {
        s.pop();
        word.erase(0, 1);
    } else
        return false;*/

    while (n != 0) {
        if (s.top() == word[0]) {
            s.pop();
            word.erase(0, 1);

            // return true only when our stack is empty
            if (s.empty())
                return true;
        } else
            return false;
    }
}

Is there a better way to do this? Are there any evident issues with the current state of the program?


texts: Retrieving database values through properties

texts:
I have a Settings table which I make frequent DlookUp calls to retrieve values. So I thought instead of having to write Nz(DLookup("FieldName", "TableName", "Condition"), vbNullString) everytime I needed the value, why not wrap it in a property in a standard module.

Public Property Get ActiveKey() As String
    ActiveKey = Nz(DLookup("[_ActiveKey]", "WmSettings"), vbNullString)
End Property

Public Property Let ActiveKey(ByVal pValue As String)
    CurrentDb.Execute StringFormat("UPDATE WmSettings SET [_ActiveKey]='{0}';", pValue), dbFailOnError
End Property

Then I can call it like this:

key_ = Settings.ActiveKey       'I tend to write the module name for clarity

Settings.ActiveKey = "FAD22L"

The same approach could easily apply to an objectFrame/subform scenario.

Public Property Get PageFrame() As Object
    Set PageFrame = Forms.frmMain.SubForm.Form.InnerSubForm
End Property

Public Property Get Page() As Form
    Set Page = Forms.frmMain.SubForm.Form.InnerSubForm.Form
End Property

So my question is, is this approach I've taken considered to be a good practice and does it add a considerable amount of overhead to the application?


texts:
I'm new at this and I'm almost done with learning basic Java. I made this just to see if I could do it. I just want to know if there's anything I can do to make it better.

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import static java.lang.Double.*;

class Calculator {
    private JFrame frame = new JFrame("Simple Calculator");
    private JPanel panel = new JPanel();
    private JTextField inputOne = new JTextField(5);
    private JTextField inputTwo = new JTextField(5);
    private JTextField output = new JTextField(20);
    private String[] symbols = {"\u002b", "\u2212", "\u00f7", "\u00d7"};
    private JComboBox list = new JComboBox(symbols);
    private JButton calculateButton = new JButton("Calculate");

    public static void main(String[] args) {
        Calculator calculator = new Calculator();
        calculator.run();
    }

    public void run() {
        buttonListener buttonListener = new buttonListener();

        calculateButton.addActionListener(buttonListener);
        calculateButton.setFocusPainted(false);
        calculateButton.setBackground(Color.WHITE);
        calculateButton.setForeground(Color.BLACK);

        inputOne.addActionListener(buttonListener);
        inputTwo.addActionListener(buttonListener);
        output.setEditable(false);

        list.setBackground(Color.GRAY);
        list.setForeground(Color.WHITE);
        list.setEditable(false);
        list.setFocusable(false);

        panel.setBackground(Color.DARK_GRAY);
        panel.add(inputOne);
        panel.add(list);
        panel.add(inputTwo);
        panel.add(output);

        frame.getContentPane().add(BorderLayout.SOUTH, calculateButton);
        frame.getContentPane().add(BorderLayout.CENTER, panel);
        frame.setSize(300, 200);
        frame.setVisible(true);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }

    static double calculate(double a, double b, String c) {
        double result = 0;

        if (c.equals("\u002b")) {
            result = a + b;
        } else if (c.equals("\u2212")) {
            result = a - b;
        } else if (c.equals("\u00f7")) {
            result = a / b;
        } else if (c.equals("\u00d7")) {
            result = a * b;
        }

        return result;
    }

    class buttonListener implements ActionListener {
        public void actionPerformed(ActionEvent e) {
            if (!inputOne.getText().equals("") & !inputTwo.getText().equals("")) {
                double numberOne = (parseDouble(inputOne.getText()));
                double numberTwo = (parseDouble(inputTwo.getText()));

                String function = (String) list.getSelectedItem();

                output.setText("" + Calculator.calculate(numberOne, numberTwo, function));
            }

        }
    }
}


texts:
I'm fairly new to C++ and I want to simulate the Hodgkin-Huxley neuron model with it. I have used a MATLAB implementation before and I hope that the C++ code will be faster.

Both seem to take the same time when I time them. For the C++ implementation I used the Linux time command and in MATLAB tic/toc. I let both simulations run for 1000 times with 100000 time steps each. Both take around 13-15s to complete.

I hope anybody can tell me if I have some mayor issues in my C++ implementation or if the difference between C++/MATLAB for such a task is just small.

I compiled the C++ code with g++ -std=gnu++11 -O3 -o hh hhModel.cpp

#include <iostream>
#include <cstdlib>
#include <stdio.h>
#include <math.h>
#include <array>
using namespace std;

int main()
{
    double dt = 0.01;
    int numSamples = 100000;

    // create an rectangular external stimulus
    double I[numSamples];
    for(int i = 0; i <= numSamples; i++)
        I[i] = 0;
    for(int i = 25000; i <= 75000; i++)
            I[i] = 0.01;

    // init constants
    double Vinit = -65;
    double Vref = -65;

    double Smemb = 4000;  // [um^2] surface area of the membrane
    double Cmemb = 1.0;   // [uF/cm^2] membrane capacitance density
    double Cm = Cmemb * Smemb * 1e-8;   // [uF] membrane capacitance

    double GNa = 120;
    double GK = 36;
    double GL = 0.3;
    double ENa = 125;
    double EK = -55;
    double EL = -25;

    double v[numSamples]; // [mV] membrane potential vector

    double m, h, n, aM, bM, aH, bH, aN, bN, dv_dt, dn_dt, dm_dt, dh_dt, IL, IK, INa;

    double gNa = GNa * Smemb * 1e-8;// Na conductance [mS]
    double gK = GK * Smemb * 1e-8;  // K conductance [mS]
    double gL = GL * Smemb * 1e-8;  // leak conductance [mS]

    // initial values
    v[0] = Vinit;           // initial membrane potential
    m = 0;
    h = 0;
    n = 0;

    // To compare the code to Matlab I run the numerical integration 1000 times
    for (int nn = 0; nn <= 1000; nn++){

    // Numerical integration
    for (int j = 0; j <= numSamples; j++){
        // ionic currents
        INa = gNa * m*m*m * h * (ENa - v[j]);
        IK = gK * n*n*n*n * (EK - v[j]);
        IL = gL * (EL - v[j]);

        aM = 0.1 * (v[j] - Vref -25) / ( 1 - exp(-(v[j]-Vref-25)/10));
        bM = 4 * exp(-(v[j]-Vref)/18);

        aH = 0.07 * exp(-(v[j]-Vref)/20);
        bH = 1 / ( 1 + exp( -(v[j]-Vref-30)/10 ) );

        aN = 0.01 * (v[j]-Vref-10) / ( 1 - exp(-(v[j]-Vref-10)/10) );
        bN = 0.125 * exp(-(v[j]-Vref)/80);

        // derivatives
        dv_dt = ( INa + IK + IL + I[j] ) / Cm;
        dm_dt = (1.0-m) * aM - m * bM;
        dh_dt = (1.0-h) * aH - h * bH;
        dn_dt = (1.0-n) * aN - n * bN;

        // calculate next step
        v[j+1] = v[j] + dv_dt * dt;
        m = m + dm_dt * dt;
        h = h + dh_dt * dt;
        n = n + dn_dt * dt;
    }
    }
}


texts: Data structure that is fast to read and modify

texts:
I'm working on an apllication that needs to process a lot of objects in realtime. I've separated the logic from the UI so that it isn't as much of a mess. The basic idea is that every tick I'm trying to populate a list of objects to process and once they are processed I update the UI accordingly.

I've written this collection class for use in the main processing loop. Here is the reasoning behind some of my decisions:

The objects are processed sequentially in a loop. I only care for fast sequential reading so I've decided to use arrays at the base of it all hoping to get some kind of cache hit benefit.
The maximum amount of objects is known at compile time so I've tried to avoid rapid heap allocations by pooling my data objects. I allocate a maximum amount but only use the amount that is active.
I needed a way to correlate the logical objects with the presentation layer, so I've decided to use identifiers. These identifiers allow me to know what actual UI object the data belongs to.

Through basic stopwatch benchmarking I've arrived to the following solution:

class FixedCapCollectionIntGuids<T> where T : struct
{
  public T[] m_array;
  Dictionary<int, int> m_guidToIDs;
  int[] m_idToGuids;
  int m_capacity;

  public int Size { get; private set; }

  public FixedCapCollectionIntGuids(int capacity)
  {
    Size = 0;
    m_capacity = capacity;
    m_array = new T[capacity];
    m_guidToIDs = new Dictionary<int, int>(capacity);
    m_idToGuids = new int[capacity];
  }

  public T this[int key]
  {
    get
    {
      Debug.Assert(key < Size, "Illegal read");
      return m_array[key];
    }
  }

  public void Add(T value, int guid)
  {
    Debug.Assert(!m_guidToIDs.ContainsKey(guid), "Double insertion");
    m_array[Size] = value;
    m_guidToIDs[guid] = Size;
    m_idToGuids[Size] = guid;
    ++Size;
  }

  public void Remove(int guid)
  {
    Debug.Assert(m_guidToIDs.ContainsKey(guid), "Not found");
    int i = m_guidToIDs[guid];
    int lasti = Size - 1;
    int lastGuid = m_idToGuids[lasti];
    m_array[i] = m_array[lasti];
    m_guidToIDs.Remove(guid);
    m_guidToIDs[lastGuid] = i;
    m_idToGuids[i] = lastGuid;
    --Size;
  }
}

Please try to ignore the dumb naming, this is WIP so I didn't put much thought into what the best names for variables and classes are at this point.

My benchmarks show that this approach appears to be faster than just having a dictionary for reading(presumably because an array is cache friendlier), but slower for adding\removing(presumably because I'm maintaining 3 separate collections instead of one). I'm somewhat fine with this because addition and removal is going to be less frequent than iteration, but I'm still wondering whether I've solved the problem in a stupid way or not. Can it be done better?


texts:
I'm using SQL Server 2014 with Visual Studio 2013. When I add a new record, identity column (seed 1, increment 1) "ID" increases by 1, and record added to the database.

My table consist of two rows:

ID, set identity, seed=1, increment=1
Column1, int
Column2, nvarchar(10), Primary Key

    ID Column1 Date
1.  1  300     01.01.2001
2.  2  301     02.01.2001

My query is as follows:

insert into Table values(302,'02.01.2001')

Clearly it gives an error, because 02.01.2001 already exists.

This, however:

insert into Table values(302,'03.01.2001')

successfully inserts data.

But when I select:

select * from Table

the result is:

    ID Column1 Date
1.  1  300     01.01.2001
2.  2  301     02.01.2001
3.  4  302     03.01.2001

Sometimes after this unsuccessful attempts of inserting data, the ID increases but the data doesn't recorded to data, because I have made a mistake. (Like I show above.) Then, after a successful insert query, data records and ID jump to 4 instead of 3.

I have thought of a workaround (it works from my point of view):

declare @maxIDValue int
if exists (select ID from NVDB.dbo.V where ID=1) --check if table has its first record.
    begin
        if (select count(ID) from NVDB.dbo.V) >= 1
        set @maxIDValue = (SELECT MAX(ID) FROM NVDB.dbo.V)
    end
else set @maxIDValue = 1
if not exists (select Date from NVDB.dbo.V where Date='03.10.2010')
    begin
        dbcc checkident ('NVDB.dbo.V', RESEED, @maxIDValue)
        insert into NVDB.dbo.V values(300,'03.10.2010')
    end

SELECT * FROM NVDB.dbo.V

With this piece of code, I want my table in order and after the insertion attempts. It gives no error, and of course ID goes sequentially.

Is this a right approach? What is the best practice? Do we have a simple way to achieve this or did I write so much code?

Note: My table is small, so performance is not an issue. But when it becomes big, like 3000 records, does this code affect performance? (I'll be using these queries in my C# application.)


texts: Divide an alphanumeric string into a map of numbers and strings

texts:
Below is a bit of code which divides an alphanumeric string to a map of numbers and strings (assume numbers are single digits and non-repeating).

Example input:

String alphaNumericStr = "1abcdef2xyz9aaa6xxx";

Output:

Map<Integer, String> map = {1=abcdef, 2=xyz, 9=aaa, 6=xxx}

This is the code i wrote. While it gets the work done, this does not look like a clean solution to me. How can I make this better?

    String alphaNumericStr = "1abcdef2xyz9aaa6xxx";

    Map<Integer, String> map = new LinkedHashMap<Integer, String>();

    Character key = null;
    StringBuffer s = new StringBuffer();

    for (int i = 0; i < alphaNumericStr.length(); i++) {
        Character c = alphaNumericStr.charAt(i);

        if (Character.isDigit(c)) {
            if (s.length() > 0) {
                map.put(Character.getNumericValue(key), s.toString());
                s = new StringBuffer();

            }
            key = c;

        } else {
            s.append(c);
            if (i == alphaNumericStr.length() - 1) {
                map.put(Character.getNumericValue(key), s.toString());
            }
        }
    }

    System.out.println(map);


texts:
How can I change my two functions to be more readable functions (i.e. in steps), because I am using pycharm.

import collections

def compute_word_importance(fpath1,fpath2):

    mylist1 = []
    mylist2 = []
    with open(fpath1, 'rt', encoding='UTF-8') as f:
        for line1 in f:
            for word in line1.split(" "):
                if word.strip('\n'):
                    mylist1.append(word.strip())
    with open(fpath2, 'rt', encoding='UTF-8') as x:
        for line2 in x:
            for word in line2.split(" "):
                if word.strip('\n'):
                    mylist2.append(word.strip())

    if mylist1==0 and mylist2==0:
        return None

    c=collections.Counter(mylist1)
    c.subtract(mylist2)
    return c


texts: Generates a bare git repo from existing one and copy it to a central server

texts:
This is a Bash script that takes the name of a local Git repo and a remote server host/path, generates a bare repo, and copies the bare repo to a Git server located in another server.

Example usage:

centralize-git-repo.sh arepo user@gitserver:/srv/git

It generates a folder in server:/srv/git/arepo.git and adds the remote in the local repo.

#!/bin/bash
set -e

GIT="/usr/bin/git"
SCP="/usr/bin/scp"

if [ "$1" == "--help" ] | [ $# -eq 0 ] ; then
    echo "$0 [repo] [user@]hostname:[remote_git_path]"
    exit 0
fi

# Assign parameters
LOCAL_REPO=$(basename $1)
REMOTE_DIR=$2

# Checks if the repo exists in current directory.
if [ ! -d "${LOCAL_REPO}" ]; then
    echo "${LOCAL_REPO} is not a repo in current directory."
    exit 1
fi

# Checks second parameter is present
if [ ! "${REMOTE_DIR}" ]; then
    echo "Remote is missing, pass the target dir on the remote "
    echo " server as the second parameter as: user@server:/dir/../git/"
    echo ""
    echo "e.g.: $0 localrepo user@gitserver:/srv/git"
    exit 1
fi

######

# Creates a container for the bare repo
BARE_TMP_DIR=$(mktemp --quiet --directory)
NEW_REPO_DIRNAME=${LOCAL_REPO}.git
BARE_REPO_PATH=${BARE_TMP_DIR}/${NEW_REPO_DIRNAME}

mkdir ${BARE_REPO_PATH}

$GIT clone --bare ${LOCAL_REPO} ${BARE_REPO_PATH}/

$SCP -r ${BARE_REPO_PATH} ${REMOTE_DIR}

# add remote
cd ${LOCAL_REPO}
$GIT remote add origin ${REMOTE_DIR}/${NEW_REPO_DIRNAME}
$GIT remote -v

# clean
rm -rf ${BARE_TMP_DIR}
cd ..


texts:
Task: Take every 2nd char from the string, then the other chars, that are not every 2nd char, and concat them as new String.
Do this n times!

Examples:

"This is a test!", 1 -> "hsi  etTi sats!"
"This is a test!", 2 -> "hsi  etTi sats!" -> "s eT ashi tist!"

Code:

const split = (text) => {
  const firstPart = text.split('').filter((element, index) => index % 2 != 0).join('')
  const secondPart = text.split('').filter((element, index) => index % 2 == 0).join('')

  return firstPart + secondPart
}

const encrypt = (text, n) => {
  if (text == null) {
    return null
  }

  let result = text

  for (let i = 0; i < n; i++) {
    result = split(result)
  }

  return result
}

const decrypt = (text, n) => {
  if (text == null) {
    return null
  }

  for (let i = 0; i < n; i++) {
    let firstPartLength = text.length % 2 == 0 ? text.length / 2 : (text.length - 1) / 2 + 1
    let secondPartLenght = text.length % 2 == 0 ? text.length / 2 : (text.length - 1) / 2
    let firstPart = text.substring(0, firstPartLength)
    let secondPart = text.substring(secondPartLenght, text.length)

    secondPart = secondPart.split('').map(element => element + ' ').join('')
    let position = -1
    secondPart = secondPart.split('').map((element, index) => index % 2 != 0 ? firstPart[++position] : element).join('').substring(0, text.length)

    text = secondPart
  }

  return text
}

console.log(decrypt(encrypt('This is a test!', 3), 3))

console.log(encrypt('Some text!', 4))


texts:
I have built this Generic Graph traverser, I have this implemented with DFS, I feel it will work equally fine with BFS too.

What do you think of this implementation?

I want help in reviewing the Visitor interface.
Should I have Generics in it or just use the base Object?

public abstract class GraphTraverser {
  protected final Visitor visitor;

public GraphTraverser(Visitor visitor) {
    this.visitor = visitor;
}

public abstract void traverse(Object startNode);
}

Generic DFS

public class DepthFirstSearch extends GraphTraverser {
    public DepthFirstSearch(Visitor visitor) {
        super(visitor);
    }

    public void traverse(Object startNode) {
        visitor.reset();
        traverse(startNode, 1);
    }

    private boolean traverse(Object obj, int nodeCount) {
        if (visitor.preVisit(obj, nodeCount)) {
            visitor.visit(obj, nodeCount);
            return true;
        }

        List<? extends Object> objs = visitor.getNeighbours(obj);
        visitor.visit(obj, nodeCount);
        for (Object o : objs) {
            if (traverse(o, nodeCount + 1)) {
                return true;
            }
        }
        visitor.postVisit(obj);
        return false;
    }
}

Visitor Interface

import java.util.List;

public interface Visitor {

    boolean preVisit(Object obj, int nodeVisitCount);

    void postVisit(Object obj);

    void visit(Object obj, int i);

    List<? extends Object> getNeighbours(Object obj);

    Object getResult();

    void unVisit(Object obj);

    void reset();
}


texts:
I have created this simple code:

  For the size of an array with 2 values (n and m), verify if n and m are >= 1. m = width and n = height.

The code works but I'm sure it isn't optimized.

printf("Number of ligns.");
scanf("%d",n);
printf("Number of columns.");
scanf("%d",m);

if(*n >= 1)
{
    if(*m >= 1)
    {
        printf("Number of ligns : %x, Number of columns : %x \n", *n, *m);
    }
    else
    {
        while(*m < 1)
        {
            printf("Error, number of colums/ligns < 1. \n");
            scanf("%d",m);
        }
        printf("Number of ligns : %x, Number of columns : %x \n", *n, *m);
    }
}
else
{
    while(*n < 1)
    {
        printf("Error, number of colums/ligns < 1. \n");
        scanf("%d",n);
    }
            if(*m >= 1)
    {
        printf("Number of ligns : %x, Number of columns : %x \n", *n, *m);
    }
    else
    {
        while(*m < 1)
        {
            printf("Error, number of colums/ligns < 1. \n");
            scanf("%d",m);
        }
        printf("Number of ligns : %x, Number of columns : %x \n", *n, *m);
    }
}


texts: Replace an element of a list to get maximum sum of subsequence

texts:
I was practicing for interview questions, and my friend recommended this one:

Given an initial list of integers L, and a number N, find the smallest member M of L, which on being replaced by N, gives the subsequence with the largest sum S for any subsequence within the modified list.
Examples:
L = [1, 2, -1, 3, 4], N = 4 => M = -1, S = 14
L = [1, 2, 3, 4], N = 4 => M = 1, S = 13
L = [4, 4, 4, 4], N = 4 => M = 4, S = 16
L = [1, 2, 10, -3, -10, 8, 5], N = 4 => M = -10, S = 27
L = [1, 3, 2, -1, 4], N = -2 => M=-1, S = 8

How can I improve this code?
def find_replaceable_element(arr, n):
    max_sum = [0] * len(arr)
    low = [-10000] * len(arr)
    current_sum = 0
    for index, val in enumerate(arr):
        current_sum += val
        max_sum[index] = max(current_sum, val)
        if index >= 1:
            if low[index-1] > val:
                low[index] = val
            else:
                low[index] = low[index-1]
        else:
            low[index] = val

        if val > current_sum:
            current_sum = val
            low[index] = val
    print low
    print max_sum
    max_got = 0
    lowest = 0
    for i, val in enumerate(max_sum):
        cur_max = max_sum[i] - low[i] + n
        if max_got < cur_max:
            max_got = cur_max
            lowest = low[i]
    return lowest, max_got

arr = [1, 2, 10, -3, -10, 8, 5]
print find_replaceable_element(arr, 8)


texts:
Have the function VowelSquare(strArr) take the strArr parameter being
  passed which will be a 2D matrix of some arbitrary size filled with
  letters from the alphabet, and determine if a 2x2 square composed
  entirely of vowels exists in the matrix. For example: strArr is
  {{"a","b","c","d"},{"e","i","k","r"}, {"o","u","f","j"}} then this matrix looks like the following:

  $$\begin{array}{cccc}
a & b & c & d \\
\color{red}e & \color{red}i & k & r \\
\color{red}o & \color{red}u & f & j \\
\end{array}$$

  Within this matrix there is a 2x2 square of vowels starting in the
  second row and first column, namely, ei, ou. If a 2x2 square of vowels
  is found your program should return the top-left position (row-column)
  of the square, so for this example your program should return 1-0. If
  no 2x2 square of vowels exists, then return the string not found. If
  there are multiple squares of vowels, return the one that is at the
  most top-left position in the whole matrix. The input matrix will at
  least be of size 2x2.

Are there any improvements I can make in terms of readability?

bool must_be_2x2(std::vector<std::vector<std::string>>& letters)
{
    constexpr int MIN_SIZE = 2;
    if (letters.at(0).size() > MIN_SIZE && letters.at(1).size() > MIN_SIZE)
    {
        return true;
    }

    return false;
}

std::string matrix_vector_to_string(std::vector<std::vector<std::string>>& matrix)
{
    std::string str;

    for (int row = 0; row < matrix.size(); ++row)
    {
        for (int col = 0; col < matrix.at(row).size(); ++col)
        {
            str += matrix.at(row).at(col);
        }
    }

    return str;
}

bool alphabet_only(std::vector<std::vector<std::string>>& letters)
{
    std::string str = matrix_vector_to_string(letters);

    for (std::size_t pos = 0; pos < str.length(); ++pos)
    {
        if (!std::isalpha(str.at(pos)))
        {
            return false;
        }
    }

    return true;
}

bool equal_length(std::vector<std::vector<std::string>>& letters)
{
    const size_t SIZE = letters.at(0).size();

    for (std::size_t row = 1; row < letters.size(); ++row)
    {
        if (letters.at(row).size() != SIZE)
        {
            return false;
        }
    }

    return true;
}

bool is_vowel(std::string element) noexcept
{
    static const auto vowels = std::array<std::string,5> { "a","e","i","o","u" };

    return std::find(vowels.begin(), vowels.end(), element) != vowels.end();
}

std::string find_vowel_square(std::vector<std::vector<std::string>>& letters)
{
    for (std::size_t row = 0; row < letters.size()-1; ++row)
    {
        for (std::size_t col = 0; col < letters.at(row).size()-1; ++col)
        {
            if (is_vowel(letters.at(row).at(col)) && is_vowel(letters.at(row).at(col + 1)) && is_vowel(letters.at(row + 1).at(col)) && is_vowel(letters.at(row).at(col + 1)))
            {
                return std::to_string(row) + "-" + std::to_string(col);
            }
        }
    }

    return "not found";
}


texts: Efficiency with strcpy, strcat and malloc

texts:
I'm still learning C, but I'm trying to make sure I've got a decent grasp on working with "strings" and data structures.

If possible, I'd like a little input on how I'm handling this and see if

it could be done more efficiently
I'm setting myself up for unforeseen negative consequences
I'm using the functions appropriately

void test(char *username, char *password) {

    printf("Checking password for %s - pw: %s\n",username,password);
    char *query1 = "SELECT password FROM logins WHERE email = '";
    char *query2 = "' LIMIT 1";

    char *querystring = malloc(strlen(query1) + strlen(username) + strlen(query2) * sizeof(char));

    strncpy(querystring,query1,strlen(query1));
    strncat(querystring,username,strlen(username));
    strncat(querystring,query2,strlen(query2));

    printf("Query string: %s\n",querystring);

    mysql_query(mysql_con,querystring);
    MYSQL_RES *result = mysql_store_result(mysql_con);

    int num_fields = mysql_num_fields(result);
    int num_rows = mysql_num_rows(result);

    if (num_rows != 0) {

        MYSQL_ROW row;
        printf("Query returned %i results with %i fields\n",num_rows,num_fields);

        row = mysql_fetch_row(result);

        printf("Password returned: %s\n",row[0]);

        int comparison = strncmp(password, row[0], strlen(password));

            if (comparison == 0) {
                printf("Passwords match!\n");
            } else {
                printf("Passwords do NOT match!\n");
            }

            }
    else {
        printf("No such user... Password is invalid");
    }
        free(querystring);
}

Output of program:

Checking password for test@blah.com - pw: 5f4dcc3b5aa765d61d8327deb882cf99
Query string: SELECT password FROM logins WHERE email = 'test@blah.com' LIMIT 1
Query returned 1 results with 1 fields
Password returned: 5f4dcc3b5aa765d61d8327deb882cf99
Passwords match!


texts:
I'm trying to learn Python, so I made this project. I think there are problems with the code, but I don't know how to improve it.

import os
import random
clear = lambda: os.system('cls')
def game():
    def printOutCorrectGuess():
        print('Correct! There is/are ', lettersInWord, 'of this letter in this word.')
    def printOutStars():
        print('Currently revealed of the word: ', ''.join(stars))
    def printOutVictory():
        print('You won!')
        print('The word was ', theWord)
        print('Press enter to quit...')
    def printOutWords():
        print('You guessed these letters : ', words)
    def printOutLifes():
        print('You have ', lives, ' more lives.')
    print("Let's start guessing!")
    correctLetters = 0
    lives = 10
    words = []
    stars = list('*' * len(theWord))
    while True:
        guess = str(input('Please give me a letter: '))
        if len(guess) > 1 or len(guess) < 1:
            clear()
            print('I need 1 and letter, thanks.')
            printOutStars()
        elif guess in words:
            clear()
            print('You already wrote this letter.')
            printOutStars()
        elif guess in theWord:
            theStart = 0
            theEnd = 1
            lettersInWord = 0
            letterPosition = []
            for i in range(len(theWord)):
                tempWords = theWord.find(guess, theStart, theEnd)
                theStart = theStart + 1
                theEnd = theEnd + 1
                if tempWords >= 0:
                    lettersInWord = lettersInWord + 1
                    letterPosition.append(i + 1)
                    stars[i] = guess
            correctLetters = correctLetters + lettersInWord
            if correctLetters == len(theWord):
                clear()
                printOutVictory()
                if input() == '':
                    break
                else:
                    break
            clear()
            printOutCorrectGuess()
            printOutStars()
        else:
            lives = lives - 1
            if lives == 0:
                clear()
                print('You lost.')
                print('The word was: ', theWord)
                print('Press enter to quit the game')
                if input() == '':
                    break
                else:
                    break
            clear()
            printOutLifes()
            printOutStars()
        if guess not in words and len(guess) == 1:
            words.append(guess)
        printOutWords()
def welcome():
    print('Now we will play the classic Hangman game, but for this time without drawing it.')
    print('1 or 2 player game mode? Write 1 or 2 please.')
welcome()
while True:
    try:
        gameMode = int(input('INPUT: '))
    except ValueError:
        print('Write 1 or 2 please.')
        continue
    if gameMode == 1:
        words = ['letters', 'sloppy', 'bedroom', 'jazzy', 'discovery', 'wistful', 'unadvised', 'help', 'line', 'shake', 'mend', 'time', 'attempt', 'dare', 'straw', 'destroy', 'health', 'shiny']
        theWord = random.choice(words)
        clear()
        game()
        break
    elif gameMode == 2:
        theWord = str(input('Please write here the word: '))
        clear()
        game()
        break
    elif gameMode < 1 or gameMode > 2:
        print('Write 1 or 2 please.')


texts: Rotate a given number of variables in-place

texts:
A very simple but useful algorithm: rotate the values of a given number of variables in-place to the left so that the first variable gets the value of the second, the second gets the value of the third, etc... and the last variable gets the value of the first one.

#include <type_traits>
#include <utility>

template<typename Head, typename... Tail>
struct are_same:
    std::conjunction<std::is_same<Head, Tail>...>
{};

template<typename T, typename... Args>
auto rotate_left_inner(T& first, T& second, Args&... args)
    -> T&
{
    first = std::move(second);
    if constexpr (sizeof...(Args) == 0) {
        return second;
    } else {
        return rotate_left_inner(second, args...);
    }
}

template<typename Head, typename... Tail>
auto rotate_left(Head& first, Tail&... args)
    -> void
{
    static_assert(are_same<Head, Tail...>::value,
                  "elements passed to rotate_left shall have the same type");

    if constexpr (sizeof...(Tail) > 0) {
        auto tmp = std::move(first);
        auto& last = rotate_left_inner(first, args...);
        last = std::move(tmp);
    }
}

This function can be used as follows:

int a=0, b=1, c=2, d=3, d=4;
rotate_left(a, c, e);
rotate_left(b, d);
// Now (a, b, c, d, e) = (2, 3, 4, 1, 0)

The code above generated the same assembly than the hand-rolled version when I gave it five integers to rotate in the compiler explorer, with both GCC and Clang.

I wanted to make a companion rotate_right function, but repeatedly finding the last element of a template parameter pack is not as easy, so the easiest solution for a programmer is to pass the variables to rotate to rotate_left in reverse order.

Do you see any way to improve this simple algorithm? Anything that I might be missing?


texts:
I've been through a lot of posts over the web(and in SO) saying that it is not possible. However, I did the following code:

var a = {
 _sum: 0,
 _timer: null,
 _resetTimer: function() {
  if (this._timer) {
   window.clearTimeout(this._timer);
  }

  this._timer = window.setTimeout(this._endChain.bind(this), 0);
 },
 _endChain: function() {
  console.log(this._sum);
 },

 A: function() {
  this._resetTimer();
  this._sum+= 1;
  return this;
 },
 B: function() {
  this._resetTimer();
  this._sum+= 2;
  return this;
 }
};

a.A().B().B().A();

Demo in JsFiddle

I want to know how problematic this can be, if this is not encouraged to be used.

Edit:

A negative point is: if you need anything that would be processed by _endChain you could not use return, only with a promise or another timeout outside the whole chain. Example.


texts:
I just want to make sure there aren't any deadlocks or inconsistencies (the code is also available on GitHub).

Disclaimer - In real life, I would not implement a queue myself, but use an existing implementation. This is just preparations for job interviews.

package org.basic.concurrent;

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

public class SynchedQueue<T> {
    private final Object lock = new Object();
    private final Object full = new Object();
    private final Object free = new Object();

    private final List<T> buffer;
    private int head;
    private int tail;
    private int size;
    private final int capacity;

    public SynchedQueue(int capacity) {
        // http://stackoverflow.com/questions/4912088/how-to-create-a-fixed-size-generic-buffer-in-java
        buffer = new ArrayList<T>(capacity);
        for (int i = 0; i < capacity; ++i)
            buffer.add(null);
        this.capacity = capacity;
    }

    public void enqueue(T x) {
        if (x == null)
            throw new RuntimeException("Doesn't allow storing nulls");

        synchronized (lock) {
            while (!tryEnqueue(x)) {
                try {
                    free.wait();
                } catch (InterruptedException ignored) {
                }
            }
            full.notify();
        }
    }

    public T dequeue() {
        synchronized (lock) {
            while (true) {
                T item = tryDequeue();
                if (item != null)
                {
                    free.notify();
                    return item;
                }
                try {
                    full.wait();
                }
                catch (InterruptedException ignored) {}
            }
        }
    }

    private boolean tryEnqueue(T x) {
        assert size <= capacity;
        if (size >= capacity) {
            return false;
        }

        buffer.set(tail, x);
        tail = (tail + 1) % capacity;
        ++size;
        return true;
    }

    private T tryDequeue() {
        assert size >= 0;
        if (size == 0)
            return null;
        T item = buffer.get(head);
        head = (head + 1) % capacity;
        --size;
        return item;
    }
}


texts: A minimalistic kind of read-copy-update class

texts:
This is a very simple read-copy-update (RCU)-inspired synchronization class:

#include <atomic>

template<typename T>
class RCU
{
private:

    std::atomic<T*>  curr;
    std::atomic<T*>  prev;
    std::atomic<int> readers;

public:

    RCU()
    : curr   (new T),
      prev   (nullptr),
      readers(0)
    {

    }

    ~RCU()
    {
        delete curr;
        delete prev;
    }

    void lock()
    {
        readers++;
    }

    void unlock()
    {
        readers--;
    }

    T* get()
    {
        return curr.load();
    }

    T* clone()
    {
        return new T(*curr.load());
    }

    bool swap(T* t)
    {
        /* If prev is full, a swap is still pending. Clean up memory and
        abort the operation. */

        if (prev.load() != nullptr)
        {
            delete t;
            return false;
        }

        /* Store the current pointer into prev. Readers might still be reading
        through the pointer. */

        prev.store(curr);

        /* Curr contains the new proposed value. No one is reading from this
        right now. */

        curr.store(t);

        /* Spin until there are no more readers to *prev. When so, free the
        memory it points to and say goodbye. */

        while (readers.load() > 0);

        T* old = prev.load();
        prev.store(nullptr);
        delete old;

        return true;
    }
};

The idea is to have many reader threads that repeatedly read from some shared data, while a writer thread that rarely updates it. The writer thread takes care of cleaning up the memory when no readers are reading. Readers are "tracked" through the lock() and unlock() methods. The RCU-like class should synchronize the threads in a lock-free way.

Usage:

struct Data
{
    int x;
    int y;
    int z;
};

RCU<Data> rcu;

void writer_thread()  // the writer rarely runs
{
    while (true)
    {
        Data* data = rcu.clone();
        // modify data as needed
        data->x++;
        data->y++;
        data->z++;
        rcu.swap(data); // Checking the return value might be useful
    }
}

void reader_thread()
{
    while (true)
    {
        rcu.lock();
        std::cout << rcu.get()->x << "\n"; // read from data
        rcu.unlock();
    }
}

Questions: does it make sense? Is it really thread-safe? Can a thread slip through the cracks somewhere, somehow?