texts:
I recently started learning C, and this is my first fairly large (to me) program. It's a basic Tic Tac Toe game for the console. There's no AI, it's just a 2-player game. Is there anything I can improve?

Some problems I've been told elsewhere:

There's no case for tying/drawing.
I should split the place function into two.

I also think it would be better to use global variables for board and player, since they're used so often.

// Tic Tac Toe in C. V1.0 by James 26/05/2019

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

#define SIZE 3

// Draws the board along with rows/cols, numbered.
void draw_board(char board[])
{
    system("clear");
    printf("# 1 2 3\n");

    // Rows
    for (int i = 0, n = 0; i < SIZE; i++)
    {
        // Columns
        printf("%d ", i + 1);
        for (int j = 0; j < SIZE; j++)
        {
            printf("%c ", board[n]);
            n++;
        }
        printf("\n");
    }
}

// Initializes board to '-' characters.
void init_board(char board[])
{
    for (int i = 0; i <  SIZE * SIZE; i++)
    {
        board[i] = '-';
    }
}

// Returns true if the piece was successfully placed,
// false if the position was invalid or already taken.
bool place(char board[], char player)
{
    char posinput[64];

    printf("%c, pick your position (xy, rc): ", player);
    scanf("%s", posinput); // <-- I realise that this is potentially bad, but realistically,
                           // the user would have to be trying to break something, and
                           // this is just a little program I made for practice.

    int row = (posinput[0] - '0') - 1;
    int col = (posinput[1] - '0') - 1;

    int pos = col + row * SIZE;

    if (pos >= 0 && pos < SIZE * SIZE)
    {
        if (board[pos] == 'x' || board[pos] == 'o')
            return false;

        board[pos] = player;
        return true;
    }

    return false;
}

// Returns true if there are three of the same chars in a row.
// b = board, p = player. Shortened for readability.
bool check(char b[], char p)
{
    // Check rows
    if (b[0] == p && b[1] == p && b[2] == p)
        return true;
    if (b[3] == p && b[4] == p && b[5] == p)
        return true;
    if (b[6] == p && b[7] == p && b[8] == p)
        return true;

    // Check columns
    if (b[0] == p && b[3] == p && b[6] == p)
        return true;
    if (b[1] == p && b[4] == p && b[7] == p)
        return true;
    if (b[2] == p && b[5] == p && b[8] == p)
        return true;

    // Check diagonals
    if (b[0] == p && b[4] == p && b[8] == p)
        return true;
    if (b[2] == p && b[4] == p && b[6] == p)
        return true;

    // If no one won, return false
    return false;
}

int main(void)
{
    char board[SIZE * SIZE];
    char player = 'x';
    init_board(board);

    while (true)
    {
        draw_board(board);

        if (place(board, player))
        {
            if (check(board, player))
                break;

            if (player == 'x')
                player = 'o';
            else
                player = 'x';
        }
    }

    draw_board(board);
    printf("-----------------------------\n");
    printf("Player %c wins!!!\n", player);
    printf("-----------------------------\n");
}


texts: PHP magic function for accessors and mutators

texts:
I have implemented the following PHP magic method behavior to save my time of creating accessor and mutators for properties of any class that extends this base class.

I am looking for suggesiongs on improving it for my application that assumes the following:

Properties of the form:

$_first_name
$_user_id

Methods of the form:

getUserId()
setFirstName("Mohammad")

I have some points that I think need more research:

Is it a secure way? What are the insecurities here?
Is my way of handling errors by using throw new Exception('my message'); a good practice? What are the alternatives?
Is there a best practice or a design pattern that addresses such a solution for reusability?
Am I exaggerating the steps? Are there any steps can be combine into one step with the same results?

The __call function of my Base class:

class Base
{
    private $_first_name; // just an example

    public function __call($name, $args)
    {
        // The begining of a method must be in all lower case characters.
        // E.g. set, get
        $result = preg_match('/^[a-z]*/', $name, $matches);

        if($result !== 1)
        {
            throw new Exception('Action not recognized.');
        }

        // Hold the found action.
        $action = $matches[0];

        // Find the rest of the method name.
        $result = preg_match_all('/[A-Z][a-z]*/', $name, $matches);

        // $matches will hold a multi-dimensional array
        // we need the first 1D array only.
        $matches = $matches[0];

        if($result < 1 || $result === FALSE)
        {
            throw new Exception('Malformed method name.');
        }

        // Construct the property name.
        $property = '_' . strtolower(implode('_', $matches));

        if(! property_exists($this, $property))
        {
            throw new Exception("Property: '{$property}' not found.");
        }

        switch($action)
        {
            // Mutator
            case 'set':
            {
                if(count($args) === 1)
                {
                    $this->$property = $args[0];
                    return;
                }
                else
                {
                    throw new Exception('You must provide 1 argument only.');
                }
            }

            // Accessor
            case 'get':
            {
                return $this->$property;
            }
        }
    }
}


texts: DataTable extension methods and proper disposing of unneeded resources

texts:
I've build two extension methods, that allows me to show DataTable inside window.
Below is my code:

public static class DataTableExtensions
{
    public static void Show(this DataTable dataTable, string title = null, Size? size = null, DataGridViewCellFormattingEventHandler onCellFormatting = null)
    {
        Show(dataTable, title, size, onCellFormatting,false);
    }

    public static void ShowDialog(this DataTable dataTable, string title = null, Size? size = null, DataGridViewCellFormattingEventHandler onCellFormatting = null)
    {
        Show(dataTable,title,size,onCellFormatting,true);
    }

    private static void Show(DataTable dataTable, string title, Size? size, DataGridViewCellFormattingEventHandler onCellFormatting, bool modal)
    {
        var f = new Form
        {
            StartPosition = FormStartPosition.CenterScreen,
            FormBorderStyle = FormBorderStyle.SizableToolWindow,
            Size = size ?? new Size(500, 300)
        };

        if (!string.IsNullOrWhiteSpace(title))
        {
            f.Text = title;
        }
        else if (!string.IsNullOrWhiteSpace(dataTable.TableName))
        {
            f.Text = dataTable.TableName;
        }

        var dgv = new DataGridView
        {
            ReadOnly = true,
            AutoGenerateColumns = true,
            Dock = DockStyle.Fill,
            SelectionMode = DataGridViewSelectionMode.FullRowSelect,
            MultiSelect = false,
            EnableHeadersVisualStyles = false
            /*other settings*/
        };

        f.Disposed += (sender, args) =>
        {
            Debug.WriteLine("Disposed");
            if(!dgv.IsDisposed) dgv.Dispose();
        };

        dgv.CellMouseEnter += (sender, e) =>
        {
            dgv.InvalidateCell(e.ColumnIndex, e.RowIndex);
        };

        dgv.CellMouseLeave += (sender, e) =>
        {
            dgv.InvalidateCell(e.ColumnIndex, e.RowIndex);
        };

        dgv.CellPainting += (sender, e) =>
        {
            if (e.RowIndex != -1) return;
            Point cursorPosition = dgv.PointToClient(Cursor.Position);
            if (e.CellBounds.Contains(cursorPosition))
            {
                using (var brush = new LinearGradientBrush(e.CellBounds, Color.White, Color.Black, LinearGradientMode.Vertical))
                {
                    e.Graphics.FillRectangle(brush, e.CellBounds);
                }
            }
            else
            {
                using (var brush = new LinearGradientBrush(e.CellBounds, Color.Red, Color.Green, LinearGradientMode.Vertical))
                {
                    e.Graphics.FillRectangle(brush, e.CellBounds);
                }
            }
            //paint rest, we only want to override background and borders
            e.Paint(e.CellBounds, DataGridViewPaintParts.ContentForeground | DataGridViewPaintParts.ContentBackground | DataGridViewPaintParts.Border);
            e.Handled = true;
        };
        dgv.DataSource = dataTable;

        if (onCellFormatting != null)
            dgv.CellFormatting += onCellFormatting;

        f.Controls.Add(dgv);

        if (modal)
            f.ShowDialog();
        else
            f.Show();
    }
}

I've asked similar question on StackOverflow, but because I've cleared cod a bit not I'd like to get it's review.

In previous version I had only ShowDialog function, I was able to have everything inside using blocks, but now I want to have two functions, so I can't use using blocks.

Most important thing is proper resource disposing. I'm not that advanced so I can't tell what parts can be problematic and figure a way to change/optimize them.


texts: Implementation of Longest Common Subsequence

texts:
So I implemented the LCS algorithm once using a 2-D matrix to store values while the other one used a python dictionary. I found the dictionary implementation was easier to implement and was a more natural and intuitive way of solving the problem.

I just wanted to make sure if it's a correct way of implementing the LCS algorithm and how can I improve on it.

Using 2-D matrix

def LowestCommonSubstring(s1, s2):
    LCS = [[0 for x in range(len(s2) + 1)] for x in range(len(s1) + 1)]
    for i in range(1, len(s1)+1):
        for j in range(1, len(s2)+1):
            if s1[i - 1] == s2[j - 1]:
                LCS[i][j] = 1 + LCS[i-1][j-1]
            else:
                LCS[i][j] = max(LCS[i-1][j], LCS[i][j-1])
    return LCS[i][j]

using dictionary

cache = {}

def lcs(s1, s2):
  global cache
  if len(s1) == 0 or len(s2) == 0:
      return 0
  if (s1, s2) in cache:
      return cache[(s1, s2)]
  else:
      if s1[-1] == s2[-1]:
          cache[(s1, s2)] = 1 + lcs(s1[:-1], s2[:-1])
      else:
          cache[(s1, s2)] = max(lcs(s1[:-1], s2), lcs(s1, s2[:-1]))
  return cache[(s1, s2)]

This is the problem I'm trying to implement and for now my solution only calculates the length of the longest common substring.


texts: Generating a list of unique random longs

texts:
I'm using the
Bogus for .NET: C#, F#, and VB.NET library.
What would be a more efficient way to generate a list of unique random longs?
public IEnumerable<long> GenerateRandomNumbers(int count = 1)
{
      var f = new Faker();
      List<long> temporaryList = new List<long>();

      for (int i = 0; i < 10000; i++)
      {
          var number = f.Random.Long(5000000000, 8000000000);
          temporaryList.Add(number );
      }

      return temporaryList.Distinct().Take(count).ToList();
}


texts: Extract rotation values from css string Javascript

texts:
I have the following function that takes out the rotation values from a css string and returns them as an array.

var extractRotationValues = function(code) {
  var getAllIndexes = function(arr, val) {
    var indexes = [],
      i = -1;
    //To understand the second parameter of indexOf function
    //have a look at this : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf
    while ((i = arr.indexOf(val, i + 1)) != -1) {
      indexes.push(i);
    }
    return indexes;
  };
  var indexes = [];
  var closingIndexes = getAllIndexes(code, ")")
  var values = [];
  var rindexes = [];
  rindexes.push(code.indexOf("X("), code.indexOf("Y("), code.indexOf("Z("));
  //No value for rotateX was found so consider it 0
  if (rindexes[0] == -1)
    values.unshift(0);
  else {
    //We have a value for rotateX
    //Where does rotateX start from => rindexes[0]
    //Where does it end? =>closingIndexes[0]
    var value = code.substr(rindexes[0], closingIndexes[0]).split("(")[1].split("deg)")[0];
    values.push(value)
  }
  //No value for rotateY
  if (rindexes[1] == -1)
    values.splice(1, 0, 0);
  else {
    //We have a value for rotateY
    //Where does rotateY start from => rindexes[1]
    //Where does it end? =>closingIndexes[1]
    values.push(code.substr(rindexes[1], closingIndexes[1]).split("(")[1].split("deg)")[0])
  }
  //No value for rotateZ
  if (rindexes[2] == -1)
    values.splice(2, 0, 0);
  else {
    //We have a value for rotateZ
    //Where does rotateZ start from => rindexes[2]
    //Where does it end? =>closingIndexes[2]
    var zvalue = code.substr(rindexes[2], closingIndexes[2]).split("(")[1].split("deg)")[0]
    values.push(zvalue);
  }
  return values;
};

