texts: Return whether the cards can be rearranged

texts:
I solved this question on LeetCode.com:

Alice has a hand of cards, given as an array of integers.  Now she wants to rearrange the cards into groups so that each group is size W, and consists of W consecutive cards.  Return true if and only if she can.  For e.g., for hand=[1,2,3,6,2,3,4,7,8] and W=3, the answer should be true.

as:
class Solution {
public:
    bool isNStraightHand(vector<int>& nums, int k) {
        if(nums.size()%k!=0) return false;

        map<int, int> _m;
        for(int num: nums) _m[num]++;

        while(_m.size()) {
            auto it=_m.begin();
            int count=1;
            int prev=it->first;
            while(count<=k) {
                it->second--;
                if(count>1 && it->first-prev!=1) return false;
                else prev=it->first;
                count++;
                if(it->second==0) {
                    auto backupIt=it;
                    _m.erase(backupIt);     //am I causing UB here?
                }
                it++;
            }
        }

        return true;
    }
};

This works, but it doesn't look like a sturdy solution. I am curious to know if I am causing Undefined Behavior (UB) when erasing the element above.  Earlier, I just had _m.erase(it);, but that wasn't good either.  I think so, since the official website says:

References and iterators to the erased elements are invalidated.

so, when I do a it++ in the following line, isn't that invalid? That part in particular can probably be improved.


texts: The efficiency of looping over nested dictionaries in Python

texts:
How to make the following code more efficient?

"""
Calculate the posterior distribution of p(pos|word) using Baye's rule:
p(pos|word) \propto p(word|pos)p(pos).
"""
word_pos_dict = defaultdict(float)  # Example, word|pos -> 0.0012
pos_dict = defaultdict(float)       # pos -> 0.005
pos_word_dict = defaultdict(float)  # pos|word -> 0.017

for word_pos, word_pos_prob in word_pos_dict.items():
    word, pos = word_pos.split('|')
    marginal_prob = 0
    for pos_prob in pos_dict.values():
        marginal_prob += word_pos_prob * pos_prob    # Marginal prob of p(word)
    pos_word_prob = word_pos_prob * pos_dict[pos]
    pos_word = pos + '|' + word
    pos_word_dict[pos_word] = pos_word_prob / marginal_prob

In practice, the length of word_pos_dict is 57,602, and pos_dict has 984 elements, which make this calculation much slower. Is there something wrong with the implementation, design or algorithm?


texts: Node.js Is this a great way to show pages in a minimal way as possible?

texts:
I'm trying to make a Node.js server as minimal as possible to show a landing page, but i'm not sure this is the greatest and fastest way to do it.

I'm using dirty to store my html data.

My app.js file

var http = require('http')
, db = require('dirty')('pages.db')
, url = require('url')
, fs = require('fs');

http.createServer(function (request, response) {
    var pathname = url.parse(request.url).pathname;
    var html = db.get(pathname);

    //Check if the requsted file is CSS or JS
    if (/\.(css)$/.test(pathname) || /\.(js)$/.test(pathname)){

        fs.createReadStream(__dirname + pathname, {
            'bufferSize': 4 * 1024
        }).pipe(response)

    } else if (!!html && pathname !== '/admin' ) {
        //Pages from our Dirty DB
        response.writeHead(200, {'Content-Type': 'text/html'});
        response.end(html);
    } else if (pathname === '/admin') {
        //Display Admin page
        response.writeHead(200, {'Content-Type': 'text/html'});
        response.end('Admin!');
    } else {
        //Show 404 Page
        response.writeHead(404, {'Content-Type': 'text/html'});
        response.end(db.get('404'));
    }
 }).listen(80);

console.log('Server running at http://192.168.56.101:80/');


texts: Evaluating a series of Legendre polynomials

texts:
The following function represents the electrostatic potential, in spherical coordinates, due to a ring of charge \$q=1\$ and radius \$R=1\$, placed in the plane \$x\$-\$y\$:

$$\phi(r,\theta) = \sum_{n=0}^\infty \frac{r_\min^n}{r_\max^{n+1}} P_n(\cos\theta) P_n(0) $$

where \$P_n\$ are the Legendre Polynomials of degree \$n\$, \$r_\min = \min(r,1)\$, and \$r_\max = \max(r,1)\$.

I wrote a code in python to plot this function, with the sum truncated to \$0\leq n \leq 35\$, in a cartesian grid of 50x50 points. But this takes several minutes to complete. The same code in other languages gives almost instantaneous results in mi computer.

This is the code I want to improve:

import matplotlib.pyplot as plt         # plotting routines
import scipy.special as sp              # legendre polynomials
import numpy as np
from timeit import default_timer as timer

# Potential from a ring of radius c=1 and charge q=1
#    phi(r,th) = \sum_{n=0}^\infty (rmin^n/rmax^{n+1}) P_n(cos(th)) P_n(0.0)
#
# where rmin=min(r,1) and rmax=max(r,1).
# The potential is normalized with respect to q/c, where q is the charge of the ring.
# The radii is normalized with respect to c.

def phi(x, z):
    r = np.sqrt(x**2 + z**2)
    costh = z/r

    rmin = min(r,1)
    rmax = max(r,1)

    dr = rmin/rmax

    suma = 0.0
    for n in range(0,35):
        suma += dr**n * sp.legendre(n)(costh) * sp.legendre(n)(0.0)

    return suma/rmax

phivec = np.vectorize(phi)

# grid for plotting
X, Y = np.meshgrid( np.linspace(-2,2,50),
                    np.linspace(-2,2,50) )

# evaluating phi(X,Y)
start = timer()

Z = phivec(X,Y)

end = timer()
print "time = ", end-start

# plotting phi
plt.figure()
CS = plt.contour(X, Y, Z)
plt.clabel(CS, inline=1, fontsize=10)
plt.title(r'$\psi(r,\theta) = \sum_{\ell=0}^\infty \frac{r_<^\ell}{r_>^{\ell+1}} P_\ell(0) P_\ell(\cos\theta)$', y=1.03)
plt.xlabel(r'$x/c$', fontsize=20)
plt.ylabel(r'$z/c$', fontsize=20)

plt.show()

Here is the result:


texts:
A simple selection sort functions in R. Just for practice.

Given the choice of algorithm and tools I wonder what can most easily be improved about the functions.

NB. I wanted to keep the first function as elemental as possible.

# Selection sort playing with loops
sels <- function(x) {
  n <- length(x)
  for (i in 1:(n - 1)) {
    min <- i # this variable keeps track of smallest number in unsorted
             # just some prior, update if confronted with better info
    for (j in (i + 1):n) {
      if (x[j] < x[min]) {
        min <- j # update as we find something smaller
      }
    }
  if (min != i) { # now if we did update prior; swap
      temp   <- x[i]
      x[i]   <- x[min]
      x[min] <- temp
    }
  }
  x
}

# Selection sort in more R'ish-style
selsr <- function(x) {
  # Selection sort a vector
  n <- length(x)
  for (i in 1:(n - 1)) {
    j <- i + which.min(x[(i + 1):n])
    if (j != i) {
      temp <- x[i]
      x[i] <- x[j]
      x[j] <- temp
    }
  }
  x
}


texts: Find Square root of number only with addition or/and subtraction

texts:
My problem is following: I want to Find Square root of a number (which is the square of integer) only with addition or subtraction (or together). I wrote the algorithm which works, but I am really interested in what will be better solution to solve this problem.

static void FindSquareRoot(int S)
{
    int i = 1;

    for (; i <= S; i++)
    {
        int k = S;
        int j = i;

        while (j>0)
        {
            k = k - i;
            j--;
        }

        if (k == 0)
        {
            Console.WriteLine("Square root of {0} is {1}", S, i);
            break;
        }
        else if (k < 0)
        {
            Console.WriteLine("Not found");
            break;
        }
    }
}

The basic idea of this algorithm is to choose one number(i) and subtract it from S (i) times. if the result will be 0, then it means that this(i) is the number I was looking for..


texts:
I am new to C# and am leaning ASP.NET MVC and Entity Framework and I am trying to create an application where a user can manager Job Postings and Applicants where an Applicant can apply for many Jobs.

I am trying to pull a list of Applicants, along with a list of the Jobs they have applied for.

The following is the solution I have come up with.

HomeViewModel.cs

public class HomeViewModel
{
    public IEnumerable<ApplicantList> Applicants { get; set; }
    public IEnumerable<Jobs> Jobs { get; set; }
}

public class ApplicantList
{
    public Applicants Applicant { get; set; }
    public List<Jobs> Jobs { get; set; }
}

HomeController.cs

using(var context = new HR())
{
    HomeViewModel viewModel = new HomeViewModel();

    // Get grouped applicants list by Email Address
    var applicants = context.Applicants.GroupBy(a => a.EmailAddress)
                             .Select(grp=>grp.FirstOrDefault())
                             .ToList() ;
    List<ApplicantList> applicantList = new List<ApplicantList>();

    foreach (var a in applicants)
    {
        //get Jobs for each applicants
        var query = from dba in context.Applicants.Include("Jobs")
                    where a.EmailAddress == dba.EmailAddress
                    select dba.Jobs;
        List<Jobs> jobs = query.ToList();
        applicantList.Add(
            new ApplicantList (){ Applicant = a, Jobs = jobs }
        );
    }

    viewModel.Applicants = applicantList;

    viewModel.Jobs = context.Jobs.ToList();

    return View(viewModel);
}

HomeView.cshtml

@foreach (var applicant in Model.Applicants)
{
    Applicant name: @applicant.Applicant.FirstName

            @foreach(var job in applicant.Jobs)
            {
               * @job.JobTitle

            }

}

Result in View

Applicant name: Bob Lois

Job Title 1
Job Title 2

Applicant name: Kevin Bacon

Job Title 1

It works, but it's horrible code produced by a beginner like me.I want to know how I can achieve the same result in a much more eloquent way.


texts:
I have spent about 2 weeks reading about hashing passwords and website security. As there seems to be many different ways to achieve this, I'm a bit confused as to whether my code is secure.

Can anyone please have a look through and let me know what they think and what needs to be changed?

I have not added any error trapping yet, as to allow me to concentrate on just the hashing.

The steps I have took are as follows:

Create random salt
Add random salt and email together to create salt for password (email will be encrypted in database)
Hash password and salt and store in database

public const int HashBytes = 128;
public const int DefaultIterations = 10000;

    //Create random bytes for salt
    public static string SaltSHA256()
    {
        const int minSaltSize = 8;
        const int maxSaltSize = 16;
        var random = new Random();
        int saltSize = random.Next(minSaltSize, maxSaltSize);
        byte[] saltBytes = new byte[saltSize];
        var rng = new RNGCryptoServiceProvider();
        rng.GetNonZeroBytes(saltBytes);
        HashAlgorithm hash = new SHA256Managed();
        byte[] bytes = hash.ComputeHash(saltBytes);
        return Convert.ToBase64String(bytes);
    }

    //Create salt using email and public static string SaltSHA256()
    //Store email and public static string SaltSHA256() in database
    public static string SaltRfc2898(string email,string hashedSalt)
    {
        var salt = new Rfc2898DeriveBytes(email, Encoding.UTF8.GetBytes(hashedSalt), DefaultIterations);
        return Convert.ToBase64String(salt.GetBytes(HashBytes));
    }

    //Hash password and salt
    public static string PasswordHashRfc2898(string password,string salt)
    {
        var hashedPassword = new Rfc2898DeriveBytes(password, Encoding.UTF8.GetBytes(salt), DefaultIterations);
        return Convert.ToBase64String(hashedPassword.GetBytes(HashBytes));
    }
    //Get salt and password from database based on username
    //Salt in from data created by public static string SaltSHA256()

    public static bool DoPasswordsMatch(string password,string salt)
    {
        //Password would be pulled from db based on username
        byte[] testPassword = Convert.FromBase64String("basestring");

        //Salt would be pulled from database based on username
        var saltFromDatabase = salt;

        //Hash password and salt
        var hashUserInputAndSalt = PasswordHashRfc2898(password, saltFromDatabase);

        //Convert to byte[] ready for comparison
        byte[] convertUserInputFromBase64 = Convert.FromBase64String(hashUserInputAndSalt);

        //Compare and return true or false
        return convertUserInputFromBase64.SequenceEqual(testPassword);

    }


