texts:
I've implemented a concurrent multimap that support concurrent put and remove but I'm unsure of its correctness. I would appreciate your feedback.

public class ConcurrentMultiMap<K, V> {
    private static ConcurrentHashMap emptySet = new ConcurrentHashMap();
    private ConcurrentHashMap<K, ConcurrentHashMap<V, Object>> map = new ConcurrentHashMap<>();

    // return true if the method increased the size of the multimap or false if the multimap already contained the key-value pair
    public boolean put(K k, V v) {
        Preconditions.checkNotNull(k);
        Preconditions.checkNotNull(v);
        boolean tryAgain;
        boolean success = true;
        do {
            ConcurrentHashMap<V, Object> oldSet = map.get(k);
            if (oldSet == null) {
                tryAgain = map.putIfAbsent(k, new ConcurrentHashMap<>(Collections.singeltonMap(v, 1))) != null;
            } else {
                success = oldSet.putIfAbsent(v, 1) == null; //I do not allow multiple equal values for the same key
                if (success) {
                    // if the put was a success we check that the key was not removed from the map by a concurrent remove operation.
                    ConcurrentHashMap<V, Object> currentSet = map.get(k);
                    tryAgain = currentSet == null || !currentSet.contains(v);
                } else {
                    return false;
                }
            } while(tryAgain);
            return success;
    }

    // returns true if the multimap changed
    public boolean remove(K k, V v) {
        Preconditions.checkNotNull(k);
        Preconditions.checkNotNull(v);
        ConcurrentHashMap<V, Object> oldSet = map.get(k);
        if (oldSet == null) {
            return false;
        }
        if (oldSet.remove(v) != null) {
            if (oldSet.size() == 0) {
                map.remove(k, emptySet);
            }
            return true;
        }
        return false;
    }
}


texts:
Just recently I've wanted to update the PHP scripts I use to fetch information from a database for an iOS application. I've got around to it today, and I had a few questions that'd I like a second opinion on before I use these scripts.

Will this method of operation work? As in, since the query and connection are in two different try/catch blocks, will the query work differently?
Is this safe against SQL injection?
Can this support multiple/no parameters?
Overall, is this an efficient way of querying a database?

databaseHelper.php

<?php

error_reporting(E_ALL);
ini_set('display errors', 1);

$connection = // redacted
$username = // redacted
$password = // redacted

function initiateConnection() {
    try {
        $dbh = new PDO($connection, $username, $password);
        $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        return $dbh;
    } catch(PDOException $e) {
        return null;
    }
}

function performQuery($connection, $queryString, $parameters) {
    try {
        $query = $connection->prepare($queryString);
        $query->execute($parameters);

        if($sth->rowCount()) {
            $row = $sth->fetchAll(PDO::FETCH_ASSOC);
            return $row;
        } else {
            return null;
        }
    } catch(PDOException $e) {
        return null;
    }
}

?>

This is how I would plan on utilizing these functions:

<?php

include '../php_include/database.php';

$connection = initiateConnection();
if($connection != null) {
    $response = preformQuery($connection, 'SELECT * FROM users WHERE username = ?', 'test') // the username will NOT be hardcoded, it will be found in the $POST variable, this is just for example purposes
    if($response != null) {
        // echo json_encode($response);
    } else {
        // print false
    }
} else {
    // print error message
}

?>


texts: Checking user input for boxing sim engine

texts:
I am creating a simple Boxing sim engine and have got things working fairly well. A few months ago I was instructed to avoid copy and pasting code and to try and "conserve my logic".

Anyways, I feel I have done a fairly good job overall but there is one area (posted below) that I feel definitely has room for improvement:

print ("1)Joe Smith\n2)Mike Jones\n3)Steve Roberts\n")
boxer1 = input("Choose a fighter: ")
boxer2 = input ("Choose his opponent: ")
if boxer1 == '1':
    B1 = JS
elif boxer1 == '2':
    B1 = MJ
elif boxer1 == '3':
    B1 = SR
if boxer2 == '1':
    B2 = JS
elif boxer2 == '2':
    B2 = MJ
elif boxer2 == '3':
    B2 = SR

MJ, JS, and SR are all variables for objects in my Boxer class. My concern is that I will have to continue adding four lines of code for each boxer I add to the program. While I don't mind typing each line out, I realize there may be a much more efficient way to approach this that I'm not seeing. I realize this isn't a major issue but, as I mentioned, this program is mainly for practice and therefore I want to make sure I'm programming as efficiently as possible.


texts: Count the number of occurences of X's within a range in Java

texts:
Given an integer X within the range of 0 to 9, and given two positive

  integers as upper and lower bounds respectively, find the number of
  times X occurs as a digit in an integer within the range, excluding
  the bounds. Print the frequency of occurrence as output.

  Input: The first line of input is an integer T, denoting the number of
  test cases. For each test case, there are two lines of input, first
  consisting of the integer X, whose occurrence has to be counted.
  Second, the lower and upper bound, L and U which are positive
  integers, on the same line separated by a single space, respectively.

  Output: For each test case, there is only one line of output, the
  count of the occurrence of X as a digit in the numbers lying between
  the lower and upper bound, excluding them.

  Constraints: 1<=T<=100 0<=X<=9 0

  Example: Input 5 3 100 250 2 10000 12345 0 20 21 9 899 1000 1 1100
  1345 Output: 35 1120 0 120 398

  Explanation:

  In the first test case, the occurrence of 3 in the numbers starting
  from 101 to 249 is counted and comes out to be 35.

My approach:

/*package whatever //do not write package name here */

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;

class GFG {

    private static int numOccurences (int X, int low, int up)
        {
            String str;
            int totOcc = 0;

            //Convert a digit 0-9 to a character
            char chk = Character.forDigit(X,10);
            for (int i = low+1; i < up; i++)
                {
                    str = String.valueOf(i);
                    totOcc += numCharsInStr(str,chk);
                }
            return totOcc;
        }

    private static int numCharsInStr (String str, char ch)
        {
            int numOccurs = 0;
            for (int i = 0; i < str.length(); i++)
                {
                    if (str.charAt(i) == ch)
                        {
                            numOccurs++;
                        }
                }
            return numOccurs;
        }

    public static void main (String[] args) throws IOException {
        //code
        BufferedReader br = new BufferedReader (new InputStreamReader (System.in));
        String line = br.readLine();
        String line2;
        String line3;

        int numTests = Integer.parseInt(line);
        int X;
        String [] inps;
        int lower;
        int upper;

        for (int i = 0; i < numTests; i++)
            {
                line2 = br.readLine();
                X = Integer.parseInt(line2);
                line3 = br.readLine();
                inps = line3.split(" ");
                lower = Integer.parseInt(inps[0]);
                upper = Integer.parseInt(inps[1]);
                System.out.println(numOccurences(X,lower,upper));
            }
    }
}

I have the following questions with regards to the code:

How can I further improve my approach?
Is there a better way to solve this question?
Are there any grave code violations that I have committed?
Can space and time complexity be further improved?

Reference


texts: Mocking dependencies when unit testing AngularJS services with QUnit

texts:
I'm trying to unit test an AngularJS service that is dependent on another service, using QUnit as my testing framework. The first test I'm writing is one to verify that my service calls another service under specific circumstances.

Below is a runnable example. I'm mainly looking to get feedback on the contents of the second main closure (which represents a QUnit module). Things I'm particularly interested in:

Conventions around unit testing AngularJS services with QUnit (e.g. I'm unsure when it's common to prefix variables with a $);
I'm following this advice (which was for Jasmine though) on mocking a dependent service, but am unsure if I can improve that approach or even need a different one (heck, perhaps I even need / should use a mocking framework?);
Whether I'm using the injector features of Angular correctly.

Here's a runnable snippet with promised code:

(function() {
    var app = angular.module('demoApp', []);

    app.factory('myService', ['anotherService', function(anotherService) {
        return {
            getTheTruth: function() { return anotherService.someFunction(); }
        };
    }]);
})();

(function() {
    // Looking to get feedback on this closure...

    'use strict';

    var $injector, anotherService;

    QUnit.module('myServiceTests', {
        beforeEach: function() {
            anotherService = {};
            angular.module('demoApp').factory('anotherService', function() {
                return anotherService;
            });
            $injector = angular.injector(['ng', 'demoApp']);
        }
    });

    QUnit.test('Calling getTheTruth relays to anotherService', function(assert) {
        var service = $injector.get('myService');
        anotherService.someFunction = function() {
            assert.ok(true);
        };
        assert.expect(1);
        service.getTheTruth();
    });

    // More tests here
})();
<link href="https://cdnjs.cloudflare.com/ajax/libs/qunit/1.16.0/qunit.min.css" rel="stylesheet"/>


texts:
I do not want to call this a wrapper, but no other name comes to mind right now, so I'll use it incorrectly for the rest of the question - It's just a class that adds C++ functions to dirent.h but it's very specific to my use case.

All of the code works well, but I've never worked with the dirent.h library and jumping right into a C++ wrapper is something, so I'm really insecure about it's performance and memory usage in practical scenarios.

~But, of course please also judge the readability - I want to know if I should add comments or if my naming scheme and layout is self explanatory.

Quick Description

I'm working on C++ based file manager that needs functions that return vectors of whole directories, of course, that it can display it in one loop. It will also need some more info (metadata I guess), like it's type so it can do all the fancy color syntax.

Here is the final version so far (with some debug code):

inode.h

#ifndef INODECLASS
#define INODECLASS

#include <dirent.h>
#include <string.h>

#include <iostream>

#include <vector>
#include <string>

class Inode
{
public:
  struct InodeMeta {
    std::string name;
    std::string path;
    unsigned char type;
  };

private:
  std::string pwd_path_;
  std::vector<InodeMeta *> buffer_;

public:
  Inode(const std::string &);
  ~Inode();

  void ClearBuffer();
  bool ReloadBuffer(const std::string &);