console.log(extractRotationValues("rotateX(90deg) rotateY(87deg) rotateZ(22deg)"))

I was wondering.Is there anything that can be done in a better way here or something to improve?


texts: Translating Objective-C use of static and +(void)initialize to Swift

texts:
I am converting an old Objective-C class into Swift. My actual question is at the very end after all of the code.

Here is a cut-down version of the Objective-C class:

DateInfo.h:

#import <Foundation/Foundation.h>

@interface RMYearInfo : NSObject

// There are also some instance properties but those aren't relevant to the question

+ (NSInteger)numberOfMonths;
+ (NSArray *)shortMonthNames;
+ (NSArray *)longMonthNames;
// several other class methods

@end

DateInfo.m:

#import "DateInfo.h"

static NSArray *shortMonthNames = nil;
static NSArray *longMonthNames = nil;
// there are several other statics as well

@implementation DateInfo

+ (void)reinitialize {
    NSCalendar *cal = [NSCalendar currentCalendar];

    NSDateFormatter *yearFormatter = [[NSDateFormatter alloc] init];

    shortMonthNames = [yearFormatter shortStandaloneMonthSymbols];
    longMonthNames = [yearFormatter standaloneMonthSymbols];

    // lots of other processing for the other statics
}

+ (void)initialize {
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reinitialize) name:NSCurrentLocaleDidChangeNotification object:nil];

    [self reinitialize];
}

+ (NSInteger)numberOfMonths {
    return shortMonthNames.count;
}

+ (NSArray *)shortMonthNames {
    return shortMonthNames;
}

+ (NSArray *)longMonthNames {
    return longMonthNames;
}

// Lots of other instance and class methods

As you can see, the initialize method sets up a notification handler so all of the static variables can be reinitialized if the locale is changed while the app is running.

Here is my Swift code. Since there is no initialize in Swift (any more), my solution is to use private backing variables for the public static variables.

import Foundation

public struct DateInfo {
    // some normal instance properties irrelevant to the question

    private static var _formatter: DateFormatter!
    private static var formatter: DateFormatter {
        if _formatter == nil {
            _formatter = DateFormatter()
            NotificationCenter.default.addObserver(forName: NSLocale.currentLocaleDidChangeNotification, object: nil, queue: nil) { (notification) in
                _formatter = DateFormatter()
                _shortMonthNames = nil
                _longMonthNames = nil
                // reset all of the other statics as well
            }
        }

        return _formatter
    }

    private static var _shortMonthNames: [String]!
    public static var shortMonthNames: [String] {
        if _shortMonthNames == nil {
            _shortMonthNames = formatter.shortStandaloneMonthSymbols
        }

        return _shortMonthNames
    }

    private static var _longMonthNames: [String]!
    public static var longMonthNames: [String] {
        if _longMonthNames == nil {
            _longMonthNames = formatter.standaloneMonthSymbols
        }

        return _longMonthNames
    }

    public static var numberOfMonths: Int {
        return shortMonthNames.count
    }

    // lots of other similar private/public pairs of statics
}

Is this an appropriate way to translate the functionality given the need to be able to reinitialize the statics? I don't like having a private static backing each public static property.


texts: Performance problem when getting text from a context node with VTD-XML

texts:
I have a structure like this:

<a>
  <b>
    <c>foo</c>
    <d>bar</d>
  </b>
  <b>
    <c>baz</c>
    <d>qux</d>
  </b>
</a>

I set /a/b as context and loop through all occurrences to get the texts of c and d:

VTDGen vg = new VTDGen();
vg.parseFile("test.xml", true);

VTDNav vn = vg.getNav();

AutoPilot ap = new AutoPilot(vn);

ap.selectXPath("/a/b");

while(ap.evalXPath() != -1) {
  String c = extractText(vn, "c");
  String d = extractText(vn, "d");
}

Currently, I use the extractText() method I've written to extract the texts of the nodes inside the loop:

public String extractText(VTDNav v, String path) throws Exception {
  VTDNav vn = v.cloneNav();
  AutoPilot ap = new AutoPilot(vn);

  ap.selectXPath(path);

  int elementIndex = ap.evalXPath();

  if(elementIndex == -1) {
    return null;
  }

  int tokenIndex = (path.contains("@"))
                    ? vn.getAttrVal(vn.toString(elementIndex))
                    : vn.getText();

  return (tokenIndex == -1) ? null : vn.toString(tokenIndex);
}

In the method, I clone the VTDNav and create a new AutoPilot instance so I don't displace the cursor of those objects of my loop when selecting the new XPath.

Furthermore, I have to check the path whether it contains an @, to see if it's an text node or an attribute (i.e. to use getText() or getAttrVal()).

My profiler shows that my extractText() method takes the most time in my huge application, so there must be a better solution here.


texts:
I have some static helper class:

public static class Helper
{
    public static bool IsNull<T>(this T value) where T : class
    {
        return (value == null);
    }

    public static bool NotNull<T>(this T value) where T : class
    {
        return (!value.IsNull<T>());
    }

    public static bool IsNullOrEmpty(this string value)
    {
        return string.IsNullOrEmpty(value);
    }

    public static bool NotNullAndNotEmpty(this string value)
    {
        return (!value.IsNullOrEmpty());
    }

    public static bool NotNullAndNotEmpty(this ICollection value)
    {
        return (value.NotNull<ICollection>() && (value.Count > 0));
    }

    public static bool IsNullOrEmpty(this ICollection value)
    {
        return (!value.NotNullAndNotEmpty());
    }
}

It is comfortable (habit) for me to use this helper, but I am not sure that it is correctly (worth it). How about performance? Are there any other reasons to not use it?


texts: Files.walkTree is causing Assignment Branch Condition too high

texts:
My code is working correctly, but is resulting in a "Assignment branch condition too high" warning with a score of 12.08 on CodeBeat.

Codebeat is an automated code review utility that helps developers write clean code. I have been using it lately in order to monitor the quality of my code since clean code is being a necessity in today's word. Codebeat calculates the complexity of the code written and assigns a score, so it seems that the complexity of this method seems a bit high that usual. I would be grateful if someone can tell me what is complex about this method.

private void populateDictionary() {
    try {
        Files.walkFileTree(Paths.get(rootDirectory.getCanonicalPath()), EnumSet.of(FileVisitOption.FOLLOW_LINKS), Integer.MAX_VALUE, new SimpleFileVisitor<Path>() {
            @Override
            public FileVisitResult visitFile(Path path, BasicFileAttributes attrs) throws IOException {
                addToDictionary(path);
                return FileVisitResult.CONTINUE;
            }
        });
    }catch(IOException e) {
        System.out.println(e.getMessage());
    }
    System.out.println(this.indexedFileContents.keySet().size() + " files read in directory " + this.rootDirectory);
}

Can anyone tell me what am I doing wrong and how I can improve my code?
Thanks in advance.


texts:
Using the property that GCD(a, b) = GCD(b, r) where r is the remainder when you compute (a / b), you can write a recursive function as follows:

(define (gcd a b)
  ; recursive
  (if (= 0 b) a
      (gcd b (remainder a b))))

I also tried to write the following as an iterative function, but it still looks very similar to the recursive solution to my eye.  Is this a correct, iterative solution?

(define (i-gcd a b)
  ; is this iterative?
  (i-gcd-iter (remainder a b) b))

(define (i-gcd-iter acc b)
  (if (= 0 b) acc
      (gcd b (remainder acc b))))