texts:
I've been working on a simple forum website as a toy project, to start learning PHP and SQL. I've implemented all of the functionality I want, but I thought I'd run the code by the Code Review community to see how I could improve it.

<?php
session_start();
class database{
 protected static $connection;
 protected $state=0; //0 is fine, 1 is connection error, 2 is query error

 public function connect(){
  if(isset(self::$connection)){
   return self::$connection;
  }
  else{
   self::$connection=new mysqli('localhost','root','','mydummydatabase');
   if(self::$connection===false){
    $this -> state=1;
    return false;
   }
   return self::$connection;
  }
 }
 public function query($query){
  $connection=$this -> connect();
  $result=$connection -> query($query);
  if($result===false){
   $this -> state=2;
  }
  return $result;
 }
 public function sanitise($input){
  $connection=$this -> connect();
  return "'".$connection -> real_escape_string($input)."'";
 }
 public function get_first_row($result){
  if($result){
   return $result -> fetch_assoc();

  }
  else{
   return false;
  }
 }
 public function state(){
  return $this->state;
 }

}
$db=new database();
$_SESSION['email-exists-in-database']=false;
$_SESSION['something-weird-happened']=false;
if(isset($_POST['email'])){
 $firstname=$db->sanitise($_POST['firstname']);
 $lastname=$db->sanitise($_POST['lastname']);
 $email=$db->sanitise($_POST['email']);
 $hash=password_hash($_POST['password'],PASSWORD_DEFAULT);
 $result=$db -> query("SELECT `user-id` FROM `users` WHERE email=".$email);
 $record=$db->get_first_row($result);
 if($record!=false){
  $_SESSION['email-exists-in-database']=true;

 }
 else{
  $db -> query("INSERT INTO `users` (firstname,lastname,email,passwordhash) VALUES (".$firstname.",".$lastname.",".$email.",'".$hash."')");

  if(!($db->state())){
   $result=$db -> query("SELECT `user-id` FROM `users` WHERE email=".$email);
   $record=$db->get_first_row($result);
   $_SESSION['id']=$record['user-id'];
   header('Location: welcome.php');
   exit;
  }
  else{
   $_SESSION['something-weird-happened']=true;

  }
 }
}
?>

<link rel="stylesheet" media="screen" href="styles2.css"/>

<form action="<?php echo $_SERVER['PHP_SELF'];?>" method="post">
<input type="text" maxlength="30" name="firstname" placeholder="First name"class="sign-in-box" required/>
<input type="text" maxlength="60" name="lastname" placeholder="Last name"class="sign-in-box" required/>
<input type="email" maxlength="100" name="email" placeholder="Email"class="sign-in-box" required/>
<input type="password" maxlength="200" name="password" placeholder="Password"class="sign-in-box" required/>

<input type="submit" name="Submit" value="Sign up"class="submit-button"/>
</form>

