texts:
package xml.impl;

import java.io.FileWriter;
import java.io.IOException;
import java.util.HashMap;

public class XMLCreator {

private String parent;
private String child;
private Integer ctr = 0;
private HashMap<Integer, String> xml;
private String root;
private HashMap<Integer, String> roots;
private StringBuilder sB;

private HashMap<Integer, String> getRoot() {
    this.roots.put(1, "<" + root + ">");
    this.roots.put(2, "</" + root + ">");
    return roots;
}

public void setRoot(String root) {
    this.root = root;
}

public XMLCreator() {
    if (this.xml == null) {
        this.xml = new HashMap<Integer, String>();
    }
    if (this.roots == null) {
        this.roots = new HashMap<Integer, String>();
    }
    if (this.sB == null) {
        this.sB = new StringBuilder();
    }
}

/*
 * private void startParentField(String parent) { this.parent = "<" + parent
 * + ">"; this.ctr++; addToXML(getParentField()); }
 *
 * private void endParentField(String parent) { this.parent = "</" + parent
 * + ">"; this.ctr++; addToXML(getParentField()); }
 *
 * public void setParent(String parent) { startParentField(parent);
 * endParentField(parent); }
 */

public void addChildField(String child) {
    this.child = "<" + child + ">" + "</" + child + ">";
    this.ctr++;
    addToXML(getChildField());

}

public void addChildField(String child, String value) {
    this.child = "<" + child + ">" + value + "</" + child + ">";
    this.ctr++;
    addToXML(getChildField());
}

private String getParentField() {
    return parent;
}

private String getChildField() {
    return child;
}

private void addToXML(String element) {
    xml.put(ctr, element);
}

public void buildXMLPreview() {

    // Set<Integer> keys = xml.keySet();
    getRoot();
    System.out.println(roots.get(1));
    sB.append(roots.get(1));
    for (int x = 1; x <= xml.size(); x++) {
        sB.append(xml.get(x));
    }
    sB.append(roots.get(2));
    System.out.println(sB.toString());
    sB.delete(0, sB.length());
}

public void buildXMLToFile() throws IOException {

    FileWriter writer = new FileWriter("try.xml");
    getRoot();
    writer.append(roots.get(1));
    for (int x = 1; x <= xml.size(); x++) {
        writer.append(xml.get(x));
    }
    writer.append(roots.get(2));
    writer.flush();
    writer.close();
}

}

Sample Implementation:

package xml.impl;

import java.io.IOException;

public class XMLCreatorTester {
public static void main(String[] args) throws IOException {
    XMLCreator xmlCreator = new XMLCreator();
    xmlCreator.setRoot("Art");
    xmlCreator.addChildField("name", "Mona Lisa");
    xmlCreator.addChildField("artist", "Leonardo Da Vinci");
    xmlCreator.addChildField("adsa");
    xmlCreator.buildXMLPreview();
    xmlCreator.buildXMLToFile();
}
}

Output:

<Art>
<name>Mona Lisa</name>
<artist>Leonardo Da Vinci</artist>
<adsa></adsa>
</Art>

As you can see as of now I can only create the root element and child elements(note that the parent element implementation is commented out).

Good enough? Suggestions? Violent reactions? Thanks. :)


texts: Setting and clearing setTimeout() inside of an event handler

texts:
I have an event handler function which every time is triggered should clear a setTimeout() and set a new timeout.
Now the callback for the timeout has to take few arguments, for example the event object received by the handler.
And that's it. I did it, but I believe that my solution is not optimal, nor the cleanest:

let timer;

const handler = (event, type) => {

    clearTimeout(timer);

    if(type === 'CHANGE') timer = setTimeout(callback, 500, { argumentsForTheCallBack });
}

As you can see I have my timer as a global variable, even though I need it only in the event handler.
Is there a way to make the handler self-contained?
I am interested in ECMAScript solutions as well as solution using React.js syntax (in my original code the callback is a dispatcher for a useReducer hook)


texts: Printing all prime factors of a number input by the user

texts:
I just started teaching myself to code a few days ago using the Euler problems. I finished a variant of problem 3: print the prime factors of a number input by the user. I just want feedback and code cleaning from someone who knows better than I do to help me progress.

import math

#What is the largest prime factor of the number 600851475143?

n=raw_input('Enter the integer you wish to find the prime factors of: ')

n = int(float(n))
L=[]

def too_small():
        """to be called for int < 4"""
        L.append(n)
        if n>0:
                L.append(1)
        return L

if n < 4: #alg only works for int > 4
        L = too_small()
        print L
        exit()

if n == 4: #because I'm lazy
        L.append(2)
        L.append(2)
        print L
        exit()

def primefactor():
        """prints list of all prime factors for int > 4"""
        test=True
        b=n
        while(test):
                i=2
                while((b%i!=0)&(i<(b/2))): #find next prime
                        i=i+1
                if i>=(b/2): #number is prime
                        L.append(b)
                        L.append(1)
                        test=False
                else: #number is not prime
                        a=(b/i)
                        L.append(i)
                        b=a
        return L

L = primefactor()
print L

exit()


texts: Searching the number with the biggest amount of odd divisors in an interval

texts:
I wrote this program for school (first year in college) and it works, but it's too slow. I wondered if anyone could help me optimize this a bit, because I've been trying and trying, but it just won't get better.

If I choose a lower limit of 5000 and an upper limit of 10000 it my program 10 times longer than my professors code (I did not see his code).

This is for school, but I won't get a grade for this; I'm not even obligated to make it. I just really want to improve.

def askLowerLimit():
    lowerLimit = int(input())
    while lowerLimit <= 0:
        print()
        lowerLimit = int(input())
    return lowerLimit

def askUpperLimit(lowerLimit):
    upperLimit = int(input())
    while upperLimit < lowerLimit:
        print()
        upperLimit = int(input())
    return upperLimit

def amountOddDivisorsOf(number):
    amountOddDivisors = 1
    divisor = 2
    if number % 2 != 0:
        divisor = 3
    for i in range(3, number//divisor +1, 2):
        if number % i == 0:
            amountOddDivisors += 1
    return amountOddDivisors

def numberWithMostOddDivisors(lowerLimit, upperLimit):
    numberWithMostDivisors = lowerLimit
    amountOfNumberWithMostDivisors = amountOddDivisorsOf(numberWithMostDivisors)
    for x in range(lowerLimit + 1, upperLimit + 1):
        amountOfCurrentNumber = amountOddDivisorsOf(x)
        if amountOfCurrentNumber > amountOfNumberWithMostDivisors:
            numberWithMostDivisors = x
            amountOfNumberWithMostDivisors = amountOfCurrentNumber
    return numberWithMostDivisors

def biggestAmmountOddDivisorsInInterval():
    lowerLimit = askLowerLimit()
    upperLimit = askUpperLimit(lowerLimit)
    numberWithMostD = numberWithMostOddDivisors(lowerLimit, upperLimit)
    amountOfOddDivisorsOfNumber = amountOddDivisorsOf(numberWithMostD)
    print("Number with most odd divisors in interval [{0} {1}] is {2}:".format(lowerLimit, upperLimit, numberWithMostD))
    print("{0} has {1} odd divisors!".format(numberWithMostD, amountOfOddDivisorsOfNumber))

biggestAmmountOddDivisorsInInterval()

The problem should be somewhere in amountOddDivisorsOf(number) or numberWithMostOddDivisors(lowerLimit, upperLimit).


texts:
Did I write this code to correctly be tail call optimized? Am I forcing computations more than I need with !? Did I generally write this asynchronously correctly to allow sends and receives to occur in their own time? Is this using multiple threads needlessly? Other general critiques?

open System
open System.Net.Sockets

let asyncGetInput = async { return BitConverter.GetBytes(Console.Read()) }
let rec asyncSendInput (stream : NetworkStream) = async {
    let! input = asyncGetInput
    stream.WriteByte |> Array.map <| input |> ignore
    do! asyncSendInput stream
    }

let asyncGetResponse (stream : NetworkStream) = async { return Char.ConvertFromUtf32(stream.ReadByte()) }
let rec asyncPrintResponse (stream : NetworkStream) = async {
        let! response = asyncGetResponse stream
        Console.Write(response)
        do! asyncPrintResponse stream
        }

#light
[<EntryPoint>]
let main args =
    let client = new System.Net.Sockets.TcpClient()
    client.Connect(args.[0], Int32.Parse(args.[1]))
    printfn "Connected to %A %A..." args.[0] args.[1]
    let stream = client.GetStream()
    printfn "Got stream, starting two way asynchronous communication."
    Async.Parallel [asyncSendInput stream; asyncPrintResponse stream] |> Async.RunSynchronously |> ignore
    0


texts: Game object structure for Minecraft server

texts:
I'm trying to write a Minecraft server in Ruby as an educational project and I've hit the point now where I need to decide on how I am going to structure the in-game objects (entities). In my mind, an Entity is an in-game thing such as a block, or a player, or a skeleton.

The reason this is code review, and not game design, is because I am interested in what you think of the design from a general programming perspective, as this is an open source project and I want it to be as programmer friendly as possible.

When I started writing the current spike, I came up with a few methods I could use for entity structure.

Standard Object-Orientated Programming Inheritance

In this example, I would have used the standard OOP class hierarchy to design my entities. you would have a base class Entity which would be extended by Player, Sign, Skeleton, you get the idea. The upside of this is that it's simple and fast to come up with - until you start wanting to share functionality in two derivatives. Ruby does not have multiple inheritance, so it gets messy when I want an Enderdragon entity to share some functionality with a Sheep. It also limits functionality unless you do a lot of code duplication at runtime if you want to, say, make a Villager controllable by a Player.

Modules and Inheritance

This approach would use modules to share functionality and have it all defined at compile-time. We would have modules such as Positionable, Orirentable, Nameable and a base Entity class would define all of these at compile time in derivatives (for want of a better word - no compiling in Ruby). The advantage of this is that it's more 'clear' to other programmers. Player would have Positionable and RemoteControllable whereas a Sheep might have Positionable. These subclasses are all designed at compile time.

Modules and Meta-Programming

Finally, this one would utilize the Factory (or Builder) pattern to have a similar approach to Modules and Inheritance, except this time, it would define the mixins at runtime. Instances of Entity would be re-opened at runtime and have the appropriate modules mixed-in in their factory. This has the benefit of huge flexibility at the cost of maybe perhaps slightly violating POLA.

I'm currently siding on the side of meta-programming.  What do you think?

module Entity
  # The Id of the Entity
  attr_accessor :id

  def to_s
    "Entity <ID:#{id}>"
  end
end

module Positionable
  attr_accessor :x, :y, :z
end

module Orientable
  attr_accessor :yaw, :pitch
end

module Nameable
  attr_accessor :name
end

entity = Entity.new
entity.extend(Positionable)
entity.extend(Nameable)
entity.extend(Orientable)

entity.x # => 0f


texts:
LINQ Select usually works like this:

IEnumerable<Task<int>> res = new[] {1,2,3}.Select(async i => i);

I would like to have the following though:

IEnumerable<int> res = new[] {1,2,3}.Select(async i => i);

This extension method helps to get it:

static class SelectAsync
{
    public static IEnumerable<TResult> Select<T, TResult>(
        this IEnumerable<T> source, Func<T, Task<TResult>> selector)
    {
        return source
            .ToObservable()
            .Select(value => Observable.FromAsync(() => selector(value)))
            .Concat()
            .ToEnumerable();
    }
}

So the following is true:

public class AsyncSelect_Should
{
    [Test]
    public void Not_Block()
    {
        var src = new[] { 1, 2, 3 };
        var res = src.Select(async i => i);
        CollectionAssert.AreEqual(src, res);
    }
}

There should be something bad, really bad about it. Does it? :)