EDIT: It appears that the first solution was actually iterative, and in fact very similar to the solution written in SICP (http://mitpress.mit.edu/sicp/full-text/book/book-Z-H-11.html).  What would a recursive solution to this problem look like?


texts:
I have written script that does the following. It uses cbl-log program to decode several log files in binary format. cbl-log only decodes 1 file at a time, so the script decodes files in bulk. If no arguments are given, it assumes log files (with extension .cbllog) are in the current directory, and it'll output files to decoded directory. Otherwise you need to give 2 arguments. The first is the directory with all cbllog files, and the second is the output directory.

#!/usr/bin/env bash

if (( $# == 1 || $# > 2 )); then
    echo "Usage:    cbldecode"
    echo "          cbldecode <source directory> <target directory>"
    exit 1
fi

cmd="$(command -v {./,}cbl-log | head -n1)"
if [[ -z "$cmd" ]] ; then
   echo "cbl-log should be in PATH or current directory"
   exit 1
fi

log_dir=${1:-$PWD}
out_dir=${2:-"decoded"}
count=$(find "$log_dir" -maxdepth 1 -name "*.cbllog" | wc -l)

if (( "$count" == 0 )); then
    echo "no cbllog files in source directory"
    exit 1
fi

if ! [[ -d "$out_dir" ]]; then
    mkdir -p "$out_dir"
elif ! [[ -w "$out_dir" ]]; then
    echo "no write permission to $out_dir"
    exit 1
fi

for path in "$log_dir"/*.cbllog; do
    file=${path//$log_dir/}
    out_file="${file%.cbllog}"
    "$cmd" logcat "$path" "$out_dir"/"$out_file"
done

While this works, I'm looking for ways to make the code more compact and optimize for speed.


texts: Haskell: downpair :: (Monad m) => m (a, b) -> (m a, m b) implementation

texts:
I'm trying to implement function downpairs which takes monad of pairs and transform it into pair of monad

My current implementation is

import Control.Monad
import Control.Arrow
import Data.Maybe

downpair :: (Monad m) => m (a, b) -> (m a, m b)
downpair = ((return . fst =<<) &&& (return . snd =<<))

main = do
    print $ downpair $ Just ("Hello", "World")

Is there way to implement downpair in more compact maner?

PS Sorry for my poor English


texts: Static to Instance method trampolining with templates

texts:
I finally have a working trampoline mechanism. Would anyone care to critique it?

Ideone

#include <iostream>
using namespace std;

#include <map>

template<typename T>
class Base
{
public:
    typedef void (T::*PFunc)(void);
    typedef void (*PHandler)(void*);

    using method_map_t = map< string, PHandler >;
    static method_map_t& methods( ) {
        static method_map_t* map_of_methods{};
        if( ! map_of_methods ) map_of_methods = new method_map_t;
        return *map_of_methods;
    }

    static void register_method( string name, PHandler handler ) {
        methods()[name] = handler;
    }

    // generic trampoline
    template<PFunc sig>
    static void Handler( void* pInstance ) {
        T* f = reinterpret_cast<T*>(pInstance);
        (f ->* sig)();
    }
};

...

class Final : Base<Final>
{
public:
    void Foo(){cout<<"got foo";}
    void Bar(){cout<<"got bar";}

    static void init(){
        // register_method populates a table of "extern C" function pointers.
        register_method( "foo", static_cast<PHandler>( &Handler<&Final::Foo> ) );
        register_method( "bar", static_cast<PHandler>( &Handler<&Final::Bar> ) );
    }
};

void InvokeFromC(void* inst, string name) {
    Base<Final>::PHandler h = Base<Final>::methods()[name];
    (*h)(inst);
}

int main() {
    Final* f = new Final{};
    f->init();
    // simulate invoking from C
    InvokeFromC( f, "foo" );

    // your code goes here
    return 0;
}

This question follows from here.


texts: Check if a string contains matching brackets

texts:
Trying to solve a case for a set of multiple types of brackets.

class BracketHelper {
    // checks if the string contains properly formatted brackets
    public static bool ProperBrackets(string s) {
        int p = 0;
        return ProperBrackets(s.ToCharArray(), ref p);
    }

    // main method, uses recursion to check if the brackets are properly formatted
    private static bool ProperBrackets(char[] arr, ref int ptr, char oppBracket = ' ') {

        for(;ptr<arr.Length;ptr++) {
            var ch = arr[ptr];

            if ( IsOpen(ch)) {  // found an open bracket - let's check the inner content
                ptr +=1; // start checking from the next position
                if (ProperBrackets(arr, ref ptr, OppositeOf(ch)) == false) // inner content is malformed?
                    return false;
            }
            if ( IsClose(ch) ) // found a closing bracket
                return ch == oppBracket; // is this what we were looking for? If not - then we found a malformity!
        }

        // we reached the end. are we still searching for the closing bracket?
        return oppBracket == ' ';
    }

    private static char[] OpenBrackets = new char[] { '{', '[', '(' };
    private static char[] CloseBrackets = new char[] { '}', ']', ')' };

    // check helpers
    private static bool IsOpen(char ch)  {      return OpenBrackets.Contains(ch);       }
    private static bool IsClose(char ch) {      return CloseBrackets.Contains(ch);      }

    // returns a closing bracket character
    private static char OppositeOf(char ch) {
        for(var i=0;i<OpenBrackets.Length;i+=1)
            if ( ch == OpenBrackets[i] )
                return CloseBrackets[i];
        throw new Exception($"'{ch}' is not an open bracket");
    }
}

Some test cases for LinqPad:

(BracketHelper.ProperBrackets("{}") == true).Dump();
(BracketHelper.ProperBrackets("{[]()}") == true).Dump();
(BracketHelper.ProperBrackets("{[()][{}]{}}") == true).Dump();
(BracketHelper.ProperBrackets("{[}]}") == false).Dump();
(BracketHelper.ProperBrackets("{[{(}])}") == false).Dump();
(BracketHelper.ProperBrackets("{[][][][{(})}]}") == false).Dump();
(BracketHelper.ProperBrackets("{[]}}") == false).Dump();
(BracketHelper.ProperBrackets("{") == false).Dump();

This can be done with the ref argument, so the pointer is a member of a class but in this case the method won't be static and I just wanted to make its usage as convenient as possible.


texts: Model validation from within the Service Layer

texts:
I'm interested in the idea of not having my BLL dependent on ASP.NET MVC. This means that I would like to have model binding occur within my service layer. But I want to take advantage of ASP.MVC's model validation as well. So I'm considering returning a custom validation dictionary from my BLL service methods like so

    [Authorize(Roles = "ADMIN")]
    [HttpPost]
    public ActionResult Create(PostEditViewModel postEditViewModel)
    {
        BlogPost post = new BlogPost();

        postEditViewModel.MapTo(post);

        //returns custom validation dictionary
        var dic = _postService.CreatePost(post);

        //extension method that allows Controller ModelState to merge with customer error dictionary (returns ModelState)
        if (!ModelState.Merge(dic).IsValid)
            return View();

        return RedirectToAction("Index", "Home");
    }

and merge the returned validation errors with my Controller's ModelState using an extension method on ModelStateDictionary (the extension method will be part of the MVC application and not the BLL). Can anyone foresee any problems going down the road? Is there a more elegant or intelligent way to accomplish what I'm trying to do here? I've also considered this approach.


texts:
My .htaccess redirects everything to my index.php, but I wonder if it's vulnerable to XSS attacks. Am I safe?

.htaccess file

RewriteBase /

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule .*$ index.php/$1 [L]
php_value auto_append_file none

index.php

<?php
require_once 'dbliteconnect.php';
$req['status'] = (php_sapi_name() == 'cli') ? "true" : 'false';
if (php_sapi_name() == 'cli' || (isset($_SERVER['argc'])) && $_SERVER['argc'] > 0)     {
$var = isset($argv[1]) ? $argv[1] : '';
$var = strreplace("/", "", $var);
$req['var'] = $var;
}
if (isset($_SERVER['REQUEST_URI']) && php_sapi_name() != 'cli-server') {
$var = strreplace('/'.basename(DIR_), "", $_SERVER['REQUEST_URI']);
$var = str_replace("/", "", $var);
$var = str_replace(".html", "", $var);
$req['var'] = $var;
}
if (php_sapi_name() == 'cli-server') {
$var = $_SERVER['REQUEST_URI'];
$var = substr($var, 1);
$var = strreplace("/", "", $var);
$var = str_replace(".html", "", $var);
$req['var'] = $var;
}
request($req);
?>


texts: Elegantly check for null before method call

texts:
How do I elegantly check for null before calling a method on an object? This is how I do it right now:

var title = document.querySelector('title');
title = title ? title.text : '';

Null Object pattern would be nice in this case but I don't own the document.querySelector code.


texts: ASP.NET Core 3.1 AddHttpClient call that includes a call to the database

texts:
So, I have an ASP.NET Core 3.1 web site that makes occasional calls to a vendor's RESTful API. I use the HttpClient class to perform these calls.

Currently, the web site is relatively low traffic (probably a couple of users per day). The current primary use case will result in 3 calls to the API for the complete workflow.

Even in previous versions of the framework, Microsoft recommended just creating a single instance of HttpClient and using it throughout the entire lifecycle of your application (to prevent port exhaustion). The new recommendation for ASP.NET Core is to register a service in your Startup class to act as a factory for your HttpClient. I initially used my own Singleton for but recently switched to follow Microsoft's recommendation.

My one concern is that I have to add my API Key as a header for each request, or it will be rejected.

I currently store the database key in SQL Server, using its always-encrypted feature to make sure that it stays private.

Here's the relevant logic in the ConfigureServices method in my Startup class:

services.AddDbContext<DatabaseContext>();

// Use TLS 1.3 for requests
// I'm a little uncertain if this is still the recommended way to configure this in ASP.NET Core
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls13;

services.AddHttpClient("VendorAPICall", c =>
        {
            c.BaseAddress = new Uri("https://api.vendorname.com/");

            c.Timeout = new TimeSpan(4, 0, 0);

            c.DefaultRequestHeaders.Accept.Clear();

            c.DefaultRequestHeaders.Add("Accept", "application/json");

            // I store the API Key securely using SQL Server's Always Encrypted feature: https://docs.microsoft.com/en-us/sql/relational-databases/security/encryption/always-encrypted-database-engine?view=sql-server-ver15
            // I'm a little concerned about the potential performance impact of this, especially how
            // many extra database calls it could result in (particularly since I'm not doing
            // the async calls).
            using (var ctx = new DatabaseContext())
            {
                Security security = ctx.Security.First();

                // Header must include the API Token for all requests, or the request will be rejected
                c.DefaultRequestHeaders.Add("ApiToken", security.Apikey);
            }
        });

I have two points that I'm concerned about:

First, is the call to ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls13; still the recommended (or, at least, acceptable) way of doing this configuration in ASP.NET Core, or am I doing this wrong?

Secondly, I'm concerned about the database call and how many back-and-forths this could result in for the database. This seems a little unnecessary, since the API Key will only be renewed every 6 months or so, so it seems wasteful at a minimum and a potential scalability issue at worst.

I'm also a little annoyed that I'm not using the async version of the Entity Framework calls here. (I'm otherwise using the async version of all of the database calls wherever possible).

Am I worrying too much here, or is there actually a better way to do this? (I already established in a separate Q&A on Stack Overflow that I was, in fact, being paranoid about the possibility of keeping the API Key in memory, but that's probably a separate issue).


texts: Filtering and adding additional properties to array of objects

texts:
Hi I am working on a complex application and currently adding two additional properties to objects that match the condition and returning it back. I was able to achieve the expected output, but just wanted to know if there is any other way which is more efficient than what I have tried.

Step 1 : Filtering the array to get only car objects.

Step 2 : Add firstlayer and lastlayer prop to car objects

Step 3 :

If it is first car object in the filtered array then mark firstlayer
as true.     If it is last car object in the filtered array then mark
lastlayer as true.

Step 4 : concat it with the other non-car objects

Original array:

[{
  id: 10,
  name: "Truck",
  status: "Cancelled"
}, {
  id: 11,
  name: "Bus",
  status: "Approved"
}, {
  id: 12,
  name: "Car1",
  status: "Approved"
}, {
  id: 19,
  name: "Car2",
  status: "Cancelled"
}, {
  id: 13,
  name: "Car3",
  status: "Cancelled"
}]

Expected array:

[{
      id: 10,
      name: "Truck",
      status: "Cancelled"
    }, {
      id: 11,
      name: "Bus",
      status: "Approved"
    }, {
      id: 12,
      isFirstLayer: true,
      isLastLayer: false,
      name: "Car1",
      status: "Approved"
    }, {
      id: 19,
      isFirstLayer: false,
      isLastLayer: false,
      name: "Car2",
      status: "Cancelled"
    }, {
      id: 13,
      isFirstLayer: false,
      isLastLayer: true,
      name: "Car3",
      status: "Cancelled"
    }]

This is the code I have tried

var array = [
  {
    "name": "Truck",
    "status": "Cancelled",
    "id": 10
  },
  {
    "name": "Bus",
    "status": "Approved",
    "id": 11
  },
  {
    "name": "Car1",
    "status": "Approved",
    "id": 12
  },
  {
    "name": "Car2",
    "status": "Cancelled",
    "id": 19
  },
  {
    "name": "Car3",
    "status": "Cancelled",
    "id": 13
  }
];

var i=0;
var arrayLength=array.length;
var newArray = array.filter(function(a) {
  if((a.name !='Bus'&&a.name!='Truck'))
  {

      if(i==0){
    a.isFirstLayer=true;
          a.isLastLayer=false;
      }else if(i==arrayLength-i-1){
         a.isFirstLayer=false;
          a.isLastLayer=true;
      } else{
          a.isFirstLayer=false;
          a.isLastLayer=false;
      }
      i++;
  };
  return a
});

console.log(newArray);

https://jsfiddle.net/fierce_trailblazer/q2uvf06r/24/

Any suggestions to improve the code would be helpful


texts:
I'm a beginner currently learning Python. I made a simple program, a random number guessing game, to apply in practice what I have already learned (not much) and hopefully be able to get a better understanding of the basics. Are there any more things or suggestions on how I could improve my code? I would be glad to hear some feedback and also, if possible, some tips on how to learn Python more efficiently so I can improve my programming skills. I would appreciate it a lot!

import random

print("Welcome to the Guessing Game!")
user_name = input("What should I call you? ")
print("Hello, " + user_name)

def gameplay():
    number = random.randint(1, 10)
    user_guess = ""
    guess_limit = 3
    no_of_guesses = 0
    out_of_guesses = False

    while user_guess != number and not(out_of_guesses):
        if no_of_guesses < guess_limit:
            user_guess = int(input("Guess the number from 1 to 10 that I'm thinking of... "))
            if user_guess < number:
                print("Your number was too low...")
            elif user_guess > number:
                print("Your number was too high...")
            no_of_guesses += 1
        else:
            out_of_guesses = True

    if out_of_guesses:
        print("You ran out of guesses, try again")
    else:
        print("You guessed it! Congratulations, you win the game!")

    def restart_game():
        user_reply = input("Do you want to play again? Type YES if you want to play again or NO if you want to quit... ")
        if user_reply.upper() == "YES":
            gameplay()
        elif user_reply.upper() == "NO":
            print("Script terminating. Exiting game...")
        else:
            print("Sorry, you didn't type \"YES\" or \"NO\"...")
            restart_game()
    restart_game()

gameplay()


texts: Two duration widgets for a break timer, with ± buttons

texts:
I'm sure I can optimise this code, but I can't find how in order to be generic. I'm not sure that .parent and .child combination is good in the long term here.

$(document).ready(function() {
  var lengthInit = $("#lengthSession").text();
  $("#timer").text(lengthInit);
  $("#dimBreak").click(function() {
    dimLength();
  });
  $("#augBreak").click(function() {
    augLength();
  });
  $("#dimSession").click(function() {
    dimLengthSession();
  });
  $("#augSession").click(function() {
    augLengthSession();
  });
});

function dimLength() {
  var length = parseInt($("#lengthBreak").text());
  length = length - 1;
  $("#lengthBreak").text(length);
}

function augLength() {
  var length = parseInt($("#lengthBreak").text());
  length += 1;
  $("#lengthBreak").text(length);
}

function dimLengthSession() {
  var length = parseInt($("#lengthSession").text());
  length = length - 1;
  $("#lengthSession").text(length);
}

function augLengthSession() {
  var length = parseInt($("#lengthSession").text());
  length += 1;
  $("#lengthSession").text(length);
}

Break length

      <button class="boutons" id="dimBreak">-</button>
      5
      <button class="boutons" id="augBreak">+</button>

Session length

      <button class="boutons" id="dimSession">-</button>
      25
      <button class="boutons" id="augSession">+</button>


texts:
I have written the below bubble sort code in Python.

def bubble_sort():
    num_list=[]
    list_cnt=input("How many numbers you would like to sort:")
    for i in range(int(list_cnt)): ### need to convert the value returned by input()
        num_list.append(input("Enter " +str(i)+" number:")) ##here we are using append method of list

    print("The values input are as follows:")
    print(num_list)

    print(len(num_list))
    ### Below new line of code added to convert list to integer###
    num_list=list(map(int,num_list))
    ## with the above line the code is now working as expected##
    max_index=len(num_list)-1 ## because list begins with 0
    print("max_index is:",max_index)
    for i in range(len(num_list)-1):
        j=0
        swapped=False
        for j in range(len(num_list)-1):
            if num_list[j] > num_list[j+1]:
                num_list[j],num_list[j+1]=num_list[j+1],num_list[j]
                print("Sorted when j=" +str(j)+ " and i=" + str(i)+ " is:\n ")
                print(num_list)
                swapped=True
        if not swapped:
            break

    print("The sorted list is :")
    print(num_list)

bubble_sort()


texts:
Purpose of the code:
I have 3 Excel files to deal with.
Those file have already been filtered or hidden because the content is very large. And I only need part of the content for every excel files.
I don't want to open every file and worksheets in order to copy the desired range.
I want to write a code to combine every filtered or hidden cells and put those cells to a brand new workbook.
Steps of the code:

Combine every filtered or hidden cells of all worksheets for every excel files.

Create a new empty single-worksheet workbook.

Put all cells of Step 1 into Step 2.

Problem of the code:

Running too slow

import openpyxl
import os
import glob

path = os.getcwd()
data=[]
x=input('name：') + '.xlsx'
target_xls = os.path.join(path,x)
for file in glob.glob(path+'\*.*'):
    if file.endswith((".xlsx")):
        wb = openpyxl.load_workbook(file, data_only=True)
        for sheet in wb.worksheets:
            for j in range(2, sheet.max_row+1 ):
                for i in range(1,sheet.max_column+1):
                    ihidden = sheet.row_dimensions[j].hidden  # Row Visibility True / False
                    svalue = sheet.cell(column=i,row=j).value
                    if ihidden == True:
                        shidden = "HIDDEN"
                    else:
                        shidden = "VISIBLE"
                        data.append(svalue)
WP= openpyxl.Workbook()
ws = WP.active
ws.title = "Sheet1"
x=sheet.max_column
new_list = [data[i:i+x] for i in range(0, len(data), x)]
for elem in new_list:
    ws.append(elem)
WP.save(target_xls)


texts:
I am having a scenario where I need to execute observables that depends on the result of the first one. However I need to keep the result of the first observable. I couldn't find any extension that would help me do this. For instance SelectMany does a projection of the first observable discarding the source results. Therefore I made my own extension:

public static IObservable<T> MergeWithResultPropagation<T>(this IObservable<T> src, Func<T, IEnumerable<IObservable<T>>> elems)
{
    return src.SelectMany(result => elems(result).Union(new[] { Observable.Return(result) }))
        .SelectMany(r => r);
}

Here's a dummy example:

Observable.Range(1, 3)
.MergeWithResultPropagation(item => new[]{
    Observable.Return(item * 2),
    Observable.Return(item * 3)
}).Dump();

Is this an adequate way to solve the problem? Did I miss an extension method that does this?


texts: Using `from select`-syntax to pass through elements from a collection unmodified

texts:
While working on a project with a friend of mine, I noticed the following syntax:

public IObservable<X> GetXs()
{
    return from x in xs
           select x;
}

He said that while xs is an IObservable<X> field, this is the way it is supposed to be written in Linq, and everyone does it this way. It also allows one to add where-clauses later on easily.

On the other hand, Reflector shows that a new delegate is created that is passed to the Select() function on the observable, but that function always returns just this, so it seems to me it also has a slight overhead.

So I don't agree with him and would have written it as follows:

public IObservable<X> GetXs()
{
    return xs;
}

Are there any other reasons for using the from select-syntax without filtering, selecting or ordering that I might have missed? Which syntax is better and why?


texts: Decompose string into parenthesed blocks in OCaml

texts:
The purpose of the OCaml code below is to decompose (or "parse")
a string into parenthesed (or possibly non-parenthesed) blocks.

(*

Decompose a string into parenthesed blocks.
Sample example at the end of this file

*)

type parenthesis_pair=PP of string*string;;

type data_for_decomposition={
   mutable partial_result : ((parenthesis_pair option)*string) list;
   mutable currently_open_pars : parenthesis_pair list;
   mutable smallest_unprocessed_index : int;
   mutable cursor_location : int;
};;

let initial_data={
  partial_result=[];
  currently_open_pars=[];
  smallest_unprocessed_index=1;
  cursor_location=1;
};;

let all_parenthesis_pairs=
  [
    PP("(",")");
    PP("{","}");
    PP("BEGIN","END");
  ]
  ;;

type small_string=string;;
type big_string=string;;

let test_for_substring_at_index (s1:big_string) (s2:small_string) i=
  if i-1+String.length(s2)>String.length(s1)
  then false
  else String.sub s1 (i-1) (String.length s2)=s2;;

let substring_in_interval s i j=String.sub s (i-1) (j-i+1);;

let test_for_left_paren_at_index
   s i (PP(lparen,rparen))=test_for_substring_at_index  s lparen i;;

let test_for_right_paren_at_index
   s i (PP(lparen,rparen))=test_for_substring_at_index  s rparen i;;

let look_for_left_paren_at_index s i=
   let rec finder=(fun
    possibilities->match possibilities with
    []->None
    |paren::other_parens->
      if test_for_left_paren_at_index s i paren
      then Some(paren)
      else finder other_parens
   ) in
   finder all_parenthesis_pairs;;

let process_without_open_pars  s data=
   match look_for_left_paren_at_index s data.cursor_location with
     None->(data.cursor_location<-data.cursor_location+1)
    |Some(paren)->
                let (PP(lparen,rparen))=paren in
               let _=(if data.currently_open_pars=[]
               then
                    let i_start=data.smallest_unprocessed_index
                    and i_end=data.cursor_location-1 in
                    let enclosed_substring=substring_in_interval s i_start i_end in
                    let new_result=(None,enclosed_substring) in
                    (
                     data.partial_result<-new_result::(data.partial_result);
                     data.smallest_unprocessed_index<-data.cursor_location
                    )
               ) in
               (
                data.currently_open_pars<-(paren::data.currently_open_pars);
                data.cursor_location<-data.cursor_location+String.length(lparen)
               );;

let process_with_open_pars  s data=
  let nearest_paren=List.hd(data.currently_open_pars)
  and i=data.cursor_location in
  if not(test_for_right_paren_at_index s i nearest_paren)
  then process_without_open_pars  s data
  else
       let (PP(lparen,rparen))=nearest_paren
       and new_list=List.tl(data.currently_open_pars) in
       let _=(
          data.currently_open_pars<-new_list;
        (data.cursor_location<-data.cursor_location+String.length(rparen))
       ) in
       if new_list<>[]
       then ()
       else let i_start=data.smallest_unprocessed_index+String.length(lparen)
            and i_end=i-1 in
            let enclosed_substring=substring_in_interval s i_start i_end in
            let new_result=(Some(nearest_paren),enclosed_substring) in
            (
                data.partial_result<-new_result::(data.partial_result);
                data.smallest_unprocessed_index<-data.cursor_location
             )
            ;;

let process s data=
  if data.currently_open_pars=[]
  then process_without_open_pars s data
  else process_with_open_pars s data;;

let decompose s=
  let data=initial_data in
  while data.cursor_location<=(String.length s)
  do
     process s data
  done;
  List.rev(data.partial_result);;

(*

Sample example :

decompose("How (much (research effort) is {expected} when) BEGIN posting a"^
"Code Review ENDquestion? A "^
"lot. {{(An absurd amount)}}. More BEGIN than  BEGIN you think END"^
"you ENDare capable of.");;

*)


texts:
I'm not entirely sure on how to handle errors on this:

Is returning a nullptr in case of bad parameters okay, or is it better to return a ENFMPCodegenData.Empty, like there is Rectangle.Empty or Point.Empty in the .NET Framework?
What about handling errors, if any should occur when creating the native object Codegen?
Should I just encompass this in a try / catch block and wrap a native exception inside  a managed one?

This my first attempt on creating such helper.  It's working, but I'm not really sure about its robustness.

public ref class ENMFPCodegen
{
    private:
        ENMFPCodegen()
        {
        }

    public:

        static ENMFPCodegenData ^ GetData ( array<float> ^ pcm , uint numberOfSamples, uint start_offset )
        {
            if ( pcm == nullptr || pcm->Length <= 0  || numberOfSamples <= 0 )
                return nullptr;

            pin_ptr<float> pFloat = &pcm[0];
            Codegen * codegen = new Codegen ( pFloat, numberOfSamples, start_offset );

            if ( codegen == nullptr )
                return nullptr;

            std::string codeString = codegen->getCodeString();
            const char* chars = codeString.c_str();
            String ^ code = gcnew System::String ( chars );
            int numCodes =  codegen->getNumCodes();
            float version = codegen->getVersion();
            delete codegen;
            ENMFPCodegenData ^ data = gcnew ENMFPCodegenData ( code, numCodes, version );
            return data;
        }

};

public ref class ENMFPCodegenData {
    internal:
        ENMFPCodegenData ( String ^ code, int numCodes, float version )
        {
            Code = code;
            NumCodes = numCodes;
            Version = version;
        }

    public:
        String ^ Code;
        int NumCodes;
        float Version;

        virtual String ^ ToString() override
        {
            StringBuilder ^ sb = gcnew StringBuilder;
            sb->AppendFormat ( "{{Version: {0}, NumCodes: {1}, Code: {2}}}", Version, NumCodes, Code );
            return sb->ToString();
        }
};


texts: Rspec test to confirm rejection of four invalid dates

texts:
require_relative '../price_entry_class.rb'
require_relative '../exceptions.rb'
require 'spec_helper'

describe PriceEntry do
    it "throws expection on invalid date format" do
        expect { described_class.date_from_input_to_storage("20010101") }.to raise_error(InvalidInputData)
        expect { described_class.date_from_input_to_storage("zażółć") }.to raise_error(InvalidInputData)
        expect { described_class.date_from_input_to_storage(nil) }.to raise_error(InvalidInputData)
        expect { described_class.date_from_input_to_storage(-19_199) }.to raise_error(InvalidInputData)
    end
end

Is it OK to have multiple expectations in a single Rspec test? rubocop-rspec claims that it would be preferable to separate this test into 4:

spec/price_entry_class_spec.rb:14:2: C: Example has too many expectations [4/1].

Claim that it is always better to have single assert in every unit test is quite surprising for me. Is there a good reason to split test like this into four separate ones?

This test is testing only one thing at a time (is obviously malformed input resulting in exceptions).

I can imagine rewriting it to

["20010101", "zażółć", nil, -19_199].each do |malformed_input|
    expect { described_class.date_from_input_to_storage(malformed_input) }.to raise_error(InvalidInputData)
end

but I am not convinced that it is improving readability, maintainability or anything else.


texts: Using Python to get data from a Star Wars API

texts:
I am learning Python (about 6 months in, sporadically) and today I decided to write a script to download JSON information from an API.

To start, I wrote a one-page script with a few functions.

The script does the following:

The user enters the script on the terminal with a search value.
The script gets the response information from the Star Wars API (https://swapi.co). This is an open API, so I don't need any keys or tokens.
If the API returns one value, the information is displayed immediately.
If the API returns several values, the script prompts the user to make a choice. Then the information is displayed.

Right now, the script only works for people in the SWAPI (e.g., Luke Skywalker).

Any feedback on my code would be helpful.

#!/usr/bin/python3

'''Script to get information from https://swapi.co/'''

import requests
import json
import sys

#TODO: Print useful information such as movie titles or names of worlds instead of showing links
#Break up URL to allow for more dynamic searching in the future. Right now, script only handles the people parameter when getting info from the API.

UNDERLINE_LEN = 30

def show(data, index=0):
    '''
        Displays an individual Swapi object.
        data = data retrieved from api
        index = which entry to select. Default is 0 for single item lists.
    '''
    info = data['results'][index]
    print()
    print('-' * UNDERLINE_LEN)
    print("Name : {0}\n{1}".format(data['results'][index]['name'], '-' * UNDERLINE_LEN))
    for k, v in info.items():
        if type(v) is list:
            counter = 0
            print(k, ':')
            for j in v:
                print("\t{0}".format(v[counter]))
                counter += 1
        else:
            if k != 'name':
                print(k, ':', v)

def show_choices(data):
    '''Shows a list of Swapi objects and prompts users to select an object [integer]'''
    info = data['results']
    counter = 0
    for i in info:
        print("[{0}] {1}".format(counter + 1, data['results'][counter]['name']))
        counter += 1
    print()
    choice = int(input("Which item would you like to view? "))
    try:
        show(data, choice - 1)
    except IndexError as ie:
        print(ie)

def grab():
    '''Main function.'''
    try:
        search = sys.argv[1]
        url = 'https://swapi.co/api/people/?search={0}'.format(search)      #need to divide url to make search process more dynamic
        r = requests.get(url)
        data = json.loads(r.text)
        if data is not None:
            numResults = int(data['count'])
            txt = "results"
            if numResults == 1:
                txt = "result"
            resText = "{0} {1} found for search parameter '{2}'".format(numResults, txt, search)
            print(resText)
            if numResults == 1:
                show(data)
            else:
                show_choices(data)
    except Exception as e:
        print(e)

grab()


texts: Function to parse floats optionally followed by %, more strict than parseFloat in javascript

texts:
I'm not a Javascript expert, so please review this function for me. Also, it  could be that there is something in any of the library we're using in our project that can do something similar for me (angular, foundation, jquery, underscore), but I'm not too familiar yet with most of them.

// helper function, parses numeric input also ending with %
  /*
  [parseNumeric('123') === 123,
   parseNumeric('10 abc') === undefined
   parseNumeric('10.10%') === 10.1,
   parseNumeric(' 10.1000 ') === 10.1,
   parseNumeric('10. 01%' ) === undefined,
   parseNumeric('10.0 %') === 10] */
  function parseNumeric(number) {
    if (number === undefined || typeof(number) === 'number')  {
      return number;
    }

    // delete trailing zeros and whitespaces between number digits and %,
    // leaving % if present
    var numberString = number.trim().replace(/\.?0*\s*(\%)?$/g,'$1');

    var parsedNumber = parseFloat(number);
    if (isNaN(parsedNumber)) {
      return undefined;
    }

    var parsedNumberLength = (parsedNumber+'').length;

    if (numberString.length === parsedNumberLength) {
      return parsedNumber;
    }

    if (numberString.charAt(numberString.length - 1) === '%' &&
        (numberString.length - 1) === parsedNumberLength) {
      return parsedNumber;
    }

    return undefined;
  }


texts: Form validation - security and input specification

texts:
So I'm working on a register form and I have four fields: name, username, email and password. I pick up the values of these fields in jQuery and depending on if all the fields are filled, I pass them onto a PHP script via ajax. Is that safe for form validations? I was worried about data getting manipulated by the user.

Further on in the php script, I check if all the posted values have data in them, only then will I proceed onto doing some validations... The validations are the parts where I'm worried that it's not the best and there are many flaws with it.

$name = $_POST['name'];
$username = $_POST['username'];
$email = $_POST['email'];
$password = $_POST['password'];

if (!preg_match("/^[A-Za-z '-]+$/i", $name)) {

    $errors = "Please enter a valid name.";

} else if (!preg_match("/^[A-Za-z]+\s[A-Za-z]+$/", $name)) {

    $errors = "Please enter your first and last name.";

} else if (strlen($username) <= 3 || strlen($username) > 15) {

    $errors = "Please pick a username between 4 - 15 characters. Be creative.";

} else if (!preg_match("/^[A-Za-z][A-Za-z0-9_.-]{4,15}$/", $username)) {

    $errors = "Please pick an alphanumeric username between 4 - 15 characters.";

} else if (filter_var($email, FILTER_VALIDATE_EMAIL) === false) {

    $errors = "Please enter a valid email.";

} else if (strlen($username )< 6 || strlen($username) > 32) {

    $errors = "Your password must atleast be 6 characters.";

} else {

    echo "valid";

}

Are these validation steps secure? Are there any loop holes that the user can manipulate the data?

The requirements for the fields are as follows - which im not so sure i hit on the head with my code: - The username should have alphanumeric characters with underscores (optional) - the name should have BOTH the first name and the last name

Thank you.


texts: Improving excution time for list and sampling in Python

texts:
Here is my code for generating edge list based on Price model algorithm. I think there have two points to reduce execution time:

use proper data type
use faster random sampling

Originally, I used list instead of NumPy array and then changed from extending array till c x n to setting initial fixed array (and change the initial values).

It made execution time faster but still way slower than same implementation written in Matlab.

import pickle
from random import random, sample
import numpy as np

def gen_edge_list(a, c, n):
    """
    Generate edge list based on 14.1.1
    """
    edge_list = np.zeros(c*n)
    p = float(c) / (float(c)+a) # % for preferential attachment edges
    edge_list[0] = 1            # edge from vertex 2 to 1
    idx = 1                     # point to the next index
    for t in range(3, n+1):
        if t <= c+1:
            """
            If network size is smaller than c+1,
            connect among all vertices.
            """
            edge_list[idx:idx+t-1] = [i for i in range(1, t)]
            idx = idx+t-1
        else:
            """
            decide preferential attachment or uniformly random attachment
            by given p
            """
            n_pref = len([True for i in range(c) if random() < p])
            edge_list[idx:idx+n_pref] = sample(edge_list[0:idx-1], n_pref)
            idx += n_pref
            edge_list[idx:idx+c-n_pref] = sample(range(1, t+1), c-n_pref)
            idx = idx + c - n_pref

if __name__ == "__main__":
    a = [1.5]
    c = [3]
    n = 10**6
    edge_lists = []
    for i in range(len(a)):
        edge_lists.append(gen_edge_list(a[i], c[i], n))
    output = open('edge_list.pkl', 'wb')
    pickle.dump(edge_lists, output)
    output.close()

My biggest concern is especially the following:

        """
        decide preferential attachment or uniformly random attachment
        by given p
        """
        n_pref = len([True for i in range(c) if random() < p])
        edge_list[idx:idx+n_pref] = sample(edge_list[0:idx-1], n_pref)
        idx += n_pref
        edge_list[idx:idx+c-n_pref] = sample(range(1, t+1), c-n_pref)
        idx = idx + c - n_pref

Here is my friends code written in Matlab:

a = [1.5];
c = [3];
n = 1^6;
edgelist = cell(numel(c),1);
for i = 1:numel(c)
    p = c(i)./(c(i)+a(i));
    edgelist{i} = zeros(1, c(i).*n);
    edgelist{i}(1) = 1;
    idx = 2;
    for t = 3:n
        if t <= c(i)+1
            edgelist{i}(idx:(idx+t-2)) = 1:(t-1);
            idx = idx+t-1;
        else
            pref_or_rand = rand(1,c(i)) < p;
            prefn = sum(pref_or_rand);
            edgelist{i}(idx:(idx+c(i)-1)) = [edgelist{i}(randi(idx-1,1,prefn)) randi(t,1,c(i)-prefn)];
            idx = idx+c(i);
        end
    end
end

I don't know what makes this huge difference on execution time between them. (40 sec in Matlab on mac book pro vs 40 min with Python code in recent i5 machine on Debian)

If you have any idea, please let me know.


texts: Finding the longest word without these characters

texts:
My goal is to go through the list of all English words (separated by '\n' characters) and find the longest word which doesn't have any of these characters:  "gkmqvwxz". And I want to optimize it as much as possible. Here's what I came up with:

#include <string.h>
#include <ctype.h>
#include <stdlib.h>
#include <stdio.h>
#include <stddef.h>
#include <unistd.h>

static inline int is_legal(size_t beg, size_t end, char* buffer)
{
  static const char* bad = "gkmqvwxzio"; /* unwanted chars */
  for (; beg != end; ++beg) {            /* go through current word */
    char ch = tolower(buffer[beg]);      /* The char might be upper case */
    for (size_t j = 0; bad[j]; ++j)
      if (ch == bad[j])                  /* If it is found, return false */
        return 0;
  }

  return 1;                              /* else return true */
}

int main(void)
{
  char *buffer = NULL;                   /* contents of the text file */

  size_t length = 5000000;               /* maximum size */
  FILE* fp;
  fp = fopen("words.txt", "rb");

  if (fp) {
    fseek(fp, 0, SEEK_END);
    fseek(fp, 0, SEEK_SET);
    buffer = malloc(length);
    if (buffer) {
      fread(buffer, 1, length, fp);       /* read it all */
    }
    fclose(fp);
  }

  size_t beg = 0;                         /* current word boundaries */
  size_t end = 0;

  size_t mbeg = 0;                        /* result word */
  size_t mend = 0;

  while (buffer[end]) {
    beg = end++;

    for (; buffer[end] && buffer[end] != '\n'; ++end) /* read the next word */
      ; /* for loop doesn't have a body */

    if ((end - beg) > (mend - mbeg) && is_legal(beg, end, buffer)) { /* if it is a fit, save it */
      mbeg = beg;
      mend = end;
    }
  }

  printf("%.*s\n", mend - mbeg, buffer + mbeg);  /* print the output */
  return 0;
}

I read it all at once, then go through it with two indexes denoting beginning and ending of current word. When I find a word that fits, I save the corresponding indexes. Finally I print the output, which is "supertranscendentness". The output is correct, but I'd like to know:

If there's undefined behavior in my code
If there's a better way of doing this (without sacrificing performance)
If there's a way to improve the performance

Another point is the size_t length = 5000000; part. It is an estimated size of the string based of the file size.


texts:
A function f is defined
  by the rule that f(n) = n if n < 3 and
  f(n) = f(n-1) + 2f(n-2) + 3f(n-3) if
  n>=3.  Write a recursive and an
  iterative process for computing f(n).

I wrote the following:

(define (f_r n)
  ; recursive
  (cond ((< n 3) n)
        (else (+ (f_r (- n 1))
                 (* 2 (f_r (- n 2)))
                 (* 3 (f_r (- n 3)))))))

(define (f_i n)
  ;iterative
  (f_i-prime 1 0 0 n))

(define (f_i-prime n n-1 n-2 count)
  (cond ((= count 0) n)
        ((f_i-prime (+ n n-1 n-2)
                    (+ n n-1)
                    n-1
                    (- count 1)))))

What do you think?

EDIT 1: Since my first iterative solution was erroneous, here is a corrected version:

(define (f_i n)
  ;iterative
  (f_i-prime 2 1 0 n))

(define (f_i-prime f_x+2 f_x+1 f_x n-x)
  (cond ((= n-x 0) f_x)
        ((f_i-prime (+ f_x+2 (* 2 f_x+1) (* 3 f_x) )
                    f_x+2
                    f_x+1
                    (- n-x 1)))))


texts:
This is a very basic script. If the screen width is larger than say a tablet, and a portfolio link is hovered over, it will fade out the original text and replace it with the text held in the 'data-portfolio' attribute. I'm fairly new to jQuery so any improvements will be welcomed.

You can see it working here.

(function () {

width = $(window).width();

if(width >= 620) {
    $('.portfolio-piece__link').hover(function(){

    var $this = $(this);
        prev = $this.text();
        data = $this.attr('data-portfolio');

        $this.fadeOut(300, function(){
            $this.text(data).fadeIn(300);
        });

    }, function(){

    var $this = $(this);
        $this.fadeOut(300, function(){
            $this.text(prev).fadeIn(300);
        });
    });
}

})();


texts: Representing a property with a non-nullable getter & a nullable setter

texts:
I have a class as follows, where I want the user of the class to know that setting the Slug property to null is supported, and its getter will still return a valid value:
public class Post
{
    public string Title { get; }
    public Post(string title)
    {
        Title = title;
    }

    private string? slug;
    public string Slug
    {
        get
        {
            if(slug is null)
            {
                slug = Title.Slugify();
            }
            return slug;
        }
        set => slug = value;
    }
}

There are two possible cases here:
CASE 1: No slug is set on/after initialization OR the slug is initialized with a non-null string.
var post = new Post("foo bar");
var slug = post.Slug;               // foo-bar

var post2 = new Post("foo bar 2") { Slug = "foo-bar-2" };
var slug2 = post.Slug;              // foo-bar-2

CASE 2: The slug set on is initialization with a nullable string.
string? maybeNull = viewModel.Slug; // may or may not be null
var post = new Post("foo bar") { Slug = maybeNull! };
var slug = post.Slug;               // returns an expected value

Is there a better way to do this, than using the null forgiving operator? The above code looks worse if I had to set it to null:
var post = new Post("foo bar") { Slug = null! };
var slug = post.Slug;               // returns an expected value

The reason I dont want to use the null forgiving operator is because it requires the user of the Post class to know that a null value can be safely passed into its Slug property -- something I wish to avoid.
If it's not possible to have different nullability for getters and setters (appears to me like it's not), what is the best way to communicate my intent (users can safely set Slug to null + users will always get a valid slug, irrespective of what was set).
For some more context:

the Post class is instantiated with a nullable value only while creating a Post. Every other time, it's going to be pulled from a database, and so will always be instantiated with a valid slug.
the Post class is not a ORM model.


texts: Finding all pairs of elements in an array that sum to a target value using multiple pointers (follow up)

texts:
The previous question was not clear enough so I will try to clarify it more in this follow-up question.
I tried the multiple pointers technique to solve the problem that find pair of values that sums up to a target value.

We are assuming that:

the array is already sorted.
we are working with a static array of size 16 (testing purpose only).
we are not working with actual pointers; because we don't need them in this case (I think), I named the question on the algorithm's
name only.

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

struct result
 {
     int num1;
     int num2;
     result() {}

     result(int num1, int num2)
         : num1{ num1 }, num2{ num2 } {}
 };

 vector<result> mult_pt(int arr[], int target)
 {
     int p1 = 0;
     int p2 = 15;
     bool flag = false;
     vector<result> res;
     while (p1 <= p2)
     {
         if (arr[p1] + arr[p2] == target)
         {

             for (int k = 0; k < res.size() - 1; k++)
             {
                 if (res.size() == 0)
                     res.push_back(result(arr[p1], arr[p2]));
                 else if (res[k].num1 != arr[p1] && res[k].num2 != arr[p2])
                 {
                     flag = false;
                 }
                 else flag = true;
             }
             if(flag) res.push_back(result(arr[p1], arr[p2]));
             p1++;
         }
         else if (arr[p1] + arr[p2] < target)
         {
             p1++;
             continue;
         }
         else if (arr[p1] + arr[p2] > target)
         {
             p2--;
             for (int i = p1; i >=0; i--)
             {
                 if (arr[i] + arr[p2] == target)
                 {
                     res.push_back(result(arr[p1], arr[p2]));
                 }
                 else if (arr[i] + arr[p2] > target)
                 {
                     continue;
                 }
                 else break;
             }
         }
     }
     return res;
 }

int main ()
{
  int array[16] = { 0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15};
  vector <result> res = mult_pt(array, 19);
  for (int j = 0; j < res.size(); j++)
    {
        cout << "[ " << res[j].num1 << " , " << res[j].num2 << " ]" << endl;
    }
  return 0;
}

The output should be like:
[ 4 , 15 ]
[ 5 , 14 ]
[ 6 , 13 ]
[ 7 , 12 ]
[ 8 , 11 ]
[ 9 , 10 ]
[ 10 , 9 ]

You can check the previous post here.


texts: VBA Excel Looping through recordset and storing the data to use later

texts:
I have a loop to add Recordset items to a Dictionary so I can do comparisons and retrieve specific data later in the code (not shown below).

The first loop I tried takes around 17 seconds, the second takes 16 seconds, the third takes 15 seconds. It seems like a long wait to add 500-700 records.

The connection is to a SQL Server database.

'add all apps to dictionary
Dim cn As ADODB.Connection
Dim rs As ADODB.Recordset
Set dict = New Scripting.Dictionary
Set rs = New ADODB.Recordset
rs.Open SQLStr2, cn, adOpenStatic

Dim StartTime As Double
Dim SecondsElapsed As Double
StartTime = Timer

'This takes 16 seconds - class module separate
'Source: https://codereview.stackexchange.com/questions/25956/storing-recordset-data
'Dim entity As MyEntity
'Dim entities As New Collection
'While Not rs.EOF And Not rs.BOF

    'Set entity = New MyEntity
    'With entity
        '.Property1 = rs.Fields("app_number").value
        '.Property2 = rs.Fields("FlexFstDispAmt").value
        '.Property3 = rs.Fields("FlexSecDispAmt").value
        '.Property4 = rs.Fields("NonFlexAmt").value
    'End With

    'entities.Add entity
    'rs.MoveNext
'Wend

'this takes 15 seconds
Dim Key1 As String
Dim Key2 As String
Dim Key3 As String
Dim Key4 As String
With dict
    For i = 1 To rs.RecordCount
        Key1 = rs.Fields("app_number").value
        Key2 = rs.Fields("FlexFstDispAmt").value
        Key3 = rs.Fields("FlexSecDispAmt").value
        Key4 = rs.Fields("NonFlexAmt").value
        .Add Key1, Array(Key2, Key3, Key4)
        '.Add rs.Fields("app_number").Value, Array(rs.Fields("FlexFstDispAmt").Value, rs.Fields("FlexSecDispAmt").Value, rs.Fields("NonFlexAmt").Value)
        rs.MoveNext
    Next
End With

'this takes 17 seconds
'With dict
    'For i = 1 To rs.RecordCount
        '.Add rs.Fields("app_number").value, Array(rs.Fields("FlexFstDispAmt").value, rs.Fields("FlexSecDispAmt").value, rs.Fields("NonFlexAmt").value)
        'rs.MoveNext
    'Next
'End With

Debug.Print Round(Timer - StartTime, 2)

rs.Close
cn.Close
Set cn = Nothing
Set rs = Nothing

I'd really like some help speeding this up. Anything is appreciated.


texts:
I took a test at Codility called TapeEquilibrium. The task description that I received can be seen here.

I came up with a solution that worked, and I was pretty happy with. However, the performance was apparently awful. The expected time complexity is apparently supposed to be \$O(N)\$, but I got \$O(N * N)\$. I'm not quite sure what exactly that means, but I've heard about it several times.

I'd like some help on improving my solution and get information about what I did wrong and how it could be done better, and why. I'm doing this to learn and improve.

public int solution(int[] A) {
    int min = Int32.MaxValue;
    for (int i = 0; i < A.Length - 1; i++) {
        // p = i + 1
        int part1 = 0, part2 = 0;
        for (int j = 0; j <= i; j++) part1 += A[j];
        for (int j = i + 1; j <= A.Length - 1; j++) part2 += A[j];

        int val = Math.Abs(part1 - part2);
        if (val < min) min = val;
    }
    return min;
}


texts:
I have stored in a XML file some Travel packages, each package has a code( the codes are stored in an array = $code).

I am using the below code to pull the requested data from the XML based on the given code. At this time I have copy/paste the code for each given code, but I have lots more and I dont want to copy paste code over and over

How can I simplify the below code so I don't have to paste it for all code that I have?

 <?php
    $code = array("BAS12", "BAS12", "BAS13", "BAS14");

    $dom    = new DOMDocument();
    $xpath  = new DOMXPath($dom);
    $reader = new XMLReader();
    $reader->open("file.xml");

    while ($reader->read()) {
        if ($reader->nodeType == XMLReader::ELEMENT && $reader->name == 'Hotel') {
            $node = $dom->importNode($reader->expand(), true);
            $dom->appendChild($node);
            $nume1 = $xpath->evaluate('string(self::Hotel[HotelCode = "'.$code[0].'"]/HotelName)', $node);
            $tara1 = $xpath->evaluate('string(self::Hotel[HotelCode = "'.$code[0].'"]/Country)', $node);
            $oras1 = $xpath->evaluate('string(self::Hotel[HotelCode = "'.$code[0].'"]/City)', $node);
            $adresa1 = $xpath->evaluate('string(self::Hotel[HotelCode = "'.$code[0].'"]/Adress)', $node);
            $stele1 = $xpath->evaluate('string(self::Hotel[HotelCode = "'.$code[0].'"]/Stars)', $node);
            $masa1 = $xpath->evaluate('string(self::Hotel[HotelCode = "'.$code[0].'"]/TipMasa)', $node);
            $camera1 = $xpath->evaluate('string(self::Hotel[HotelCode = "'.$code[0].'"]/TipCamera)', $node);
            $pret1 = $xpath->evaluate('string(self::Hotel[HotelCode = "'.$code[0].'"]/Pret)', $node);
            $descriere1 = $xpath->evaluate('string(self::Hotel[HotelCode = "'.$code[0].'"]/Descriere)', $node);
            $persoane1 = $xpath->evaluate('string(self::Hotel[HotelCode = "'.$code[0].'"]/Persoane)', $node);
            $img1 = $xpath->evaluate('string(self::Hotel[HotelCode = "'.$code[0].'"]/Imagine1)', $node);
              $dom->removeChild($node);
            if ($nume1) {
                 break; }
            if ($tara1) {
                 break; }
            if ($oras1) {
                 break; }
             if ($adresa1) {
                 break; }
                  if ($stele1) {
                 break; }
                  if ($camera1) {
                 break; }
                  if ($masa1) {
                 break; }
                  if ($pret1) {
                 break; }
                  if ($persoane1) {
                 break; }
                   if ($img1) {
                 break; }

        }
    }
    ?>


texts:
I am just starting to code by myself in Flutter. I've built this so far and here is the image. Can you show me what would be better or cleaner code? I used Row widget for it, but I guess I should maybe go with the Stack. Because now I want to add a text field box in the middle of the app bar that overflows in the down direction.

child: Stack(
    children: <Widget>[
      Scaffold(
        backgroundColor: Color.fromRGBO(255, 202, 6, 1),
        appBar: PreferredSize(
          preferredSize: Size.fromHeight(90.0),
          child: Padding(
            padding: const EdgeInsets.only(left: 20, top: 20, bottom: 10),
            child: Row(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: <Widget>[
                CircleAvatar(backgroundImage: NetworkImage(
                      "https://res.cloudinary.com/demo/image/upload/w_200,h_200,c_thumb,g_face,r_max/face_left.png"),
                  radius: 32,
                  backgroundColor: Colors.white,
                  child: AppBar(
                    backgroundColor: Colors.transparent,
                    elevation: 0,
                  ),
                ),
                Padding(
                  padding: const EdgeInsets.only(left: 13, top: 8),
                  child: Text(
                    'Someones Name',
                    textAlign: TextAlign.center,
                    overflow: TextOverflow.ellipsis,
                    style: TextStyle(
                        fontWeight: FontWeight.bold, fontSize: 20),
                  ),
                ),
                Padding(
                  padding: const EdgeInsets.only(left: 100, bottom: 30),
                  child: Switch(
                    inactiveThumbColor: Colors.white,
                    activeColor: Colors.grey[700],
                    value: false,
                    onChanged: (bool state) {
                      print(state);
                    },
                  ),
                ),
              ],
            ),
          ),
        ),
        body: Container(
          height: 800,
          width: 500,
          decoration: BoxDecoration(
            color: Color.fromRGBO(251, 251, 251, 1),
            borderRadius: BorderRadius.vertical(
              top: Radius.circular(15),
            ),
          ),
        ),
      ),
    ],
    overflow: Overflow.visible,
  ),
);

And this is look I want to achieve:


texts: Creating list ViewModels in the correct way

texts:
I'm using Caliburn Micro to create a WPF application.

So what I want to do here is a typical Master/Detail situation. I'm displaying a list of Users and you can can add/edit a User and save the changes back to the database.

Everything works, but I'm just not sure if I'm creating the UserViewModels in the correct way. I lay awake at night yearning for a more elegant way.

Anything else that I'm doing wrong please let me know. It greatly helps me out and I appreciate every comment I get. Even if you must call me an idiot. Many thanks in advance!

PS: I left a few implementation details out to keep it brief. But let me know if anything else would help.

public class UserWorkspaceViewModel : Conductor<UserViewModel>.Collection.OneActive
{
    private IUnitOfWork _unitOfWork;
    private UserViewModelFactory _userViewModelFactory;

    public UserWorkspaceViewModel(IUnitOfWork unitOfWork, IUserViewModelFactory userViewModelFactory)
    {
        _unitOfWork = unitOfWork;
        _userViewModelFactory = userViewModelFactory;
        LoadUsers();
    }

    public void LoadUsers()
    {
        var users = _unitOfWork.Users.GetByDepartmentId(1);
        foreach (User user in users)
        {
            // Use the factory to create the ViewModel
            UserViewModel viewModel = _userViewModelFactory.CreateInstance(user);

            // Caliburn Micro specific: add user to the screen collection
            this.Items.Add(viewModel);
        }
    }
}

Here's the UserViewModelFactory implementation:

public class UserViewModelFactory
{
    private IUnitOfWork _unitOfWork;

    public UserViewModelFactory(IUnitOfWork unitOfWork)
    {
        _unitOfWork = unitOfWork;
    }

    public UserViewModel CreateInstance(User user)
    {
        UserViewModel vm = new UserViewModel(_unitOfWork);

        // Use AutoMapper to map properties from user to VM
        Mapper.Map<User, UserViewModel>(user, vm);

        return vm;
    }
}

And finally here's the UserViewModel:

public class UserViewModel : Screen
{
    private IUnitOfWork _unitOfWork;

    #region Properties
    // Properties like FirstName, LastName, etc.
    #endregion

    public UserViewModel(IUnitOfWork unitOfWork)
    {
        _unitOfWork unitOfWork;
    }

    public void Save()
    {
        if (this.Id == 0)
        {
            User user = Mapper.Map<UserViewModel, User>(this);
            _unitOfWork.Users.Add(user);
            _unitOfWork.SaveChanges();
        }

        if (this.Id > 0)
        {
            User user = _unitOfWork.Users.GetById(this.Id);
            Mapper.Map<UserViewModel, User>(this, user);
            _unitOfWork.SaveChanges();
        }
    }
}


texts: Recursive Matrix Multiplication Algorithm

texts:
Can I improve on this any further. Is there a prettier way of passing the array sizes?
#include <stdio.h>

void matrix_addition(size_t n, int A[n][n], int B[n][n], int C[2*n][2*n], size_t c_start, size_t c_end) {
    for(size_t i = 0; i < n; ++i) {
        for(size_t j = 0; j < n; ++j) {
            C[i+c_start][j+c_end] = A[i][j] + B[i][j];
        }
    }
}

void recursive_matrix_multiply(
        size_t l, size_t n, int A[l][l], int B[l][l], int C[n][n],
        size_t a_r_start, size_t a_r_end, size_t a_c_start, size_t a_c_end,
        size_t b_r_start, size_t b_r_end, size_t b_c_start, size_t b_c_end
    ) {
    if(n == 1) {
        C[0][0] = A[a_r_start][a_c_start]*B[b_r_start][b_c_start];
    } else {
        int m = n/2;
        int C1[m][m];
        int C2[m][m];

        recursive_matrix_multiply(l, m, A, B, C1, a_r_start, a_r_end-m, a_c_start, a_c_end-m, b_r_start, b_r_end-m, b_c_start, b_c_end-m);
        recursive_matrix_multiply(l, m, A, B, C2, a_r_start, a_r_end-m, a_c_start+m, a_c_end, b_r_start+m, b_r_end, b_c_start, b_c_end-m);

        matrix_addition(m, C1, C2, C, 0, 0);

        recursive_matrix_multiply(l, m, A, B, C1, a_r_start, a_r_end-m, a_c_start, a_c_end-m, b_r_start, b_r_end-m, b_c_start+m, b_c_end);
        recursive_matrix_multiply(l, m, A, B, C2, a_r_start, a_r_end-m, a_c_start+m, a_c_end, b_r_start+m, b_r_end, b_c_start+m, b_c_end);

        matrix_addition(m, C1, C2, C, 0, m);

        recursive_matrix_multiply(l, m, A, B, C1, a_r_start+m, a_r_end, a_c_start, a_c_end-m, b_r_start, b_r_end-m, b_c_start, b_c_end-m);
        recursive_matrix_multiply(l, m, A, B, C2, a_r_start+m, a_r_end, a_c_start+m, a_c_end, b_r_start+m, b_r_end, b_c_start, b_c_end-m);

        matrix_addition(m, C1, C2, C, m, 0);

        recursive_matrix_multiply(l, m, A, B, C1, a_r_start+m, a_r_end, a_c_start, a_c_end-m, b_r_start, b_r_end-m, b_c_start+m, b_c_end);
        recursive_matrix_multiply(l, m, A, B, C2, a_r_start+m, a_r_end, a_c_start+m, a_c_end, b_r_start+m, b_r_end, b_c_start+m, b_c_end);

        matrix_addition(m, C1, C2, C, m, m);
    }
}

int main()
{
    int A[4][4] = {{1, 2, 3, 4}, {4, 3, 2, 1}, { 0, 0, 1, 1 }, {1, 1, 0, 0}};
    int B[4][4] = {{2, 2, 4, 4}, {4, 1, 1, 4}, {1, 0, 1, 0}, {1, 0, 1, 0}};
    int C[4][4];

    recursive_matrix_multiply(4, 4, A, B, C, 0, 3, 0, 3, 0, 3, 0, 3);

    for(size_t i = 0; i < 4; ++i) {
        for(size_t j = 0; j < 4; ++j) {
            printf("C[%i][%i] = %i, ", i, j, C[i][j]);
        }
        printf("\n");
    }

    return 0;
}

It currently works as intended but I'm looking to beautify this a bit. Even an improvement on variable naming would be appreciated. I'm trying to build up a portfolio so if you saw this from a professional standpoint what would you think?


texts:
Is there anything that can be done to improve this code? Even if its using a comepltey different technique.

This code gets a list of vanruns with rules, cutoff time and fittinging time offset. We pass in the date (either now or for future that works out the best vanrun time) We want the latest cutofftime in that day for the same warehouse. Generally is this code OK for long term use or should it be broken down more? or possibly the entire logic is flawed? Use different mechanics? Just a review if anything seriously bad is happening.

private ServiceData.Models.CalculatedCutOff VarnRunEngine(List<Models.VanRunPrototype.VanRun> vanRuns, DateTime matchDate)
        {
            //get the date we are interested in
            System.DayOfWeek dayOfWeek = matchDate.DayOfWeek;
            DateTime dateOfWeekLoop = new DateTime(matchDate.Ticks);

            if (vanRuns == null | (vanRuns != null && vanRuns.Count == 0))
                throw new Exception("There are no Vanruns available to work out fitting times");

            Models.VanRunPrototype.VanRun vr = null;

            int loopkill = 0;
            while (true)
            {
                loopkill += 1;

                var _vrs = vanRuns.Where(v => v.DayOfWeek == (int)dateOfWeekLoop.DayOfWeek).ToList();
                var _vrss = _vrs.Where(v => v.CutOff > dateOfWeekLoop.TimeOfDay).ToList();
                var _vrsss = _vrss.OrderBy(t => t.CutOff).ToList();

                if (_vrsss != null && _vrsss.Count > 0)
                {

                    foreach (var v in _vrsss)
                    {
                        if (v.CutOff > DateTime.Now.TimeOfDay &&
                            (vr == null || (vr.FittingFor <= v.FittingFor && (v.CutOff > vr.CutOff && v.WareHouseID == vr.WareHouseID))))
                        {
                            vr = v;
                        }
                    }

                    vr = vr ?? _vrsss.First();
                    break;
                }

                //Go to next morning
                dateOfWeekLoop = dateOfWeekLoop.Date + new TimeSpan(8, 0, 0); //For 8 in da morning? or 00:00??
                dateOfWeekLoop = dateOfWeekLoop.AddDays(1);

                if (loopkill > 14)
                    throw new Exception("Infinite loop");

            }

            DateTime co = dateOfWeekLoop.Date + vr.CutOff;

            return new TyresAndServiceData.Models.CalculatedCutOff()
            {
                CutOffTime = co,
                FittingFor = co.AddMinutes(vr.FittingIn).AddMinutes(vr.FittingInAdjust ?? 0),
                QueryDate = matchDate,
                WareHouseID = vr.WareHouseID ?? 0
            };

        }


texts: Kill All Connections For Domain Account Users

texts:
I have an application that has hundreds of users. Every now and again we need all users out of the application to run apply a fix on the data in DB (edit tables, causing triggers to be disabled during fix, etc). We don't want to set the DB to SINGLE_USER mode, which would kill the connections and ROLL BACK TRANSACTIONS, since often the work is being done by a third part remotely. So, we wrote the script below to remove Domain users and then set it to RESTRICTED_USER. I'm not overly concerned with performance since the query shouldn't take long, but am concerned with unanticipated results, underlying flaws that I'm not aware of, and what would be best practice in this case.

SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS ON
GO

declare @domain varchar(64) = 'myDomain'

--used to exclude domain logins running on the server, like an agent account, etc...
declare @server varchar(64) = 'theServer'

--create temp to store sp_who2 results
if object_id('tempdb..#Who2') is not null drop table #Who2
create table #Who2 (
                    SPID int,
                    Stat varchar(4000),
                    LoginUser varchar(256),
                    HostName varchar(256),
                    BlkBy varchar(256),
                    DBName varchar(256),
                    Command varchar(4000),
                    CPUTime bigint,
                    DiskIO bigint,
                    LastBatch varchar(64),
                    ProgramName varchar(256),
                    SPID2 int,
                    RequestID int
                    )