<?php
if($_SESSION['email-exists-in-database']){
 echo("
We already have an account associated with that email.
");
}
if($_SESSION['something-weird-happened']){
 echo("
Something went wrong, please try again.
");
}?>

This is the Register page for the website. Some issues I'm concerned about are security, and good practice.

Any thoughts?


texts: YUV422 to RGB24 using Intel Performance Primitives

texts:
I have a C++ method that uses the Intel performance primitives library to convert an image from YUV422 format into RGB 24. I am PInvoking this method from C# (WPF) where the YUV images are coming from a high frame rate camera. The method takes a pointer to the image data, and the width and height and returns a pointer to the modified data.

This single method is taking up 23% of my entire application CPU and must be running at all times (the video is always visible).

I am not a C++ maestro and I am sure that this code could be improved significantly in terms of performance, but I am not sure where to start.

Any suggestions for improvements would be most appreciated

extern "C" __declspec(dllexport)unsigned char* YUV422ToRGB24(unsigned char* input, int width, int height)
    {
        const int       ALIGNMENT_64BIT_MASK = 64u;
        int             stepRGB, stepYUV;

        Ipp8u           *rgbImg, *imgYUV422_IPP;

        bool            success = false;
        IppiSize        size;

        UINT32 width3 = width * 3;
        UINT32 width2 = width * 2;

        unsigned char *ptr = NULL;

        unsigned char* pBGR = new unsigned char[(width * height) * 3];

        // ippi functions require 32Bit alignment, if not a

        if ((((uintptr_t)pBGR % ALIGNMENT_64BIT_MASK) == 0) && (width3 % ALIGNMENT_64BIT_MASK == 0))
        {
            rgbImg = pBGR;
            stepRGB = width3;
        }
        else
        {
            rgbImg = ippiMalloc_8u_C3(width, height, &stepRGB);
            if (rgbImg == NULL)
                return false;
        }

        if ((((uintptr_t)input % ALIGNMENT_64BIT_MASK) == 0) && (width2 % ALIGNMENT_64BIT_MASK == 0))
        {
            imgYUV422_IPP = input;
            stepYUV = width2;
        }
        else
        {
            imgYUV422_IPP = ippiMalloc_8u_C2(width, height, &stepYUV);

            if (imgYUV422_IPP == NULL)
            {
                ippiFree(imgYUV422_IPP);
                return false;
            }

            // copy source to yuv
            ptr = imgYUV422_IPP;

            // simple case where step is compatable, can copy entire row
            if (stepYUV == width2) {
                memcpy(ptr, input, height * stepYUV);
            }
            else {
                for (int col = 0; col < height; ++col)
                {
                    memcpy(ptr, input, width2);
                    input += width2;
                    ptr += stepYUV;
                }
            }
        }

        // convert yu422 to rgb
        size.width = width;
        size.height = height;

        if (ippiYCbCr422ToBGR_8u_C2C3R(imgYUV422_IPP, stepYUV, rgbImg, stepRGB, size) == 0)
        {
            // ouptut destination not same location as result, so copy over memory
            if (pBGR != rgbImg) {
                // copy memory to destination
                ptr = rgbImg;

                // simple case where step is compatable, can copy entire row
                if (stepRGB == width3) {
                    memcpy(pBGR, ptr, height * stepRGB);
                }
                else {
                    for (int col = 0; col < height; ++col) {
                        memcpy(pBGR, ptr, width3);
                        pBGR += width3;
                        ptr += stepRGB;
                    }
                }
            }
            success = true;
        }

        // only free memory if not same as pointers provided
        if (pBGR != rgbImg)         ippiFree(rgbImg);
        if (input != imgYUV422_IPP) ippiFree(imgYUV422_IPP);

        return pBGR;
    }


texts:
I have some questions regarding a common implementation of the UoW, Repository Pattern and EF:

public interface IAppUow
{
    void Commit();
    IRepository<Customer> Customer{ get; } // IRepository<T>
    IOrderRepository Order{ get; }         // implements IRepository<T>
}

My questions are:

If I need to add a new repository of whatever type, I have to change the UoW.  Is this a good practice? If not, is there a better way?
If I run Commit() { context.SaveChanges(); }, it will save the state of all the context's repositories. Is this a good way?


texts: Centered finite difference approximation for edge enhancement

texts:
I implemented a centered finite difference approximation for edge enhancement in images. The difference approximation has a step size h of the partial derivatives in the x- and y-directions of a 2D-image. However, the function that calculates the difference approximation is slow on big images.

Here is the code:

import matplotlib.pyplot as plt
from matplotlib import cm
import matplotlib
from skimage import io
import numpy as np

# read image as a numpy array
sample_img = io.imread('samlpe.png')

def findiff(image, stepsize):
    # Padding to handle the boundaries when incrementing with step size
    padded_img = np.pad(image, pad_width=1, mode='constant', constant_values=0)
    img = padded_img.astype(float)
    M, N = img.shape # Get the dimensions of the image.
    pdfx = np.zeros(shape=(M, N))
    pdfy = np.zeros(shape=(M, N))
    img_lst = []
    for x in range(M-1):
        for y in range(N-1):
            pdfx[x][y] = (img[x][y + stepsize] - img[x][y - stepsize]) / (2 * stepsize) # partial with relation to x
            pdfy[x][y] = (img[x + stepsize][y] - img[x - stepsize][y]) / (2 * stepsize) # partial with relation to y

    img_lst.append(pdfx)
    img_lst.append(pdfy)
    return img_lst

fig, img_lst = plt.subplots(1, 2)
imgs = findiff(sample_img, 1)
img_lst[0].imshow(imgs[0], cmap="gray")
img_lst[1].imshow(imgs[1], cmap="gray")
img_lst[0].set_title('pdfx')
img_lst[1].set_title('pdfy')
plt.show()

This solution works for step size=1. How can I improve this code? Can I avoid the nested loops? How can I generalize the function so that it can handle different step sizes?

I'm new to Python by the way.


texts:
It seems to play up sometimes and I'm not sure if this is due to the class itself or the way I'm using it. Can someone confirm that this is a 'good' implementation of a VertexArrayObject class?

//The following code is public domain

public class VertexArray : GraphicsResource
{
    protected readonly int ID;
    DrawMode _drawMode;
    VertexLayout _vertexType;

    protected BufferUsageHint bufferUsage = BufferUsageHint.StaticDraw;
    int vertexCount;
    int vertexBufferID;

    public DrawMode DrawMode
    {
        get { return _drawMode; }
        set { _drawMode = value; }
    }
    public int VertexCount
    {
        get { return vertexCount; }
    }
    public BufferUsageHint BufferUsage
    {
        get { return bufferUsage; }
        set { bufferUsage = value; }
    }

    public VertexArray()
        : base()
    {
        ID = createVAO();
        disposed = false;
    }
    public VertexArray(DrawMode drawMode)
        : base()
    {
        _drawMode = drawMode;
        ID = createVAO();
        disposed = false;
    }
    int createVAO()
    {
        int id;
        GL.GenBuffers(1, out vertexBufferID);
        GL.GenVertexArrays(1, out id);
        GL.BindVertexArray(id);
        GL.BindBuffer(BufferTarget.ArrayBuffer, vertexBufferID);
        VenGFX.currentVAO = this;
        return id;
    }
    public void Bind()
    {
        if (vertexCount == 0)
            throw new Exception("Vertex buffer has no data, and therefore can't be used");
        if (disposed)
            throw new ObjectDisposedException(ToString());
        GL.BindVertexArray(ID);
        VenGFX.currentVAO = this;
    }
    public void SetData<T>(T[] Array) where T : struct, IVertex
    {
        GL.BindVertexArray(ID);
        if (Array.Length > 0 && Array[0].Layout != _vertexType)
            setVertexType(Array[0].Layout);
        GL.BindBuffer(BufferTarget.ArrayBuffer, vertexBufferID);
        GL.BufferData(BufferTarget.ArrayBuffer, (IntPtr)(Array.Length * _vertexType.SizeInBytes), Array, bufferUsage);
        vertexCount = Array.Length;
        VenGFX.currentVAO = this;
    }
    public void SetData<T>(T[] Array, int length) where T : struct, IVertex
    {
        GL.BindVertexArray(ID);
        if (Array != null && Array.Length > 0 && Array[0].Layout != _vertexType)
            setVertexType(Array[0].Layout);
        GL.BindBuffer(BufferTarget.ArrayBuffer, vertexBufferID);
        GL.BufferData(BufferTarget.ArrayBuffer, (IntPtr)(length * _vertexType.SizeInBytes), Array, bufferUsage);
        vertexCount = length;
        VenGFX.currentVAO = this;
    }
    void setVertexType(VertexLayout layout)
    {
        _vertexType = layout;
        layout.Set();
    }
    protected override void Release()
    {
        if (VenGFX.currentVAO == this)
        {
            GL.BindVertexArray(0);
            VenGFX.currentVAO = null;
        }

        int id = ID;
        GL.DeleteBuffers(1, ref vertexBufferID);
        GL.DeleteVertexArrays(1, ref id);
    }
}

To draw with it, I write

if (mesh.VertexCount == 0)
    return;
if (currentVAO != mesh)
    mesh.Bind();

GL.DrawArrays((BeginMode)(int)mesh.DrawMode, 0, mesh.VertexCount);


texts:
I'm trying to write a piece of code that will mimic ASCII keyboard output. It uses the keyboard library from pjrc, but the application I'm working on requires outputting string sequences rather than individual keys (the C++ interface exposes Keyboard.print, which does exactly what I want, except that I'm trying to stick to C for learning purposes).

Here's a kick at it;

[snip]
#include <string.h>
#include "usb_keyboard.h" // definitions for the /KEY_\w+/ symbols

int key_from_char(char c){
  if (c >= 'a' && c <= 'z') return c + KEY_A - 'a';
  if (c >= 'A' && c <= 'Z') return c + KEY_A - 'A';
  if (c >= '1' && c <= '9') return c + KEY_A - '1';
  if (c == '0') return 39; // 0 is low in ASCII, high in the USB key definition

  // there's no easy mapping between the other ASCII characters and
  // USB keyboard keys, so these are all manually represented
  switch (c) {
  case ' ': return KEY_SPACE; break;
  case '!': return KEY_1; break;
  case '"': return KEY_QUOTE; break;
  case '#': return KEY_NUMBER; break;
  case '$': return KEY_4; break;
  case '%': return KEY_5; break;
  case '&': return KEY_7; break;
  case '\'': return KEY_QUOTE; break;
  case '(': return KEY_9; break;
  case ')': return KEY_0; break;
  case '*': return KEYPAD_ASTERIX; break;
  case '+': return KEYPAD_PLUS; break;
  case ',': return KEY_COMMA; break;
  case '-': return KEYPAD_MINUS; break;
  case '.': return KEY_PERIOD; break;
  case '/': return KEYPAD_SLASH; break;

  case ':': return KEY_SEMICOLON; break;
  case ';': return KEY_SEMICOLON; break;
  case '<': return KEY_COMMA; break;
  case '=': return KEY_EQUAL; break;
  case '>': return KEY_PERIOD; break;
  case '?': return KEY_SLASH; break;
  case '@': return KEY_2; break;

  case '[': return KEY_LEFT_BRACE; break;
  case '\\': return KEY_BACKSLASH; break;
  case ']': return KEY_RIGHT_BRACE; break;
  case '^': return KEY_6; break;
  case '_': return KEY_MINUS; break;
  case '`': return KEY_TILDE; break;

  case '{': return KEY_LEFT_BRACE; break;
  case '|': return KEY_BACKSLASH; break;
  case '}': return KEY_RIGHT_BRACE; break;
  case '~': return KEY_TILDE; break;

  default: return 0;
  }
}

int modifier_from_char(char c){
  if ((c >= 'A' && c <= 'Z') ||
      // not sure how useful it is to put chars instead of ints for the rest of these
      c == '!' || c == '"' ||
      (c >= '$' && c <= '&') ||
      c == '(' || c == ')' ||
      c == ':' || c == '<' ||
      (c >= '>' && c <= '@') ||
      c == '^' || c == '_' ||
      (c >= '{' && c <= '~')) return KEY_SHIFT;

  return 0;
}

int8_t usb_keyboard_print(char *s){
  int s_len = strlen(s);
  int i;

  for(i = 0; i < s_len; i++){
    usb_keyboard_press(key_from_char(s[i]), modifier_from_char(s[i]));
  }
}

It seems to work, when I do

int main(void) {
   ...
   usb_keyboard_print("abcdABCD1234!@#$%^&*()_+|~{}:\">?<-=\\`[];',./");
   ...
}

the character sequence

abcdABCD1234!@\$%^&*()_+|~{}:">?<-=\`[];',./

is output as if by keyboard.

All comments welcome, but I also have specific points/questions

It seems like there should be an easier way to do this. I mention above that the C++ version of the usb_keyboard library provides a Keyboard.print which does essentially the same thing, but I haven't found anything similar for plain C.
Are there any issues I'm missing about USB key codes that would make this code wonk out based on nationality settings? How would you go about internationalizing it?
This is basically the first C code I've written since getting out of high-school, so please point out style errors and inefficiencies with extreme prejudice.


texts: Completely static builder implementation

texts:
CustomClass.class

Description

The CustomClass is created with init(), which returns a CustomBuilder saving both as static fields.

public class CustomClass {

    private static CustomClass customClass;
    private static CustomBuilder customBuilder;

    public static CustomBuilder init(){
        customClass = new CustomClass();
        return customBuilder = new CustomBuilder();
    }

    public static CustomClass customClass() {
        return customClass;
    }

    public static void setMethodA() {
        customBuilder.methodA();
    }

    public static void setMethodB() {
        customBuilder.methodB();
    }

    public static class CustomBuilder {

        public CustomBuilder methodA() {
            return this;
        }

        public CustomBuilder methodB() {
            return this;
        }

        public CustomClass build() {
            return customClass();
        }
    }
}

UsageActivity.class

Description

The UsageActivity calls init(),methodA() then build() within its onCreate(savedInstanceState). When something() is called it runs CustomClass.setMethodB().

    public class UsageActivity extends AppCompatActivity {

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        CustomClass.init().methodA().build();
    }

    protected void something(){
        CustomClass.setMethodB();
    }
}

Reasoning

Once the custom class' initial method is called in the activities onCreate, all its methods are static and accessible to the activity and its fragments.

As long as I handle data saving and lifecycles, it makes the library more flexible and creates less local variable management.

I'm not sure if this is the best way to go about it however. It all works as far as I can tell.

Does anyone see any issues or glaring mistakes?

Thank you.


texts: search a given word in word file by Aspose

texts:
I implemented a function to check a MS Word document is contain a given word or not. The function will return true if filePath is contain word. Otherwise it will return false.

This is my solution based on Aspose framework. Is there any better solution?

public class FindContentOfWordDoc
{
    public bool FindContent(string filePath, string content)
    {
        var doc = new Document(filePath);

        var findReplaceOptions = new FindReplaceOptions
        {
            ReplacingCallback = new FindCallBack(),
            Direction = FindReplaceDirection.Backward
        };

        var regex = new Regex(content, RegexOptions.IgnoreCase);
        doc.Range.Replace(regex, "", findReplaceOptions);

        return (findReplaceOptions.ReplacingCallback as FindCallBack)?.IsMatch ?? false;
    }

    private class FindCallBack : IReplacingCallback
    {
        public bool IsMatch { get; private set; }
        ReplaceAction IReplacingCallback.Replacing(ReplacingArgs e)
        {
            IsMatch = true;
            return ReplaceAction.Stop;
        }
    }
}

Thanks!


texts: Safe multiplication of two 64-bit signed integers

texts:
The function below implements safe multiplication of two 64-bit signed integers, preventing overflow from occurring:

// Multiplies two 64-bit signed ints if possible.
// Returns 0 on success, and puts the product of x and y into the result.
// Returns 1 if there was an overflow.
int int64_mult(int64_t x, int64_t y, int64_t * result)
{
    *result = 0;
    if (x > 0 && y > 0 && x > INT64_MAX / y) return 1;
    if (x < 0 && y > 0 && x < INT64_MIN / y) return 1;
    if (x > 0 && y < 0 && y < INT64_MIN / x) return 1;
    if (x < 0 && y < 0 && (x <= INT64_MIN || y <= INT64_MIN || -x > INT64_MAX / -y))
        return 1;
    *result = x * y;
    return 0;
}

Did I get the logic for detecting overflows right?  I am most interested in making sure that no undefined behavior will occur, and that the function will always return the right results.

We can assume that int64_t will be a two's complement integer, because this is for GCC and GCC does not support any other type of integer.

For the convenience of the code reviewers (you), I made a complete, self-contained test suite that you can just run in your favorite C/C++ environment:

https://gist.github.com/DavidEGrayson/06cf7ea73f82a05490ba

I am not too interested in code style issues.  I am aware it might be nice to assert that the output pointer is not null, and it might be nice to add braces and parentheses.  But really I want to know if the code is actually correct.

I am somewhat interested in making the code simpler if you have a way to do that; maybe some of the cases could be combined.

I am also aware that the logic might be easier if I just used a 128-bit integer to store the multiplication result, but I would like to get it right without doing that.

The reason I am asking this is because I am working on adding intsafe.h to mingw-w64 (a GCC compiler for Windows), so I am implementing safe multiplication of signed and unsigned numbers.  This function is analogous to LongLongMult in intsafe.h.  Your contribution will help make this header safer.  You can see my progress here.


texts: Find the highest occurring digit in the prime numbers present between L and R (both inclusive)

texts:
Given two numbers L and R, find the highest occurring digit in the
  prime numbers present between L and R (both inclusive). If multiple
  digits have the same highest frequency print the largest of them. If
  there are no prime no.s between L and R, print -1.

How can I optimize this code further in terms of running time?

package com;

import java.util.Arrays;

/**
 * Created by ankur on 19/7/15.
 */
public class HighestOccuringDigit {
    private static int MAX = 1000000;
    private static boolean[] isPrime = generatePrime();
    public static void main(String...strings){

        int index = getMaxOccuredDigit(13,13);
        if (index != 0){
            System.out.println(index);
        }else{
            System.out.println(-1);
        }
    }

    private static int getMaxOccuredDigit(int lower, int higher){
    int[] highestDigitCount = new int[10];
    int max = 0;
    int maxIndex = 0;
    if (lower < 3){
        highestDigitCount[2] = 1;
        lower = 3;
    }
    for (int i = lower; i <= higher; i++){
        //System.out.println(i);
        int index = (i - 3) >> 1;
        //System.out.println(i);
        if (((i & 1) != 0)   && isPrime[index]){
            //System.out.println(i);
            int[] digitsCount = getDigitCount(i);
            for (int j = 0; j < 10; j++){
                highestDigitCount[j] = highestDigitCount[j] + digitsCount[j];
                if (highestDigitCount[j] > max){
                    max = highestDigitCount[j];
                }
            }
        }
    }
    if (max == 0){
        return 0;
    }
    for(int i = 0; i < 10; i++){
        if (highestDigitCount[i] == max){
            maxIndex =  i;
        }
    }
    return maxIndex;
}

    private static int[] getDigitCount(int prime){
        int[] digitsCount = new int[10];
        Arrays.fill(digitsCount, 0);
        while(prime != 0){
            int lastDigit = prime % 10;
            digitsCount[lastDigit] += 1;
            prime /= 10;
        }

        return digitsCount;
    }

    private static boolean[] generatePrime(){
        int root = (int) Math.sqrt(MAX) + 1;
        root = (root >> 1) - 1;
        int limit = (int) ((MAX - 1) >> 1);
        boolean[] isPrime = new boolean[limit];
        Arrays.fill(isPrime, true);
        for( int i = 0; i< root; i++){
            if(isPrime[i]){
                for(int j = ((i * (i + 3) << 1) + 3), p = (i << 1) + 3; j < limit; j += p){
                    isPrime[j] = false;
                }
            }
        }
        return isPrime;
    }
}


texts:
What my code do:

Connecting to 30 DB (consistently)
Copying DB file to temp.dat
Reading temp.dat
Writing read data to file

So, it connects 30 times with different databases. This take 6-7 second (on a powerful notebook), but if I run this code on notebook / PC with low hardware specifications these take more than 20 seconds. How can I speed this up?

func fileCopyProcedure(ptSource string, ptDest string) {
    sourceFile, err := os.Open(ptSource)
    if err != nil {
        fmt.Println(err)
    }
    defer sourceFile.Close()

    destFile, err := os.Create(ptDest)
    if err != nil {
        fmt.Println(err)
    }
    defer destFile.Close()

    _, err = io.Copy(destFile, sourceFile)
    if err != nil {
        fmt.Println(err)
    }

    err = destFile.Sync()
    if err != nil {
        fmt.Println(err)
    }

    sourceFileInfo, err := sourceFile.Stat()
    if err != nil {
        fmt.Println(err)
    }

    destFileInfo, err := destFile.Stat()
    if err != nil {
        fmt.Println(err)
    }

    if sourceFileInfo.Size() == destFileInfo.Size() {
    } else {
        fmt.Println(err)
    }

}

func DB_Handler(path string) {
    var db *sql.DB

    err := fileCopyProcedure(path, "tmp.dat")
    if err != nil {
        fmt.Println(err)
    }

    db, err = sql.Open("sqlite3", "tmp.dat")
    if err != nil {
        fmt.Println(err)
    }
    defer db.Close()

    rows, err := db.Query("select cr_value, fx_value, orm_value, speend_value, sc_source_value, datainfo, secure_only from cookies")
    if err != nil {
        fmt.Println(err)
    }
    defer rows.Close()

    for rows.Next() {
        var sql_cr_value string
        var sql_fx_value string
        var sql_orm_value string
        var sql_speend_value string
        var sql_sc_source_value string
        var sql_datainfo string
        var sql_secure_only string

        err = rows.Scan(
            &sql_cr_value,
            &sql_fx_value,
            &sql_orm_value,
            &sql_speend_value,
            &sql_sc_source_value,
            &sql_datainfo,
            &sql_secure_only,
        )

        if err != nil {
            fmt.Println(err)
        }

        if sql_cr_value != "" && sql_orm_value != "" && sql_datainfo != "" {
            var cprInfo = fmt.Sprintf("%s   %s  %s  %s  %s  %s\r\n",
                sql_cr_value,
                sql_fx_value,
                sql_orm_value,
                sql_speend_value,
                sql_sc_source_value,
                sql_datainfo,
                sql_secure_only,
            )

            var hkInfo = fmt.Sprintf("%s\r\n",
                sql_datainfo,
            )

            wfile, err := os.OpenFile(
                "data.txt",
                os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0600,
            )

            if err != nil {
                fmt.Println(err)
            }
            defer wfile.Close()

            if _, err = wfile.WriteString(cprInfo); err != nil {
                fmt.Println(err)
            }

            wfile, err = os.OpenFile(
                "opx.txt",
                os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0600,
            )

            if err != nil {
                fmt.Println(err)
            }
            defer wfile.Close()

            if _, err = wfile.WriteString(hkInfo); err != nil {
                fmt.Println(err)
            }

        }
    }

    err = rows.Err()
    if err != nil {
        fmt.Println(err)
    }
}


texts:
I am testing a quicksort implementation. Arrays of random size with random data are passed to quicksort and the return time is averaged out. The user is prompted to enter values for

minimum length of array
maximum length of array
maximum value in array
minimum value in array
if the user wishes to see the sorted and unsorted arrays
if the user wishes the program to check itself by testing to make sure the array was sorted properly

I tried breaking up the prompts for user input into several methods but things are getting ugly. Are there any guidelines to follow for when prompting the user for information? One thing I'm not sure about is when to prompt with a question mark vs a colon (e.g. "what is x?" vs "input x:").

public static void main(String[] args)
{
    getInput();
}

public static void getInput()
{
    int bound = getNumber("How many arrays should be generated for quicksort?");
    int minVal = getNumber("Minimum value of element:");
    int maxVal = getNumber("Maximum value of element:");
    int minLength = getNumber("Minimum length of an array:");
    int maxLength = getNumber("Maximum length of an array:");
    boolean giveOutput = yes_no("Would you like to see the sorted and unsorted arrays?");
    boolean checkCorrectness = yes_no("Check proccessed arrays to see if sorted correctly?");

    long totalTime = 0, sumArraySizes = 0;

    for(int i = 0; i < bound; i++)
    {
        int[] sample = generateRandomArray(minLength, maxLength, minVal, maxVal);
        sumArraySizes += sample.length;
        if(giveOutput)
            System.out.println(Arrays.toString(sample));
        long startTime = System.nanoTime();//was using System.currentTimeMillis(); but endTime and startTime would always be the same
        qs(sample, 0, sample.length-1);
        long endTime = System.nanoTime();
        totalTime += endTime-startTime;
        if(giveOutput)
            System.out.println(Arrays.toString(sample)+"\n");
        if(checkCorrectness)
            if(!isSorted(sample))
                System.out.println("WARNING! mistake detected");
    }

    System.out.println("Average size of array: "+sumArraySizes/bound);
    System.out.println("Average time taken to sort array: "+totalTime/bound+" nanoseconds");
}

/*prompts user with a message and returns number they enter*/
public static int getNumber(String message)
{
    Scanner sc = new Scanner(System.in);
    System.out.println(message);
    return sc.nextInt();
}

/*http://stackoverflow.com/questions/15927885/yes-no-with-boolean-or-if-else*/
public static boolean yes_no(String message)
{
    Scanner sc = new Scanner(System.in);
    String answer;
    boolean yn;

    System.out.print(message);
    OUTER:
    while (true) {
        answer = sc.nextLine().trim().toLowerCase();
        switch (answer) {
            case "y":
                yn = true;
                break OUTER;
            case "n":
                yn = false;
                break OUTER;
            default:
                System.out.println("Please answer with y or n");
                break;
        }
    }
    return yn;
}

What should the method yes_no be named? I wanted to call it yesOrNo but that looked strange.


texts: Parsing and plotting with numpy (or pandas)

texts:
I am trying to improve the following code to make it more broadly applicable and quick to use.

# IMPORTS
import numpy as np
import pylab as py
import matplotlib.pyplot as plt
from scipy import optimize
from scipy.optimize import curve_fit

# THE INEFFICIENT PARSING: SELECTING VALUES FROM SEVERAL TABLES ONE BY ONE

skip_bottom_lines = 5 # currently i skip all lines but one at the time, cumbersome

skip_top_lines = (7-skip_bottom_lines) # always number of picked picks + 1

residue_id = np.genfromtxt("321.list", skip_header = skip_top_lines, skip_footer = skip_bottom_lines, usecols = 0, dtype = str, delimiter = "-")

a_value00 = np.genfromtxt("321.list", skip_header = skip_top_lines, skip_footer = skip_bottom_lines, usecols = 5, unpack = True)
a_value01 = np.genfromtxt("322.list", skip_header = skip_top_lines, skip_footer = skip_bottom_lines, usecols = 5, unpack = True)
a_value02 = np.genfromtxt("323.list", skip_header = skip_top_lines, skip_footer = skip_bottom_lines, usecols = 5, unpack = True)
...
a_valueXX

a_noise00 = np.genfromtxt("321.list", skip_header = skip_top_lines, skip_footer = skip_bottom_lines, usecols = 6, unpack = True)
a_noise01 = np.genfromtxt("322.list", skip_header = skip_top_lines, skip_footer = skip_bottom_lines, usecols = 6, unpack = True)
a_noise02 = np.genfromtxt("323.list", skip_header = skip_top_lines, skip_footer = skip_bottom_lines, usecols = 6, unpack = True)
...
a_noiseXX

# NORMALIZATION OF SAID PARSED VALUES

a_norm00 = a_value00/a_value00
a_norm01 = a_value01/a_value00
a_norm02 = a_value02/a_value00
...
a_normXX

a_noiseval00 = a_norm00/a_noise00/2
a_noiseval01 = a_norm01/a_noise01/2
a_noiseval02 = a_norm02/a_noise02/2
...
a_noisevalXX

# FITTING AND PLOTTING

spin_lock_durations = (0.005, 0.010, 0.020, 0.050, 0.100)

y_signal_a = (a_norm00, a_norm01, a_norm02,..., a_normXX)

e_signal_a = (a_noiseval00, a_noiseval01, a_noiseval02,..., a_noisevalXX)

new_x = np.linspace(0, 0.105)

def exp_decay():
    x = spin_lock_durations

    y_signal_a = (a_norm00, a_norm01, a_norm02,..., a_normXX)

    x = np.array(x, dtype = float)

    y_signal_a = np.array(y_signal_a, dtype = float)

    plt.errorbar(x, y_signal_a, yerr = e_signal_a, fmt = ".k", markersize = 8, capsize = 3)

    def exp(x, a, b):
        return a * np.exp(-b * x)

    popt, pcov = curve_fit(exp, x, y_signal_a)

    par_err = np.sqrt(np.diag(pcov))

    print(par_err)
    plt.plot(new_x, exp(new_x, *popt))

    plt.tight_layout()
    plt.show()
exp_decay()

All the tables (321.list, 322.list, etc.) are formatted in exactly the same manner, so I am confident the process can be improved via a for loop of some kind. I am currently trying to import all the files and parse them via the following:

for file in os.listdir('.'):                                  # loop through all the files in your current folder
    if file.endswith('.list'):                                # find .list files
        file_name, file_extension = os.path.splitext(file)    # split file name and extension
        tot_data = pd.read_fwf(file, header = 0)              # import data
        print(tot_data)

But then, I fail at selecting the correct columns and proceed with the fitting plotting.

One file looks like:

     Assignment         w1         w2     w1 (Hz)    w2 (Hz)  Data Height       S/N

            X1H-H      9.482      9.482    7588.56    7588.56       926279        129
          C4H7-H7      9.419      9.419    7538.63    7538.59      2029781        282

Any help would be enormously appreciated! Thanks for your time!


texts:
We have the following validation function:

    var result = scope.CurrentUser.Surname.length > 0;
    var d = $q.defer();

    if (result) {
        apiService.UniqueEmailCheck(scope.CurrentUser.PersonId, scope.CurrentUser.Email)
            .success(function (response) {
                if (response) {
                        apiService.GetSelectetExistent(scope.CurrentUser.FirstName, scope.CurrentUser.Surname, scope.CurrentUser.DOB)
                        .success(function (response) {
                                    $scope.SelectExistent = response;
                                    d.resolve($scope.SelectExistent.length > 0);
                        });

            }
            else {
                d.resolve(false);
            }
        })
}
else
    d.resolve(false);

return d.promise;

If the incoming result is true, we have to check one or two async conditions.

It works as expected but we are not sure if we can do better. Any suggestions?


texts: Function to store data in MySQL database (using OurSQL)

texts:
I am parsing a huge XML file. It contains some million article entries like this one:

<article key="journals/cgf/HaeglerWAGM10" mdate="2010-11-12">
  <author>Simon Haegler</author>
  <author>Peter Wonka</author>
  <author>Stefan Müller Arisona</author>
  <author>Luc J. Van Gool</author>
  <author>Pascal Müller</author>
  <title>Grammar-based Encoding of Facades.</title>
  <pages>1479-1487</pages>
  <year>2010</year>
  <volume>29</volume>
  <journal>Comput. Graph. Forum</journal>
  <number>4</number>
  <ee>http://dx.doi.org/10.1111/j.1467-8659.2010.01745.x</ee>
  <url>db/journals/cgf/cgf29.html#HaeglerWAGM10</url>
</article>

I step through the file and parse those articles by LXML. If I let the code without storing the items into my database it makes some 1000 entries in ~3 seconds. But if I activate the storage which is done by the function below it makes some 10 entries per second. Is this normal? I remember parsing the file once upon a time and the database was not such a bottleneck. But I had a different approach... (looking through my files to find it)

def add_paper(paper, cursor):
    questionmarks = str(('?',)*len(paper)).replace("'", "") # produces (?, ?, ?, ... ,?) for oursql query
    keys, values = paper.keys(), paper.values()
    keys = str(tuple(keys)).replace("'", "") # produces (mdate, title, ... date, some_key)
    query_paper = '''INSERT INTO dblp2.papers {0} VALUES {1};'''.\
                    format(keys, questionmarks)
    values = tuple(v.encode('utf8') for v in values)
    cursor.execute(query_paper, values)
    paper_id = cursor.lastrowid
    return paper_id

def populate_database(paper, authors, cursor):
    paper_id = add_paper(paper, cursor)
    query_author ="""INSERT INTO dblp2.authors (name) VALUES (?) ON DUPLICATE KEY UPDATE id=LAST_INSERT_ID(id)"""
    query_link_table = "INSERT INTO dblp2.author_paper (author_id, paper_id) VALUES (?, ?)"
    for author in authors:
        cursor.execute(query_author, (author.encode('utf8'),))
        author_id = cursor.lastrowid
        cursor.execute(query_link_table, (author_id, paper_id))

Edit:

I was able to narrow the problem to those three cursor.executes. Perhaps it is a database problem. I will ask over at Stack Overflow, if someone has an idea, why it is that slow. Meanwhile I would be interested if the code can be refactored to be more pythonic. Any ideas?

Edit 2:

If use a similar approach like me storing row per row into the database, don't use the InnoDB engine.  It's slower in orders of magnitude. The code is speeding up again, after I changed the engine.


texts:
As we all know, the syntax of allocating memory is a bit clunky in C. The recommended way is:

 int *p;
 int n=10;
 p = malloc(n*sizeof *p);

You can use sizeof (int) instead of sizeof *p but it is bad practice.

I made a solution to this with a macro:

#define ALLOC(p,n) do{ *p=malloc(n*sizeof **p); } while(0)

This get called this way:

 int *p;
 int n=10;
 ALLOC(&p, n);

The reason I want to pass the address of p rather than p, is to offer a bit of protection. When you call a function with foo(x), then foo can never change the value of x. If you're not passing the address, the argument will not change. (Sure there are ways around that too.)

Any comments?


texts: Implementing insertAt for both [a] and [(i,a)] lists

texts:
I've implemented generic insertAt function which inserts element into both indexed and ordinary lists. Here are some examples:

-- ordinary list
insertAt 1 5 [1, 2]         == [1, 5, 2]
-- indexed list
insertAt 1 5 [(0,1), (1,2)] == [(0,1), (1, 5), (2, 2)]

Here is the code:

{-# LANGUAGE TypeFamilies, FlexibleInstances #-}

import Data.List
import Data.Ord

-- Determines index type of list
type family I i a where
  I i (j, e) = j -- index of `[(j, e)]` is `j`
  I i e      = i -- index of `[e]`, is `i`

-- Determines element type of list
type family E a where
  E (j, e) = e -- element of `[(j, e)]` is `e`
  E e      = e -- element of `[e]` is `e`

-- Class of element of list
class ListElem e where
  insertAt ::
    ( e ~ (i, a, b) -- `e` is a tuple where
    , i ~ I i b     -- `i` is index
    , a ~ E b       -- `a` is element
    ) => i -> a -> [b] -> [b]

enumerate :: (Num i, Enum i) => [a] -> [(i, a)]
enumerate = zip [0..]

-- Instance for non indexed lists
instance Integral i => ListElem (i, e, e) where
  insertAt i x = map snd . insertBy (comparing fst) (i, x) . enumerate

-- Instance for indexed lists
instance Integral i => ListElem (i, e, (i, e)) where
  insertAt i x xs = let (l, r) = genericSplitAt i xs in
                      l ++ (i, x) : map (\ (j, y) -> (j + 1, y)) r

Only problem I have is that type of i in instance for ordinary lists cannot be automaticaly inferred. So, I should put type annotations everywhere I use it. Instance for indexed lists works fine.


texts:
I recently created a custom model binder as a training exercise and wanted to see how I could improve it. It currently uses recursion and works great, but I was wondering how I could convert this to be non-recursive (maybe by using stack collection?). Any other ways this could be improved? Thank you for your feedback!

    public class ViewModelBinder<T> : IModelBinder where T: class
{
    #region Private Fields

    private ModelBindingContext _bindingContext;
    private ControllerContext _controllerContext;

    #endregion

    /// <summary>
    /// ADDS MODEL STATE ERRORS
    /// </summary>
    /// <param name="name">Name of Error</param>
    /// <param name="message">Error Message</param>
    private void AddModelError(string name, string message)
    {
        _bindingContext.ModelState.AddModelError(name, message);
    }

    /// <summary>
    /// Recursively Create View Model Class, Instantiating classes along the way and populating their values
    /// </summary>
    /// <param name="_returnValue">Class to create - first = Type of T</param>
    private void CreateModel(ref object _returnValue)
    {
        foreach (var item in _returnValue.GetType().GetProperties().ToList())
        {
            var itemType = item.PropertyType;
            if (!itemType.IsPrimitive && !itemType.FullName.StartsWith("System."))
            {
                var innerClass = Activator.CreateInstance(itemType);
                CreateModel(ref innerClass);
                item.SetValue(_returnValue, innerClass, null);
            }
            else
            {
                if (HasValue(_controllerContext.HttpContext.Request.Form, item.Name))
                    // if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>)) {…}
                    item.SetValue(_returnValue, Convert.ChangeType(_controllerContext.HttpContext.Request.Form[item.Name], item.PropertyType), null);
            }
        }

        // VALIDATE MAIN VIEW MODEL
        ValidateModel(_returnValue);
    }

    /// <summary>
    /// GENERATE VIEW MODEL
    /// </summary>
    /// <param name="controllerContext">Contains controller information</param>
    /// <param name="bindingContext">Contains binding information</param>
    /// <returns>vIEW MODEL OF TYPE T</returns>
    public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        _bindingContext = bindingContext;
        _controllerContext = controllerContext;
        var returnValue = Activator.CreateInstance(typeof(T));

        CreateModel(ref returnValue);

        return returnValue;
    }

    /// <summary>
    /// Check to see if key is in form collection
    /// </summary>
    /// <param name="form">Request Form</param>
    /// <param name="key">Key to key to check for (name of property)</param>
    /// <returns>bool - if true then key is in collection</returns>
    private bool HasValue(NameValueCollection form, string key)
    {
        return form.AllKeys.ToList().Contains(key);
    }

    /// <summary>
    /// create a validation context for a given model and check for validation errors
    /// </summary>
    /// <param name="model">model to validate</param>
    private void ValidateModel(object model)
    {
        var vc = new ValidationContext(model);
        var results = new List<ValidationResult>();
        var isValid = Validator.TryValidateObject(model, vc, results, true);

        if (isValid) return;

        foreach (var error in results)
            AddModelError(error.ErrorMessage, error.ErrorMessage);
    }
}


texts: Byte Array to Hexadecimal String Conversion

texts:
Another journey down the difficult path! I'd like to know if there's anything I haven't accounted for, if this can be significantly improved, etc.

(Just as a side-note, I know that some of the formatting is a bit off; some places are spaced out a bit to make it more visually appealing.)

using System;

namespace Data
{
    public class BinaryHelper
    {
        public static string ByteToHexString (byte[] bytes)
        {
            char[] c = new char[bytes.Length * 2];
            byte b;

            for (int i = 0; i < bytes.Length; i++) {
                b = ((byte)(bytes [i] >> 4));
                c [i * 2] = (char)(b > 9 ? b + 0x37 : b + 0x30);
                b = ((byte)(bytes [i] & 0xF));
                c [i * 2 + 1] = (char)(b > 9 ? b + 0x37 : b + 0x30);
            }

            return new string (c);
        }

        public static byte[] HexStringToByte (string hex)
        {
            int len = hex.Length;
            byte[] bytes = new byte[len / 2];

            for (int i = 0; len > i; i += 2) {
                bytes [i / 2] = Convert.ToByte (hex.Substring (i, 2), 16);
            }

            return bytes;
        }
    }
}


texts:
I'm making a simple program that generates a random password of some length with or without special characters, just for the sake of learning the C language. Finally I've got this working very well based on the outputs below:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>

char *generate_random_password(int password_lenght, int has_special_characters)
{
    const char *letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
    const char *digits = "0123456789";
    const char *special_characters = "!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~";

    char *random_password = malloc(sizeof(char) * (password_lenght+1));

    srandom(time(NULL));

    if(has_special_characters)
    {
        char to_be_used[95] = "\0";

        strcat(to_be_used, letters);
        strcat(to_be_used, digits);
        strcat(to_be_used, special_characters);

        for(int i = 0; i < password_lenght; i++)
        {
            const int random_index = random() % strlen(to_be_used);
            const char random_character = to_be_used[random_index];

            random_password[i] = random_character;
        }
    }
    else
    {
        char to_be_used[63] = "\0";

        strcat(to_be_used, letters);
        strcat(to_be_used, digits);

        for(int i = 0; i < password_lenght; i++)
        {
            const int random_index = random() % strlen(to_be_used);
            const char random_character = to_be_used[random_index];

            random_password[i] = random_character;
        }
    }

        return random_password;

        free(random_password);
}

int main(void)
{
    printf("%s\n", generate_random_password(17, 1));
    printf("%s\n", generate_random_password(17, 0));

    return 0;
}

The output is:

|ZzN>^5}8:i-P8197

vPrbfzBEGzmSdaPPP

It's working!

But I'm completely in doubt about these strings, pointers, char arrays, etc. I have no idea if this is written "the right way" or how it could be better. I'm concerned if I allocated the right amount for each string/char array, and if it can break or crash in some future.

PS: I'm new at C programming, that's why I don't know much about pointers and memory management yet.

If can anyone give me some feedback about it I will be very grateful!


texts:
I'm trying to create a mini social network mobile application kind of like Instagram and I'm not sure about my database organisation, it feels like something is missing, especially with the Posts table.

CREATE TABLE Users(
'user_id' int(20) NOT NULL AUTO_INCREMENT,
'email' VARCHAR(255) NOT NULL,
'username' VARCHAR(25) NOT NULL,
'password' VARCHAR(255) NOT NULL,
'first_name' VARCHAR(255) NOT NULL,
'last_name' VARCHAR(255) NOT NULL,
'gender' ENUM('M', 'F'),
'city' VARCHAR(255),
'state' VARCHAR(255),
'country' VARCHAR(255),
'profile_picture_url' VARCHAR(255),
'birth_date' VARCHAR(255),
'date_created' DATE NOT NULL,
'date_updated' DATE,
'active' ENUM('yes','no') NOT NULL DEFAULT 'no',
'activation_key' VARCHAR(255) NOT NULL,
PRIMARY KEY ('user_id'),
UNIQUE KEY 'email' ('email'),
UNIQUE KEY 'username' ('username')
);

CREATE TABLE Posts(
'post_id' int(20) NOT NULL AUTO_INCREMENT,
'user_id' int(20) NOT NULL
'caption'  VARCHAR(255),
'latitude' FLOAT NOT NULL,
'longitude' FLOAT NOT NULL,
'type' ENUM('image', 'video'),
'post_url' VARCHAR(255) NOT NULL,
'date_created' DATE NOT NULL,
'date_updated' DATE,
PRIMARY KEY ('post_id'),
FOREIGN KEY ('user_id') REFERENCES Users('user_id')
);

CREATE TABLE Followings(
'user_id' INT NOT NULL,
'following_id' INT NOT NULL,
'date_created' DATE NOT NULL,
PRIMARY KEY ('user_id', 'following_id'),
UNIQUE INDEX ('following_id', 'user_id')
FOREIGN KEY ('user_id') REFERENCES Users('user_id')
FOREIGN KEY ('following_id') REFERENCES Users('user_id')
);

CREATE TABLE Comments(
'comment_id' INT(20) NOT NULL AUTO_INCREMENT,
'post_id' INT(20) NOT NULL,
'user_id' INT(20) NOT NULL,
'content' TEXT NOT NULL,
'date_created' DATE NOT NULL,
'date_updated' DATE,
PRIMARY KEY ('comment_id'),
FOREIGN KEY ('post_id') REFERENCES Posts('post_id')
FOREIGN KEY ('user_id') REFERENCES Users('user_id')
);

CREATE TABLE Messages(
'message_id' INT(20) NOT NULL AUTO_INCREMENT,
'user_id_from' INT(20) NOT NULL,
'user_id_to' INT(20) NOT NULL,
'content' text NOT NULL,
'date_created' date NOT NULL,
PRIMARY KEY ('message_id'),
FOREIGN KEY ('user_id_from') REFERENCES Users('user_id'),
FOREIGN KEY ('user_id_to') REFERENCES Users('user_id')
);

CREATE TABLE Likes(
'user_id' INT(20) NOT NULL AUTO_INCREMENT,
'post_id' int(20) NOT NULL,
'date_created' DATE NOT NULL,
PRIMARY KEY ('user_id', 'post_id'),
UNIQUE INDEX ('post_id', 'user_id'),
FOREIGN KEY ('post_id') REFERENCES Posts('post_id'),
FOREIGN KEY ('user_id') REFERENCES User('user_id')
);

Regarding the Posts table, would you recommend that I split it for each type of post, like one for the pictures and another one for the videos?

All the pictures/videos will be hosted on the AWS and therefore not on my server.

What would you recommend I change with these tables that I currently have, based on your experience? What tables should I implement?


texts: Optimizing a divide-and-conquer algorithm for counting inversions

texts:
I have the following code:

inversions :: (Ord a) => [a] -> Int
inversions xs = snd $ countInv' (xs, length xs)

countInv' :: (Ord a) => ([a], Int) -> ([a], Int)
countInv' ([], _) = ([], 0)
countInv' ([x], _) = ([x], 0)
countInv' (xs, n) = (sorted, leftInv + splitInv + rightInv)
    where
        leftLen = n `div` 2
        rightLen = n - leftLen
        (left, right) = splitAt leftLen xs
        (sortedLeft, leftInv) = countInv' (left, leftLen)
        (sortedRight, rightInv) = countInv' (right, rightLen)
        (sorted, splitInv) = countSplitInv' (sortedLeft, leftLen) (sortedRight, rightLen)

countSplitInv' :: (Ord a) => ([a], Int) -> ([a], Int) -> ([a], Int)
countSplitInv' ([], _) ([], _) = ([], 0)
countSplitInv' (xs, _) ([], _) = (xs, 0)
countSplitInv' ([], _) (xs, _) = (xs, 0)
countSplitInv' (x : xs, nx) (y : ys, ny)
    | x > y     = (y : sortedY, nx + splitInvY)
    | otherwise = (x : sortedX, splitInvX)
    where
        (sortedX, splitInvX) = countSplitInv' (xs, pred nx) (y : ys, ny)
        (sortedY, splitInvY) = countSplitInv' (x : xs, nx) (ys, pred ny)

main :: IO ()
main = do
    contents <- getContents
    print $ inversions (map read (lines contents) :: [Int])

How could I write this code in a way that is more idiomatic, reduces the amount of repetition, and reduces the amount of data being copied?

As a Haskell beginner, I would appreciate it if you give an indepth explanation of the code you write and try to keep your code as simple as possible.


texts:
I was wondering if I could get a second look at my program before I turn it in. The job was to code a program in java that adds two integers to an array gather the sum while displaying the integers that belong in the carry column section. I am curious if there is a simpler way to do what I am trying to do.
I hope the output is enough to give you the idea behind the program.

Here is a sample output.

Enter the first number : 9999
Enter the second number : 9999
Carry : 1110
Num1 : 9999
Num2 : 9999
Sum : 19998
Continue(Y/N)

import java.util.Arrays;
import java.util.Scanner;
import java.util.*;

public class Main {

public static void main(String args[]) {

 Integer[]  num1 = new Integer[10];
 Integer[]  num2 = new Integer[10];
 Integer[]  temp = new Integer[10];
 Integer[] carry = new Integer[10];
 Integer[]   sum = new Integer[10];

Scanner input = new Scanner(System.in);

do{

     int g;
     int a=0;
     int b=0;
     int t;
     int s1;
     int c=0;

     //Read two integer values from user input
     System.out.print("\n Enter the first number : ");
     int m = input.nextInt();

     System.out.print("\n Enter the second number : ");
     int n = input.nextInt();

     for(int i = 0; i < 10; i++){

         num1[i]=0;
         num2[i]=0;

     }

      //Placing the two integer numbers into array
     while(m > 0){

         g = m % 10;
         m = m / 10;
         num1[a] = g;
         temp[a] = g;
         a++;

     }

     while(n > 0){

         g = n % 10;
         n = n / 10;
         num2[b] = g;
         b++;
     }

     if(a > b) c = a;
     else   c = b;

     for(int i = 0; i < c; i++){

         carry[i]=0;
         sum[i]=0;

     }

     //finding sum and handling carry
     for(int i = 0; i < c; i++){

         sum[i] = num1[i]+num2[i];
         s1=sum[i];
         t=0;

         while(s1 > 0){

             s1= s1 / 10;
             t++;

         }

         if(t > 1 && ((i+1)<c)){

             carry[i+1] = 1;
             num1[i+1] = num1[i+1] + 1;
             sum[i] = sum[i] % 10;

         }

     }

      // Printing the sum value to user
     System.out.print("\n Carry : " );
     for(int x = c-1; x >= 0; x--)
         System.out.print(carry[x]);

     System.out.print("\n");
     System.out.print("\n Num1 : " );
     for(int x=c-1;x>=0;x--)
         System.out.print(temp[x]);
     System.out.print("\n");

     System.out.print("\n Num2 : " );
     for(int x=c-1;x>=0;x--)
         System.out.print(num2[x]);
     System.out.print("\n");

     System.out.print("\n Sum : " );
     for(int x=c-1;x>=0;x--)
         System.out.print(sum[x]);
     System.out.print("\n");

 } while(Continue());
}

 public static boolean Continue(){

  char choice;

   Scanner input = new Scanner(System.in);
   System.out.println("Continue(Y/N)");
   choice = input.next().charAt(0);

   return Character.toLowerCase(choice) == 'y';

  }

}


texts:
Imagine I have connection in which I have to write numbers, represented by this contract:

interface ISocket
{
    Task WriteAsync(Byte[], Int32 offset, Int32 count, CancellationToken cancel);
}

There is one single thread calling this WriteAsync method.

Till now each caller to ISocket was buffering independently and knows when it has to flush, however I would like to centralize that logic. Also I want to make sure that when such buffer is being transmitted, I can take advantage of async/await and release the thread pool thread.

My idea would be to create something like this:

class SocketWriter
{
    private ISocket _socket;
    private Byte[] _buffer; // assume 8K
    private Int32 _cursor;

    [ ... ]

    private async Task FlushCacheIfNotEnoughSpace(Int32 length, CancellationToken cancel)
    {
        if(!FitsInBuffer(length))
        {
            await _socket.WriteAsync(_buffer, 0, _cursor, cancel).ConfigureAwait(false);
            _cursor = 0;
        }
    }

    [ ... ]

    public async Task WriteAsync(UInt64 value, CancellationToken cancel)
    {
        await FlushCacheIfNotEnoughSpace(8, cancel).ConfigureAwait(false);
        CopyToByteArray(value);
    }

    public Task Flush(CancellationToken cancel)
    {
        return FlushCacheIfAny(cancel);
    }
}

There are some memory constraints, so I cannot create more than one of those Byte[] buffers. CopyToByteArray requires enough space in the _buffer and increments _cursor accordingly.

Note that FlushCacheIfNotEnoughSpace only awaits if the given length does not fit the current buffer.

My intention is that when the buffer is not complete and there is space for another number this method call executes synchronously, or properly awaits using IO completion ports otherwise:

await _writer.WriteAsync(1UL, cancel).ConfigureAwait(false);

I wonder if there is a better or more elegant way of doing this, because it seems like a lot of "noise":

await _writer.WriteAsync(obj.Member1, cancel).ConfigureAwait(false);
await _writer.WriteAsync(obj.Member2, cancel).ConfigureAwait(false);
await _writer.WriteAsync(obj.Member3, cancel).ConfigureAwait(false);
await _writer.WriteAsync(obj.Member4, cancel).ConfigureAwait(false);


texts:
I needed a simple parser that could do both logical and math operations expressed in a string, as well as being able to use variables stored in json.
None of what I found online seemed to do all of the above, so I came up with my own. Below is the source code for my ExpressionParser as well as my JExpressionParser, in case your variables are stored in a JSON.
Hopefully this post will help someone, as well as allow others to improve my code.
Here is the base parser:
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;

public class ExpressionParser
{
    public virtual IDictionary<string, object> Variables { get; }
    protected ExpressionParser() { }
    protected virtual DataTable GetComputer()
    {
        var computer = new DataTable();
        if (Variables != null)
        {
            computer.Columns.AddRange(Variables.Select(v => new DataColumn(v.Key) { DataType = v.Value.GetType() }).ToArray());
            computer.Rows.Add(Variables.Values.ToArray());
        }
        return computer;
    }
    public ExpressionParser(IDictionary<string, object> variables = null)
    {
        Variables = variables ?? new Dictionary<string, object>();
    }
    public object Compute(string expression)
    {
        StringBuilder sb = new StringBuilder(expression);
        foreach (var key in Variables.Keys)
            sb.Replace(key, $"Sum({key})");
        sb.Replace("==", "=");
        using (var computer = GetComputer())
            return computer.Compute(sb.ToString(), null);
    }
}

And here is one that works with json objects:
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;

public class JExpressionParser : ExpressionParser
{
    public JObject JVariables { get; set; }
    public override IDictionary<string, object> Variables =>
        JVariables.Properties().ToDictionary(p => p.Name, p => p.Value.ToObject(conversions[p.Value.Type]));
    static readonly Dictionary<JTokenType, Type> conversions = new Dictionary<JTokenType, Type>()
    {
        [JTokenType.Integer] = typeof(int),
        [JTokenType.Float] = typeof(float),
        [JTokenType.Boolean] = typeof(bool),
    };
    public JExpressionParser(JObject jVariables = null)
    {
        JVariables = jVariables ?? new JObject();
    }
}

Usage:
var variables = new Dictionary<string, object>() { ["budget"] = 1000, ["cost"] = 965 };
var parser = new ExpressionParser(variables);
Console.WriteLine("We have $" + parser.Compute("budget - cost") + " of budget left.");


texts:
A friend and I at IT school tasked ourselves with writing something just for the hell of it. Trying to simulate in a very basic way something that you may want to do in the real world. We thought of the following problem that we could solve ourselves.

X, Y and X INC is in need of a program. They wish to promote the sales of their products in bigger quantity. They wish to give the following discounts to promote better sales.

If 1 to a 100 of a certain item is sold the company wishes to grant a 10 percent discount.
If the amount of the product sold is between 101 and 200 the company wishes to grant a 12 percent discount.
If the amount of the product sold is between 201 and 500 the company wishes to grant a 15 percent discount
If the amount of product sold is greater than 500 the discount should be 20 percent.

The program should take a price input and a quantity input and should give a total with the applicable discount to the end user without divulging the percentage of the discount.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DiscountApp
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Please enter the quanitity of the product bought.");
            var x = Console.ReadLine();
            int x1 = int.Parse(x);

            Console.WriteLine("Please enter the price of the product bought.");
            var y = Console.ReadLine();
            double y1 = double.Parse(y);

            double discount = 0;
            double outValue = 0;

            if (x1 <= 100)
            {
                discount = 0.1;
                outValue = returnTotal(discount, y1, x1);
                Console.WriteLine("The total with the discount is R{0}",outValue);
            }
            else if (x1 > 100 && x1 <= 200)
            {
                discount = 0.12;
                outValue = returnTotal(discount, y1, x1);
                Console.WriteLine("The total with the discount is R{0}",outValue);
            }
            else if (x1 > 200 && x1 <= 500)
            {
                discount = 0.15;
                outValue = returnTotal(discount, y1, x1);
                Console.WriteLine("The total with the discount is R{0}",outValue);
            }
            else
            {
                discount = 0.2;
                outValue = returnTotal(discount, y1, x1);
                Console.WriteLine("The total with the discount is R{0}",outValue);
            }

        }
        public static double returnTotal(double discount, double price, int quantity)
        {
            double Total = (price * quantity);
            double discountTotal = Total - (Total * discount);
            return discountTotal;
        }

    }

}