  std::vector<InodeMeta> DumpBuffer(const std::string &);
};

#endif

inode.cc

#include "inode.h"

Inode::Inode(const std::string &arg_path = ".") {
  if ( !ReloadBuffer(arg_path) )
    ClearBuffer();
}

Inode::~Inode() {
  ClearBuffer();
}

void Inode::ClearBuffer() {
  for (auto &item : buffer_)
    delete item;
  buffer_.clear();
}

bool Inode::ReloadBuffer(const std::string &arg_path = "") {
  if (arg_path.length() != 0) pwd_path_ = arg_path;
  DIR *dirstream;
  dirent *diritem;

  ClearBuffer();

  if ( (dirstream = opendir(pwd_path_.c_str())) != NULL )
  {
    while ( (diritem = readdir(dirstream)) != NULL ) {
      if ( strcmp(diritem->d_name, ".") != 0 &&
           strcmp(diritem->d_name, "..") != 0 )

        buffer_.emplace_back( new InodeMeta{ std::string(diritem->d_name),
          std::string(pwd_path_) + "/" + std::string(diritem->d_name),
      diritem->d_type} );
    }
    closedir(dirstream);
  }

  else return false;
  return true;
}

std::vector<Inode::InodeMeta> Inode::DumpBuffer(const std::string &arg_path = "") {
  if (arg_path.length() != 0) ReloadBuffer(arg_path);

  std::vector<InodeMeta> ret_list;

  for (auto &item : buffer_)
    ret_list.push_back(*item);

  return ret_list;
}

//DEBUG ONLY//

#include <iostream>

int main() {
  Inode I;

  std::vector<Inode::InodeMeta> inodelist = I.DumpBuffer();

  for (auto &item : inodelist)
    std::cout << item.name << " ; " << item.path << '\n';

  I.ReloadBuffer("/tmp/");
  inodelist.clear();
  inodelist = I.DumpBuffer();

  for (auto &item : inodelist)
    std::cout << item.name << " ; " << item.path << '\n';
}

Just in case you either want to see the whole project (I started it like 3 days ago, don't judge me too hard), or just make a quick git clone and test it yourself here.


texts: Std lib-like C++ function to find nearest elements in a container

texts:
Initial problem

For a project I found myself in the need to search for elements in a container that are the closest neighbours to another precise element I have. In my case it was points in any dimension, but it can apply to various other things that we are not used to compute "distance" for.

So I decided to write a generic function to perform this search, so I can use it for whatever type I want, provided that I can compute the "distance" between two elements of this type. I tried to make it in the style of standard library's algorithm.

My solution

template<typename T, class Distance>
struct Comp
{
    using result_type = typename std::result_of<Distance(const T&, const T&)>::type;
    using type = std::less<result_type>;
};

template<class InputIt, typename T, class Distance,
class Compare = typename Comp<T, Distance>::type>

std::vector<T> find_n_nearest(
    InputIt start,
    InputIt end,
    const T& val,
    size_t n,
    Distance dist,
    Compare comp = Compare())
{
    std::vector<T> result{start, end};

    std::sort(std::begin(result), std::end(result),
        [&] (const T& t1, const T& t2)
        {
            return comp(dist(val, t1), dist(val, t2));
        });

    result.erase(std::begin(result) + n, std::end(result));

    return result;
}

What this (the function) basically does is :

create a copy of the range we want to look in
sort it, by comparing values returned from the distance function between val and the element of the range, so that we have the nearest neighbours of val at the begining of our vector
compare the distances with a custom operator if provided, std::less if not
only keep the n elements we want

Now about the boilerplate :

I want to default the Compare type to std::less, which needs a type parameter. So we need to find the return type of the Distance object provided, and my solution here is what I found to work with both functions and lambdas.

Examples

Simple use case : retrieve the nearest values to an int. Distance between two ints will be the absolute value of their substraction.

const auto distance_int =
    [] (int i, int j)
    {
        return std::abs(i-j);
    };

std::vector<int> v = {56, 10, 79841651, 45, 59, 68, -20, 0, 36, 23, -3256};
auto res = {0, 10, 23, -20, 36};
auto found = find_n_nearest(std::begin(v), std::end(v), 4, 5, distance_int);

if(std::equal(std::begin(res), std::end(res), std::begin(found)))
    std::cout << "Success !" << std::endl;

To illustrate the use of the comparator, let's say I now define my "neighbourhood" of ints as being as distant as possible. In a word, the opposite of the precedent example.

std::list<int> v = {56, 10, 79841651, 45, 59, 68, -20, 0, 36, 23, -3256};
auto res = {79841651, -3256, 68, 59, 56};
auto found = find_n_nearest(std::begin(v), std::end(v), 4, 5, distance_int, std::greater<int>());

if(std::equal(std::begin(res), std::end(res), std::begin(found)))
    std::cout << "Success !" << std::endl;

Review

When I used this function, it was convenient to me to receive the results as a std::vector<T> but this is not very good as a generic algorithm.

There are two problems with this : I think we should not alter the original range, so sorting it is not an option. Then we have to copy it elsewhere, and for that I used my cache vector (not that much time to think about it during the project, and it was not a critical piece of code). I thought of replacing this by providing an OutputIt to the function, indicating where to put the results (for example an user-provided vector or whatever container), but I don't think I could sort the range in my algorithm, because the Output Iterator concept is used only to ... output things.

If there are more efficient algorithms (instead of sorting from distance) to do it feel free to tell me, but that's not my main concern. I'd like to have an elegant solution, and pieces of advice on anything you think is not quite good in my code.


texts:
For an embedded project I want to shift a (byte) array left by a certain amount of bits. I've built this template function to do so:

template <typename T>
constexpr void shift_array_left(T *arr, const size_t size, const size_t bits, const bool zero = false) {
    const size_t chunks = bits / (8 * sizeof(T));

    if (chunks >= size) {
        if (zero) {
            memset(arr, 0, size);
        }
        return;
    }

    if (chunks) {
        memmove(arr, arr + chunks, size - chunks);
        if (zero) {
            memset(arr + size - chunks, 0, chunks);
        }
    }

    const size_t left = bits % (8 * sizeof(T));

    // If we have non directly addressable bits left we need to move the whole thing one by one.
    if (left) {
        const size_t right = (8 * sizeof(T)) - left;
        const size_t l = size - chunks - 1;
        for (size_t i = 0; i < l; i++) {
            arr[i] = ((arr[i] << left) & ~left) | (arr[i+1] >> right);
        }
        arr[l] = (arr[l] << left) & ~left;
    }
}

Some questions I have:

I inferred from the memmove and memcpy relationships that memmove doesn't guarantee zeroing out any 'gap' created. Can I do away with the zeroing parts?
This function only makes sense for unsigned integer types, what is the best way to force the compiler to only accept these, without repeating function bodies?

I'd, of course, appreciate any further feedback / criticism.

Update: Live example in compiler explorer: https://godbolt.org/g/I3qDsL


texts: Returning status codes from business layer

texts:
This is what I've been doing so far in my business layer to return error messages to the user.

public void CreateMerchant(MerchantCreationModel model, out MerchantCreationStatus status)
{
    //check if merchantId exists
    MerchantDTO merchant = _merchantRepo.GetMerchant(model.MerchantId);

    if (merchant != null)
    {
        status = MerchantCreationStatus.MerchantAlreadyExists;
        return;
    }

    // Rest of merchant creation logic has been removed for clarity

    status = MerchantCreationStatus.Success;
}

I have a ErrorCodeToString() method in my controller that gets the text to display.

What do you think of this technique?


texts: Return a collection of most frequent characters in a string

texts:
My task was write a method that has input parameter - string  and this method must return a collection of symbols which are most frequently , for example:

input: ааа bbb с
ouput: а, b
input:  ааа bb с
ouput: a
а, b, с

а b с

Here is my bad code:

 static void test(string s)
        {
            int[] cc = new int[255];
            char c;

            for (c = (char)0; c < 255; c++)
            {
                cc[c] = 0;
            }

            for (int i = 0; i < s.Length; i++)
            {
                cc[s[i]]++;
            }
            int cntMax = 0;

            for ( c =(char) 0; c < 255; c++)
            {
             if(cc[c] > cntMax)
                {
                    cntMax = cc[c];
                }
            }
            string L = "";
            if(cntMax >0 )
            {
                for ( c = (char)0; c < 255; c++)
                {
                    if(cc[c] == cntMax)
                    {
                        if(c > (char) 32)
                        {
                            L = L + c + " ";
                            Console.WriteLine(L);
                        }
                    }

                }
            }
        }

So  , I don't sure if understand  , I must return collection of symbols , how to do it? How can I change my code?? And also I have a question about input: if I input a b c , then my program count spaces instread of symbols , how to fix it? Sorry for my very bad code


texts: Calculate the time it takes to achieve your money goal in Kotlin

texts:
I am writing a very simple test application in Kotlin for Android, where I just want to calculate the time it takes for someone to reach a specific amount of money, taking into count his salary and increase in salary each year.

I am very new to Android Studio, which is why I don't really know about the best practises yet. Currently, I wonder wheather I should put the EditText into global scope, so that I can access them without passing any parameters to all the functions.

This is my class:

class MainActivity : AppCompatActivity() {

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

        findViewById(R.id.resultsButton).setOnClickListener {

            val moneyField: EditText = findViewById(R.id.moneyField) as EditText
            val moneyGoal: Float = getNumberFromTextField(moneyField)

            val salaryField: EditText = findViewById(R.id.salaryField) as EditText
            val salary: Float = getNumberFromTextField(salaryField)

            val increaseField: EditText = findViewById(R.id.increaseField) as EditText
            val increase: Float = getNumberFromTextField(increaseField)

            calculateAndDisplayTimeUntilMoneyGoal(moneyGoal, salary, increase)
        }
    }

    fun getNumberFromTextField(field: EditText): Float {
        return field.text.toString().toFloat()
    }

    fun calculateAndDisplayTimeUntilMoneyGoal(goal: Float, salary: Float, increaseInPercent: Float){
        var moneyEarned: Float = 0f
        var currentSalary = salary
        var months: Int = 0
        var yearsPassed: Int = 0

        while (moneyEarned < goal){
            moneyEarned += currentSalary
            months++

            if (oneYearPassed(months)){
                currentSalary += increaseSalary(currentSalary, increaseInPercent)
                months = 0
                yearsPassed++
            }
        }

        val resultsString = "After $yearsPassed years and $months months you will have earned $moneyEarned!"
        (findViewById(R.id.displayText) as TextView).text = resultsString
    }

    fun oneYearPassed(months: Int): Boolean = (months == 12)

    fun increaseSalary(currentSalary: Float, increaseInPercent: Float): Float {
        return (currentSalary / 100) * increaseInPercent
    }
}

Any suggestions on how I can improve it? (Altough Kotlin is new to me, I have experience in other programming languages)


texts:
I just wrote an advanced CSV parser that translates CSV to SQL(SQLite Compatible) statements, which are then inserted into the database. It translates variable names in the CSV to values defined in the script.

Example CSV

0,1,An empty black tile,${ASSET_PATH}/BlackTile.png
1,1,Grassy Tile,${ASSET_PATH}/Grass.png
2,1,Lava Tile,${ASSET_PATH}/Lava.png
3,1,Stone Brick Texture,${ASSET_PATH}/StoneBrick.png

The code

# Variables that are used in the CSV files
ASSET_PATH=~/spacegame/assets

# $1 - File to read. Named same as table to insert to plus .csv
# $2 -
function parseCsvAdv2Db {
    local oldIFS=$IFS
    local table=$(echo $1 | cut -d'.' -f 1)
    local ins="INSERT INTO $table$2 VALUES"
    IFS='|'
    while read line
    do
        # Preprocess the line
        local data=$(eval echo "$line" | \
            awk 'BEGIN { FS=","; OFS="|"; } { $1=$1; print $0; }')
        local tmpdata=\(
        for field in $data
        do
            tmpdata+="'$field'"
        done
        tmpdata+=')'
        ins+="$tmpdata"
    done < $1

    ins=$(echo $ins | sed -e 's/)(/),(/g' -e "s/''/','/g")
    ins+=';'

    sqlite3 $dbfile "$ins"

    # Restore state
    IFS=$oldIFS
}

parseCsvAdv2Db test.csv '(id,type,descr,path)'


texts:
I'm using SharePoint 2013 JSOM. My variable this.templates contains a collection of templates with many different names. The only way to iterate through this collection is by using an Enumerator. I can only get the name of each template by using get_title().

I want to get the templates whose names respect the following rules:

It contains "espace_projet"
It contains the letter "v" followed by any number, once

Then, out of the templates i got, I want to get the one with the highest value that was after the "v".

I'm not used to JavaScript, this code works fine, but feels like overkill. How could I make it shorter/more readable?

ApplyTemplate()
{
    var highestVersion = {number: -1, template: null};
    var templateEnum = this.templates.getEnumerator();

    while(templateEnum.moveNext())
    {
        //Gets the element name in my collection
        var templateName = templateEnum.get_current().get_title();
        if(templateName.includes('espace_projet'))
        {
            var version = templateName.match('v[0-9]+|v_[0-9]+');
            if(version){
                var versionNumber = version[0].match('[0-9]+');
                if(versionNumber[0] > highestVersion.number)
                    highestVersion = {number: versionNumber[0], template: templateEnum.get_current()};
            }
        }
    }

    return highestVersion;
}


texts:
We have recently started working in ASP.NET and starting a simple CRUD Web application in ASP.Net. Here is the approach we are following to connect to DB.

Connection.cs

public class Connection
{
    public SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["CWConnectionString"].ConnectionString);
    private readonly log4net.ILog logger = log4net.LogManager.GetLogger("Connection.cs");

    public Connection()
    {
        //
        // TODO: Add constructor logic here
        //
    }

    public bool CheckOpenConnection()
    {
        try
        {
            if (con.State == ConnectionState.Open)
            {
                con.Close();
                return true;
            }
            else
            { return false; }
        }
        catch (Exception Ex)
        {
            logger.Error("Error in CheckOpenConnection : " + Ex.Message);
            return false;
        }
    }

    public void OpenConnection()
    {
        try
        {
            if (CheckOpenConnection() == false)
                con.Open();
        }
        catch (Exception Ex)
        {
            logger.Error("Error in OpenConnection : " + Ex.Message);
        }
    }

    public void CloseConnection()
    {
        try
        {
            if (CheckOpenConnection() == true)
                con.Open();
        }
        catch (Exception Ex)
        {
            logger.Error("Error in CloseConnection : " + Ex.Message);
        }
    }
}

Then we use some methods like this in another cs file

Dal_authentication.cs

public DataTable AuthenticateUser(string UserName, string Password)
{
    try
    {

        DataTable results = new DataTable();
        Connection cn = new Connection();
        cn.OpenConnection();
        string sql_SP = "uspAuthenticateLogin";

        using (SqlCommand cmd = new SqlCommand(sql_SP, cn.con))
        {
            cmd.CommandType = CommandType.StoredProcedure;

            cmd.Parameters.Add(new SqlParameter("@UserName", SqlDbType.NVarChar, 50));
            cmd.Parameters["@UserName"].Value = UserName;

            cmd.Parameters.Add(new SqlParameter("@Password", SqlDbType.NVarChar, 50));
            cmd.Parameters["@Password"].Value = Password;

            SqlDataAdapter da = new SqlDataAdapter(cmd);
            da.Fill(results);
        }
        cn.CloseConnection();

        return results;
    }
    catch (Exception Ex)
    {
        //logger.Error("AuthenticateUser : " + Ex.Message);
        return null;
    }
}

Is there any flaw in this approach? Is it the right way to connect to DB?  Are there any possible improvements?


texts: Listing WordPress posts with thumbnail images

texts:
I am using the following code poor form. I am interested in how I can optimise this and use the correct methods. I understand the DRY concept and will look to employ that throughout my code. However, this works and its pretty quick too, even with large result sets. I would like to learn and improve this code.