--load sp_who2 results
insert into #Who2 exec sp_who2

--delete all users who aren't domain accounts
--remove your SPID from the list to be deleted
--remove anything running locally on the box
delete from #Who2
where
    LoginUser not like + @domain + '%'
    or HostName = @server
    or SPID = @@SPID

--return the logins that will be dropped
select LoginUser as LoginsToBeDropped from #Who2

--cursor for the SPIDs
declare cur cursor fast_forward for
    select
        SPID
    from #Who2

declare @Spid varchar(16)
declare @sql varchar(4000)

--loop through the SPIDs and kill them
open cur
fetch next from cur into @Spid

while @@FETCH_STATUS = 0

    begin
        --select @Spid
        set @sql = 'kill ' + @Spid
        exec(@sql)
        fetch next from cur into @Spid
    end

close cur
deallocate cur
go

--see what connections remain
exec sp_who2


texts:
Are the final templated functions allocate and deallocate thread safe? The Cache object is a thread_local and that also makes FreeList a thread_local, the only parts that I'm still in doubt are the calls to std::malloc and std::free. Are they always thread safe or that depends on the implementation? Is it better to put a lock on them?

I think that the cached memory doesn't need locks since all the objects here are thread_local and each thread has a local copy of it. The only problem really are std::malloc and std::free, are they already synchronized?