texts:
I took a training challenge on Codility that checks for the proper nesting of brackets in a string. The brackets to be checked are {,},(,),[,]. I have written the following Java program which passes in O(n) time and space, but I have a feeling that the extra space I use can be reduced. Also I think that there must be a data structure that can handle this scenario more efficiently. Using an ArrayList instead of an array might help. What I need here is a critique of my code.

import java.util.HashMap;
class Solution {
    public int solution(String S) {
        char[] stack = new char[S.length()];
        int last = -1;
        HashMap hm = new HashMap();
        hm.put('}', '{');
        hm.put(')', '(');
        hm.put(']', '[');
        for(int i=0; i<S.length(); i++){
            char next = S.charAt(i);
            if(next == '}' || next == '{' || next == ')' || next == '(' ||
            next == ']' || next == '[')
            {
                if(last!=-1 && hm.containsKey(next) && stack[last] == hm.get(next)){
                    last--;
                }
                else{
                    last++;
                    stack[last] = S.charAt(i);
                }
            }
        }
        if(last == -1){
            return 1;
        }
        return 0;
    }
}


texts: Allowing messages to be passed to listeners

texts:
I have written an implementation of the observer pattern that allows messages to be passed to listeners in what would normally be the notify() method. For example a subscriber sub-class might look like the pseudo-code below, where Message is a simple class that can be subclassed and made to contain value objects or other data.

class MySubscriber extends Subscriber
{
    @Override
    public void notify( Message m )
    {
        if( m.getClass == MyMessage )
        {
            MyMessage myMessage = ( MyMessage ) m;
            if( myMessage.name == MyMessage.START )
            {
                // -- Finally do something here
            }
        }

        if( m.getClass == MyOtherMessage )
        {
            MyOtherMessage myOtherMessage = ( MyOtherMessage ) m;
            if( myOtherMessage.name == MyOtherMessage.INIT_SOMETHING )
            {
                // -- Finally do something else here
            }
        }

    }
}

Using conditionals like this to determine the message type seems a bit redundant and can get tedious in cases where a subscriber is listening for many message types. However, it is pretty explicit, easy to read and the implementation is quite simple. Is there a cleaner approach to achieve a similar result?


texts:
Is there a better way to implement my carousel in less lines?

    <% @photos.each_with_index do |photo, index| %>
      <% if index == 0 %>

        <img src="<%= photo.image_url(:large) %>" alt="<%= photo.title %>">

TITLE

      <% end %>
      <% if index == 1 %>

        <img src="<%= photo.image_url(:large) %>" alt="<%= photo.title %>">

      <% end %>
      <% if index == 2 %>

        <img src="<%= photo.image_url(:large) %>" alt="<%= photo.title %>">

      <% end %>
      <% if index == 3 %>

        <img src="<%= photo.image_url(:large) %>" alt="<%= photo.title %>">

      <% end %>
      <% if index == 4 %>

        <img src="<%= photo.image_url(:large) %>" alt="<%= photo.title %>">

      <% end %>
      <% if index == 5 %>

        <img src="<%= photo.image_url(:large) %>" alt="<%= photo.title %>">

      <% end %>
    <% end %>


texts:
I understand that using eval is extremely dangerous as it can execute deadly commands as an input by the user.

I'm trying to write a code to get a letter grade from a number between 0 to 1. I was trying to write it in the most elegant way. Is this safe?

try:
    score = float(raw_input('Enter score: '))
except Exception as ex:
    print 'Score must be a number!'
    quit()

if score > 1:
    print 'Score must be less than 1'
    quit()

grades = {
    'A': str(score) + '>= 0.9',
    'B': str(score) + '>= 0.8',
    'C': str(score) + '>= 0.7',
    'D': str(score) + '>= 0.6',
    'F': str(score) + '< 0.6',
}

for key in sorted(grades):
    if eval(grades[key]):
        print key
        quit()


texts: Parsing ODataQueryOptions to Expression>

texts:
I am following up on this answer for a scenario that I am currently working on. Like the OP, I am too concerned about the longevity of the code.

public IQueryable<TEntity> EmptyEnumerable()
{
    return Enumerable.Empty<TEntity>().AsQueryable();
}

private Expression<Func<TEntity, bool>> GetFilterExpression(FilterQueryOption filter)
{
    var enumerable = this.EmptyEnumerable();
    var param = Expression.Parameter(typeof(TEntity));
    if(filter != null)
    {
        enumerable = (IQueryable<TEntity>)filter.ApplyTo(enumerable, new ODataQuerySettings());

        var mce = enumerable.Expression as MethodCallExpression;
        if(mce != null)
        {
            var quote = mce.Arguments[1] as UnaryExpression;
            if(quote != null)
            {
                return quote.Operand as Expression<Func<TEntity, bool>>;
            }
        }
    }
    return Expression.Lambda<Func<TEntity, bool>>(Expression.Constant(true), param);
}

My questions are:

Is there anything that I should be checking, which I am not already checking?
Is returning a truth expression a sensible default?

Any refactorings/improvements are welcome.


texts: Validation rules with support for immediate termination of processing

texts:
I am picking up a code smell from this code and I am not sure of the best way to rid myself of it.

I have a validation class that has a function that returns a list of IValidationRule<T> implementations (RuleOne, RuleTwo, RuleThree).

public interface IValidationRule<T>
{
    ValidationRuleResult Validate(T instance);
}

public override ValidationRules<Order> AllRules()
=> new ValidationRules<Order>
{
    Rules =
    {
        RuleOne(),
        RuleTwo(),
        new StopProcessingIfInvalidCheckpoint<Order>(),
        RuleThree()
    }
};

As the rules are iterated through, the IValidationRule<T>.Validate method is called on them.  They will return their results which are added to a collection.

I implemented a class that inherits from IValidationRule<T> called StopProcessingIfInvalidCheckpoint which will cease the processing of any rules following it if any of the rules before it fail.
I felt this was a clean and visual way to kick out of the validation routine early.

What I don't like is that the StopProcessingIfInvalidCheckpoint class has to be passed the same generic as all the other rules around it.  The Validate method on this class is never even called and thus, it does not matter that it knows it's generic is an Order.

Below is the extension method I use to validate a list of rules and you can see where I kick out if I come across the StopProcessingIfInvalidCheckpoint class:

public static ValidationRuleResult Validate<T>(
    this IEnumerable<IValidationRule<T>> validationRules,
    T instance
)
{
    var validationResults = new List<ValidationResult>();

    foreach (var vr in validationRules)
    {
        if (vr is StopProcessingIfInvalidCheckpoint<T> && validationResults.Any()) { break; }
        var result = vr.Validate(instance);
        if (result.IsValid) { continue; }
        validationResults.AddRange(result.ValidationResults);
    }

    var res = new ValidationRuleResult
    {
        ValidationResults = validationResults,
        IsValid = !validationResults.Any()
    };
    return res;
}

How can I improve this code?


texts:
This is one of my first simple javascript projects. Feedback is appreciated! Basically, everytime the select option is changed, the result is shown.

<!DOCTYPE html>

  <meta charset="UTF-8">
  <title>Document</title>

  </select>

    <select onchange="onChange('from'); calculate()" id="selectFrom">
     <option value="Celcius">Celcius</option>
     <option value="Farenheit">Farenheit</option>
     <option value="Kelvin">Kelvin</option>
    </select>
    to
    <select onchange="onChange('to'); calculate()" id="selectTo">
     <option value="Celcius">Celcius</option>
     <option value="Farenheit">Farenheit</option>
     <option value="Kelvin">Kelvin</option>
    </select>

    <input type="text" id="from" onchange="calculate()">  to  <input type="text" id="to">


texts: Read from DataInputStream (Socket connection)

texts:
I am interfacing with a network device and must read a response after I issue a command. Sometimes when I attempt to read, nothing has been returned from the terminal. This means I must wait, but not forever, right?

My solution: Enter a loop with a time comparison guard (time elapsed since start). Then inside, I will check to see if there is anything available to read. If so read it and break of the loop if nothing left.

I couldn't figure out another approach. Having a while loop on the number of bytes read was fine up to the point where there was no data left, in which case it would just wait until the timeout to occur. My way will return as soon as everything has bead read or else timeout occurs.

Does this make sense? I currently have the timeout set to 10 seconds.

private Socket socket;
private DataInputStream reader;
private DataOutputStream writer;

socket = new Socket(device.getHostAddress(), device.getHostPort());

socket.setSoTimeout((int) READ_TIMEOUT_MILLIS);

reader = new DataInputStream(socket.getInputStream());
writer = new DataOutputStream(socket.getOutputStream());

writer.write(data.getBytes(ENCODING_CHARSET));
writer.flush();

ByteArrayOutputStream bufferStream = new ByteArrayOutputStream();

byte[] buffer = new byte[1024];

long opStartMillis = System.currentTimeMillis();

while(System.currentTimeMillis() - opStartMillis < READ_TIMEOUT_MILLIS) {

    if(reader.available() > 0) {

        int bytesRead = reader.read(buffer);

        bufferStream.write(buffer, 0, bytesRead);

        if(reader.available() == 0) {

            break;
        }
    }
}

callback.dataReceived(bufferStream.toString(ENCODING_CHARSET));


texts: Finding two numbers that add to a given total

texts:
Given there's a list of random number and the amount I want to find.

For example:

  [80, 98, 83, 92, 1, 38, 37, 54, 58, 89]

And I want two numbers that add up to a given total in this case it's 181. So, it's going to be (92+89). The list could be really big.

Here's the solution I come up with. But it's kinds brute force and I was wondering if there's a better way of doing this.

for i, item in enumerate(numbers):
    for j in range(i+1, len(numbers)):
        total_of_two_items = numbers[i] + numbers[j]
        if(total_of_two_items == total_number):
            print '{first_item} {second_item}'.format(first_item=i+1, second_item=j+1)
            print '\n'


texts:
I've put together this extremely simple text diff function a while ago:

function diff($old, $new) {
    $old = trim($old);
    $new = trim($new);

    if($old == $new) {
        return $new;
    }

    $old    = explode(" ", $old);
    $new    = explode(" ", $new);
    $result = "";
    $length = max(count($old), count($new));

    for($i = 0; $i < $length; $i++) {
        if(!isset($new[$i])) {
            $result .= "{$old[$i]}";
            continue;
        }

        if(!isset($old[$i])) {
            $result .= "{$new[$i]} ";
            continue;
        }

        if($old[$i] != $new[$i]) {
            $result .= "{$old[$i]}{$new[$i]} ";
            continue;
        }

        $result .= "{$new[$i]} ";
    }

    $result = str_replace(array(" ", " "), " ", $result);

    return trim($result);
}