   <?php

global $current_user;
get_currentuserinfo();

$user_id = $current_user->ID;
$blogUrl = get_site_url();
global $wpdb;
$DBquery = "
SELECT *
FROM saved_collection
WHERE userid = '".$user_id."'
";

$result = $wpdb->get_results($DBquery);

$ids = array();
foreach($result as $row)
{

$collectionID = $row->id;
$collection_name = $row->collection_name;
$collectionURL = 'Programme Link';

echo '
';
echo '
' . $collection_name . '
';
echo  $collectionURL;
echo '

';
$cleandata = unserialize($row->collection_data);

  foreach($cleandata as $data)
  {
          $ids[] = $data['ExerciseID'];
        // START OF QUERY TO GET THE FIRST IMAGE FROM EACH EXERCISE
          global $wpdb;
            $query = "
            SELECT *
            FROM imagemap
            WHERE exercise = '".$data['ExerciseID']."'
            LIMIT 1
            ";

            $result = $wpdb->get_results($query);

            foreach($result as $row)

                 {
                  echo '
';
                // START OF QUERY TO GET NAME OF EACH IMAGE
                    global $wpdb;
                    $exerciseTitleQuery = "
                    SELECT post_title
                    FROM wp_posts
                    WHERE id = '".$data['ExerciseID']."'
                    LIMIT 1
                    ";
                    $exerciseTitleQueryResult = $wpdb->get_results($exerciseTitleQuery);
                    foreach ($exerciseTitleQueryResult as $returned_post_title)
                        {echo '
';
                             echo '
' .$returned_post_title->post_title. '
';
                             echo '
';
                        }
                // END OF QUERY TO GET NAME OF EACH IMAGE

                echo "id. ".jpg />";
                    //echo '
id. '.jpg);">
';

                  echo '
';
                  // end of div imageGridImages
         }
  }

echo '

';
echo '
';

}
?>


texts: Tic Tac Toe getWinner() method logic for a grid of any size nxn

texts:
I have a college assignment in which I have to make a Tic Tac Toe game work. Some of the code has been provided by my instructor like method signatures etc. Now the rules for this particular project state that a player wins if they get n consecutive spaces on an nxn grid. So 3 for 3x3, 5 for 5x5, etc. Now I got it to work for a 3x3 grid by kind of hard coding it.

Please have a look at how it is done in my code. Now I check if 3 cells contain the same player (X or O). But I don't know how to generalize my method as n increases.

package tictactoe;

/**
 * An implementation of the TicTacToeGame interface.
 *
 * ATTENTION STUDENTS: You MUST use exactly this class specification. Do not
 * rename the class, and do not remove the "implements TicTacToeGame", or
 * you will receive no credit for your submission.
 */
public class TicTacToe implements TicTacToeGame {
    int size;
    String whoseTurn = "X";//X,O,""
    String[] board;
    int count;
    /**
     * Constructs a new instance, implementing the TicTacToeGame interface.
     *
     * ATTENTION STUDENTS: You MUST use exactly this signature for your constructor.
     * Do not rename the class and do not change the argument, or you will receive
     * no credit for your submission.
     *
     * @param n the length and width of the board; n >= 3
     */
    public TicTacToe(int n) {
        size = n*n;
        board = new String[size];
        resetBoard();
        count = 0;
    }

    @Override
    public int getN() {
        return size;
    }

    @Override
    public String toString() {
        String result = "";
        int ctr = 1;
        for(int i = 0; i < size; i++){
            result += board[i];
            if(ctr % Math.sqrt(size) == 0)
                result += '\n';
            ctr++;
        }
        return result;
    }

    @Override
    public String getWinner() {
        int len = (int)(Math.sqrt(size));
        int diag = len - 1;
        int antiDiag = len + 1;
        for(int i = 0; i < (size - len); i++){
            if((board[i].equals("X")) && (board[i+1].equals("X")) && (board[i+2].equals("X")))
                return "X";
            if((board[i].equals("O")) && (board[i+1].equals("O")) && (board[i+2].equals("O")))
                return "O";

            if((board[i].equals("X")) && (board[i+len].equals("X")) && (board[i+2*len].equals("X")))
                return "X";
            if((board[i].equals("O")) && (board[i+len].equals("O")) && (board[i+2*len].equals("O")))
                return "O";

            if((board[diag].equals("X")) && (board[2*diag].equals("X")) && (board[3*diag].equals("X")))
                return "X";
            if((board[diag].equals("O")) && (board[2*diag].equals("O")) && (board[3*diag].equals("O")))
                return "O";

            if((board[antiDiag].equals("X")) && (board[2*antiDiag].equals("X")) && (board[3*antiDiag].equals("X")))
                return "X";
            if((board[antiDiag].equals("O")) && (board[2*antiDiag].equals("O")) && (board[3*antiDiag].equals("O")))
                return "O";
        }
        return "";
    }

    @Override
    public String getCurrentPlayer() {
        while(count < size)
            return whoseTurn;
        return "";
    }

    @Override
    public boolean isValidMove(int space) {
        if((count<(size)) && (board[space].equals(" ")))
            return true;

        whoseTurn = "";
        return false;

    }

    @Override
    public void move(int space) throws IllegalArgumentException {
        board[space] = this.getCurrentPlayer();
        if(whoseTurn.equals("X"))
            whoseTurn = "O";
        else
            whoseTurn = "X";

        count++;

    }
    private void resetBoard(){
        for(int i = 0; i < size; i++)
            board[i] = " ";
    }

}


texts:
I am trying to create a filter string according to the fields available with the following code, how could i improve the following with a switch case or better way?

   if ((this.selectedCity === 'City') && this.selectedCategory === 'Category' && this.fromDate === '') {
            this.filter = `{}`;
        } else if ((this.selectedCity !== 'City') && this.selectedCategory === 'Category' && this.fromDate === '') {
            this.filter = `{"location.city":"${this.selectedCity}"}`;
        } else if ((this.selectedCity === 'City') && this.selectedCategory !== 'Category' && this.fromDate === '') {
            this.filter = `{"category":"${this.selectedCategory}"}`;
        } else if ((this.selectedCity === 'City') && this.selectedCategory !== 'Category' && this.fromDate !== '') {
            this.filter = `{"date.start":{"$gte":"${this.fromDate}"},"date.end":{"$lt":"${this.toDate}"}}`;
        } else if ((this.selectedCity !== 'City') && this.selectedCategory !== 'Category' && this.fromDate === '') {
            this.filter = `{"location.city":"${this.selectedCity}","category":"${this.selectedCategory}"}`;
        } else if ((this.selectedCity !== 'City') && this.selectedCategory === 'Category' && this.fromDate !== '') {
            this.filter = `{"location.city":"${this.selectedCity}","date.start":{"$gte":"${this.fromDate}"},"date.end":{"$lt":"${this.toDate}"}}`;
        } else if ((this.selectedCity === 'City') && this.selectedCategory === 'Category' && this.fromDate !== '') {
            this.filter = `{"date.start":{"$gte":"${this.fromDate}"},"date.end":{"$lt":"${this.toDate}"}}`;
        } else if ((this.selectedCity !== 'City') && this.selectedCategory !== 'Category' && this.fromDate !== '') {
            this.filter = `{"location.city":"${this.selectedCity}","category":"${this.selectedCategory}","date.start":{"$gte":"${this.fromDate}"},"date.end":{"$lt":"${this.toDate}"}}`;
        }


texts:
This servlet takes an input from the user and

Stores the number inside the bean but with spaces in between each digit then stores the bean in the request scope.
If the last digit is even, sums the numbers and stores it in the request attribute. It will be displayed by even.jsp. Otherwise, the servlet forwards to odd.jsp and just displays the numbers.

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    numberBean bean = new numberBean();
    int sum = 0;
    char[] inputNumbers = request.getParameter("input").toCharArray();
    StringBuilder inputs = new StringBuilder();
    for (char digit: inputNumbers) {
        inputs.append(digit).append(" ");
    }
    bean.setInput(inputs.toString());
    request.setAttribute("input", bean);
    if (inputNumbers[inputNumbers.length - 1] % 2 == 0) {
        for (char digit: inputNumbers) {
            sum += Character.getNumericValue(digit);
        }
        request.setAttribute("sum", sum);
        request.getRequestDispatcher("/WEB-INF/even.jsp").forward(request, response);
    } else {
        request.getRequestDispatcher("/WEB-INF/odd.jsp").forward(request, response);
    }
}

I can't help thinking that this code is too long and can be shorter and better. How can I improve this code?


texts:
In an attempt to begin properly programming in Haskell, I wrote two functions for calculating numbers and sequences with Collatz's conjecture. I also commented the program quite a lot, because it helps me with my remembering of certain things.

-- The Collatz sequence takes in a number, and either
-- divides by 2 if it is even, or
-- multiplies it by 3 and adds 1 if it is odd.
-- The famous Collatz conjecture asks whether the sequence,
-- from any positive initial value, will reach 1.