Here's a self contained example of all of my code:

#include <iostream>

class FreeList {
    struct Node {
        Node * next;
    };

    Node * this_head;

public:
    static constexpr auto const NODE_SIZE = sizeof(Node);

    FreeList() noexcept
        : this_head() {
    }

    FreeList(FreeList &&) = delete;
    FreeList(FreeList const &) = delete;

    FreeList & operator =(FreeList &&) = delete;
    FreeList & operator =(FreeList const &) = delete;

    void push(void * const address) noexcept {
        auto const head = static_cast<Node *>(address);
        head->next = this_head;
        this_head = head;
    }

    auto pop() noexcept {
        void * const head = this_head;
        if (head) {
            this_head = this_head->next;
        }
        return head;
    }
};

template <uint64_t const SIZE>
class Cache {
    static_assert(SIZE >= FreeList::NODE_SIZE);

    FreeList this_free_list;

public:
    Cache() noexcept
        : this_free_list() {
    }

    Cache(Cache &&) = delete;
    Cache(Cache const &) = delete;

    ~Cache() noexcept {
        while (auto const address = this_free_list.pop()) {
            // Do I need a lock here?
            std::free(address);
        }
    }

    Cache & operator =(Cache &&) = delete;
    Cache & operator =(Cache const &) = delete;