I'm not sure if a switch statement would be better. I'm not entirely sure how you would do multiple conditions in the switch statement.


texts: Ugly Number problem using dynamic programming

texts:
I am learning Dynamic Programming and tried to solve the nth ugly number problem using it. Here's my code for the problem in Java:
import java.util.HashSet;

public class UglyNum {
    //using DP bottom up
    public static int getUgly(int n) {
        HashSet<Integer> u = new HashSet<>();
        if (n < 6)
            return n;
        for (int i = 1; i < 6; i++) {
            u.add(i);
        }
        int x = 5;
        int i = 6;
        boolean flag;
        while (x < n) {
            flag = false;
            flag = checkContains(i, 2, u, flag);
            if(!flag)
            flag = checkContains(i, 3, u, flag);
            if(!flag)
            flag = checkContains(i, 5, u, flag);
            if (flag) {
                u.add(i);
                x++;
            }
            if (x == n)
                return i;
            i++;
        }
        return -1;
    }

    private static boolean checkContains(int x, int n, HashSet<Integer> u, boolean flag) {
        if (x % n == 0) {
            if (u.contains(x / n))
                return true;
            else
                return false;
        }
        return flag;
    }
    //DP ends here

}

The idea is that a new number, say x, is ugly only if x/2 or x/3 or x/5 is ugly.
I analysed the code wrt the 2 codes given in the  GFG site article and here are the results for 100 ugly numbers:

The first time (26.3992 ms) is the time using my dynamic programming approach. The other 2 are the ones given on the site. Clearly my program is taking relatively too much time. Can you help me optimise it?
PS: I am aware of the awesome methods to solve the problem but wondering why mine is so slow.


texts: Enumerate directories to a given search depth

texts:
Since I had been in the need of finding directories from a startpath with different search depth levels, I created this little helper class.

This class is using objects of the System.IO namespace.

public class IOHelper
{
    public const int AllDirectories = -1;
    public const int TopDirectoryOnly = 0;
    private const char WildCard = '*';

    public static IEnumerable<String> EnumerateDirectories(String startDirectory,  int depth)
    {
        return EnumerateDirectories(startDirectory, "*.*", depth);
    }

    public static IEnumerable<String> EnumerateDirectories(String startDirectory, String searchPattern, int depth)
    {
        if (depth < AllDirectories) { throw new ArgumentOutOfRangeException("depth", "Depth needs to be -1(AllDirectories) or greater"); }

        switch (depth)
        {
            case AllDirectories:
                return Directory.EnumerateDirectories(startDirectory, searchPattern, SearchOption.AllDirectories);

            case TopDirectoryOnly:
                return Directory.EnumerateDirectories(startDirectory, searchPattern, SearchOption.TopDirectoryOnly);

            default:
                return EnumerateDirectoriesInDepth(startDirectory, searchPattern, depth);
        }
    }