$string1 = "Hello World!! Please review my diff function. Be gentle.";
$string2 = "Hello world! Please critique my diff function. Be extra vigilant.";

echo diff($string1, $string2);
// Hello World!!world! Please reviewcritique my diff function. Be gentle.extra vigilant.

The html output is:

  Hello World!!world! Please reviewcritique my diff function. Be gentle.extra vigilant.

The purpose of the function wasn't something important, as I can't even remember why I built it (found in my sandbox directory, which is full of little experiments). Is it any good? I've always used PEAR Text_Diff for text diffs, but if I'm not doing anything inherently wrong in my simple function, I'd love to use it instead.

Any suggestions on an easy way to move html out of the function?


texts: Usertool to Edit Forum Members from Desktop

texts:
I've created a Forum website tool for admins to add, edit, and delete users from their desktop, saving to a file, and uploading the file to the database, the program is not completed I'm posting it here for review thus far

(People I'm creating it for would prefer me not having access to database, I understand I would be using activerecord model/structure if I where saving directly to the database.)

What the program does is simple:

It prompts the user for which he/she would like to do via add, edit,
delete users.
The program then runs through a case statement of available options
and if the option isn't found it exits the program
In the add_user method the program saves the input of the user into a YAML file, and prompts the user for more users, if none follow exits the program.
During the delete_user method, the program does the same as adding except deletes the users from the YAML file there is a bug where the program deletes the entire YAML file, not just the edited users
In the edit_user the program will edit various elements of the hash inside the YAML file and save over the old element of the file. Not ready yet will post follow up later

  The edit user section hasn't been setup yet, still working out the kinks in delete_user method.

So what I'm looking for is:

A possible explanation of why the delete_user method wipes the
entire file and not just the user entered, is this because I'm deleting
the entire section and not just the users input?
Would using a JSON file be better then using a YAML file, I'm aware
that A LOT of websites don't support YAML's so would it be a good idea to convert the require 'yaml' to a require 'json' and regroup from there?
Any possible areas of improvement? Meaning do you notice anything
right off the bat that should be changed, can my syntax be updated or more developed?

Source Code:

#!/usr/bin/env ruby

require 'yaml'
require 'open-uri'

def menu
    print "Welcome to User Menu. Would you like to [A]dd users, [D]elete users, [E]dit users, [V]iew all users, or [Q]uit the system?\n"
    input = gets.chomp!
    case input
    when /a/i
        add_user
    when /d/i
        delete_user
    when /e/i
        edit_user
    when /v/i
        view_all
    else
        puts "Exiting system.."
        exit
    end
end

def add_user
    puts "Please enter Username:"
    username = gets.chomp
    data = {username: username}
    puts "Please enter user Email:"
    email = gets.chomp
    data[:email_address] = email
    puts "Please enter users status(member, vip, gold, etc..):"
    status = gets.chomp!
    data[:member_status] = status
    File.open('users.yml', 'a') { |s| s.write(data.to_yaml) }
    add_user if restart
end

def delete_user
    puts "Enter Username:"
    username = gets.chomp
    delete_data = {username: username}
    puts "Enter Email:"
    email = gets.chomp
    delete_data[:email_address] = email
    puts "Enter Status:"
    status = gets.chomp
    delete_data[:status] = status
    hash = YAML.load_file('users.yml')
    hash.delete("#{username}")
    hash.delete("#{email}")
    hash.delete("#{status}")
    File.open('users.yml', 'w') { |f| YAML.dump(delete_data.to_yaml) }
    delete_user if restart
end

def edit_user
    edit_user if restart
end

def view_all
    content = URI('#Website URL here taken out for security of site').read
end

def restart
    puts "Would you like to edit another user?"
    input = gets.chomp
    if input =~ /yes/i
        return true
    else
        puts "Exiting program.."
        exit
    end
end
menu

Overview of YAML file:

---
:username: TEST
:email_address: TEST
:member_status: TEST


texts: The correct way to calculate MIPs of a function on a microcontroller

texts:
I want to calculate MIPs of a function on a microcontroller. Here is how I do it.
1. keil setting. Use Simulator and Xtal = 25MHz

Run simulator in debug mode.

As you can see, it takes 200ms to run fun() once.
200ms(0.2s) * 25MHz = 5M. Does it mean that running fun() takes 5MIPs?
One thing to note that the MIPs of fun() is independent of platform or crystal's oscillation frequency.
Thank you.


texts: Algorithm optimization on date calculation

texts:
I need to calculate the calendar week of a given date. Constraints:

It should be properly calculated based on ISO 8601 if week starts on
Monday
It should calculate based on US standards if the week starts on
Sunday
It should be compact and fast, as the routine gets called very often
It should work even if the year start is not January (Fiscal Year starts on October for instance)

That's what I have currently:

Date.prototype.getWeek = function() { // ISO Week

    this.firstDay = 4;  // ISO 8601: Week with the first thursday which contains the 4th of January
    this.thursday = 4;  // 0 = Sunday OR Monday (if WeekStart = "M")

    if ( this.weekStart != 'M' )
    {
        this.firstDay = 1;  // switch to US norm: Week with the 1st of January
        this.thursday = 0;
    }

    // finding the date of the "thursday" in this week
    var donnerstag = function(datum, that) {
        var Do = new Date(datum.getFullYear(), datum.getMonth(),
                   datum.getDate() - datum.getDay() + that.thursday, 0, 0, 0);
        return Do;
    };

    // copy date, hourly times set to 0
    var Datum = new Date(this.getFullYear(),this.getMonth(),this.getDate(), 0, 0, 0);

    var DoDat = donnerstag(Datum, this);        // the date of the first week
    var kwjahr = DoDat.getFullYear();           // the year of that date

    // diff from there to this date
    var DoKW1 = donnerstag(new Date(kwjahr, this.FYStart, this.firstDay), this);
    //console.log(DoDat + " - " + DoKW1);

    // calculate the week
    var kw = Math.floor(1.5+(DoDat.getTime()-DoKW1.getTime())/86400000/7)

    // adjust overflow
    if ( kw < 1 )
        kw = 52 + kw;

    return kw;
};

Is there any more compact algorithm or can this be optimized in terms of performance?


texts: Neatest way to filter an array of strings by another array in ruby

texts:
I have an array of strings which are file names files, and an array of allowed file types or suffixes allowed_types. I want to filter out files which don't end with an allowed suffix.

This does the trick, but I'm wondering if anyone can suggest a neater solution? Such as a way keep with ruby's usual streamlined style without using flag variables.

valid_files = Dir.entries(path).select do |f|
  valid = false
  allowed_types.each { |suffix| next valid = true if f.end_with? suffix }
  next valid
end


texts: RPG Skeleton, Part 2 - The Entity, and a SpecType

texts:
This question is a followup to Simple RPG skeleton, Part 1 - The Character.

This is the second "part" of my development of this skeleton, and it now includes two new classes, Entity, and SpecType. The Entity class essentially serves as a base class for any character-like object, and has the following attributes and methods:

name - The name of the entity.
health - How much health the entity has.
toString() - Return a string representation of the entity.

The SpecType class serves as a small utility class for creating number-related specs that apply to character-like object, and has the following attributes and methods:

specValue - The value of the spec itself.
changeValue() - Change the value of the spec, and make sure it stays in the range \$0\rightarrow\infty\$.

I'm wondering the following things:

Should SpecType be an immutable class? Right now, it's just modifying itself when changeValue is called.
Is the Entity class designed in an appropriate way?
Am I following standard C++ practices?

entity.h

#ifndef RPGGAME_ENTITY_H_
#define RPGGAME_ENTITY_H_

#include <string>
#include "spectype.h"

/// <summary>
/// A base class that represents an entity, and implements
/// some base attributes, like health or name, and a few helper
/// methods for apply damage.
/// </summary>
class Entity
{
public:
    std::string name;
    SpecType    health;

    Entity(const std::string& name, SpecType health);
    std::string toString();
};

#endif

entity.cpp

#include <string>
#include <random>
#include "entity.h"

/// <summary>
/// Constructor for the Entity class.
/// </summary>
/// <param name="name">The name of the entity.</param>
/// <param name="health">The health of the entity.</param>
Entity::Entity(const std::string& name, SpecType health):
    name(name),
    health(health)
{}

/// <summary>
/// Return a string value representing the entity.
/// </summary>
/// <remarks>
/// This is mostly not used unless a raw Entity is being
/// used by itself, which should be very uncommon, or not
/// happen at all.
/// </remarks>
std::string Entity::toString()
{
    return "Name: "   + name                             + ", " +
           "Health: " + std::to_string(health.specValue) + "\n";
}

spectype.h

#ifndef RPGGAME_SPECTYPE_H_
#define RPGGAME_SPECTYPE_H_

/// <summary>
/// The SpecType class describes a non-constant unsigned
/// integer spec that can be used in any entity-derived class.
/// or structure.
/// </summary>
class SpecType
{
public:
    int specValue;

    SpecType(int specValue);
    void changeValue(int value);
};

#endif

spectype.cpp

#include "spectype.h"

/// <summary>
/// Constructor for the SpecType class.
/// </summary>
/// <param name="specValue">The value that the SpecType contains.</param>
SpecType::SpecType(int specValue):
    specValue(specValue)
{}

/// <summary>
/// Change the Spec's value by a certain amount.
/// <summary>
/// <param name="value">The value to change specValue by.</param>
void SpecType::changeValue(int value)
{
    if (specValue + value >= 0) { specValue += value; }
    else { specValue = 0; }
}

main.cpp (tests)

#include <iostream>
#include "spectype.h"
#include "entity.h"

int main()
{
    SpecType testSpec1(0);
    testSpec1.changeValue(10);
    testSpec1.changeValue(-11);
    std::cout << testSpec1.specValue << "\n";

    SpecType testSpec2(51);
    testSpec2.changeValue(-2143);
    testSpec2.changeValue(10);
    std::cout << testSpec2.specValue << "\n";

    std::cin.get();

    Entity testEntity1("FooBarBlahName", 30);
    std::cout << testEntity1.toString();

    Entity testEntity2("Goku", 9001);
    std::cout << testEntity2.toString();

    std::cin.get();
}


texts:
I had this code repeated in many Actions:

    public ActionResult History(int? patientId)
    {
        if (patientId == null)
        {
            return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
        }

        var patient = patientService.GetPatient(patientId.Value);

        if (patient == null)
        {
            return HttpNotFound();
        }
       ...
    }

So I extracted a method to:

    private ActionResult CheckPatientId(int? patientId, ref Patient patient)
    {
        if (patientId == null)
        {
            return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
        }

        patient = patientService.GetPatient(patientId.Value);

        if (patient == null || patient.PharmacyId != User.PharmacyId())
        {
            return HttpNotFound();
        }

        return null;
    }

Which I call like so:

 var patient = new Patient();
            if (CheckPatientId(patientId, ref patient) != null)
            {
                return CheckPatientId(patientId, ref patient);
            }

I don't like that I have to call CheckPatient twice if it fails and the returning of null - is there a better way to do this or is it ok?


texts: Removing objects from a list that don't appear in a list of ID's

texts:
I have a list of objects with each of them having an ID. I have a second list that is just a list of media ID's. I want to remove the objects from the first list that don't match a mediaID contained in the second list. What is an efficient way of going about this? The only way I could think of was to have a nested for loop but that seems inefficient.

Here is my implementation. Note that "items" is the first list, containing MediaDetailsItem objects, with each of these objects having a specific mediaId. The second list is mediaIds.

List<MediaDetailsItem> shortenedList = new ArrayList<MediaDetailsItem>();
                        for(MediaDetailsItem item : items){
                            for(String id : mediaIds){
                                if(item.getMediaId().equals(id)){
                                    shortenedList.add(item);
                                    break;
                                }
                            }
                        }
                        items.clear();
                        items.addAll(shortenedList);


texts: Pass class property as parameter to extension method

texts:
I have the following class structure:

MyAttribute.cs

public sealed class MyAttribute : Attribute
{
    public MyAttribute(string name)
    {
        if (string.IsNullOrEmpty(name))
        {
            throw new ArgumentNullException(nameof(name));
        }

        Name = name;
    }

    public string Name { get; }
}

Matrix.cs

public class Matrix
{
    [MyAttribute("awesome_name")]
    public string AwesomeName { get; set; }
}

And we make an method to "extract" the value defined on name of MyAttribute:

AttributeExtensions.cs

public static class AttributeExtensions
{
    public static string GetMyAttributeNameOfProperty<TClass>(Expression<Func<TClass, object>> expression)
    {
        if (expression.Body is MemberExpression memberExpression)
        {
            var propertyInfo = (PropertyInfo)memberExpression.Member;

            var hasMyAttribute = propertyInfo.IsDefined(typeof(MyAttribute), false);

            if (hasMyAttribute)
            {
                return propertyInfo.GetCustomAttribute<MyAttribute>().Name;
            }
        }

        return default;
    }
}

Finally, we call this way:

AttributeExtensions.GetMyAttributeNameOfProperty<Matrix>(exp => exp.AwesomeName)

This call, returns: "awesome_name"

We have some doubts:

Exists an more "clean" way to pass the property of <TClass>(exp.AwesomeName) to this extension method?
We really need of Expression<>? It's possible to make this only with Func<TClass, object>?

Like:

GetMyAttributeNameOfProperty<TClass>(Func<TClass, object> expression)

Any suggestions?


texts:
The task: sort the characters in a string, as provided by the ICU UnicodeString. This is because I want to be able to find anagrams using the suggestion from "Programming Pearls", which is, find "signatures" for each word in the dictionary, then sort according to these. It is enough if it works for the European languages and scripts.

The input file is for example the word list found in /usr/share/dict/words. For now, I just read from standard input, print them to standard output, sort the characters in the word, and print the sorted word:

$ cat sort-each-word.cpp
#include <iostream>
#include <algorithm>
#include "unicode/ustream.h"
#include "unicode/unistr.h"
#include "unicode/schriter.h"

int main()
{
    icu::UnicodeString word;
    while (std::cin >> word) {
        std::cout << word << '\t';
        auto n = word.length();
        UChar *begin = word.getBuffer(n+1);
        UChar *end = begin + n;
        std::sort(begin, end);
        *(begin+n) = 0;
        word.releaseBuffer(n);
        std::cout << word << '\n';
    }
}

To compile it:

g++  -pedantic -Wall -O2 --std=c++0x    -L/usr/lib -licui18n -licuuc -licudata   -licuio   sort-each-word.cpp   -o sort-each-word

Then, for example:

$ cat naivete
naiveté
$ < naivete ./sort-each-word
naiveté aeintvé

I feel most uncomfortable about getBuffer(n+1), where n is the current string length. I need the extra space to terminate the sorted string, but must I check that length() + 1 =< getCapacity()?

Other suggestions and comments are of course most welcome.


texts:
The following code writes a 16x16 bitmap to a framebuffer using up to AVX2 instuctions.  I'm sure it can be improved with AVX512 but I'm only interested in improvements using AVX2 and below.  Specifically, I want to know if there is a more efficient way of doing it.  Each bit in the bitmap represents a pixel and requires a dword attribute to be written.  Each 2 byte word of the 32 byte data does one 16 pixel row for a total of 16 rows.  The below code does 8 loads and 32 stores for each 16x16 written.

FColor  dd  0x00ffffff  ; white
BColor  dd  0x000000ff  ; blue

ALIGN 32
bitshift_to_MSB   dd 24, 25, 26, 27, 28, 29, 30, 31

; 95 * 32 byte bitmaps (SPACE to '~')

CH_ARIAL db 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
.
.
.
0x00,0x00,0x00,0x00,0x02,0x00,0x02,0x00,0x02,0x00,0x02,0x00,0x02,0x00,0x02,0x00,0x02,0x00,0x02,0x00,0x02,0x00,0x02,0x00,0x00,0x00,0x02,0x00,0x00,0x00,0x00,0x00,

    ; rdi = framebuffer address to write to
    ; edx = printable ascii character (assumed to be between 32 and 126
    sub     edx, 32
    shl     edx, 5
    mov     ecx, 8

    vpbroadcastd    ymm4, [FColor]
    vpbroadcastd    ymm3, [BColor]
    vmovdqa         ymm2,  yword [bitshift_to_MSB]
@@:
    vpbroadcastd    ymm0, dword [CH_ARIAL + edx]        ; broadcasts dword (32 bits, for 2 x 16 pixel rows)
    vpsllvd         ymm1, ymm0, ymm2                    ; shifts left according to ymm2 to set dword MSB based on 1st byte
    vblendvps       ymm1, ymm3, ymm4, ymm1              ; set dwords in ymm1 = (each dword MSB)?ymm4:ymm3
    vmovdqa         [rdi], ymm1

    vpsrld          ymm0, ymm0, 8                       ; shift 2nd byte of each dword to first position
    vpsllvd         ymm1, ymm0, ymm2
    vblendvps       ymm1, ymm3, ymm4, ymm1
    vmovdqa         [rdi+32], ymm1

    add     rdi, 1920*4                                 ; mov down to next row of pixels

    vpsrld          ymm0, ymm0, 8
    vpsllvd         ymm1, ymm0, ymm2
    vblendvps       ymm1, ymm3, ymm4, ymm1
    vmovdqa         [rdi], ymm1

    vpsrld          ymm0, ymm0, 8
    vpsllvd         ymm1, ymm0, ymm2
    vblendvps       ymm1, ymm3, ymm4, ymm1
    vmovdqa         [rdi+32], ymm1

    add     edx, 4
    add     rdi, 1920*4
    dec     ecx
    jnz     @b


texts: Singly linked list implementation in python 3

texts:
I have implemented a Singly linked list. It works well. But if you think something needs to be improved, say it. This code was tested in Python 3.7.4.

class Node(object):

    def __init__(self, data):
        self.data = data
        self.nextNode = None

class LinkedList(object):

    def __init__(self):
        self.head = None
        self.size = 0

    # O(1) !!!
    def insertStart(self, data):

        self.size = self.size + 1
        newNode = Node(data)

        if not self.head:
            self.head = newNode
        else:
            newNode.nextNode = self.head
            self.head = newNode

    def remove(self, data):

        if self.head is None:
            return

        self.size = self.size - 1

        currentNode = self.head
        previousNode = None

        while currentNode.data != data:
            previousNode = currentNode
            currentNode = currentNode.nextNode

        if previousNode is None:
            self.head = currentNode.nextNode
        else:
            previousNode.nextNode = currentNode.nextNode

    # O(1)
    def size1(self):
        return self.size

    # O(N)
    def insertEnd(self, data):

        self.size = self.size + 1
        newNode = Node(data)
        actualNode = self.head

        while actualNode.nextNode is not None:
            actualNode = actualNode.nextNode

        actualNode.nextNode = newNode

    def traverseList(self):

        actualNode = self.head

        while actualNode is not None:
            print(actualNode.data)
            actualNode = actualNode.nextNode


texts:
I have been struggling with a regular expression involving path names.  Immediately, this is a bit troublesome, owing to the embedded / in the pattern,  but braces to the rescue.

First the convention I have imposed:

Every path in the set looks like:

/ifmxdev/files/file.0123

but that top directory can take a suffix, for example:

/ifmxdev_test/files/file.8765

The final suffix is exactly 4 digits

After much struggle and an hour of composing this plea, as well as my own thoughts, I came up with a truly ugly but working pattern:

$rawfile_pattern = qr{/ifmxdev[_0-9A-Za-z]*/files/file.\d{4}};
if (! $fname =~ $rawfile_pattern) {....

Now I'd just like some help in making that pattern more elegant, mainly compacting that bracketed section of the regex.


texts: Printing primes between user-given numbers

texts:
I want to display all the prime numbers between two integers taken from the user as input. Also I have to take a user input to specify the number of times the loop should run. Here is the Java code that I have written. I have to now reduce the run-time.

 import java.util.Scanner;

    public class Main{
        private static Scanner x;

        public static void main(String[] args) {
            Scanner x = new Scanner(System.in);
            int num = x.nextInt();
            for (int t = 1; t <= num; t++) {
                int m = x.nextInt();
                int n = x.nextInt();

                if (m >= 1 && n <= 1000000000 && n - m <= 100000) {
                    for (int current = m; current <= n; current++) {
                        int sqr_root = (int) Math.sqrt(current);
                        boolean is_prime = true;
                        for (int i = 2; i <= sqr_root; i++) {
                            if (current % i == 0) {
                                is_prime = false;
                            }
                        }
                        if (is_prime) {
                            System.out.println(current);
                        }
                    }
                }
            }
        }
    }


texts:
Below is my attempt at the beginnings of a reusable ado.net data access class.  Please let me know of any improvements that I could make.

Thanks!

public class DataAccess : IDisposable
{
    public DbProviderFactory Factory { get; set; }
    public string Connection { get; set; }
    public string ProviderName { get; set; }

    public DataAccess()
    {
        Get_ConnectionString_From_AppSettings();
        Get_ProviderName_From_AppSettings();
    }

    private void Get_ConnectionString_From_AppSettings()
    {
        this.Connection = ConfigurationManager.AppSettings.Get("Database");
    }

    private void Get_ProviderName_From_AppSettings()
    {
        this.ProviderName = ConfigurationManager.AppSettings.Get("DBProvider");
    }

    public DataTable Connection_Return_DataTable( string sql)
    {
        DbConnection connection = null;

            try
            {
                DbProviderFactory factory = DbProviderFactories.GetFactory(this.ProviderName);
                this.Factory = factory;
                connection = Factory.CreateConnection();
                connection.ConnectionString = Connection;
                DataTable dt = FillDataTable(connection, sql);
                return dt;
            }
            catch (DataException ex)
            {
                Debug.WriteLine(ex.ToString());
                throw;
            }
            finally
            {
                connection.Close();
                connection.Dispose();
            }
    }

    private DataTable FillDataTable(DbConnection connection, string sql)
    {
        DbCommand command = connection.CreateCommand();
        command.CommandText = sql;
        command.Connection = connection;

        DbDataAdapter adapter = this.Factory.CreateDataAdapter();
        adapter.SelectCommand = command;

        DataTable table = new DataTable();
        adapter.Fill(table);

        return table;
    }

    public void Dispose()
    {
        this.Factory = null;
        this.Connection = null;
        this.ProviderName = null;

    }
}


texts:
I have a Winforms MVP application where I need to use the ErrorProvider on the view. I have added the following methods to my presenter to allow me to show the ErrorProvider but it just doesn't feel right. Please review my code and tell me if you think there is a more efficient way of carrying out the validation.

private bool IsValid(string sender)
{
    bool isValid = true;

    ResetValidation();

    //FilePath Validation
    if(!ValidationService.StringHasValue(_view.FilePath))
    {
        _view.SetFilePathErrorMessage(Messages.FieldRequired);
        isValid = false;
    }

    if (sender == "OnImportClicked") return isValid;

    //BatchRef Validation
    if (!ValidationService.StringHasValue(_view.BatchRef.ToString()))
    {
        _view.SetBatchRefErrorMessage(Messages.FieldRequired);
        isValid = false;
    }

    //Transfer Validaion
    if(!_transferredToHoldingTable)
    {
        _view.SetTransferErrorMessage(Messages.NoRawData);
        isValid = false;
    }

    return isValid;
}

private void ResetValidation()
{
    _view.SetFilePathErrorMessage(string.Empty);
    _view.SetBatchRefErrorMessage(string.Empty);
    _view.SetTransferErrorMessage(string.Empty);
}


texts: Achieve error differentiation in Promises

texts:
Background

I have a REST API using MongoDB, Node.js and Express that makes a request to my NoSQL DB and depending on different results, I want to differentiate which error I send the customer.

Problem

The current version of my code has a generic error handler and always sends the same error message to the client:

api.post("/Surveys/", (req, res) => {
        const surveyJSON = req.body;
        const sender = replyFactory(res);

        Survey.findOne({_id: surveyJSON.id})
            .then(doc => {
                if(doc !== null)
                    throw {reason: "ObjectRepeated"};

                //do stuff
                return new Survey(surveyJSON).save();
            })
            .then(() => sender.replySuccess("Object saved with success!"))
            .catch(error => {
                /*
                 * Here I don't know if:
                 * 1. The object is repeated
                 * 2. There was an error while saving (eg. validation failed)
                 * 3. Server had a hiccup (500)
                 */
                sender.replyBadRequest(error);
            });
    });

This is a problem, because the client will always get the same error message, no matter what and I need error differentiation!

Research

I found a possible solution, based on the division of logic and error/response handling:

https://stackoverflow.com/questions/26076511/handling-multiple-catches-in-promise-chain

However, I don't understand a few things:

I don't see how, at least in my example, I can separate the logic from the response. The response will depend on the logic after all!
I would like to avoid error sub-classing and hierarchy. First because I don't use bluebird, and I can't subclass the error class the answer suggests, and second because I don't want my code with a billion different error classes with brittle hierarchies that will change in the future.

My idea, that I don't really like either

With this structure, if I want error differentiation, the only thing I can do is to detect an error occurred, build an object with that information and then throw it:

.then(doc => {
    if(doc === null)
        throw {reason: "ObjectNotFound"};

    //do stuff
    return doc.save();
})
.catch(error => {
    if(error.reason === "ObjectNotFound")
        sendJsonResponse(res, 404, err);
    else if(error.reason === "Something else ")
        sendJsonResponse(/*you get the idea*/);
    else //if we don't know the reasons, its because the server likely crashed
        sendJsonResponse(res, 500, err);
});

I personally don't find this solution particularly attractive because it means I will have a huge if then else chain of statements in my catch block.

Also, as mentioned in the previous post, generic error handlers are usually frowned upon (and for a good reason imo).

Questions

How can I improve this code?


texts:
I've started learning F# and functional programming in general, but the code I wrote doesn't seems to be really functional. Could you take a look and say how to make it more as it should be in functional programming?

type internal CsvReader(source : Stream) =

    // input stream
    let stream = source

    // reader
    let mutable reader : StreamReader = new StreamReader(source)

    [<Literal>]
    let bufferSize = 1000

    // currently processed line
    let mutable buffer : char[] = Array.zeroCreate bufferSize

    // current position
    let mutable currentPosition : int = bufferSize

    // end of file
    let mutable EndOfFile : bool = false

    // loads new chunk of data from file to buffer
    let UpdateBuffer() : bool =
        match reader.ReadBlock(buffer, 0, buffer.Length) with
        | 0 -> false
        | _ -> true

    // initialization method
    let Initialize() =
        let pos = source.Seek(0L, SeekOrigin.Begin)
        if not (pos = 0L) then raise(Exception("sdf"))
        ()

    // read one char from stream
    let rec GetChar(eat : bool) : (bool * char) =
        let position = currentPosition
        match position with
        | 1000 ->
            match UpdateBuffer() with
            | false ->
                EndOfFile <- true
                (false, Char.MinValue)
            | true -> currentPosition <- 0; GetChar(eat)
        | _ ->
            let item = System.Convert.ToInt32(buffer.[position])
            match item with
            | 0 -> (false, Char.MinValue)
            | _ ->
                match eat with
                | true ->
                    currentPosition <- currentPosition + 1;
                    (true, buffer.[position])
                | false ->
                    (true, buffer.[position])

    // default constructor logic
    do
        if Utils.IsNull source then raise(ArgumentNullException("source"))
        if not source.CanRead then raise(ArgumentException("source"))
        if not source.CanSeek then raise(ArgumentException("source"))

        Initialize()

        ()

    // parameterless constructor
    // always throws ArgumentNullException
    private new() = CsvReader(null)

    // just for testing
    member x.PublicGetChar = GetChar

Right now the only think it does it stream content of Stream char by char by PublicGetChar method. I wrote UT to make sure it works:

[<TestClass>]
type CsvReaderTests() =

    let GetStringStream(input : string) : Stream =
        let stream = new MemoryStream()
        let writer = new StreamWriter(stream)
        ignore(writer.Write(input))
        writer.Flush()
        stream.Position <- 0L
        stream :> Stream

    [<TestMethod>]
    member this.TestMethod1 () =
        let input = "test"
        let reader = new CsvReader(GetStringStream(input))
        let chars = seq { while fst(reader.PublicGetChar(false)) do yield snd(reader.PublicGetChar(true)) }
        let output = (new System.String(chars |> Array.ofSeq))
        input |> should equal output

Main concerns I have about the code:

usage of match/with
a lot of mutable stuff within CsvReader type
if I had to write it in C# it would look really similar :D

That's the very first F# code I've ever written, so be polite, please :)


texts:
I wrote some code in Python, to benchmark mathematical operations. It does not do anything in particular besides just calculating a lot of floating point numbers.

To clarify: I need 128-bits precision floating point numbers.

from __future__ import division
from numpy import arctan, sin, absolute, log10
from mpmath import *
import time
imax = 1000001
x = mpf(0)
y = mpf(0)
z = mpf(0)
t = mpf(0)
u = mpf(0)
i = 1
mp.prec = 128
start_time = time.time()
while i < 1000001:
    i += 1
    x = mpf(x + 1)
    y = mpf(y + x * x)
    z = mpf(z + sin(y))
    t = mpf(t + absolute(z))
    u = mpf(u + log10(t))

print("--- %s seconds ---" % (time.time() - start_time))
print x
print y
print z
print t
print u

This took approximately 87 secs to print results. How can I improve this code? My friend in fortran wrote similar program and it took only 3.14 secs for him to  print results in 128-bit precision.

Also in general I want to improve speed of my code. Instead 87 secs I want to reach times much closer to fortran.


texts:
I have recently started code kata and learning for myself, as I would like to
learn test-first development. I have started doing a shopping cart as my code kata. I have included a test as well.  I would like to know what are the ways I could improve my below code.  I know I need to use dependency injection next step. If you find anything I can improve in my code, please let me know.

using System.Collections;
using System.Collections.Generic;
using System.Linq;
using NUnit.Framework;

namespace Domain.Tests.Shopping_Cart_Tests
{
    [TestFixture]
    public class ShoppingCartTest
    {
        private IShoppingCart _shoppingCart;

        [SetUp]
        public void SetUp()
        {
            _shoppingCart = new ShoppingCart();
        }

        [Test]
        public void ShouldBeAbleToAddToCart()
        {
            var item1 = new CartItem{ProductId="P1001",Name = "Logitech Mouse", Qty = 1, Price = 5.00};

            _shoppingCart.AddToCart(item1);

            Assert.AreEqual(_shoppingCart.GetCartItems().Count, 1);
        }

        [Test]
        public void ShouldBeAbleToAddToCartMultipleItems()
        {
            var item1 = new CartItem { ProductId = "P1001", Name = "Logitech Mouse", Qty = 1, Price = 5.00 };
            var item2 = new CartItem { ProductId = "P1002", Name = "Logitech Keyboard", Qty = 1, Price = 9.00 };

            _shoppingCart.AddToCart(item1);
            _shoppingCart.AddToCart(item2);

            Assert.AreEqual(_shoppingCart.GetCartItems().Count, 2);
        }

        [Test]
        public void ShouldBeAbleToIncrementWhenAddTheSameItem()
        {
            var item1 = new CartItem { ProductId = "P1001", Name = "Logitech Mouse", Qty = 1, Price = 5.00 };
            var item2 = new CartItem { ProductId = "P1001", Name = "Logitech Mouse", Qty = 2, Price = 5.00 };
            var item3 = new CartItem { ProductId = "P1001", Name = "Logitech Mouse", Qty = 3, Price = 5.00 };

            _shoppingCart.CheckItemExistThenAddToCart(item1);
            Assert.AreEqual(_shoppingCart.GetCartItems().Count, 1);
            _shoppingCart.CheckItemExistThenAddToCart(item2);
            Assert.AreEqual(_shoppingCart.GetCartItems().Count, 1);
            _shoppingCart.CheckItemExistThenAddToCart(item3);
            Assert.AreEqual(_shoppingCart.GetCartItems().Count,1);
        }
    }

    public interface IShoppingCart
    {
        void AddToCart(CartItem item);
        List<CartItem> GetCartItems();
        void CheckItemExistThenAddToCart(CartItem item);
    }

    public class ShoppingCart : IShoppingCart, IEnumerable
    {
        private static List<CartItem> CartItems = null;

        public ShoppingCart()
        {
            CartItems = new List<CartItem>();
        }

        public void AddToCart(CartItem item)
        {
            CartItems.Add(item);
        }

        public void CheckItemExistThenAddToCart(CartItem item)
        {
            var cartItem = CartItems.FirstOrDefault(ci => ci.ProductId == item.ProductId);
            if (cartItem == null)
                AddToCart(item);
            else
                cartItem.Qty += item.Qty;
        }

        public List<CartItem> GetCartItems()
        {
            return CartItems;
        }

        public IEnumerator GetEnumerator()
        {
            return (CartItems as IEnumerable).GetEnumerator();
        }
    }

    public class CartItem
    {
        public string Name { get; set; }

        public double Price { get; set; }

        public int Qty { get; set; }

        public string ProductId { get; set; }
    }
}


texts:
I'm trying to solve Wildcard Matching on Leetcode. I found a great solution using the Finite-state machine. The author builds an FSM and searches with BFS.

I rewrite the solution with the same idea (FSM) but use DFS:

class Solution:

    def isMatch(self, s: str, p: str) -> bool:
        # build the fsm
        fsm = {}
        state = 0
        for i in range(len(p)):
            if p[i] == "*":
                # connect to state itself
                fsm[state, p[i]] = state
            else:
                fsm[state, p[i]] = state + 1
                state += 1

        self.accept = state

        self.fsm = fsm
        return self.dfs(s, idx=0, state=0)

    def dfs(self, s: str, idx: int, state: int) -> bool:
        """deep first search through the finite state machine"""
        if idx == len(s):
            # processing string finished
            if state == self.accept:
                return True
            else:
                return False

        for value in [s[idx], "*", "?"]:
            if (state, value) not in self.fsm:
                # invaild state
                continue

            next_state = self.fsm[state, value]
            if self.dfs(s, idx + 1, next_state):
                return True

        return False

Since we need to iterate the whole string s, I think the time complexity of DFS and BFS are the same. However, I had the Time Limit Exceeded on the testing case:

"babbbbaabababaabbababaababaabbaabababbaaababbababaaaaaabbabaaaabababbabbababbbaaaababbbabbbbbbbbbbaabbb"
"b**bb**a**bba*b**a*bbb**aba***babbb*aa****aabb*bbb***a"

Are the time complexity of DFS and BFS the same?
Is there something wrong with my code?


texts:
I've been doing some programming challenges and problems lately and it seems like many involve primes. I concluded that I would benefit from optimizing how I'm checking for them. Currently I'm using the following method:

private static boolean isPrime(int num) {
    if (num < 1) {
        throw new IllegalArgumentException(
            "Argument must be a positive integer." +
            "\n Argument was: " + num + "."
        );
    }
    if (num <= 3){ return num > 1; }
    if ((num & 1) == 0) { return false; }

    for (int i = 5; i * i <= num; i += 2) {
        if (num % i == 0) {
            return false;
        }
    }
    return true;
}

Sometimes altering longs.

Excluding bitwise hacks that would likely come at the cost of readability is this as good as it gets or is there some enhancement that would raise performance?


texts: Extracting a list of objects from a repository as JSON

texts:
Currently, I am using the below code to make JSON data from list of objects.

public IActionResult getWardsFromVDC(long vdc_id)
{
    try
    {
        List<Ward> wards = wardRepo.getByVdcId(vdc_id).ToList();
        List<Dictionary<string, string>> values = new List<Dictionary<string, string>>();

        foreach (var ward in wards)
        {
            Dictionary<string, string> value = new Dictionary<string, string>();
            value["ward_id"] = ward.ward_id.ToString();
            value["ward_name"] = ward.ward_name;
            values.Add(value);
        }
        Dictionary<string, object> data = new Dictionary<string, object>();
        data["data"] = values;

        var json = JsonConvert.SerializeObject(data);
        return Json(json);
    }
    catch (Exception ex)
    {
        return Json(ex.Message);
    }
}

List<Ward> wards = wardRepo.getByVdcId(vdc_id).ToList();

is getting list of Ward class from database. Then a loop is used to put all the values in List of Dictionaries .

 Dictionary<string, object> data = new Dictionary<string, object>();
 data["data"] = values;

 var json = JsonConvert.SerializeObject(data);

is putting all those values in "data" key in another dictionary and then value is serialized and returned as JSON

The JSON data formed is :

{
  "data": [
    {
      "ward_id": "132",
      "ward_name": "1"
    },
    {
      "ward_id": "133",
      "ward_name": "2"
    },
    {
      "ward_id": "134",
      "ward_name": "3"
    },
    {
      "ward_id": "135",
      "ward_name": "4"
    },
    {
      "ward_id": "136",
      "ward_name": "5"
    },
    {
      "ward_id": "137",
      "ward_name": "6"
    },
    {
      "ward_id": "138",
      "ward_name": "7"
    },
    {
      "ward_id": "139",
      "ward_name": "8"
    },
    {
      "ward_id": "140",
      "ward_name": "9"
    },
    {
      "ward_id": "141",
      "ward_name": "10"
    },
    {
      "ward_id": "142",
      "ward_name": "11"
    },
    {
      "ward_id": "143",
      "ward_name": "12"
    }
  ]
}

To build even a simple data , I am creating dictionary and list of dictionaries and again adding data key .

Is there any simple way to build JSON in same format but in simplest way?


texts:
The user can provide a JSON object to configure the plugin when they initialise it. I want those options to be available whenever a plugin action is performed.

I have read the plugin documentation but I'd like to get confirmation that I am going about this the right way.

Plugin is initialised with:

$(selector).hide_and_peek("init", {options:here});

And individual methods may be called with:

$(selector).hide_and_peek("action", {options:here});

Here's the plugin definition:

(function( $ ) {

// Plugin definition.
$.fn.hide_and_peek = function(action,  options ) {

    //define plugin defaults.
    $.fn.hide_and_peek.defaults = {
        peek_offset: -10,
        peek_position: "bottom",
        default_shown: true,
        peek_show_duration:1000,
        peek_hide_duration:1000,
        center: true
    };

    //check to see if options are provided and extend if required.
    $.fn.hide_and_peek.custom = function(){
        if(typeof options === "undefined"){
            return $.fn.hide_and_peek.custom;
        }else{
            return $.fn.extend($.fn.hide_and_peek.custom,options);
        }
    }();

    //merge defaults and custom options
    var oOptions = $.fn.extend({}, $.fn.hide_and_peek.defaults, $.fn.hide_and_peek.custom);

    // *snip* Plugin implementation
})( jQuery );


texts: Script to move images into year and month folder

texts:
This following code searches for jpg files of size larger than 500 KB. Its purpose is to move/cp files, depending on their EXIF data, into folders that correspond to the files' year and month.

find . -type f -iname '*.jpg' -size +500k | while read file; do
    yr=$(stat -f '%Sm' -t '%Y' "$file")
    month=$(stat -f '%Sm' -t '%m' "$file")
    folder="/path/to/backup/folder/$yr"
    subFodler=$folder"/"$month
    [[ -d "$folder" ]] || echo mkdir "$folder"
    [[ -d "$subFodler" ]] || echo mkdir "$subFodler"
    echo mv "$file" "$folder/$month"
done

Currently it´s a lot of duplicate lines.


texts:
Lets say I build functions.php and I have 3 functions inside of it that I use. Lets say that I build a 4th function, but what I really want to do is simply put the instructions of function 4 into function 1 for example. Is there anything wrong with this?

Consider my example here, where I have included a function inside of a function. I am aware that the variables inside of a function are local, and that you cannot call a variable inside a function outside of it, however I have tested this with a simple echo test and it seems to work. Is there anything wrong with doing this? If so, can you explain how you might go about doing this generally? You do not have to be specific.

functions.php

function validate_registration($password, $confirmpassword, $email) {
    if ((empty($email)) || (empty($password)) || (empty($confirmpassword))) {
        registration_form();
        echo "Please enter the required information:";
    }
    elseif ((filter_var($email, FILTER_VALIDATE_EMAIL)) && ($password == $confirmpassword)) {
        input_registration($email, $password);
    }
    elseif ((filter_var($email, FILTER_VALIDATE_EMAIL)) && ($password !== $confirmpassword)) {
        registration_form();
        echo "Your password does not match!";
    }
    else {
        registration_form();
        echo "You have not entered a valid email address!";
    }

}

the input_registration function:

function input_registration ($email, $password) {
$email_clean = htmlspecialchars($email);
$password_clean = htmlspecialchars($password);

$hash = md5($password_clean);

$db = new PDO("mysql:host=localhost;dbname=users", "root", "")

$statement = $db->prepare("INSERT into userinfo(email, hash) VALUES (:email, :hash)")

//continue with inputting info into database


texts: Return the product of the pythagorean triplet if a+b+c == 1000

texts:
I have found the answer to the problem I am trying to solve, but I am curious if there can be any improvements made to my code.

#include <iostream>
#include <limits>
#include <cmath>
using namespace std;

unsigned long pythagoreanTriplet();
int main() {
cout << pythagoreanTriplet() << endl;
}

unsigned long pythagoreanTriplet()
{
int a,b;
   unsigned long c;
for(a = 1; a < 1000;a++)
{
    for(b = a+1; b <= 1000;b++)
    {
        c = sqrt(pow(a,2)+pow(b,2));

        if(pow(a,2)+pow(b,2) == pow(c,2))
        {
            if(a+b+c == 1000)
            {
                unsigned long product = a*b*c;
                return product;
            }
        }
    }
 }
}


texts:
I'm studying C with a Deitel's book. The book asks me to write a program that simulates a virtual PC (with virtual memory in an array called memory[100]).
Then the book asks me to write a program that sums 10 numbers. I did it but I had to initialize some variables (memory[20], memory[21], memory[22]) before running the program.
There is any way to make this program without initially storing the variables
and using the same number of instructions?

These are valid instructions:

#define READ 10;
#define WRITE 11;
#define LOAD 20;
#define STORE 21;
#define ADD 30;
#define SUBTRACT 31;
#define DIVIDE 32;
#define MULTIPLY 33;
#define BRANCH 40;
#define BRANCHANG 41;
#define BRANCHZERO 42;
#define HALT 43;

And the code:

int main(){
int memory[100] = {2022,1022,3022,2122,2021,3120,2121,4209,4000,1122,4300}; // my set of instruction for sum 10 numbers
memory[99] = -99999;
memory[20] = 1; // the variables initializations that i want to remove
memory[21] = 10;
memory[22] = 0;
int accumulator = 0000;
int instCounter = 00;
int instRegistrer = 0000;
int operationCode = 00;
int operand = 00;

while(memory[instCounter] >= 0){
    printf("\n**%d**  ", instCounter);
    instRegistrer = memory[instCounter];
    operationCode = instRegistrer / 100;
    operand = instRegistrer % 100;
    switch(operationCode){
        case READ:
            printf("READ ");
            scanf("%d", &memory[operand]);
            instCounter++;
            break;
        case WRITE:
            printf("WRITE ");
            printf("%d", memory[operand]);
            instCounter++;
            break;
        case LOAD:
            printf("LOAD ");
            accumulator = memory[operand];
            instCounter++;
            break;
        case STORE:
            printf("STORE ");
            memory[operand] = accumulator;
            instCounter++;
            break;
        case ADD:
            printf("ADD ");
            accumulator += memory[operand];
            instCounter++;
            break;
        case SUBTRACT:
            printf("SUBTRACT ");
            accumulator -= memory[operand];
            instCounter++;
            break;
        case DIVIDE:
            printf("DIVIDE ");
            accumulator /= memory[operand];
            instCounter++;
            break;
        case MULTIPLY:
            printf("MULTIPLY ");
            accumulator *= memory[operand];
            instCounter++;
            break;
        case BRANCH:
            printf("BRANCH ");
            instCounter = operand;
            break;
        case BRANCHANG:
            printf("BRANCHANG ");
            if(accumulator < 0)instCounter = operand;
            else instCounter++;
            break;
        case BRANCHZERO:
            printf("BRANCHZERO ");
            if(accumulator == 0)instCounter = operand;
            else instCounter++;
            break;
        case HALT:
            printf("HALT ");
            instCounter = 99;
            break;
    }
}
return 0;
}


texts:
I am trying to make a textbox which filters user input to match specified type, so I can discard some of my validation logic.

For example, if I specify ushort I want my textbox to only accept text changes which result in a valid ushort value and nothing else.

This is what I've ended up with:

public abstract class CustomTextBox<T> : TextBox
{
    public static readonly DependencyProperty ValueProperty = DependencyProperty.Register("Value", typeof(T), typeof(CustomTextBox<T>), new FrameworkPropertyMetadata(default(T), FrameworkPropertyMetadataOptions.BindsTwoWayByDefault | FrameworkPropertyMetadataOptions.Inherits, OnValueChanged));
    public T Value
    {
        get { return (T)GetValue(ValueProperty); }
        set { SetValue(ValueProperty, value); }
    }

    protected override void OnPreviewTextInput(System.Windows.Input.TextCompositionEventArgs e)
    {
        if (_regex != null && !_regex.IsMatch(e.Text))
        {
            e.Handled = true;
        }
        else
        {
            base.OnPreviewTextInput(e);
        }
    }

    protected override void OnTextChanged(TextChangedEventArgs e)
    {
        if (String.IsNullOrEmpty(Text))
        {
            return;
        }

        T val;
        if (!TryParse(out val))
        {
            var index = CaretIndex;
            Text = _validText;
            CaretIndex = index > 0 ? index - 1 : 0;
            e.Handled = true;
        }
        else
        {
            Value = val;
            _validText = Text;

        }
    }

    protected CustomTextBox(string regexPattern = null)
    {
        if (!String.IsNullOrEmpty(regexPattern))
        {
            _regex = new Regex(regexPattern);
        }
        _validText = ToString(Value);

        Loaded += OnTextboxLoaded;
    }

    protected override void OnLostFocus(RoutedEventArgs e)
    {
        ValidateText();

        base.OnLostFocus(e);
    }

    protected virtual string ToString(T value)
    {
        return value.ToString();
    }

    protected abstract bool TryParse(out T val);

    private readonly Regex _regex;
    private string _validText;

    private void ValidateText()
    {
        T val;
        if (!TryParse(out val))
        {
            Text = ToString(Value);
        }
    }

    private void OnTextboxLoaded(object sender, RoutedEventArgs e)
    {
        ValidateText();
    }

    private static void OnValueChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        var tb = (CustomTextBox<T>)d;
        if (!e.OldValue.Equals(e.NewValue))
        {
            var str = tb.ToString((T)e.NewValue);
            if (!str.Equals(tb.Text))
            {
                tb.Text = str;
            }
        }
    }
}

ushort implementation:

public sealed class UshortTextBox : CustomTextBox<ushort>
{
    public UshortTextBox()
        : base(@"^[0-9]$")
    {
    }

    protected override bool TryParse(out ushort val)
    {
        return UInt16.TryParse(Text, out val);
    }
}

I'm new to this whole custom-control-making, so if you see some rookie mistakes or ways to improve my code, please let me know.


texts:
I have a login web page where a user enters their email and password and I need to check if:

the entered email exists in the DB and
the entered password matches the hashed one from the db.

The password in the DB was hashed with

$pw = password_hash($_POST["pw"], PASSWORD_BCRYPT);

and is stored in a VARCHAR(255) column.
Email is set to primary and unique in the DB so there cannot be a duplicate record for this.

To achieve the above I came to the below which works as intended for me.
However, since I am new to this and because of the double DB connection I was wondering if there is a way to shorten or otherwise improve this code.

$email = $_POST["email"];
$pw = $_POST["pw"];

$stmt = $conn->prepare("SELECT email FROM Users WHERE email = ?");
$stmt->bind_param('s', $email);
$stmt->execute();
$result = $stmt->get_result();
if(mysqli_num_rows($result) == 0){
    echo "Email has not been registered yet";
}else{
    $stmt = $conn->prepare("SELECT pw FROM Users WHERE email = ? LIMIT 1");
    $stmt->bind_param('s', $email);
    $stmt->execute();
    $result = $stmt->get_result();
    $pwHashed = $result->fetch_assoc();
    if(password_verify($pw, $pwHashed["pw"])){
        echo "Password correct";
    }else{
        echo "Password incorrect";
    }
}


texts:
I believe this code prints both the DFS and BFS of a directed graph. As with some of my previous posts, this is mainly to share my code with other people working on a similar issue but I would also appreciate any feedback.

In the code I have written, DFS and BFS use a pre-order technique, as follows:

DFS (Depth first search) starts with a given node and explores the first unexplored node it comes across before returning to itself again and exploring its remaining nodes (e.g: if the parent node 1 has 2 children 2, 3 the DFS method will explore 2 and its children nodes before exploring 3. It will print self before exploring its children (so 1->(2,3) will print 1,2,3))
BFS (Breadth first search) works down a tree in a top-to-bottom manner (e.g: a graph with parent 1 and children 2, 3 will print level 1 first (1) then level 2 (2, 3) and then level 3 (the children of nodes 2 and 3). The level of a given node is determined by the highest level it could appear on (e.g: if 2 is a child of an item on level 1 and level 4, it would be printed as if it were a level 2 item)

from collections import defaultdict

class Graph():
    def __init__(self):
        self.value = defaultdict(list)

    def addConnection(self, parent, child):
        self.value[parent].append(child)

    def DFS(self, start):
        visited = [start]
        stack = [start]
        print(start, end = " ")
        while stack:
            s = stack[-1]
            if any([item for item in self.value[s] if item not in visited]):
                for item in [item for item in self.value[s] if item not in visited]:
                        stack.append(item)
                        visited.append(item)
                        print(item, end= " ")
                        break
            else:
                stack.pop()

    def BFS(self, start):
        visited = [start]
        queue = [start]
        while queue:
            x = queue.pop(0)
            print(x, end= " ")
            for item in self.value[x]:
                if item not in visited:
                    queue.append(item)
                    visited.append(item)

#Build the graph
g=Graph()
g.addConnection(1,4)
g.addConnection(1,2)
g.addConnection(2,3)
g.addConnection(2,6)
g.addConnection(4,5)
g.addConnection(4,7)
g.addConnection(7,96)

#Explore the graph
g.DFS(1)
print("\n")
g.BFS(1)

Output is

DFS: 1 4 5 7 96 2 3 6
BFS: 1 4 2 5 7 3 6 96

Adding a (2,4) node gives

DFS: 1 4 5 7 96 2 3 6
BFS: 1 4 2 5 7 3 6 96


texts: Doubly linked list implementation in C++

texts:
I made this C++ doubly linked list implementation and it seems to work right, handle everything well, and not have any errors. However, I've been working with it for a while and would like some fresh eyes to take a look and see if I am missing anything large or if my code contains any 'gotchas'.

Side note: I ran valgrind on several tests of this implementation and never got any memory leaks so I suspect it is handling that end of this correctly.

DLL.H

#ifndef DLL
#define DLL

class DoublyLinkedNode {
public:
    int info;
    DoublyLinkedNode *next, *prev;

    DoublyLinkedNode() {
        next = prev = 0;
    }

    DoublyLinkedNode(int nu, DoublyLinkedNode *ne = 0, DoublyLinkedNode *pre = 0) {
        info = nu;
        next = ne;
        prev = pre;
    }
};

class DoublyLinkedList {
private:
    DoublyLinkedNode *head, *tail;
public:
    DoublyLinkedList() {
        head = tail = 0;
    }

    ~DoublyLinkedList();

    bool isEmpty() const {
        return head == 0;
    }

    void addToHead(int);
    void addToTail(int);
    int removeFromHead();
    int removeFromTail();
    void remove(int);
    bool isInList(int) const;

};

#endif

DLL.cpp

#include <iostream>
#include "DLL.h"

DoublyLinkedList::~DoublyLinkedList() {
    for (DoublyLinkedNode *p; !isEmpty();) {
        p = head->next;
        delete head;
        head = p;
    }
}

void DoublyLinkedList::addToHead(int n) {
    if(head == 0){
        head = new DoublyLinkedNode(n);
        tail = head;
        return;
    }

    DoublyLinkedNode *tmp = new DoublyLinkedNode(n, head);
    head->prev = tmp;
    head = tmp;

}

void DoublyLinkedList::addToTail(int n) {
    if (tail != 0) {
        tail = new DoublyLinkedNode(n, 0, tail);
        tail->prev->next = tail;
    } else {
        head = tail = new DoublyLinkedNode(n);
    }
}

int DoublyLinkedList::removeFromHead() {
    int el = head->info;
    if(head == tail) {
        delete head;
        head = tail = 0;
    } else {
        head = head->next;
        delete head->prev;
        head->prev = 0;
    }
    return el;
}

int DoublyLinkedList::removeFromTail() {
    int el = tail->info;
    if(head == tail) {
        delete tail;
        head = tail = 0;
    } else {
        tail = tail->prev;
        delete tail->next;
        tail->next = 0;
    }
    return el;
}

void DoublyLinkedList::remove(int n) {
    if (head != 0) {

        if(head == tail) {
            delete head;
            head = tail = 0;
        }

        if(head->info == n) {
            removeFromHead();
            return;
        }

        if(tail->info == n) {
            removeFromTail();
            return;
        }

        DoublyLinkedNode *tmp;
        tmp = head;
        while(tmp != 0) {
            if (tmp->info != n) {
                tmp = tmp->next;
            } else {
                tmp->prev->next = tmp->next;
                tmp->next->prev = tmp->prev;
                delete tmp;
                tmp = 0;
                //return;
            }
        }
    }
}

bool DoublyLinkedList::isInList(int el) const {
    DoublyLinkedNode *tmp;
    for (tmp = head; tmp != 0 && !(tmp->info == el); tmp = tmp->next);
    return tmp != 0;
}


texts:
We had a question in examination to compute determinant of general square matrix.
Now I had made the normal program using Laplace Formula of determinant, ie, recursive solution.

Now I was thinking of reducing it into Upper Triangle Matrix and then the product of diagonal elements gives the determinant.

The code is following.

#include <iostream>
using namespace std;

const int N = 5;
int main()
{
    double array[N][N], det = 1;

    // initialise
    cout << "Enter " << N << "*" << N << " matrix:\n";
    for (int i = 0; i < N; ++i) {
        for (int j = 0; j < N; ++j) {
            cin >> array[i][j];
        }
    }

    for (int i = 0; i < N; ++i)
    {
        bool flag = false; // flag := are all entries below a[i][i] including it zero?
        if (array[i][i] == 0) // If a[i][i] is zero then check rows below and swap
        {
            flag = true;
            for (int j = i; j < N; ++j)
            {
                if (array[j][i] != 0) {
                    det *= -1;
                    for (int k = 0; k < N; ++k) {
                        double t = array[i][k]; // swapping
                        array[i][k] = array[j][k];
                        array[j][k] = t;
                        flag = false;
                    }
                }
            }
        }

        if (flag == true) {
            det = 0;
            break;
        }

        else {

            for (int j = i+1; j < N; ++j)
            {
                double store = array[j][i];
                for (int k = i; k < N; ++k) {
                    array[j][k] -= (array[i][k]*store)/array[i][i];

                }
            }
            det *= array[i][i];
        }
    }

    cout << "Determinant: " << det;
    return 0;
}

The problems with this approach is that matrix needs to be of floating point datatypes. Worse, it gives wrong result for least significant place (ones digit) for all integral entries if I use datatype of entries as float. To overcome that, we can use double.

But still I :

need tips on improving performance of this method
need to know whether this method is better than Simple Laplace Formula?


texts: Calling multiple functions in image upload form

texts:
I have an image upload form with which I call multiple functions before uploading the file such as checking the size and dimensions, and that it is in a valid image. The code works, but calling the functions and dealing with the results seems quite cumbersome and complex.

Is there a tidier way of structuring the code?

This is what I currently have:

//Upload an image
if(checkvalidfile("img",$ext)){
    if(checksize($size, 524288)) {
        if(checkdimensions($tmp, 300)) {
            $newfilename = renamefile($ext);
            recordfileindb($brand_id, $newfilename, $mysqli);
            uploadfile($tmp, $bucket, "user_docs/agency_".$agency_id."/brand_logos/", $newfilename, $s3);
            header('Location: ./message.php?action=newlogo');
        } else {
            echo "Your image can't be bigger than 300 x 300px";
            die;
        }
    } else {
        echo "File size is too big!";
        die;
    }
} else {
    echo "Not a valid file";
    die;
}


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 the string
Space complexity: O(n/2) where n is length of string

Looking for code review, optimizations and best practices.

public final class BalancedParanthesis {

    private static final Map<Character, Character> brackets = new HashMap<Character, Character>();
    static {
        brackets.put('[', ']');
        brackets.put('{', '}');
        brackets.put('(', ')');
    }

    private BalancedParanthesis() {};

    /**
     * Returns true is parenthesis match open and close.
     * Understands [], {}, () as the brackets
     * It is clients responsibility to include only valid paranthesis as input.
     * A false could indicate that either parenthesis did not match or input including chars other than valid paranthesis
     *
     * @param str   the input brackets
     * @return      true if paranthesis match.
     */
    public static boolean isBalanced(String str) {
        if (str.length() == 0) {
            throw new IllegalArgumentException("String length should be greater than 0");
        }
        // odd number would always result in false
        if ((str.length() % 2) != 0) {
            return false;
        }

        final Stack<Character> stack = new Stack<Character>();
        for (int i = 0; i < str.length(); i++) {
            if (brackets.containsKey(str.charAt(i))) {
                stack.push(str.charAt(i));
            } else if (stack.empty() || (str.charAt(i) != brackets.get(stack.pop()))) {
                return false;
            }
        }
        return true;
    }

    public static void main(String[] args) {
        assertEquals(true, isBalanced("{}([])"));
        assertEquals(false,isBalanced("([}])"));
        assertEquals(true, isBalanced("([])"));
        assertEquals(true, isBalanced("()[]{}[][]"));
    }
}


texts:
I'd like the user to be able to add rows to a table in my Play application written in Scala. The row is defined in a custom tag and makes use of Bootstrap via the plugin by Adrian Hurt.

My current way of doing this is by calling jQuery that clones a row and appends it to the table body.

testTable.scala.html

@(testForm: Form[(String, String)], siteTitle: String)(implicit messages: Messages)
@import tags._

@main(title = siteTitle) {

        Some text
        A selection

    @myTestRow(testForm, "firstRowId")

    Add a row

}

The row is defined in tags.myTestRow.scala.html:

@(testForm: Form[(String, String)], rowId: String)(implicit messages: Messages)

@import b3.vertical.fieldConstructor
@myTestOptions = @{
  // Turn the list into a Sequence of pairs
  List("Option A", "Option B").map(str => str -> str)
}

  @b3.text(testForm("textFieldName"), 'placeholder -> "Enter text")
  @b3.select(testForm("selectionName"), options = myTestOptions)

This is the table after adding two rows:

Is there a more elegant way of letting the user add rows to a table in Play?


texts:
I'm learning Java, and would really appreciate any tips on how to improve this code.

It's just a simple date validation class.

import java.util.Map;
import java.util.HashMap;

class DateValidator {
    private int day;
    private int month;
    private int year;

    private enum Months {
        JANUARY(1, 31), FEBRUARY(2, 28), MARCH(3, 31), APRIL(4, 30), MAY(5, 31), JUNE(6, 30),
        JULY(7, 31), AUGUST(8, 31), SEPTEMBER(9, 30), OCTOBER(10, 31), NOVEMBER(11, 30), DECEMBER(12, 31);

        private final int MonthNumber;
        private final int numberOfDaysInMonth;

        private static Map<Integer, Integer> map;

        private Months(int monthMnumber, int numberOfDays) {
            this.MonthNumber = monthMnumber;
            this.numberOfDaysInMonth = numberOfDays;
        }

        static {
            map = new HashMap<Integer, Integer>();

            for (Months m : Months.values()) {
                map.put(m.MonthNumber, m.numberOfDaysInMonth);
            }
        }

        public static Map<Integer, Integer> getMap() {
            return map;
        }

    }

    DateValidator(int d, int m, int y) {
            this.day = d;
            this.month = m;
            this.year = y;
    }

    private static boolean leapYear(int y) {
        return ((y % 4 == 0) && (y % 100 != 0) || (y % 400 == 0));
    }

    public boolean checkDay() {
        if (this.month == 2 && this.leapYear(this.year)) {
            Months.getMap().put(this.month, 29);
        }

        return (this.day <= Months.getMap().get(this.month));
    }
}

class Main {
    public static void main(String[] args) {
        DateValidator d = new DateValidator(31, 10, 90);

        System.out.print(d.checkDay());
    }
}


texts: C# class that handle MySQL db connection

texts:
I've built a class that handles all my connections to a MySql database.

These are the function I use to create the connection(not really sure about the two dispose functions) :

 public class dbConnection : IDisposable
{
    public MySqlConnection conn;
    public MySqlTransaction transaction;

    private static Logger logger = LogManager.GetCurrentClassLogger();

    public dbConnection()
    {
        string host = "1.1.1.1";
        string usernameMySql = "admin";
        string pswMySql = "password";
        string nomeDb = "db1";

        string connStr = "Database=" + nomeDb + ";" +
                "Data Source=" + host + ";" +
                "User Id=" + usernameMySql + ";Password=" + pswMySql + "";
        conn = new MySqlConnection(connStr);
    }

    public void openConnection()
    {
        conn.Close();
        conn.Open();
        transaction = conn.BeginTransaction();
    }

    public void closeConnection()
    {
        transaction.Commit();
        conn.Close();
    }

    protected virtual void Dispose(Boolean disposing)
    {
        if (disposing)
        {
        }
    }

    public void Dispose()
    {
        Dispose(true);
        GC.SuppressFinalize(this);
    }

These are the functions I use to read/write data:

public void ExecuteSQL(string sSql)
    {
        MySqlCommand cmd = new MySqlCommand(sSql, conn);
        cmd.ExecuteNonQuery();
    }

    public MySqlDataReader readerSQL(string sSql)
    {
        MySqlCommand cmd = new MySqlCommand(sSql, conn);
        MySqlDataReader readerSql = cmd.ExecuteReader();

        return readerSql;
    }

    protected int ExecuteSQLReturnId(string sSql)
    {
        MySqlCommand cmd = new MySqlCommand(sSql, conn);
        cmd.ExecuteNonQuery();
        return Convert.ToInt32(cmd.LastInsertedId);
    }

In others part of my project i then use

db = new dbConnection();
db.openConnection();

to create a new connection.

This code works but I'm not really sure it's the right way to handle things, Are there any improvements that can be made ?


texts: MySQL limit across multiple tables in multiple queries

texts:
I have a website that keeps track of 'changes' that users make. These changes come in all shapes and sizes and each shape and size has a different MySQL table to store them in. In total there are 8 different tables. Each table has completely different columns, so I don't think a simple JOIN would be possible, however they all have a time column.

What I would like to do is show the last x number of changes made across all tables (i.e. sorted by time). How I am doing it now is querying all tables like this:

foreach ($tables as $table) {
    $stmt = $this->_dbh->prepare("SELECT $table.*,
            realname,
            time,
            reservations.conf_num,
            reservations.conf_letters
        FROM
            $table
        LEFT JOIN users ON $table.user_id = users.id
        LEFT JOIN reservations
            ON $table.conf_num = reservations.conf_num
        ORDER BY
            time DESC
        LIMIT ".$this->_num_values);
    $stmt->execute();

    $changes[$table] = $stmt->fetchAll();
}

Then I sort and slice the resultant array:

ksort($changes);
$changes = array_reverse($changes);

// Make sure to limit it if we have a maximum number of values
if ($this->_num_values > 0) {
    $changes = array_slice($changes, 0, $this->_num_values);
}

This works fine, however it just seems extremely inefficient to me since we are retrieving the latest x values from all tables instead of just returning the exact number so that the sum of the number of rows from the individual queries equals x. Is there a better way to do this, or am I just trying to micro-optimize too much here?


texts: "Prev" / "Next" buttons for a circular list

texts:
I have an array of strings and on click of the "NEXT" button it displays the next array item in a
 tag while on click of the "PREV" button it displays the previous one. When it reaches to the end (beginning) it continues from the first (last) item.

I have had some hard time to find a way to get the right item index when PREV is clicked and this is what i could have come up with.

I've used a  modulo operator on decreasing array indices.  I would like to know if there is a better way of doing this. By the way ES6 syntax is just what I like so I am not interested in any ES5 compatibility improvements.

var message = ["dog", "cat", "bear", "penguin", "tiger", "eagle", "John Doe"],
        pel = document.getElementById("text"),
        idx = 0,
    getNext = e => pel.innerText = e.target.id == "right" ? message[idx = ++idx%message.length]
                                                          : message[idx = (message.length - (message.length - --idx)%message.length)%message.length];
document.getElementById("right").onclick = getNext;
document.getElementById("left").onclick = getNext;
<!DOCTYPE html>

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

dog

   <button id="left" style = "width: 50px; background-color:gold" onclick="getNext">PREV</button>
   <button id="right" style = "width: 50px; background-color:tomato" onclick="getNext">NEXT</button>


texts: Is there a better "Go" way to implement LC Add Two Numbers solution

texts:
Problem Statement:

You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order, and each of their nodes contains a single digit. Add the two numbers and return the sum as a linked list.
You may assume the two numbers do not contain any leading zero, except the number 0 itself.

Implementation
func addTwoNumbers(l1 *ListNode, l2 *ListNode) *ListNode {
    return helper(l1, l2, 0)
}

func helper(left *ListNode, right *ListNode, carry int) *ListNode {

    if left == nil && right == nil {
        if carry > 0 {
            return &ListNode{
                Val: carry,
            }
        }
        return nil
    }

    if left == nil {
        r := right.Val + carry
        return &ListNode{
            Val:  r % 10,
            Next: helper(nil, right.Next, r / 10),
        }
    } else if right == nil {
        r := left.Val + carry
        return &ListNode{
            Val:  r % 10,
            Next: helper(left.Next, nil, r / 10),
        }
    }

    r := left.Val + right.Val  + carry
    return &ListNode{
        Val: r % 10,
        Next: helper(left.Next, right.Next, r / 10),
    }
}

```