    auto allocate() {
        if (auto const address = this_free_list.pop()) {
            return address;
        }
        // Do I need a lock here?
        if (auto const address = std::malloc(SIZE)) {
            return address;
        }
        throw std::bad_alloc();
    }

    void deallocate(void * const address) noexcept {
        if (address) {
            this_free_list.push(address);
        }
    }
};

template <typename TYPE>
auto & get() noexcept {
    thread_local TYPE local;
    return local;
}

template <typename TYPE>
auto & get_cache() noexcept {
    return get<Cache<sizeof(TYPE)>>();
}

// Are these thread safe?

template <typename TYPE>
auto allocate() {
    auto const address = get_cache<TYPE>().allocate();
    return static_cast<TYPE *>(address);
}

template <typename TYPE>
void deallocate(void * const address) noexcept {
    get_cache<TYPE>().deallocate(address);
}

int main() {

    auto x = allocate<int64_t>();

    *x = 5;

    std::cout << *x << '\n';

    deallocate<int64_t>(x);

}


texts:
Given an expression string exp, write a program to examine whether the
  pairs and the orders of

"{","}","(",")","[","]"

  are correct in exp.

  For example, the program should print true for

exp = "[()]{}{[()()]()}"

  and false for

exp = "[(])"

Complexity:

Time complexity: \$O(n)\$ where \$n\$ is length of string
Space complexity: \$O(\frac{n}{2})\$ where \$n\$ is length of string