-- a guard expression is used for the 'collatz' variable,
-- used for finding the next number in a sequence. This is
-- neater than if / else if.
collatz n
    | n `mod` 2 == 0 = n `div` 2 -- if n is even, return n / 2
    | otherwise = 3 * n + 1 -- else return 3n + 1

-- another guard expression, this time for the variable that
-- generates whole sequences. it is recursive, and takes
-- advantage of the 'collatz' variable too.
cltzList n
    | n <= 0 = error "The number must be positive."
    | n == 1 = [n] -- if n is 1 return n:[]
    | otherwise = n:cltzList (collatz n) -- else, recursive-call

How have I done? Are there any big mistakes, or small things I can improve?


texts: A PHP script used on my home server to download YouTube videos

texts:
I have a PHP page I used to download YouTube videos, hosted on my Pi 4.

The site is only going to be used on my home network (so a dot local address), but it allows me to download videos on my phone or computer without downloading any executables or special apps.

The user can submit a request on an HTML page with four options:

Form ID      : Description to user
----------------------------------------
bestquality  : MP4 (video with sound)
worstquality : MP4 (video without sound)
bestaudio    : M4A
worstaudio   : WEBM

This is a majority of the code used to make this:

<?php

//the file extension
$formatExt = "";

switch($_GET['format']) {
    case 'bestvideo': case 'worstvideo': $formatExt = "MP4"; break;
    case 'bestaudio': $formatExt = "m4a"; break;
    case 'worstaudio': $formatExt = "webm";
        break;
    default:
        echo("Illegal video format '".$_GET['format']."'!");
        exit(1);
}

$url = $_GET['url'];
$format = $_GET['format'];
$ytcmd = 'youtube-dl';

$directoriesInUse = array_filter(glob("./workers/*"), 'is_dir');

$integerIDs = array(sizeof($directoriesInUse));

//if the working directory changes, make sure to change the 2 at the end of the
//expression in the for loop to match the amount of '/' characters.
for($i = 0; $i < sizeof($directoriesInUse); $i++)
    $integerIDs[$i] = (int)explode("/", $directoriesInUse[$i])[2];

//If these are not sorted, it will see a list of 1 thru 14 and pick 9 as the largest number (because that's how the directory would be listed)
sort($integerIDs);

$numberToUse = $integerIDs[sizeof($integerIDs) - 1] + 1;

//prevent exploiting and issuing server commands
$url = str_replace(" ", "", $url);
$url = str_replace("|", "", $url);

//url may contain & for a playlist, so it will be removed here to prevent other issues.
$url = substr($url, 0, strpos($url, "&"));

//Download the video, the "--format" option will not download audio for a video (worstvideo is video w/o audio)
if($format === "bestaudio" or $format === "worstaudio" or $format === "worstvideo")
        $response = exec('mkdir ./workers/'.$numberToUse.' && cd ./workers/'.$numberToUse.'/ && '.$ytcmd.' --no-playlist --format '.$format.' -o \'%(title)s.%(ext)s\' '.$url);
else
        $response = exec('mkdir ./workers/'.$numberToUse.' && cd ./workers/'.$numberToUse.'/ && '.$ytcmd.' --no-playlist -o \'%(title)s.%(ext)s\' '.$url);

//Get the first file in a directory, this SHOULD be the video that was downloaded.  It is not possible (AFAIK) to get the file name of a video from the youtube-dl binary
function magicWorkers($path) {
    return array_diff(scandir($path), array('.', '..'))[2];
}

//change file date so the crontab doesn't delete the file too early (youtube-dl may save the file with the date it was uploaded)
echo exec("touch ./workers/".$numberToUse."/".magicWorkers("./workers/".$numberToUse));

//sleep 2 seconds for good measure (in case things haven't updated for whatever reason, this has happened!)
sleep(2);

//This works, but I would like to find an alternative soon (prompt download vs direct)
header("Location: ./workers/".$numberToUse.'/'.magicWorkers("./workers/".$numberToUse));

exit(0);

The server is being hosted on an Apache2 web server in the /var/www/html/ directory, and Apache2 has rw- access in the /var/www/html/workers/ directory.

I have seen some security problems with this before, for instance, inputting example.com/video && cowsay MOO will execute the cowsay command, so I made a small patch by disabling the characters " " (space), "&", and "|".

My other concern is that I am linking the user directly to the file to download, whereas it would be better (and probably more secure) if they were prompted for the download.

One last thing: I have a crontab that runs every minute to delete files in the workers directory (older than two hours) to make sure that the space on the Pi doesn't fill up (directories do not get deleted).


texts: Finding the possible number of equal pairs in an array

texts:
I got this test online last week.
here is an example:
given this array:

{ 1 , 2 , 4 , 5 , 1 , 4 , 6 , 2 , 1 , 4 }

on condition that

index(x) < index (y)

find the number of possible pairs (x,y).
where x = y.
the answer would be:

count = 7 - (0,4), (0,8), (4,8), (1,7), (2,5), (2,9), (5,9)

Edit3: added picture to clarify the pairs are elements from the same array. the picture has the first 3 pairs.

the first solution I came up with which was obviously bad:
public static int solution(int[] A)
    {
        int count = 0;
        for (int i = 0; i < A.Length; i++)
        {
            for (int j = i + 1; j < A.Length; j++)
            {
                if (A[i] == A[j])
                    count++;
            }
        }
        return count;
    }

basically, just count the number of possible pairs in each loop.
then after a bit of struggle I managed to do this:
public static int solution(int[] A)
        {
            int count = 0;
            var dict = new Dictionary<int, int>();
            for (int i = 0; i < A.Length; i++)
            {
                if (!dict.Any(x => x.Key == A[i]))
                    dict.Add(A[i], 1);
                else
                    dict[A[i]]++;
            }

            foreach (var item in dict)
            {
                count += Factorial(item.Value) / 2 * Factorial(item.Value - 2);
            }

            return count;
        }

1- count how many times the number is present.
2- calculate the possible pairs for each number which is given by this formula:

where n is the number of repetitions and r = 2 (pair, 2 items)
Factorial is just a simple implementation of the function.
I feel like there is a lot to improve on this. what do you think?
Edit: added the Factorial Function as requested:
public static int Factorial(int N)
        {
            return N == 0
                       ? 1
                       : Enumerable.Range(1, N).Aggregate((i, j) => i * j);
        }

Edit2:
I tested both and got 20s for the first method and 500ms for the second improved method.
the 100000 was the limit set by the test details.
here is the code for the test:
int[] testArray = new int[100000];
Random x = new Random();
for (int i = 0; i < testArray.Length; i++)
{
   testArray[i] = x.Next(1, 10);
}
Stopwatch sw = new Stopwatch();
sw.Start();
solution(testArray);
sw.Stop();

Edit4:
Well, it seems like I messed up!
calculating factorial for numbers bigger 19 in intger is not possible, out of range.
the worse is I didn't even have to calculate it.
in my formula since r is a constant I could simplify it to

n* (n -1) / 2

thus avoiding the entire thing.


texts: Populating monthly report with new data each month

texts:
This code basically checks a cell for the current date and then fills out the report by finding that date and placing the correct values in the correct places. It works fine I just know that I am going to need to build something similar for many other reports so I am hoping to update, streamline and improve in any way I can.

 Sub Copy_Data()
        Dim Data As Worksheet
            Set Data = ThisWorkbook.Worksheets("Data")
        Dim Turnover2017 As Worksheet
            Set Turnover2017 = ThisWorkbook.Worksheets("2017 Turnover")      '*************** Edit Year Number here upon creation of next year's tab
        Dim FindDate As Date
            FindDate = Data.Range("FindDate").Value
        Dim HCRNG As Range
        Dim NTRNG As Range
        Dim PTRNG As Range
        Dim X As Integer
        Dim HCNUM As Integer
        Dim NTNUM As Integer
        Dim PTNUM As Integer

        For X = 1 To 11
            '******* This  block scoops data from the Data tab
            HCNUM = Data.Range("B2").Offset(X, 0).Cells.Value
            NTNUM = Data.Range("C2").Offset(X, 0).Cells.Value
            PTNUM = Data.Range("D2").Offset(X, 0).Cells.Value
                With Turnover2017.Range("A:AM")      '*************** Edit Year Number here upon creation of next year's tab
                    Set HCRNG = .Find(What:=(FindDate), _
                        After:=Range("A1"), _
                        LookIn:=xlFormulas, _
                        LookAt:=xlPart, _
                        SearchOrder:=xlByRows, _
                        SearchDirection:=xlNext, _
                        MatchCase:=False, _
                        SearchFormat:=False)
                            HCRNG.Offset(X, 2).Cells.Value = HCNUM   '******** This updates the appropriate column based on the date determined in Data G2 aka. range "FindDate"
                            HCRNG.Offset(X + 15, 2).Cells.Value = HCNUM   '******** This updates the appropriate column based on the date determined in Data G2 aka. range "FindDate"
                    End With
                With Turnover2017.Range("A:AM")      '*************** Edit Year Number here upon creation of next year's tab
                    Set NTRNG = .Find(What:=(FindDate), _
                        After:=Range("A18"), _
                        LookIn:=xlFormulas, _
                        LookAt:=xlPart, _
                        SearchOrder:=xlByRows, _
                        SearchDirection:=xlNext, _
                        MatchCase:=False, _
                        SearchFormat:=False)
                            NTRNG.Offset(X, 1).Cells.Value = NTNUM     '******** This updates the appropriate column based on the date determined in Data G2 aka. range "FindDate"
                    End With
                With Turnover2017.Range("A:AM")      '*************** Edit Year Number here upon creation of next year's tab
                    Set PTRNG = .Find(What:=(FindDate), _
                        After:=Range("A1"), _
                        LookIn:=xlFormulas, _
                        LookAt:=xlPart, _
                        SearchOrder:=xlByColumns, _
                        SearchDirection:=xlNext, _
                        MatchCase:=False, _
                        SearchFormat:=False)
                            PTRNG.Offset(X, 1).Cells.Value = PTNUM    '******** This updates the appropriate column based on the date determined in Data G2 aka. range "FindDate"

                     End With

        Next X

    End Sub


texts:
I am just trying to use Go so I will be thankful for all remarks and corrections:

package main

import "fmt"

func selectionSort(a []int) []int {

    for i := 0; i < len(a); i++ {

        min := i

        for j:= i + 1; j < len(a); j++ {
            if a[j] < a[min] {
                min = j;
            }
        }

        var tmp int = a[i]
        a[i] = a[min]
        a[min] = tmp
    }

    return a
}

func main() {

    values := []int { 5, 8, 4, 1, 7,  2, 3, 6 }
    result := selectionSort(values)
    fmt.Println(result)
}


texts:
I wrote a simple and small projects that present 3 buttons, each one loads a different list to the screen on the same place but not in the same time.

In my HTML, I think I can maybe use some more generic way to present the lists:

  <button md-button
          (click)="showFirstList()"
          class="md-primary">List 1
  </button>

  <button md-button
          (click)="showSecondList()"
          class="md-primary">List 2

  </button>

  <button md-button
          (click)="ThirdList()"
          class="md-primary">List 3

  </button>

    <md-content>

            ID: {{item.id}}

 name: {{item.name}}

            ID: {{item.id}}

 age: {{item.age}}

            ID: {{item.id}}

 age: {{item.age}}

    </md-content>

Now this is my component.ts. I know it's horrible and I would love to get suggestions how cI can make it look better and not repetitive. Specifically, how I can use enums instead of the booleans to make it look much better, and where I should put the calls I do for the service to get the data. It's an API calls and it doesn't make sense to call them all three when the class is loaded.