    private static IEnumerable<String> EnumerateDirectoriesInDepth(String startDirectory, String searchPattern, int depth)
    {
        IEnumerable<String> directories = EnumerateDirectoriesInDepth(startDirectory, depth);

        Boolean isWildCardSearch = searchPattern.Contains(WildCard);

        if (!isWildCardSearch)
        {
            searchPattern = String.Concat("\\", searchPattern);
            return directories.Where(d => d.EndsWith(searchPattern));
        }

        IEnumerable<String> enumeratedDirectories = Enumerable.Empty<String>();
        foreach (String directory in directories)
        {
            enumeratedDirectories = enumeratedDirectories.Concat(Directory.EnumerateDirectories(directory, searchPattern));
        }

        return enumeratedDirectories;
    }

    private static IEnumerable<String> EnumerateDirectoriesInDepth(String startDirectory, int depth)
    {
        if (depth <= TopDirectoryOnly) { return Enumerable.Empty<String>(); }

        IEnumerable<String> directories = Directory.EnumerateDirectories(startDirectory, "*.*", SearchOption.TopDirectoryOnly);

        if (!directories.Any()) { return directories; }

        depth = depth - 1;

        IEnumerable<String> subDirectories = Enumerable.Empty<String>();
        foreach (String directory in directories)
        {
            subDirectories = subDirectories.Concat(EnumerateDirectoriesInDepth(directory, depth));
        }

        return directories.Concat(subDirectories);
    }
}