I saw the Java version and thought "I want to submit a JavaScript version." Looking for code review, optimizations, and best practices.

In my version, the string can contain other characters than parentheses, "" is accepted as input, and I did not care about short circuiting odd length strings.

function parenthesesAreBalanced(s)
{
  var parentheses = "[]{}()",
    stack = [], //Parentheses stack
    i, //Index in the string
    c; //Character in the string

  for (i = 0; c = s[i++];)
  {
    var bracePosition = parentheses.indexOf(c),
      braceType;
    //~ is truthy for any number but -1
    if (!~bracePosition)
      continue;

    braceType = bracePosition % 2 ? 'closed' : 'open';

    if (braceType === 'closed')
    {
      //If there is no open parenthese at all, return false OR
      //if the opening parenthese does not match ( they should be neighbours )
      if (!stack.length || parentheses.indexOf(stack.pop()) != bracePosition - 1)
        return false;
    }
    else
    {
      stack.push(c);
    }
  }
  //If anything is left on the stack <- not balanced
  return !stack.length;
}

console.log('{}([]) true', parenthesesAreBalanced('{}([])'));
console.log('{{ false', parenthesesAreBalanced('{{'));
console.log('[(]) false', parenthesesAreBalanced('[(])'));
console.log("{}([]) true", parenthesesAreBalanced("{}([])"));
console.log("([}]) false", parenthesesAreBalanced("([}])"));
console.log("([]) true", parenthesesAreBalanced("([])"));
console.log("()[]{}[][]", parenthesesAreBalanced("()[]{}[][]"));