This is my sorting-lists.component.ts:

@Component({
  selector: 'sorting-lists',
  styles: [require('./sorting-lists.css')],
  directives: [DND_DIRECTIVES],
  providers: [DND_PROVIDERS],
  template: require('./sorting-lists.component.html')
})

@Injectable()
export class MyCmp implements OnInit {

  listOneToDisplay  = this._myService.getFirstListData();
  listTwoToDisplay = this._myService.getSecondListData();
  listThreeToDisplay = this._myService.getThirdListData();

  showingListOne = false;
  showingListTwo = false;
  showingListThree = false;

  constructor(private _myService: MyService) {
  };

  public showFirstList(): void {
    this.showingListOne = true;
    this.showingListTwo = false;
    this.showingListThree = false;
  }

  public showSecondList(): void {
    this.showingListTwo = true;
    this.showingListOne = false;
    this.showingListThree = false;
  }

  public showThirdList(): void {
    this.showingListThree = true;
    this.showingListTwo = false;
    this.showingListOne = false;
  }

}


texts: Validating a search string for an SQL text search

texts:
Is it safe to allow these special characters when validating a string? The user is currently allowed to send alpha numeric and the following special characters from the browser:

',.!&()_-

My main concern is code injection. I'm still learning Laravel and I understand it handles a lot security wise. I'd like to make sure I'm taking solid precautions for good security.

I have the following code which uses the PHP Laravel framework to validate on the server side:

$this->validate($request, [
    'str' => 'bail|required|regex:/^[a-zA-Z0-9 \',.!&_-]+$/u'
]);

$search_str = $request->str;

$query = Story::where('story_text', 'LIKE', '%'.$search_str.'%');

Is this sufficiently secure or is there more I should be doing?


texts: Simplify SQL query that utilizes GROUP BY and HAVING BY and uses aggregation

texts:
I am taking Stanford's Introduction to Databases Self-Paced online course. I have gone through the videos in the SQL mini-course, and I am having trouble completing the exercises.

The following is the question from the SQL Movie-Rating Query Exercises, Question 6:

  For all cases where the same reviewer rated the same movie twice and
  gave it a higher rating the second time, return the reviewer's name
  and the title of the movie.

The database can be found here.

My answer to this question is very complex; so much so that I the length of my query exceeds the query character limit in class. I will post my solution in steps, since I think that might help surface some of my conceptual misunderstandings.

Step 1:Give me all the movies where the same reviewer reviewed the same movie twice

SELECT Rating.rID, Rating.mID
FROM Rating
GROUP BY Rating.rID, Rating.mID
HAVING count(*) > 1;

Step 2: Let's join the three tables so that all the information is in one place:

SELECT Movie.mID, Movie.title, Movie.year, Movie.director, Rating.rID,
       Rating.stars, Rating.ratingDate, Reviewer.name
FROM Movie, Rating, Reviewer
WHERE Movie.mID = Rating.mID and Rating.rID = Reviewer.rID;

Step 3: Filter the result set in Step 2 so that it only contains tuples that are also in Step 1

SELECT *
FROM
(SELECT Movie.mID, Movie.title, Movie.year, Movie.director, Rating.rID,
       Rating.stars, Rating.ratingDate, Reviewer.name
FROM Movie, Rating, Reviewer
WHERE Movie.mID = Rating.mID and Rating.rID = Reviewer.rID) compiled
WHERE compiled.mID in
(SELECT Rating.mID
FROM Rating
GROUP BY Rating.rID, Rating.mID
HAVING count(*) > 1) and compiled.rID in (SELECT Rating.rID
FROM Rating
GROUP BY Rating.rID, Rating.mID
HAVING count(*) > 1);

Step 4: Return the result set from Step 3 twice so that we can compare them the rating, reviewer, movie, stars and date

SELECT view_one.name, view_one.title
FROM (SELECT *
FROM
(SELECT Movie.mID, Movie.title, Movie.year, Movie.director, Rating.rID,
       Rating.stars, Rating.ratingDate, Reviewer.name
FROM Movie, Rating, Reviewer
WHERE Movie.mID = Rating.mID and Rating.rID = Reviewer.rID) compiled
WHERE compiled.mID in
(SELECT Rating.mID
FROM Rating
GROUP BY Rating.rID, Rating.mID
HAVING count(*) > 1) and compiled.rID in (SELECT Rating.rID
FROM Rating
GROUP BY Rating.rID, Rating.mID
HAVING count(*) > 1)) view_one, (SELECT *
FROM
(SELECT Movie.mID, Movie.title, Movie.year, Movie.director, Rating.rID,
       Rating.stars, Rating.ratingDate, Reviewer.name
FROM Movie, Rating, Reviewer
WHERE Movie.mID = Rating.mID and Rating.rID = Reviewer.rID) compiled
WHERE compiled.mID in
(SELECT Rating.mID
FROM Rating
GROUP BY Rating.rID, Rating.mID
HAVING count(*) > 1) and compiled.rID in (SELECT Rating.rID
FROM Rating
GROUP BY Rating.rID, Rating.mID
HAVING count(*) > 1)) view_two
WHERE view_one.rID = view_two.rID and view_one.mID = view_two.mID and
view_one.ratingDate < view_two.ratingDate and view_one.stars < view_two.stars;

This seems like a very tortured query, and it seems to me like I am missing some important concepts. Can someone help me refactor this query?


texts: Slow updates with updating rows in database with preparedStatement

texts:
I have been shifting all of my SQL queries to prepared statements in the past few weeks and all of the INSERT statements run extremely fast, however, UPDATE is taking an inordinate amount of time.  At present, I am adding to the prepared statement then sending.  Updating 20 records can take over two minutes sometimes.  Here is my code:

if (updatePhoneList.elements().size()>0) {
        LOGGER.info("Will process " + updatePhoneList.elements().size() + " records");
        Date startDate = new Date();
        try {
            String compiledQuery = "UPDATE CUSTDATA.CUST_CONTACT_INFO SET CBR = ?, LAST_UPDATED_TIME = SYSDATE "
            + "WHERE ORDER_ID = ? AND CUSTNUM = ?";
            PreparedStatement bulkInsertStatement = dbConnection.prepareStatement(compiledQuery);
            for(int arrayPos = 0; arrayPos <= updatePhoneList.elements().size() -1 ; arrayPos++) {
                currentCust = updatePhoneList.elements().get(arrayPos).prop("CUSTNUM").stringValue();
                currentPhone = updatePhoneList.elements().get(arrayPos).prop("CUSTPHONE").stringValue();
                bulkInsertStatement.setString(1, currentPhone);
                bulkInsertStatement.setString(2, currentCust);
                bulkInsertStatement.setString(3, outageId);

            }
            updatedRecords = bulkInsertStatement.executeBatch();
            bulkInsertStatement.close();
            Date endDate = new Date();
            long execTimeMSec = (endDate.getTime()-startDate.getTime());
            LOGGER.info("Returning success: " + success);
        } catch (Exception e) {
            success = false;
        }
    }

When I wrote this , I had no indices, but indexed the CUST_CONTACT_INFO to index on ORDER_ID and CUSTNUM.  It runs markedly faster.


texts: JQGrid with dynamic columns and server-side functionality

texts:
I have a requirement where I need to build a grid with dynamic columns. I am dealing with a large dataset so I would like to use server-side paging, sorting, filtering logic so that I render only a page-size. I think I got the basic functionality working but just wanted to get my approach reviewed.

An action route will be the JSON datasource for the jqgrid.

Reference

My approach:

First make an ajax call to get the dynamic col model and other grid params (rows, page etc.) except data.
Update grid params (url, datatype and mtype) to enable server-side paging, sorting etc.

I am using a flag in the query string to determine if I need the col model (or) the data.

Note: I set the async flag to false for the AJAX requests to make sure I do not run into timing issues.

As you can see, I need to make two requests to set up the grid. One to get the col model and another one to get data and to update it to enable server-side interaction for subsequent requests. Is this ok?

$.ajax({
    url: firstFetchURL, //will hit an asp.net mvc action on a controller that returns json
    dataType: "json",
    type: 'POST',
    async: false,
    success: function (result) {

        if (result) {

            if (!result.Error) {

                var colD = result.data;
                var colM = result.colModelList;
                var colN = result.columnNames;

                $("#myGrid").jqGrid('GridUnload');

                $("#myGrid").jqGrid({ datatype: 'local',
                    colModel: colM,
                    colNames: colN,
                    data: colD,
                    height: "auto",
                    rowNum: 10,
                    sortname: viewOptionText,
                    sortorder: "desc",
                    pager: '#myGridPager',
                    caption: "Side-by-Side View",
                    viewrecords: true,
                    gridview: true
                });

                //Update grid params so that subsequent interactions with the grid for sorting,paging etc. will be server-side

                $("#myGrid").jqGrid('setGridParam', { url: secondFetchURL, datatype: 'json', mtype: 'POST' }).trigger('reloadGrid');

            }
        }
    },
    error: function (xhr, ajaxOptions, thrownError) {
        if (xhr && thrownError) {
            alert('Status: ' + xhr.status + ' Error: ' + thrownError);
        }
    },
    complete: function () {
        $("#loadingDiv").hide();
    }
});

I saw a related post here, but I am looking for some direction from experienced JQGrid users.


texts: PHP autoload class design for a framework

texts:
I'm developing a php framework called Stack. I just created the autoload.php as follows.

<?php
namespace Stack\Application;

define('ROOT', __DIR__);
class AutoLoader
{
    private static $pos = false;
    private static $namespace_path = NULL;
    private static $namespace_name = NULL;
    private static $file = NULL;
    /**
     * Set qualified name Stack\Application
     */
    public static function register()
    {
        spl_autoload_register('Stack\Application\AutoLoader::useNamespace');
    }
    public function unregister()
    {
        spl_autoload_unregister('Stack\Application\AutoLoader::useNamespace');
    }
    private static function useNamespace($namespace)
    {
        /**
         * @var $namespace namespace name
         * @var $pos — Find the position of the last occurrence of a class in a fully qulified $namespace
         */
        if (false !== $pos = strrpos($namespace, '\\')) {
            $pos            = strrpos($namespace, '\\');
            $namespace_path = str_replace('\\', DIRECTORY_SEPARATOR, substr($namespace, 0, $pos)) . DIRECTORY_SEPARATOR;
            $namespace_name = substr($namespace, $pos + 1);
            $file           = ROOT . DIRECTORY_SEPARATOR . '../..' . DIRECTORY_SEPARATOR . $namespace_path . $namespace_name . '.php';
            if (!file_exists($file)) {
                return false;
            }
            include $file;
        }
    }
}

Bootstrap.php

<?php

require_once __DIR__.'/AutoLoader.php';

use Stack\Application\AutoLoader as App;

App::register();

?>

index.php

<?php

    require_once __DIR__.'/../Application/Bootstrap.php';

    $model = new Stack\Application\Models\Model();

    $controller = new Stack\Application\Controllers\Controller($model);

    $view = new  Stack\Application\Views\View($model);

    echo $view->output();

    ?>

My directory structure of the framework as follows

 - Stack
 --Application
 ---configs
 ---docs
 ---layouts
 ---modules
 ---Views
 ---Controllers
 ---forms
 ---Models
 ---services
 ---AutoLoader.php
 ---Bootstrap.php
 --data
 --docs
 --library
 --public
 ---index.php
 --scripts
 --temp

I'm going to keep same namespace name for the corresponding directory structure. Am i doing this right ?


texts: Looking to shorten method of parsing arguments in BASH

texts:
I have here a working method of parsing input arguments however it seems redundant. I would like to shorten this code so it doesn't appear so repetitive.