I would like to get a review on all aspects.


texts: JavaScript function for printing a countdown

texts:
As part of my project, a game, I have progress bars with countdown timers. These are updated every 250ms, to keep a relatively smooth animation if the countdown time is short.

Here's my function:

var time_format = function(time) {
    var elms, names, ret, i, n;
    elms = [
        time / 29030400,
        time / 2419200 % 12,
        time / 604800 % 4,
        time / 86400 % 7,
        time / 3600 % 24,
        time / 60 % 60,
        time % 60
    ];
    names = "yr mo w d h m s".split(" ");
    ret = [];
    for( i=0; i<elms.length; i++) {
        n = Math.floor(elms[i]);
        if( n) ret.push(n+names[i]);
    }
    ret = ret.join(" ");
    if( ret == "") ret = "0s";
    return ret;
};

I'm just wondering if any optimisations can be made to this code. There may be up to ten progress bars on a single page (after that data is paginated). My main concern is that Math.floor call, is there a faster way to floor a number?


texts: C++ Hashing Passwords - simple algorithm using rand()

texts:
I'm studying algorithm's and got to the point of hashing.I was excited about it and I created a little hashing function which will depend on user input and generate passwords. The passwords had to look completely random, depend largely on input and be consistent(same input - same pass generated), however not looking similar for similar inputs.I have read someware that function rand() in C++ will generate same sequence of random numbers for same seed. So I used it as a part of algorithm. I'm not sure how safe it is but so far it works well. Any ideas on improving code or algorithm are welcomed!

void User::HashPassword()//Hash pass method of User class
{
    if (IsExisting())//checking if input was valid
    {
        UserHashPassword.clear();
        std::string Combine = UserName + UserPassword + UserURL;
        const unsigned int VALUE = Combine.length();
        for (auto Letter : Combine)
        {
            srand(VALUE*Letter);//seed that depends on user input - new for each letter, and input total length
            UserHashPassword += 33 + rand() % 92;//borders set for ASCII codes that exist on english keyboards
        }
    }

}


texts: Presenting user with options and executing a function based on user choice in Javascript

texts:
I'm currently creating a text based game where the user navigates through the game via buttons and i'm trying to improve on my code because i'm pretty sure it could be alot better, the following is some code which i wrote to give the user some options (via html buttons) and then check what their selection is in order to execute the correct function.
class Room {

    constructor(description, options) {

        this.description = description;
        this.options = options;

    }
}

 var f1hallway = new Room("You see two rooms", ["Room 1", "Room 2"]);

 var f1room1 = new Room("You find a letter on a table", ["Read it", "Exit"]);

 var f1room2 = new Room("Nothing of interest here", ["Exit"]);

    whichArea = function(areaSelected) {

                selectedArea = areaSelected;
                areaSelected();

              }

    function presentChoices(options) {

              choices.innerHTML = "";

         for (var x = 0; x < options.length; x++) {

            choiceButton = document.createElement("button");
            choiceButton.setAttribute("class", "choice-button");
            choices.appendChild(choiceButton);
            choiceButton.innerHTML = options[x];
            selectedChoiceIndex = x;
            choiceButton.setAttribute("id", x);

             choiceButton.onclick = function() {

                selectedChoice = this.innerHTML;
                chosenOptionId = this.id;
                whichArea(selectedArea);

             }

        }

    }