texts:
I created my first "program": a to-do list. I would appreciate it if somebody could look at the code and give me some hints on how to improve it.

var list = document.createElement("ol");
list.id = "list";
list.className = "list";

var addTask = document.getElementById("inputBtn");
addTask.addEventListener('click', function (){

 // checking whether the field is empty
 var task = document.getElementById("task").value;
 if(task=="") alert("Are you sure you do not have any task to do?");
 else
 {
  // adding an element
  addElement (list, task);

  //clear the input field
  document.getElementById("task").value ="";
 }
}, false);

function addElement(ol, text)
{
 var element = document.createElement("li");
 element.id = "element";
 element.className = "element";
 element.appendChild(document.createTextNode(text));
 ol.appendChild(element);
 document.getElementById("board").appendChild(ol);

 //adding a remove button
 addRemoveBtn(element);

 //adding a function which change the decoration of the text
 addCrossStyle(element);
}

function addRemoveBtn(li)
{
 //creating a remove button
 var removeTask = document.createElement("input");
 removeTask.setAttribute("type", "button");
 removeTask.setAttribute("value", "Remove");
 removeTask.setAttribute("class", "remove");

 //remove task function
 removeTask.addEventListener('click', function (){
  li.parentNode.removeChild(li);
 }, false);
 li.appendChild(removeTask);
}

function addCrossStyle(li)
{
 var check = false;

  li.addEventListener('click', function (){
   if (check==false)
   {
     li.style.textDecoration = "line-through";
     li.style.textDecorationColor = "red";
     check = true;
   }
   else
   {
     li.style.textDecoration = "none";
     check = false;
   }
  }, false);
}
body
{
 margin: 0;
 background-color: #26282E;
 color: #b3b3ff;
    font-family: 'Arial', sans-serif;
    font-size: 28px;
}

h1
{
 font-size: 64px;
 font-weight: 400;
 text-align: center;
 letter-spacing: 5px;
 margin-bottom: 0px;
 margin-top: 40px;
}

.addtask
{
 margin-top: 20px;
 text-align: center;
}

input
 {
   margin-top: 10px;
   border: solid;
   padding: 10px;
   font-size: 20px;
   background-color: #b3b3ff;
}

input::placeholder
{
   color: white;
   text-align: center;
}

.inputBtn
{
 background-color: #8080ff;
 margin-top: 20px;
 border: 3px black solid;
    color: white;
    padding: 15px 32px;
    text-decoration: none;
    display: inline-block;
 font-size: 28px;
}

.inputBtn:hover
{
 cursor:pointer;
 background-color: #6b6b99;
}

.list
{
 width: 900px;
 margin: auto;
 background-color: #b3b3ff;
 margin-top: 10px;
 color: white;
}

.remove
{
 background-color: #b30000;
 border: 3px black solid;
 color: white;
    padding: 5px 15px;
 font-size: 12px;
 position: absolute;
 margin-right: 5px;
 right: 0;
 top: 0;
 opacity: 0.7;
}
.remove:hover
{
 cursor: pointer;
 opacity: 1;
 background-color: red;
}

.element
{
 position: relative;
 padding: 15px 32px;
 font-size: 22px;
 word-wrap: break-word;
 padding-bottom: 10px;
 border-bottom: solid #8080ff;
 cursor: pointer;
}

.element:hover
{
 background: #8080ff;
}
<!DOCTYPE html>

 <meta charset="utf-8">
 <title>To Do List</title>
 <meta name="author" content="Szymon Wolny">

 <meta http-equiv="X-Ua-Compatible" content="IE=edge,chrome=1">

 <link rel="stylesheet" href="todo.css">

 To Do List

    <form>

     <input type ="text" name="task" placeholder="New task..." id="task" size="45" >

    </form>
    <button type="button" id="inputBtn" class="inputBtn">Add a new task to the List </button>


texts: A faster implementation of AcceptChanges?

texts:
So I started wondering why it takes 3.5 seconds to AcceptChanges for one changed record in a large DataTable. I wrote another implementation of AcceptChanges (VB.NET) - Me is a DataTable here:

Public Shadows Sub AcceptChanges()
  'this way AcceptChanges is 35 to 700 faster than Microsoft's way
  '35 is a speed factor when all rows were changed, and 700 is when a few
  'Tested on sets of 13K and 65K records
  Dim updatedRows() As DataRow = Me.Select(Nothing, Nothing, _
    DataViewRowState.Added Or DataViewRowState.Deleted Or _
    DataViewRowState.ModifiedCurrent Or DataViewRowState.ModifiedOriginal)
  For Each row As DataRow In updatedRows
    row.AcceptChanges()
  Next
End Sub

It appears to be from 35 to 700 times faster than Microsoft's implementation. Did I just uncover/solve a great mystery of ADO.NET, or am I missing something here?


texts: Remove excessive recurrent code from store and computed

texts:
I have three getters in my store:

getActiveTournaments(state) {
  return state.tournaments.data
    ? state.tournaments.data
      .filter(tournament => tournament.state_value === 'in_progress')
    // sort tournaments by date of creation
      .sort((tournamentA, tournamentB) => tournamentA.created_at - tournamentB.created_at)
    : [];
},
getFutureTournaments(state) {
  return state.tournaments.data
    ? state.tournaments.data
      .filter(tournament => tournament.state_value === 'promo')
    // sort tournaments by date of creation
      .sort((tournamentA, tournamentB) => tournamentA.created_at - tournamentB.created_at)
    : [];
},
getPastTournaments(state) {
  return state.tournaments.data
    ? state.tournaments.data
      .filter(tournament => tournament.state_value === 'finished')
    // sort tournaments by date of creation
      .sort((tournamentA, tournamentB) => tournamentA.created_at - tournamentB.created_at)
    : [];
},

In my component I have a slider which accept an array of three items, each first one from an arrays returned by every getters.
So I created a computed property in my component in order to get these items and then pass them to the slider:

<template>
 ...
 <hovering-image-slider v-if="getLatestTournaments.length > 0"
                         :slideData="getLatestTournaments" />
 ...
</template>

<script>
 ...
 getLatestTournaments() {
  return this.getFutureTournaments[0]
  && this.getActiveTournaments[0]
  && this.getPastTournaments[0]
    ? [
      this.getFutureTournaments[0],
      this.getActiveTournaments[0],
      this.getPastTournaments[0]]
    : [];
},
</script>

It works fine but it seems like an ugly solution. Slider component will get an error of undefined data if I will not check the presence of [0] element in the computed property. I thought that by doing some checking at the level of my getters, it will not require checking in the component but apparently it does. Can you please advice how I can improve this existing code?