tool.sh <file-to-use>
tool.sh <file-to-use> -o <output-file-name>

# If arguments are set and equals "-o" then set APP_NAME
if [[ -n $3 ]] && [[ $2 = "-o" ]]; then
    APP_NAME=$3

# If argument is set and equals anything besides "-o" throw error and show help menu
elif [[ -n $2 ]] && [[ $2 != "-o" ]]; then
    echo "ERROR: Synatx error."
    bash $0 -h
    exit

# If "-o" is set but they did not give a output name throw error and display help menu
elif [[ -z $3 ]] && [[ $2 = "-o" ]]; then
    echo "ERROR: Did not specify output file name."
    bash $0 -h
    exit
fi


texts: Compare and Process Common and Uncommon files separately

texts:
I have the following files:

STUDENT_D19001.T103412_HU.txt
STUDENT_D19001.T103412_KU.txt
STUDENT_D19002.T113030_HU.txt
STUDENT_D19002.T115055_KU.txt
STUDENT_D19003.T115055_KU.txt
STUDENT_D19004.T135040_HU.txt

I want to process the common/pair files separately in this order (HU1 and then KU1; HU2 and then KU2) and the uncommon/unpaired files separately.

These two files (STUDENT_D19001.T103412_HU.txt and STUDENT_D19001.T103412_KU.txt) are common/pair files because they have same day of the year 001 in their name. However, these two files (STUDENT_D19003.T115055_KU.txt and STUDENT_D19004.T135040_HU.txt) are uncommon/unpaired because the do not have the same day of year with other files.

The output of the script is illustrated below for further clarification:

*** Uncommon/Unpaired files: ***
Processing './STUDENT_D19003.T115055_KU.txt'
Processing './STUDENT_D19004.T135040_HU.txt'

*** Common/Pair files: ***
1 of : 4 './STUDENT_D19001.T103412_HU.txt'
2 of : 4 './STUDENT_D19001.T103412_KU.txt'
3 of : 4 './STUDENT_D19002.T113030_HU.txt'
4 of : 4 './STUDENT_D19002.T115055_KU.txt'

Here is the script for review:

#!/bin/bash

SOURCE_DIR="."

#
# Create an array of all the HU files
#
HU_files=()
while IFS='' read -r -d '' file
do
    HU_files+=("$file")
done < <(find "$SOURCE_DIR" -maxdepth 1 -type f -iname "*HU*" -printf '%p\0' | sort -zn)

#
# Calculate HU total files
#
total_HU="${#HU_files[@]}"

#
# Create an array of all the BFV files
#
KU_files=()
while IFS='' read -r -d '' file
do
    KU_files+=("$file")
done < <(find "$SOURCE_DIR" -maxdepth 1 -type f -iname "*KU*" -printf '%p\0' | sort -zn)

#
# Calculate KU total files
#
total_KU="${#KU_files[@]}"

# Find common/pair HU and KU files considering partial part name 'STUDENT_D19001'
COMMON_files=()
i=0
k=0

while [ $i -lt $total_HU ]
do
    j=0
    while [ $j -lt $total_KU ]
    do
        if [[ "${HU_files[$i]/.T*/}" == "${KU_files[$j]/.T*/}" ]]
        then
            COMMON_files[$((k++))]="${HU_files[$i]}"
            COMMON_files[$((k++))]="${KU_files[$j]}"
            break
        else
            ((j++))
        fi
    done
    ((i++))
done

# Process uncommon/unpaired HU and KU files
echo "*** Uncommon/Unpair files: ***"
while IFS='' read -r -d '' file
do
    if [[ ! "${COMMON_files[@]}" =~ "${file}" ]]
    then
    echo "Processing '$file'"
    fi
done < <(find "$SOURCE_DIR" -maxdepth 1 -type f \( -iname "*HU*.txt" -o -iname "*KU*.txt" \) -printf '%p\0' | sort -zn)

#
# Process the common/pair HU and KU files
#
total_COMMOM="${#COMMON_files[@]}"
counter=0
echo "*** Common/Pair files: ***"
for file in "${COMMON_files[@]}"
do
    echo "$((++counter)) of $total_COMMOM: '$file'"
done

Your inputs are appreciated :-)


texts: JavaFX FreeTTS program lags on MacOSX. Load wheel

texts:
I am working on a personal project and I am new to app development in general also java and javafx. I have some code that works. Only, I am unsure why I get the mac loader wheel once my button to play sound is clicked.

The entire stage seems to just freeze until the program finishes a outputting speech from a given input.

In my SpeechController.java I have:

import Speech.SpeechManipulator;

public class SpeechController {
    @FXML private TextArea voiceField;

    @FXML private void playClick() {
        SpeechManipulator spm = new SpeechManipulator();
        String textString = voiceField.getText();
        spm.say(textString);
    }
}

In my SpeechManipulator.java I have:

import com.sun.speech.freetts.Voice;
import com.sun.speech.freetts.VoiceManager;
import java.io.*;

public class SpeechManipulator {
    public void say(String speech) {
        InputStream input = new ByteArrayInputStream(speech.getBytes());
        BufferedReader reader = new BufferedReader(new InputStreamReader(input));

        String voiceName = "kevin16";
        Voice voice;
        VoiceManager voiceManager = VoiceManager.getInstance();
        voice = voiceManager.getVoice(voiceName);
        voice.allocate();
        voice.setRate(160);
        voice.setPitch(90);

        String line;
        try {
            while ((line = reader.readLine()) != null) {
                voice.speak(line);
            }
            reader.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

        voice.deallocate();
    }
}

I had experimented the use of string input only before I thought about using buffered reader. My program will make a load wheel no matter the input. Even for a 2-3 word string. This is not efficient. I can't find any sources on the internet to understand why freeTTS is behaving this way.

If you wish to see more of the code that is not included I will add it. Other code in these classes are based on other FXML elements like buttons etc.

The method playClick() is defined in an fxml file as an on action event listener.


texts: Finding the closest string match for each string in two dataframe columns

texts:
I was wondering what's the fastest method to compare similarity between two lists of strings (e.g. two dataframes, documents etc.) using levenshtein distance or other procedures.

I am currently using:

def wuzzyfuzzy(df1, df2):
    myList = []
    total = len(df1)
    for idx1, df1_str in enumerate(df1.col1):
        myDict = {}
        my_str = ('Progress : ' + str(round((idx1/total)*100,3))+'%')
        sys.stdout.write('\r' + str(my_str))
        sys.stdout.flush()

        for idx2, df2_str in enumerate(df2.col1):
            s = SequenceMatcher(None, df1_str, df2_str)
            r = s.ratio()
            myDict.update({df2_str:r})
        best_match = max(myDict, key=myDict.get)
        myList.append([df1_str, best_match, myDict[best_match]])