function f1hallwayFunc() {

        mainText.innerHTML = f1hallway.description;
        choices.innerHTML = "";
        presentChoices(f1hallway.options);

        if (chosenOptionId == 0) {

            chosenOptionId = null;
            whichArea(f1roomOneFunc);

        }

        else if (chosenOptionId == 1) {

            chosenOptionId = null;
            whichArea(f1roomTwoFunc);

        }

function f1roomOneFunc() {

    mainText.innerHTML = f1room1.description;
    presentChoices(f1room1.options);

     if (chosenOptionId == 0) {

        chosenOptionId = null;
        mainTextWrap.innerHTML = "You start reading the letter";

    }

    else if (chosenOptionId == 1) {

        chosenOptionId = null;
        whichArea(f1hallwayFunc);
        mainText.innerHTML = "You exit the room and return to the hallway";

    }

}

function f1roomTwoFunc() {

    mainText.innerHTML = f1room2.description;
    presentChoices(f1room2.options);

     if (chosenOptionId == 0) {

        chosenOptionId = null;
        whichArea(f1hallwayFunc);
        mainText.innerHTML = "You exit the room and return to the hallway";

    }

}

The code works fine but seems like a mess at the same time, each area that the user ends up in goes through this same process, can someone please tell me how this could be written better and any best practices i'm missing? I'm still quite new to programming and would appreciate any help, thanks!


texts: Simple concurrency implemented in Python

texts:
Purpose of the question: learn more about ways to implement concurrency in Python / experimenting.

Context: I want to count all of the words in all of the files that match a particular pattern. The idea is that I can invoke the function count_words('/foo/bar/*.txt') and all of the words (i.e., strings separated by one or more whitespace characters) will be counted.

In the implementation I am looking for ways to implement count_words using concurrency. So far I managed to use multiprocessing and asyncio.

What do you think of these two approaches?
Do you see alternative approaches to do the same task?
What about the code style, should I implement a dedicated class for each approach?

I did not use threading as I noticed the performance improvement was not that impressive due to the limitation of the Python GIL.

import asyncio
import multiprocessing
import time
from pathlib import Path
from pprint import pprint

def count_words(file):
    with open(file) as f:
        return sum(len(line.split()) for line in f)

async def count_words_for_file(file):
    with open(file) as f:
        return sum(len(line.split()) for line in f)

def async_count_words(path, glob_pattern):
    event_loop = asyncio.get_event_loop()
    try:
        print("Entering event loop")
        for file in list(path.glob(glob_pattern)):
            result = event_loop.run_until_complete(count_words_for_file(file))
            print(result)
    finally:
        event_loop.close()

def multiprocess_count_words(path, glob_pattern):
    with multiprocessing.Pool(processes=8) as pool:
        results = pool.map(count_words, list(path.glob(glob_pattern)))
        pprint(results)

def sequential_count_words(path, glob_pattern):
    for file in list(path.glob(glob_pattern)):
        print(count_words(file))

if __name__ == '__main__':
    benchmark = []
    path = Path("../data/gutenberg/")
    # no need for benchmark on sequential_count_words, it is very slow!
    # sequential_count_words(path, "*.txt")

    start = time.time()
    async_count_words(path, "*.txt")
    benchmark.append(("async version", time.time() - start))

    start = time.time()
    multiprocess_count_words(path, "*.txt")
    benchmark.append(("multiprocess version", time.time() - start))

    print(*benchmark)

For simulating large quantity of files, I downloaded some books from Project Gutenberg (https://gutenberg.org/) and used the following command to create several duplicates of the same file.

for i in {000..99}; do cp 56943-0.txt $(openssl rand -base64 12)-$i.txt; done


texts: Median of 3 partitioning taking more time than quicksort in java

texts:
I have a quicksort code in java which I want to improve. The improved code should take less time than the quicksort code. However when using my improved code which implement median of 3 partitioning, it takes 400 miliseconds more. Can anybody help me solve this out? if possible, can you suggest me other possible ways to improve my code. I have from 10,000 to 10 million integers to sort.

Quicksort

public void quickSort(int arr[], int begin, int end) {
    if (begin < end) {
        int partitionIndex = partition(arr, begin, end);

        quickSort(arr, begin, partitionIndex-1);
        quickSort(arr, partitionIndex+1, end);
    }

}

private int partition(int arr[], int begin, int end) {
    int pivot = arr[end];
    int i = (begin-1);

    for (int j = begin; j < end; j++) {
        if (arr[j] <= pivot) {
            i++;

            int swapTemp = arr[i];
            arr[i] = arr[j];
            arr[j] = swapTemp;
        }
    }

    int swapTemp = arr[i+1];
    arr[i+1] = arr[end];
    arr[end] = swapTemp;

    return i+1;
}

}

Improved code

package sorting;

public class improvement {

Clock c = new Clock();

  public void quickSort(int[] intArray) {

    recQuickSort(intArray, 0, intArray.length - 1);

  }

  public static void recQuickSort(int[] intArray, int left, int right) {
    int size = right - left + 1;
    if (size <= 3)
      manualSort(intArray, left, right);
    else {
      double median = medianOf3(intArray, left, right);
      int partition = partitionIt(intArray, left, right, median);
      recQuickSort(intArray, left, partition - 1);
      recQuickSort(intArray, partition + 1, right);
    }
  }

  public static int medianOf3(int[] intArray, int left, int right) {
  int center = (left + right) / 2;

    if (intArray[left] > intArray[center])
      swap(intArray, left, center);

    if (intArray[left] > intArray[right])
     swap(intArray, left, right);

   if (intArray[center] > intArray[right])
     swap(intArray, center, right);

   swap(intArray, center, right - 1);
   return intArray[right - 1];
  }

  public static void swap(int[] intArray, int dex1, int dex2) {
    int temp = intArray[dex1];
    intArray[dex1] = intArray[dex2];
    intArray[dex2] = temp;
 }

  public static int partitionIt(int[] intArray, int left, int right, double
  pivot) {
    int leftPtr = left;
    int rightPtr = right - 1;

     while (true) {
       while (intArray[++leftPtr] < pivot)
       ;
       while (intArray[--rightPtr] > pivot)
       ;
       if (leftPtr >= rightPtr)
         break;
       else
       swap(intArray, leftPtr, rightPtr);
    }
    swap(intArray, leftPtr, right - 1);
    return leftPtr;
 }

 public static void manualSort(int[] intArray, int left, int right) {
    int size = right - left + 1;
    if (size <= 1)
     return;
   if (size == 2) {
  if (intArray[left] > intArray[right])
    swap(intArray, left, right);
  return;
} else {
  if (intArray[left] > intArray[right - 1])
    swap(intArray, left, right - 1);
  if (intArray[left] > intArray[right])
    swap(intArray, left, right);
  if (intArray[right - 1] > intArray[right])
    swap(intArray, right - 1, right);
  }
 }
}


texts: Loop combinations of byte for Poker simulator

texts:
In (this) Poker you have 2 hole cards that are combined with 5 shared cards on the board. Each player makes the best 5 card hand from the seven. Believe it or not that is over 2 billion runs to do them all.

I'm trying to create statistics for 2 known hole cards against random boards and random hands for a single opponent using Monte Carlo for like 20 million runs.

First get sets of 7 random for board plus 1 opponent from 50 (known 2 hole cards are removed).  From those 7 remove all 2 card combinations (21) to represent the opponent's hole cards.  The idea is better statistics with an exhaustive examination of the 7 rather than a random 5 and a random 2.  Computation on the random 5 plus random 2 is more efficient as you only need to run the known hand once for each random 5.

byte? skip1 = null;
byte? skip2 = null;
List<byte> deck50seven = null;
byte nextSevenLastStart = 42;
private IEnumerable<byte> NextSevenA(byte Skip1, byte Skip2)
{
    if (Skip1 == Skip2)
        throw new ArgumentOutOfRangeException("skip1 == skip2");
    if (Skip1 > 51 || Skip2 > 51 || Skip1 < 0 || Skip2 < 0)
        throw new ArgumentOutOfRangeException("51 0");
    if(skip1 == null)
    {
        skip1 = Skip1;
        skip2 = Skip2;
        deck50seven = new List<byte>(50);
        for(byte b = 0; b < 52; b++)
        {
            if (b == Skip1 || b == Skip2)
                continue;
            deck50seven.Add(b);
        }
    }
    else
    {
        if (Skip1 != skip1 || Skip2 != skip2)
            throw new ArgumentException("skippy");
    }
    if (nextSevenLastStart >= 42)
    {
        nextSevenLastStart = 0;
        // Yates shuffle
        for (int i = 49; i >= 1; i--)
        {   // int for indexing is faster (I think)
            int j = rand.Next(i + 1);  // it can get swapped with itself
            if (j != i)
            {   // exchange values
                byte curVal = deck50seven[i];
                deck50seven[i] = deck50seven[j];
                deck50seven[j] = curVal;
            }
        }
    }
    else
        nextSevenLastStart += 7;
    return deck50seven.GetRange(nextSevenLastStart, 7);
}
private IEnumerable<List<byte>> NextSevenAsFiveTwo(List<byte> input)
{
    // 21 ways to take 2 from 7
    // this is going to seem strange but need every combination of 2 to be the last 2
    if (input.Count() != 7)
        throw new ArgumentOutOfRangeException("input.Count() != 7");
    List<byte> output = new List<byte>();
    for (byte i = 0; i <= 5; i++)
    {
        for (byte j = (byte)(i + 1); j <= 6; j++)
        {
            output.Clear();
            for (byte k = 0; k < 7; k++)
                if (k != i && k != j)
                    output.Add(input[k]);
            output.Add(input[i]);
            output.Add(input[j]);
            yield return output;
        }
    }
}

can use this for test

for (int i = 0; i < 10; i++)
{
    List<byte> nextSevenA = new List<byte>(NextSevenA(11, 12));
    Debug.WriteLine("Base " + string.Join(", ", nextSevenA));
    foreach(List<byte> ss in NextSevenAsFiveTwo(nextSevenA))
        Debug.WriteLine("     Subset " + string.Join(", ", ss));
}


texts:
I am trying to callback C++ class methods from C. Now I have got something working, but am not sure if this is the best solution.
I am looking for feedback, as to if there is something wrong with this approach, and how could I make this better.
So, here goes my code:
This is the C++ class Foo. The class has the methods getValue() & setValue(), which I would like to like to be called-back from the C code:
Contents of Foo.h:
#ifdef __cplusplus
class Foo
{
public:
    Foo();
    int getValue() const;
    void setValue(int value);

private:
    int value_;
};
#endif

// Free functions
int  c_wrapper_getValue(void *arg1);
void c_wrapper_setValue(int value, void *arg1);

Contents of the source file, Foo.cpp:
#include "Foo.h"

Foo::Foo() :
    value_{0}
{}

int Foo::getValue() const
{
    return value_;
}

void Foo::setValue(int value)
{
    value_ = value;
}

void c_wrapper_setValue(int value, void *arg1)
{
    Foo* foo_instance = static_cast<Foo*>(arg1);
    foo_instance->setValue(value);
}

int c_wrapper_getValue(void *arg1)
{
    Foo* foo_instance = static_cast<Foo*>(arg1);
    return foo_instance->getValue();
}

Here is the code for the C files, which in turn call the Foo class members. First, the header Test.h file:
#include <stdio.h>
#include "Foo.h"

#ifdef __cplusplus
extern "C" {
#endif

// Callback function pointers
typedef int  (*get_handler_t)(void* arg1);
typedef void (*set_handler_t)(int foo, void* arg1);

void register_handler(get_handler_t g, set_handler_t s, void* p_instance);

// These are the functions which call the callback functions
int call_cpp_get_function();
void call_cpp_set_function(int value);

#ifdef __cplusplus
}
#endif

And finally the Test.c file:
#include "Test.h"

static get_handler_t get_handler_ = NULL;   /**< Getter function pointer of type int (*g)(void *). */
static set_handler_t set_handler_ = NULL;   /**< Setter function pointer of type void (*s)(int,  void *). */
static void* foo_object_instance  = NULL;    /**< Instance of Foo object. */

//! Registers the getter and setter function with the object of Class Foo
//! \param g Getter function pointer of type int (*g)(void *).
//! \param s Setter function pointer of type void (*s)(int,  void *).
//! \param p_instance Instance of Foo object.
void register_handler(
    int (*g)(void *),
    void (*s)(int,  void *),
    void* p_instance)
{
    get_handler_ = g;
    set_handler_ = s;
    foo_object_instance = p_instance;
}

//! Function calls the get function of class Foo
//! \return Value of value_ from class Foo
int call_cpp_get_function()
{
    return get_handler_(foo_object_instance);
}

//! Function calls the set function of class Foo
//! \param value Value to be set in class Foo
void call_cpp_set_function(int value)
{
    set_handler_(value, foo_object_instance);
}

Now I could create an object and call the functions present in my C file, which called back the C++ methods, like this:
Foo foo_object;
register_handler(&c_wrapper_getValue, &c_wrapper_setValue, static_cast<void *>(&foo_object));
call_cpp_get_function();
call_cpp_set_function(35);

I do have some constraints in my case, for example I can't use STL, since the code is supposed to run on an embedded system. So, how bad is my code?


texts:
I got inspired by Doorknob's blog post What’s the largest MD5 hash you can find? to get my hands dirty and learn some Python. After playing around with the code from that post, I decided to rewrite the whole thing and to make it more flexible (to get some practice).

This is what the code does:

It generates a random string (called alphabet) and calculates all of its permutations
It keeps the permutation with the largest MD5 representation (hashes are numbers)
This is repeated DEFAULT_CYCLES times, if no static alphabet is set. In the end, the winning string is printed.

It ended up having many functions and I'm not sure if this is the best way to go. This is a quite simple task, but takes almost 50 lines of code. However I'm afraid it will become less readable if I try to "compress" it or lump some of the functions together.

So, how could this code be improved and/or shortened? This is the first time I'm writing Python, so please be gentle. :)

from itertools import permutations
from hashlib import md5
from random import choice
from string import ascii_uppercase, ascii_lowercase, digits

# Number of alphabets to test. Ignored if using a static alphabet.
DEFAULT_CYCLES = 256

# Length of 8 recommended. Set to empty string for random values.
STATIC_ALPHABET = ''

def get_alphabet():
    return STATIC_ALPHABET if STATIC_ALPHABET != '' else ''.join(choice(ascii_uppercase + ascii_lowercase + digits) for _ in range(8))

def number_of_cycles():
    return DEFAULT_CYCLES if STATIC_ALPHABET == '' else 1

def numeric_md5(input_string):
    return int(md5(input_string.encode('utf-8')).hexdigest(), 16)

def unique_permutations(plain_string):
    return set([''.join(p) for p in permutations(plain_string)])

def string_with_largest_hash(plain_strings, current_leader):
    largest_hash = 0
    leading_plaintext = ''
    for current_string in plain_strings:
        current_hash = numeric_md5(current_string)
        if current_hash > largest_hash:
            largest_hash = current_hash
            leading_plaintext = current_string
    old_leader_hash = numeric_md5(current_leader)
    return leading_plaintext if largest_hash > old_leader_hash else current_leader

def find_largest_md5():
    cycles = number_of_cycles()
    print('Running {} cycles, alphabet: {}'.format(cycles, (STATIC_ALPHABET + ' (static)' if STATIC_ALPHABET != '' else 'random')))

    leading_string = ''
    for i in range(cycles):
        current_alphabet = get_alphabet()
        jumbled_strings = unique_permutations(current_alphabet)
        leading_string = string_with_largest_hash(jumbled_strings, leading_string)
    print('Largest MD5: {} from plaintext {}'.format(hex(numeric_md5(leading_string)), leading_string))

if __name__ == '__main__':
    find_largest_md5()