    return myList

As the dataframes that are passed to the function have both > 30.000 values, it takes currently around 6 hours to compare each value in df1 with all other values in df2 to find the best match.

Of course I cleaned the strings as good as possible beforehand (all lowercase, get rid of punctuations etc.)

What's the most efficient way to perfom such task?


texts: Thread-safe LRU Cache Implementation in Java

texts:
I am trying to implement a thread-safe LRU cache algorithm, please review my code and would really appreciate some criticism or suggestion.
Some assumptions:

capacity will be larger than 0

Some questions I have:

I know it is better to encapsulate variables in a class and declare them private, but since DDLNode is simply a data class, is it acceptable to make the variables public ?

I am considering to extract the following block of code (inside put) into a function (something like addEntry(key, value)
DDLNode<K, V> node = new DDLNode<>(key, value);
addNode(node);
entries.put(key, node);

do you think it's neccesary? or the original code is self-explanatory enough?

Here is the code, Thanks in advance!!
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.ReentrantLock;

interface CacheAlgorithm<K, V> {

    public V get(K key);

    public void put(K key, V value);
}

class DDLNode<K, V> {

    public V value;
    public K key;
    public DDLNode<K, V> prev;
    public DDLNode<K, V> next;

    public DDLNode() {}

    public DDLNode(K key, V value) {
        this.key = key;
        this.value = value;
    }
}

public class LRU<K, V> implements CacheAlgorithm<K, V> {

    private final ReentrantLock lock;
    private final int capacity;
    private final Map<K, DDLNode<K, V>> entries;
    private final DDLNode<K, V> head;
    private final DDLNode<K, V> tail;

    public LRU(int capacity) {
        this.capacity = capacity;
        lock = new ReentrantLock();
        head = new DDLNode<>();
        tail = new DDLNode<>();
        entries = new HashMap<>(capacity);
        head.next = tail;
        tail.prev = head;
    }

    @Override
    public V get(K key) {
        lock.lock();
        try {
            if (!entries.containsKey(key)) {
                return null;
            }
            DDLNode<K, V> node = entries.get(key);
            moveToMostRecent(node);
            return node.value;
        } finally {
            lock.unlock();
        }
    }

    @Override
    public void put(K key, V value) {
        lock.lock();
        try {
            if (entries.containsKey(key)) {
                DDLNode<K, V> node = entries.get(key);
                node.value = value;
                moveToMostRecent(node);
            } else {
                if (entries.size() == capacity) {
                    removeLeastRecentEntry();
                }
                DDLNode<K, V> node = new DDLNode<>(key, value);
                addNode(node);
                entries.put(key, node);
            }
        } finally {
            lock.unlock();
        }
    }

    private void removeLeastRecentEntry() {
        entries.remove(tail.prev.key);
        removeNode(tail.prev);
    }

    private void moveToMostRecent(DDLNode<K, V> node) {
        removeNode(node);
        addNode(node);
    }

    private void removeNode(DDLNode<K, V> node) {
        DDLNode<K, V> prev = node.prev;
        DDLNode<K, V> next = node.next;
        prev.next = next;
        next.prev = prev;
    }

    private void addNode(DDLNode<K, V> node) {
        DDLNode<K, V> headNext = head.next;
        head.next = node;
        node.prev = head;
        headNext.prev = node;
        node.next = headNext;
    }
}

```


texts: Searching for categories and storing them

texts:
This checks each row for a category. It stores ONE version of the category, ignore duplications. It then counts how many times a category appears.

There are a lot of for loops and a lot of table-checking. This takes time as the table is quite large. If it's possible, I would like to incorporate some of the loops to reduce time spent.

public partial class Stats : Form
{
    public Stats(ref TabControl languageTabs)
    {
        InitializeComponent();

        for (int i = 0; i < languageTabs.TabCount; i++)
        {
            Control[] ctrls = languageTabs.TabPages[i].Controls.Find(languageTabs.TabPages[i].Name + "Grid", true);
            DataGridView dgv = ctrls[0] as DataGridView;

            int charCount = 0;
            for (int j = 0; j < dgv.RowCount; j++)
            {
                charCount += (int)dgv.Rows[j].Cells[4].Value;
            }

            treeView1.Nodes.Add(languageTabs.TabPages[i].Text.ToUpper() + " Statistics");
            treeView1.Nodes[i].Nodes.Add("Total Number Of Strings: " + dgv.RowCount); // might need to remove '--' from count
            treeView1.Nodes[i].Nodes.Add("Total Number Of Chars: " + charCount);
            treeView1.Nodes[i].Nodes.Add("Total Number Of Strings and Chars per Category: ");

            //check for all different categories
            List<string> categories = new List<string>();

            int count = 0;
            for (int j = 0; j < dgv.RowCount; j++)
            {
                // look at every category in the dgv and see if we have a unique value in a container
                List<string> result = categories.FindAll(
                    delegate(string b)
                    {
                        return b == dgv.Rows[j].Cells[1].Value.ToString();
                    }
                );

                // if we don't have a unique ID then add it
                if (result.Count == 0)
                {
                    categories.Add(dgv.Rows[j].Cells[1].Value.ToString());
                }
            }

            int[] categoryCount = new int[categories.Count];

            foreach (string cat in categories)
            {
                for (int j = 0; j < dgv.RowCount; j++)
                {
                    if (dgv.Rows[j].Cells[1].Value.ToString() == cat)
                    {
                        categoryCount[count]++;
                    }
                }
                count++;
            }

            int countTwo = 0;
            foreach (string cat in categories)
            {
                treeView1.Nodes[i].Nodes[2].Nodes.Add(cat + ":   " + categoryCount[countTwo].ToString());
                countTwo++;
            }

        }
    }


texts: Tool to calculate the average time that takes for a GitHub pull request to get merged

texts:
I'm learning Go, and this is my first attempt at a command-line tool that uses the GitHub API to calculate the average time that takes for a pull request to get merged for a particular organisation or repository.

The algorithm follows a very simple approach:

Get all the repositories for an organisation.
For each repository, get all the closed pull requests.
Calculate the average time using merged_at and created_at of each pull request.

For large organisations/projects, step 2 can take a long time, especially if it can't get all the pull requests from a single result page. So I want to execute that part concurrently.

Here's the part of the code that does that: GitHub

c := make(chan Result, len(repos))
var wg sync.WaitGroup
for _, repo := range repos {
    wg.Add(1)
    go func(val Repository) {
        if cmd.Debug {
            fmt.Printf("Executing goroutine for value: %s", val.Name)
        }
        pullRequests, err := getPullRequests(ctx, client, val)
        c <- Result{PullRequests: pullRequests, Err: err}
        wg.Done()
    }(repo)
}
wg.Wait()
close(c)

timeAccumulator := float64(0)
prAccumulator := int64(0)

var cmdErr error
for result := range c {
    pullRequests, err := result.PullRequests, result.Err
    if err != nil {
        cmdErr = err
        break
    }
    for _, pullRequest := range pullRequests {
        if pullRequest.GetMergedAt().IsZero() {
            continue
        }
        delta := pullRequest.GetMergedAt().Sub(pullRequest.GetCreatedAt()).Hours()
        timeAccumulator += delta
        prAccumulator++
        if cmd.Debug {
            fmt.Printf("PR: %s\nCreated at: %v\nMerged at:%v\nDelta in hours: %f\n", pullRequest.GetTitle(), pullRequest.GetCreatedAt(), pullRequest.GetMergedAt(), delta)
        }
    }
}

It works, but I'd like to get some feedback about the WaitGroup usage. It does feel that I don't need it here, because looping over range c would take results until the channel is closed. It's just not clear to me when I should really close the channel without a WaitGroup.

And of course any other feedback is really welcomed!


texts: Calculating minimum size of rectangle that contains two smaller ones

texts:
My Rectangle class contains one vertex (x,y), its width a, and its height b; the opposite vertex will be (x+a,y+b). I had a task to take 2 rectangles and compute the minimal 3rd rectangle to contain 2 smaller ones.  How can I simplify this code?

Rectangle operator+(Rectangle &o){
    double x1 = x, x2 = o.Gx(), y1 = y, y2 = o.Gy(), a1 = a, a2 = o.Ga(), b1 = b, b2 = o.Gb();
    double retx, rety, reta, retb;
    if (x2 > x1){
        retx = x1;
        if (x1 + a1 <= x2)
            reta = a1 + a2 + x2 - (x1 + a1);
        else if (x1 + a1 > x2 + a2)
            reta = a1;

        else
            reta = x2 + a2 - x1;
    }
    else{
        retx = x2;
        if (x1 <= x2 + a2)
            reta = x1 + a1 - x1;
        else if (x2 + a2 > x1 + a1)
            reta = a2;
        else
            reta = a1 + a2 + x1 - (x2 + a2);
    }
    if (x1 == x2 && a1 > 0 && a2 > 0){
        retx = x1;
        if (a1 > a2)
            reta = a1;
        else
            reta = a2;
    }

    if (y2 > y1){
        rety = y1;
        if (y1 + b1 <= y2)
            retb = b1 + b2 + y2 - (y1 + b1);
        else if (y1 + b1 > y2 + b2)
            retb = b1;

        else
            retb = y2 + b2 - y1;
    }
    else{
        rety = y2;
        if (y1 <= y2 + b2)
            retb = y1 + b1 - y1;
        else if (y2 + b2 > y1 + b1)
            retb = b2;
        else
            retb = b1 + b2 + y1 - (y2 + b2);
    }
    if (y1 == y2 && b1 > 0 && b2 > 0){
        rety = y1;
        if (b1 > b2)
            retb = b1;
        else
            retb = b2;
    }
    return Rectangle(retx,rety,reta,retb);
}


texts: Get users that are presidents and compute their name

texts:
I have a user table like this

id | firstname | surname  | title
1  | Bob       | Batman   | Dr.
2  | Alice     | Grimley  | Prof.
3  | Clara     | Caprio   |

In the user model class I have a function that computes the name

class User extends Authenticatable
{
    //...

    public function computeName()
    {
      return  trim($this->title . ' ' . $this->firstname . ' ' . $this->surname);
    }

    //...
}

In addition I have a 1:n relation with a table sortUser2Pres where n can only be 0 or 1. The relation maps if a user is a president or vice-president in a country.

user_id | country | type
1       | DE      | vice-president
2       | DE      | president

Now I wish to compute a name list of all users who are president. I can achieve it as follows:

$presidents = DB::table('user')
               ->select('firstname','surname','title')
               ->join('sortUser2Pres s', 's.user_id','=','user.id')
               ->where('s.type','president')
               ->get();

$names =  [];
foreach ($presidents as $user) {
    $names[] = trim($->title . ' ' . $->firstname . ' ' . $user->surname);
}

However, I think its bad that I cannot make use of the functions from the user model like computeName and that I have to copy & paste this function. Isn't there a cleaner way of achieving such a name list in Laravel and making use of the existing functions in the user model?


texts: Using Gibbs sampling to segment an image

texts:
I have been reading some NumPy guides but can't seem to figure it out. My TA told me I should be able to speed up my code by using a NumPy array instead of a for loop in the following segment of code.

for neighbor in get_neighbors(estimates,i,j):
            pXgivenX_ *= edge_model(True,neighbor)*observation_model(obs,True)
            pX_givenX_  *= edge_model(False,neighbor)*observation_model(obs,False)

Here is the entire code of the method it is in:

def gibbs_segmentation(image, burnin, collect_frequency, n_samples):
"""
Uses Gibbs sampling to segment an image into foreground and background.

Inputs
------
image : a numpy array with the image. Should be Nx x Ny x 3
burnin : Number of iterations to run as 'burn-in' before collecting data
collect_frequency : How many samples in between collected samples
n_samples : how many samples to collect in total

Returns
-------
A distribution of the collected samples: a numpy array with a value between
0 and 1 (inclusive) at every pixel.
"""
(Nx, Ny, _) = image.shape
total_iterations = burnin + (collect_frequency * (n_samples - 1))
pixel_indices = list(itertools.product(xrange(Nx),xrange(Ny)))
# The distribution that you will return
distribution = np.zeros( (Nx, Ny) )

# Initialize binary estimates at every pixel randomly. Your code should
# update this array pixel by pixel at each iteration.
estimates = np.random.random( (Nx, Ny) ) > .5

# PreProcessing
preProObs = {}
for (i,j) in pixel_indices:
        preProObs[(i,j)] = []
        preProObs[(i,j)].append(observation_model(image[i][j],False))
        preProObs[(i,j)].append(observation_model(image[i][j],True))

for iteration in xrange(total_iterations):

    # Loop over entire grid, using a random order for faster convergence
    random.shuffle(pixel_indices)

    for (i,j) in pixel_indices:

        pXgivenX_ = 1
        pX_givenX_ = 1

        for neighbor in get_neighbors(estimates,i,j):
            pXgivenX_ *= edge_model(True,neighbor)*preProObs[(i,j)][1]
            pX_givenX_  *= edge_model(False,neighbor)*preProObs[(i,j)][0]
        estimates[i][j] = np.random.random() > pXgivenX_/(pXgivenX_+pX_givenX_)

    if iteration > burnin and (iteration-burnin)%collect_frequency == 0:
        distribution += estimates

return distribution / n_samples

def edge_model(label1, label2):
    """
    Given the values at two pixels, returns the edge potential between
    those two pixels.

    Hint: there might be a more efficient way to compute this for an array
    of values using numpy!
    """
    if label1 == label2:
        return ALPHA
    else:
        return 1-ALPHA


texts:
I have just begun learning functional programming and Haskell.

This is my attempt to implement a solution to Graham Scan Algorithm in Haskell. Note that I am not even sure if this is indeed Graham Scan Algorithm, since I implemented this solution with only a few hints of the actual Graham Scan Algorithm. But I believe it to be correct and to have a \$\mathcal O\left(n \log(n)\right)\$ time complexity. However, I am still not quite there yet when it comes to understanding Lazy Evaluation, so not sure if it is indeed \$\mathcal O\left(n \log(n)\right)\$.

data Direction = LeftTurn | RightTurn | Straight deriving (Show, Eq)

findDirBetter (x, y) (x1, y1) (x2, y2)
    | cros_product == 0 = Straight
    | cros_product > 0  = LeftTurn
    | cros_product < 0  = RightTurn
   where cros_product = (x1 - x) * (y2 - y1) - (y1 - y) * (x2 - x1)

convex_hull_find []           = []
convex_hull_find (x:[])       = x:[]
convex_hull_find (x:x1:[])    = x:x1:[]
convex_hull_find (x:x1:x2:[]) = x:x1:x2:[]
convex_hull_find a            = (find_half_hull (tail sorted_x) [head sorted_x]) ++ (find_half_hull (tail (reverse sorted_x)) [head (reverse sorted_x)])
        where sorted_x                    = sortBy predicate a
              predicate (x, y) (x1, y1)   = compare x x1
              find_half_hull ([]) hull    = tail hull
              find_half_hull l (x:[])     = find_half_hull (tail l) ((head l):x:[])
              find_half_hull l hull       = if findDirBetter (head (tail hull)) (head hull) (head l) /= RightTurn
                                            then find_half_hull (tail l) ((head l):hull)
                                            else find_half_hull l (tail hull)

Please critique everything from the algorithm to the code.

Is this Graham Scan Algorithm?
Is it \$\mathcal O\left(n \log(n)\right)\$?
Is this elegant, readable Haskell code?


texts:
I am writing a program in c++ to record audio.
Here are my structure and code snippet.

typedef struct _recorder {
    const uint32_t SAMPLE_RATE = 44100;
    const uint32_t FRAME_STEP = SAMPLE_RATE / 100;
    const uint32_t STEP_BUF_SIZE = sizeof(int16_t) * FRAME_STEP;
    int16_t *step_buf;

    const uint32_t RECORD_TIME = 10;
    const uint32_t NUM_SAMPLE = RECORD_TIME * SAMPLE_RATE;
    int16_t *total_buf;

    uint32_t sample_counter;
} recorder;

void recorder_init(recorder *r)
{
    r->step_buf = new int16_t[r->STEP_BUF_SIZE / sizeof(int16_t)];
    r->total_buf = new int16_t[r->NUM_SAMPLE];
}

void recorder_free(recorder *r)
{
    delete[] r->step_buf;
    delete[] r->total_buf;
}

void main(int argc, char *argv[])
{
    recorder rec;
    recorder_init(&rec);

    // Do something to record audio

    recorder_free(&rec);
}

Does using structures and functions make sense to you? Or should I use a class? Or there are better design patterns I can follow?

EDIT -------------------------
I add a further question of this post here.


texts: Mapping ExpandoObject to another object type

texts:
I am working on a helper method that maps properties from an ExpandoObject to a user supplied object and was wondering if the code could be cleaned up or made any more efficient. It currently has the correct behaviour from a simple test.
public static class Mapper
{
    public static void Map<T>(ExpandoObject source, T destination)
    {
        IDictionary<string, object> dict = source;
        var type = destination.GetType();

        foreach (var prop in type.GetProperties())
        {
            var lower = prop.Name.ToLower();
            var key = dict.Keys.SingleOrDefault(k => k.ToLower() == lower);

            if (key != null)
            {
                prop.SetValue(destination, dict[key], null);
            }
        }
    }
}

Full test can be seen here. There is currently no type checking. Would this be next to add?


texts:
My brother bet me that I couldn't make a game in Excel. The code is all over the place and buggy in parts. But I would appreciate it if anyone would give this game a go.

The music and the code has all been made by me, but the artwork was found online and I can't claim any of it is mine (although a few bits were photoshopped to make it work for me).

There's still a few bits of the game that don't work 100% but it shouldn't crash on you.

Full code

There's an installer or the zip file - it's probably best to just use the zip file.

Sub dogame()

Application.Visible = False

loadedgame = False

Do

    fminitScreen.Show
    playgame

    If loadedgame = False Then

        loadplayer
        fmNameHim.Show
        fmChooseWeapon.Show

            If Worksheets("options").range("B3").value = True Then

                fmrules.Show

            End If

        fminside1.Show

    ElseIf loadedgame = True Then

        Dim obj As Object
        Dim obj1 As Object

        Load fminside1
        Load fmoutside
        Load fmupstairs

        For Each obj In UserForms

                If obj.Name = player.formname Then

                            loadedgame = False
                            obj.Character.left = player.left
                            obj.Character.top = player.top
                            obj.Show
                            Exit For
                Else
                    If obj.Name = "fmMusic" Then

                    Else
                        Debug.Print "unloaded form" & obj.Name
                        Unload obj

                    End If

                End If

            Next obj

    End If

    fmranking.Show
    Set player = Nothing

Loop

End Sub


texts:
I'd like to have some feedback on this small snippet I wrote to implement a base64 encoder and decoder.

Specifically, I'm not sure I'm handling padding in the best way possible.

import string

values = string.ascii_uppercase + string.ascii_lowercase + string.digits + '+/'
ALPHABET = dict(zip(range(64), values))

def encode(unpadded_buf):
    padded_buf = unpadded_buf[:]
    if len(padded_buf) % 3 != 0:
        padded_buf += [0] * (3 - len(unpadded_buf) % 3)

    encoded_padded_buf = []

    for i in range(0, len(unpadded_buf), 3):
        encoded_padded_buf += [ padded_buf[i] >> 2 ]
        encoded_padded_buf += [ (padded_buf[i] & 3) << 4 | padded_buf[i + 1] >> 4 ]
        encoded_padded_buf += [ (padded_buf[i + 1] & 15) << 2 | padded_buf[i + 2] >> 6 ]
        encoded_padded_buf += [ padded_buf[i + 2] & 63]

    asciied = ''.join(map(lambda n: ALPHABET[n], encoded_padded_buf))

    if len(padded_buf) - len(unpadded_buf) == 2:
        return asciied[:-2] + '=='
    elif len(padded_buf) - len(unpadded_buf) == 1:
        return asciied[:-1] + '='

    return asciied[:]

def decode(asciied):
    _alphabet = dict(map(lambda p: (p[1], p[0]), ALPHABET.items()))
    encoded_buf = list(map(lambda c: _alphabet.get(c, 0), asciied))

    decoded_buf = []

    for i in range(0, len(encoded_buf), 4):
        decoded_buf += [ encoded_buf[i] << 2 | encoded_buf[i + 1] >> 4 ]
        decoded_buf += [ (encoded_buf[i + 1] & 15) << 4 | encoded_buf[i + 2] >> 2 ]
        decoded_buf += [ (encoded_buf[i + 2] & 3) << 6 | encoded_buf[i + 3] ]

    return decoded_buf

if __name__ == '__main__':
    assert bytes(decode(encode(list('foo'.encode())))).decode() == 'foo'


texts:
I have a program for finding shortest distance/path and I got a correct answer but I am getting an issue i.e., "Function 'shortestPath' has a complexity of 9. Maximum allowed is 6." This is the algorithm:
const graph = {
  start: { A: 5, D: 8 },
  A: { B: 9, C: 3 },
  D: { C: 4, E: 6 },
  C: { B: 5, E: 2 },
  B: { end: 7 },
  E: { end: 4 },
  end: {}
};

function shortestCostNode(costs, processed) {
  return Object.keys(costs).reduce((lowest, node) => {
    if (lowest === null || costs[node] < costs[lowest]) {
      if (!processed.includes(node)) {
        lowest = node;
      }
    }

    return lowest;
  }, null);
}

// this function returns the minimum cost and path to reach end
function shortestPath(graph) {
  // track lowest cost to reach each node
  const costs = Object.assign({ end: Infinity }, graph.start);

  const parents = { end: null };

  for (let child in graph.start) {
    parents[child] = 'start';
  }

  const processed = [];
  let node = shortestCostNode(costs, processed);

  while (node) {
    let cost = costs[node];
    let children = graph[node];

    for (let n in children) {
      if (children.hasOwnProperty(n)) {
        let newCost = cost + children[n];

        if (!costs[n] || costs[n] > newCost) {
          costs[n] = newCost;
          parents[n] = node;
        }
      }
    }

    processed.push(node);
    node = shortestCostNode(costs, processed);
  }

  let optimalPath = ["end"];
  let parent = parents.end;

  while (parent) {
    optimalPath.push(parent);
    parent = parents[parent];
  }

  optimalPath.reverse();

  const result = {
    distance: costs.end,
    path: optimalPath
  };
  return result;
}

How to reduce complexity of Function shortestPath?


texts: PDO connection / prep and execute in their own functions

texts:
I'm currently changing some legacy code over to PDO.  The below code works, but not 100%.  I would like to know if it's best practice or if anything can be done better.

//Database Array
$config['db'] = array(
    'host' => 'localhost',
    'username' => 'root',
    'password' => 'root',
    'dbname' => 'local');

//New PDO
$db = new PDO('mysql:host=' . $config['db']['host'] . ';dbname=' . $config['db']['dbname'], $config['db']['username'], $config['db']['password']);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
//Check connection is ok
try {
    $db->exec("SET CHARACTER SET utf8");
}
catch (PDOException $ex) {
    print "Error!: " . $ex->getMessage() . "
";
    die();
}

//Update users function
function update($db, $fn, $ln, $email, $offers, $vlue, $response)
{
    $stmt = $db->prepare("insert into local (fName_765, lName_765, email_765, signup_765) values (:fname, :lname, :email, :signup, NOW())");
    $stmt->bindParam(':fname', $fn, PDO::PARAM_STR);
    $stmt->bindParam(':lname', $ln, PDO::PARAM_STR);
    $stmt->bindParam(':email', $email, PDO::PARAM_STR);
    $stmt->bindParam(':signup', $offers, PDO::PARAM_STR);
    try {
        $stmt->execute();
        print $db->lastInsertId(); //show ID
        return true;
    }
    catch (PDOException $e) {
        print "Error!: " . $e->getMessage() . "
"; // show error
        return false;
    }
}

//Test Attributes
$fn = 'test';
$ln = 'test';
$email = 'tesst@test,com';
$offers = '1';

if (!update($db, $fn, $ln, $email, $offers, $vlue, $response)) {
    echo "no update there is a slight problem";
} else {
    echo "it seemed to work";
}

Midified version:

$functionError = array();

//Database Array
$config['db'] = array(
    'host' => 'localhost',
    'username' => 'root',
    'password' => 'root',
    'dbname' => 'root');

//Check connection is ok
try {
    $db = new PDO('mysql:host=' . $config['db']['host'] . ';dbname=' . $config['db']['dbname'], $config['db']['username'], $config['db']['password']);
    $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch (PDOException $e) {
    $functionError[] = "
{DB} - Error!: " . $e->getMessage() . "
";
    errorhandler ($functionError);
    die ();
}

//Error Handler
function errorhandler ($functionError) {
    print_r ($functionError);
    echo "Sorry we are experiencing issues we are aware of the problem";

}

//Update users function
function update($db, $fn, $ln, $email, $offers, $vlue, $response)
{
    $stmt = $db->prepare("insert into kkt (fName_765, lName_765, email_765, signup_765, kkt_resp_765, kkt_respSate_765, stamp_765) values (:fname, :lname, :email, :signup, :kkt_rsp, :kkt_respState, NOW())");

    $parameters = array(
        ':fname' => $fn,
        ':lname' => $ln,
        ':email' => $email,
        ':signup' => $offers,
        ':kkt_rsp' => $vlue,
        ':kkt_respState' => $response);

    try {
        $stmt->execute($parameters);
        return true;
    }
    catch (PDOException $ex) {
        $functionError[] = "
{INSERT} - Error!: " . $ex->getMessage() . "
";
        errorhandler ($functionError);
        return false;
    }
}

//Test Attributes
$fn = 'test';
$ln = 'test';
$email = 'tesst@test,com';
$offers = '1';
$vlue = 'value';
$response = 'resp';

if (update($db, $fn, $ln, $email, $offers, $vlue, $response)) {
    echo "it seemed to work";
    print $db->lastInsertId();
    header('Location: thank-you.php');
    exit;
}


texts: Displaying subcategories of subcategories

texts:
I wanted to know if this code is safe against SQL injection or not?
Also do I need to mysqli_close if I already did the mysqli_stmt_close?  Other suggestions are always welcome.

if ($stmt = mysqli_prepare($connect, "SELECT subcategories.subcat_name, subsubcategories.subsubcat_name, subcategories.subcat_ID FROM subcategories INNER JOIN subsubcategories ON subcategories.subcat_ID=subsubcategories.subcat_ID WHERE subcategories.cat_ID = ? OR subcategories.extra_cat_ID = ? ORDER BY subcategories.subcat_name, subsubcategories.subsubcat_name ASC")){
mysqli_stmt_bind_param($stmt, "ii", $cat_ID, $cat_ID);
mysqli_stmt_execute($stmt);
mysqli_stmt_bind_result($stmt, $subcat_name, $subsubcat_name, $subcat_ID);
$lastcat = 0;
while (mysqli_stmt_fetch($stmt)){
    if($lastcat != $subcat_ID){
        $lastcat = $subcat_ID;
        echo "
";
        echo $subcat_name;
        echo "
";
        echo "
";
        }

    echo $subsubcat_name;
    echo "
";
    }
}
mysqli_stmt_close($stmt);
mysqli_close($connect);


texts:
I'm learning Scala (and functional programming). Is there a better way to solve Euler problem 4 than either of these two solutions.

Euler 4

I like this array comprehension solution, but it wastes so much space.

def isPal(n: Int): Boolean = {
  val sN = n + ""
  sN == sN.reverse
}
def euler4Iter: Int = {
  var largestPal = 0
  for (i <- 100 to 1000; j <- i to 1000) {
    if (i * j > largestPal && isPal(i*j)) {
      largestPal = i*j
    }
  }
  largestPal
}
def euler4ArrayCompre: Int = {
  (for(i <- 100 to 1000; j <- i to 1000 if isPal(i*j)) yield i*j).max
}