texts:
I have a sorted (by x value) ArrayList of points and four separate points that make up a quadrilateral. My code deletes all points in the ArrayList that are inside of the quadrilateral. I just wanted to know if I could speed up my code:

private void quadrilateral(){
    double Xmax1 = Math.max(Math.max(NW.getX(), NE.getX()), SW.getX());
    double Xmin1 = Math.min(Math.min(NW.getX(),NE.getX()), SW.getX());

    double Xmax2 = Math.max(Math.max(SW.getX(), NE.getX()), SE.getX());
    double Xmin2 = Math.min(Math.min(SW.getX(), NE.getX()), SE.getX());

    Triangle tri1 = new Triangle(NW, NE, SW);
    Triangle tri2 = new Triangle(SW, NE, SE);
    deletePointsInTriangle(tri1, Xmin1, Xmax1);
    deletePointsInTriangle(tri2, Xmin2, Xmax2);
}

private void deletePointsInTriangle(Triangle tri, double Xmin, double Xmax){
    Point p;
    for (Iterator<Point> it = points.iterator(); it.hasNext();) {
        p = it.next();
            if (p.getX() >= Xmin && p.getX() <= Xmax) {
                if (tri.contains(p)) {
                    it.remove();
                }
            }
    }
}

Triangle class:

public class Triangle {

    private Point[] points;

    public Triangle(Point a, Point b, Point c){
        this.points = new Point[]{a, b, c};
    }

    public Triangle(){}

    public boolean contains(Point p){
        Point p1 = points[0];
        Point p2 = points[1];
        Point p3 = points[2];
        float alpha = (float) (((p2.getY() - p3.getY())*(p.getX() - p3.getX()) + (p3.getX() - p2.getX())*(p.getY() - p3.getY())) /
                        ((p2.getY() - p3.getY())*(p1.getX() - p3.getX()) + (p3.getX() - p2.getX())*(p1.getY() - p3.getY())));
        float beta = (float) (((p3.getY() - p1.getY())*(p.getX() - p3.getX()) + (p1.getX() - p3.getX())*(p.getY() - p3.getY())) /
                        ((p2.getY() - p3.getY())*(p1.getX() - p3.getX()) + (p3.getX() - p2.getX())*(p1.getY() - p3.getY())));
        float gamma = 1.0f - alpha - beta;
        return alpha > 0 && beta > 0 && gamma > 0;
    }
}

NW, NE, SW, SE are the four vertices that make up the quadrilateral.


texts:
I have N child classes of the same base class. The base contains abstract methods to convert the class to a byte array and vice versa.

It also contains a method to compare that instance to two other instances of the same type. Result shall be true if this instance is within the range of the other two instances (each property value is within the range of the corresponding property values).

Collections shall be compared by comparing each value.

Because there are N childs I really don't want to implement the compare method in each child (huge amount of testing and boring code) so I use a property bag in the base class and implement the compare method there.

Child property implementation:

    public int IntValue
    {
        get { return m_IntValue; }
        set
        {
            m_IntValue = value;
            AddOrUpdateProperty(value);
        }
    }
    public string StringValue
    {
        get { return m_StringValue; }
        set
        {
            m_StringValue = value;
            AddOrUpdateProperty((IComparable)value);
        }
    }
    public byte[] ByteArray
    {
        get { return m_ByteArray; }
        set
        {
            m_ByteArray = value;
            AddOrUpdateProperty(value);
        }
    }

Methods to add or update the property bag Dictionary<string, object> m_PropertyBag. Only properties that implement IComparable are allowed.

private Dictionary<string, object> m_PropertyBag = new Dictionary<string, object>();

protected void AddOrUpdateProperty(IComparable value, [CallerMemberName]string name = null)
{
    AddOrUpdateProperty(value, name);
}

protected void AddOrUpdateProperty<T>(IEnumerable<T> value, [CallerMemberName]string name = null)
    where T : IComparable
{
    AddOrUpdateProperty(value, name);
}

private void AddOrUpdateProperty(object value, string name)
{
    if (value == null) { throw new ArgumentNullException("value"); }
    if (name == null) { throw new ArgumentNullException("name"); }
    if (name == string.Empty) { throw new ArgumentException("Name must not be empty.", "name"); }
    if (name.Contains(" ")) { throw new ArgumentException("Name must not contain any white spaces.", "name"); }

    if (m_PropertyBag.ContainsKey(name)) { m_PropertyBag[name] = value; }
    else { m_PropertyBag.Add(name, value); }
}

Here is the compare method for the whole bag.

public bool Compare(Base min, Base max)
{
    if (GetType() != min.GetType() || GetType() != max.GetType())
            throw new InvalidOperationException("Not the same type.");

    var result = true;
    foreach (var property in m_PropertyBag)
    {
        if (property.Value is IEnumerable)
        {
            var values = (IEnumerable)property.Value;
            var minValuesEnum = ((IEnumerable)min.m_PropertyBag[property.Key]).GetEnumerator();
            var maxValuesEnum = ((IEnumerable)max.m_PropertyBag[property.Key]).GetEnumerator();

            foreach (var value in values)
            {
                result &= minValuesEnum.MoveNext();
                result &= maxValuesEnum.MoveNext();
                if (!result) return false;

                result &= Compare(value, minValuesEnum.Current, maxValuesEnum.Current);
                if (!result) return false;
            }
        }
        else
        {
            result &= Compare(property.Value, min.m_PropertyBag[property.Key], max.m_PropertyBag[property.Key]);
            if (!result) return false;
        }
    }
    return result;
}

Here is the compare method for a single IComparable property.

public bool Compare(object value, object min, object max)
{
    var comparableObject = (IComparable)value;
    return comparableObject.CompareTo(min) >= 0 && comparableObject.CompareTo(min) <= 0;
}


texts:
I have written the following code for looping through WebElements in Selenium.

Can someone please provide me with feedback on how to improve my code?

   public static void checkAbsentSearchResult(String title, String Testgoal) throws IOException{
         try{
                List<WebElement> allSearchResults = driver
                              .findElements(By
                                           .xpath("//*[contains(@class, 'teaser-list')]/li/article/div[2]/h3"));
                //Check if xpath contains any WebElements, if not check if no results message is displayed
                if(allSearchResults == null || allSearchResults.size() < 1 ){
                       String element = driver.findElement(By.xpath("//div[@class='view-empty']")).getText();
                       if(element.contains("no results found")){
                              WriteToXSL.WriteTo(Testgoal, "OK", "");
                              WriteToPDF.addRow(Testgoal, "OK", "");
                       }else{
                              WriteToXSL.WriteTo(Testgoal, "NOK", element.toString());
                              WriteToPDF.addRow(Testgoal, "NOK", "");
                       }
                }else{
                       boolean resultsFound = false;
                       for (WebElement Element : allSearchResults) {
                              if (Element.getText().contains(title)) {
                                    WriteToXSL.WriteTo(Testgoal, "NOK", "");
                                    WriteToPDF.addRow(Testgoal, "NOK", "");
                                    resultsFound = true;
                                    break;
                              }// close if
                       }// close for loop
                       if (resultsFound == false) {
                              WriteToXSL.WriteTo(Testgoal, "OK", "");
                              WriteToPDF.addRow(Testgoal, "OK", "");
                       }
                }
         }catch(Exception e){
                WriteToXSL.WriteTo(Testgoal, "NOK", e.toString());
                WriteToPDF.addRow(Testgoal, "NOK", "");
         }
   }


texts: Speech Synthesis to showcase how various voices sound with System.Speech.Synthesis

texts:
I was wondering if you would be willing to give me some suggestions on shortening this code. I feel as if the amount of if statements I have is a bit much.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Speech.AudioFormat;
using System.Speech.Synthesis;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace SpeechTutorial
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        SpeechSynthesizer synth = new SpeechSynthesizer();

        public MainWindow()
        {
            InitializeComponent();
            comboItems();
        }

        private void comboItems()
        {
                foreach (InstalledVoice voice in synth.GetInstalledVoices())
                {
                    // loop through each voice installed on machine
                    VoiceInfo info = voice.VoiceInfo;
                    // adds each installed voice's Name and location to the combobox's list
                    comboBox.Items.Add(info.Description);
                }
            }

        private void button_Click(object sender, RoutedEventArgs e)
        {
            // set the synthesizer to speak
            synth.Speak(textBox.Text);
        }

        private void comboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            // here we are setting the voices for each selected item in the combobox

            try
            {
                if (comboBox.SelectedIndex == 0)
                {
                    synth.SelectVoice("Microsoft Hazel Desktop");
                }

                if (comboBox.SelectedIndex == 1)
                {
                    synth.SelectVoice("Microsoft Heera Desktop");
                }

                if (comboBox.SelectedIndex == 2)
                {
                    synth.SelectVoice("Microsoft David Desktop");
                }

                if (comboBox.SelectedIndex == 3)
                {
                    synth.SelectVoice("Microsoft Zira Desktop");
                }

                if (comboBox.SelectedIndex == 4)
                {
                    synth.SelectVoice("Microsoft Haruka Desktop");
                }

                if (comboBox.SelectedIndex == 5)
                {
                    synth.SelectVoice("Microsoft Heami Desktop");
                }

                if (comboBox.SelectedIndex == 6)
                {
                    synth.SelectVoice("Microsoft Huihui Desktop");
                }

                if (comboBox.SelectedIndex == 7)
                {
                    synth.SelectVoice("Microsoft Tracy Desktop");
                }

                if (comboBox.SelectedIndex == 8)
                {
                    synth.SelectVoice("Microsoft Hanhan Desktop");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }

        }
    }
}


texts:
For the following C linked list implementation, please give me some suggestions for improved efficiency, style and design. This implementation is not 100% complete, please give some suggestions for additional features. Notice the data type for the list is void*, I want it to be as generic as possible.

accList.h:

#ifndef ACCLIST_H
#define ACCLIST_H

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

struct accListNode                 //the nodes of a linked-list for any data type
{
  void *data;                     //generic pointer to any data type
  struct accListNode *next;       //the next node in the list
};

struct accList                    //a linked-list consisting of accListNodes
{
  struct accListNode *head;
  struct accListNode *tail;
  int size;
};

void accList_allocate(struct accList *theList);           //allocate the accList and set to NULL
void appendToEnd(void *data, struct accList *theList);    //append data to the end of the accList
void removeData(void *data, struct accList *theList);         //removes data from accList

#endif

accList.c:

#include "accList.h"
#include "cmpsc311.h"

void accList_allocate(struct accList *theList)    //allocate and initialize to NULL values
{
   theList = Malloc(sizeof(struct accList));
   theList->head = NULL;
   theList->tail = NULL;
   theList->size = 0;
}

void appendToEnd(void *data, struct accList *theList)
{
  struct accListNode *newNode = Malloc(sizeof(struct accListNode));
  newNode->data = data;
  newNode->next = NULL;
  if(theList->head == NULL)    //the list is empty
  {
    theList->head = theList->tail = newNode;
  }
  else                        //the list is not empty
  {
    theList->tail->next = newNode;
    theList->tail = newNode;
  }
}

void removeData(void *data, struct accList *theList)
{
  if(theList->head == NULL)                                 //the list is empty
    return;
  else if(theList->head == theList->tail)                   //there is one element in the list
  {
    free(theList->head);
    theList->head = NULL;
  }
  else if(data == theList->head->data)                     //the element to be removed is the head
  {
    struct accListNode *temp = theList->head->next;
    free(theList->head);
    theList->head = temp;
  }
  else if(data == theList->tail->data)                     //the element to be removed is the tail
  {
    struct accListNode *cur;
    struct accListNode *prev = NULL;
    for(cur = theList->head; cur->next != NULL; prev = cur, cur = cur->next);
    free(theList->tail);
    prev->next = NULL;
    theList->tail = prev;
  }
  else                                                     //any other node
  {
    struct accListNode *prev = NULL;
    struct accListNode *cur;
    for(cur = theList->head; cur != NULL; prev = cur, cur = cur->next)
    {
      if(cur->data == data)   //this is the node we must free
      {
        prev->next = cur->next;
        free(cur);
      }
    }
  }
}

I think the remove function needs the most work. I did post that function on this site, however I think I needed to include the whole implementation to get the best feedback. Will this work on an embedded system?


texts: Vectorized type conversion for autocorrelation

texts:
I have a simple task as part of a larger autocorrelation DSP system - to convert from signed 16-bit integer audio samples to floating-point. This part is quite self-contained:
#include <cblas.h>

typedef int16_t sample_t;

void consume(const sample_t *samples, int N, int rate)
{
    float *input = calloc(N, sizeof(float)),
         *output = calloc(N, sizeof(float));
    assert(input);
    assert(output);

    for (int i = 0; i < N; i++)
        input[i] = (float)samples[i];

    // BLAS processing of 'input'

    for (int i = 0; i < N; i++)
    {
        output[i] = cblas_sdot(  // Standard CBLAS call
            N-i,     // N
            input,   // X
            1,       // incX
            input+i, // Y
            1        // incY
        );
    }
}

Due to external constraints - the hardware only supports S16_LE samples - ALSA cannot do this conversion for me, nor can cblas accept integer types; so I'm stuck doing this myself. I've not found anything in gsl or cblas that runs vectorized type conversion.
I'm also not in love with having to loop over a level-1 dot product, but I've not been able to find a good way in BLAS to represent a single level-2 (matrix-vector) multiplication where the matrix is just a heavily-aliased single vector.
Is there a better way to do this?


texts: Choice of tables for a project to handle attendance

texts:
I'm working on my students attendance system project. I have a list of students along with their ID (jntuno) and I need to create a database in MySQL for storing the daily attendance of each student for each subject.
Table: students
Fields:
slno int(5) auto increment,
jntuno char(15),
name char(50),
primary key(slno,jntuno).

Data:

This students table holds the list of students and their IDs.
Now I created another table:
Table: dailyatt
Fields:
date date,
subject char(10),
classesconducted int(2),
`11341A0501` int(2),
`11341A0502` int(2),
`11341A0503` int(2),
.
.
.
`11341A0537` int(2),
primary key(date,subject).

This table will look like:

+------------+-----------+-----------------+------------+-----------+-----------+
|date        |subject    |classesconducted |11341A0501  |11341A0502 |11341A0503 |....
+------------+-----------+-----------------+------=-----+-----------+-----------+
|            |           |                 |            |           |           |

Now every day upon entering the attendance on the PHP website, a new row will be created for each subject taught on that day.
But many said that the database model is not a good one. Can someone suggest a better model for this kind of problem?


texts: Concurrency and locking in a chat server

texts:
I've never done concurrent programming before, but I've written one using go channels and RWMutex, but I'm not sure if my approach is idiomatic. I feel like it could all use channels (Maybe).

The protocol is simple: Messages are delimited by '\n'. The first message client sends is it's name. The rest are normal messages. I used a map because it's add + delete is faster, and because I'm not concerned about the ordering.
I'm mostly concerned with the locks at the last 4 methods. Could I use channels here instead? Am I using locks correctly?

type message struct {
    message string
    client  *client
}

type client struct {
    conn   net.Conn
    reader *bufio.Reader
    name   string
}

type Server struct {
    l           net.Listener
    clients     map[*client]struct{}
    messageChan chan message
    port        uint16
    name        string
    m           sync.RWMutex
}

// NewServer starts listening, and returns an initialized server. If an error occured while listening started, (nil, error) is returned.
func NewServer(name string, port uint16) (*Server, error) {
    p := strconv.FormatUint(uint64(port), 10)
    l, e := net.Listen("tcp", "localhost:"+p)
    if e != nil {
        return nil, e
    }
    return &Server{l, make(map[*client]struct{}), make(chan message), port, name, sync.RWMutex{}}, nil
}

// Start starts accepting clients + managing messages.
func (r *Server) Start() {
    go r.sendMessages()
    for {
        conn, e := r.l.Accept()
        if e != nil {
            continue
        }
        go r.handleConn(conn)
    }
}

func (r *Server) handleConn(conn net.Conn) {
    reader := bufio.NewReader(conn)
    name, e := reader.ReadString('\n')
    name = strings.TrimSpace(name)
    if e != nil {
        conn.Close()
        return
    }

    c := &client{conn, reader, name}
    r.addClient(c)
    r.publishMessage(c.name + " has joined the server\n")
    r.handleClient(c)
}

func (r *Server) handleClient(c *client) {
    for {
        msg, e := c.reader.ReadString('\n')
        if e == io.EOF {
            c.conn.Close()
            r.deleteClient(c)
            r.publishMessage(c.name + " has left the server\n")
            return
        } else if e != nil {
            continue
        }
        r.messageChan <- message{c.name + ": " + msg, c}
    }
}

func (r *Server) sendMessages() {
    for {
        m := <-r.messageChan
        r.m.RLock()
        for k := range r.clients {
            if k != m.client {
                go k.conn.Write([]byte(m.message))
            }
        }
        r.m.RUnlock()
        fmt.Print(m.message)
    }
}

func (r *Server) publishMessage(msg string) {
    r.m.RLock()
    for k := range r.clients {
        go k.conn.Write([]byte(msg))
    }
    r.m.RUnlock()
    fmt.Print(msg)
}

func (r *Server) addClient(c *client) {
    r.m.Lock()
    r.clients[c] = struct{}{}
    r.m.Unlock()
}

func (r *Server) deleteClient(c *client) {
    r.m.Lock()
    delete(r.clients, c)
    r.m.Unlock()
}

I would appreciate if anyone could give some suggestions/feedback.


texts: Mastermind game - Evaluating the guess in Ruby

texts:
I am a novice coder and I am very new to algorithms. Something about my code leads me to believe that it is unnecessarily verbose and/or inefficient. I am building a command line Mastermind game, and part of the project is to provide feedback for a user's guess. In the game, the codemaker creates a secret code with four "pegs" of any of the six predefined colors.

The codebreaker has 12 chances to guess the correct code while gradually improving their guess with the help of feedback from the codemaker each time. The feedback consists of four "key pegs", which must be either black or white.

The codemaker puts down a black peg to indicate that the player chose the correct position and the correct color. A white key peg indicates that the user selected a color that exists in the secret code but is in the wrong position.

However, only one white peg is put down for each correct color guess, even if there is many of that color in the secret code.

For example, if:

secret_code = ["Red", "Blue", "Green", "Red"]
guess = ["Blue", "Green", "Red", "Red"],
#=> feedback is ["White, "White", "Black", "White"] in any order

Here is another example:

secret_code = ["Red", "Blue", "Red", "Red"]
guess = ["Blue", "Red", "Green", "Green"]

p computer.provide_feedback(secret_code, guess)
#=> ["White", "White", " ", " "]

The first step of my code is to turn the two arrays into hashes with the colors as values and an array of their indices as the values. This way I can compare the frequency and position of each color in each array.

The next step is to iterate through the guess hash, and for each iteration create an intersection array that contains the elements that exist in both. The number of intersected elements determines the number of black pegs to be placed into the feedback array.

To find the number of white pegs,  the program checks if the array for the color indices in the guess array is less in size than the secret_code indices to avoid counting more of that color than is in the secret_code. Then the program finds the number of elements left over that aren't intersected, and that determines the number of white pegs.

Here is the code for this specific portion of my game:

def provide_feedback(secret_code, guess)
  secret_indices = hash_of_indices(secret_code)
  guess_indices = hash_of_indices(guess)
  feedback = format_feedback(calculate_feedback(secret_indices, guess_indices))
  feedback
end

def hash_of_indices(array)
  array.each_with_index.inject(Hash.new {Array.new}) do |hash, (elem, i)|
    hash[elem] += [i]
    hash
  end
end

def calculate_feedback(secret_hash, guess_hash)
  feedback = []
  black = "Black"
  white = "White"
  guess_hash.each do |k, v|
    intersection = (v & secret_hash[k])
    intersection.length.times { feedback << black }
    if v.length <= secret_hash[k].length
      (v.length - intersection.length).times { feedback << white }
    end
  end
  feedback
end

def format_feedback(feedback)
  formatted = feedback
  formatted << " " until formatted.length == 4
  formatted
end


texts: HackerRank Ransom Note, solved using Data.Map as a hash table

texts:
I try to solve this hackerrank using Haskell but not sure if I use Data.Map corretly.

Problem in brief:

given 2 strings, magazine and note
check if you can make note from words in magazine

Here is my code, which passes all the tests.

import Control.Applicative
import qualified Data.Map as M

readInts =  map read . words <$> getLine :: IO [Int]

main = do
  [a,b] <- readInts
  ms <- words <$> getLine
  ls <- words <$> getLine

  -- create magazine words table
  let mss = zip ms (repeat 1)
  let mms = M.fromListWith (+) mss

  -- create note words table
  let lss = zip ls (repeat 1)
  let lms = M.fromListWith (+) lss

  -- check for intersections, decrease wordcount for every intersection
  let dm = M.intersectionWith (-) mms lms

  -- see if any words need more than it avaliablity
  let a = M.filter (<0) dm

  -- print answer
  putStrLn $ if a == M.empty then "Yes" else "No"

If I would do this problem in python I would use a dictionary of int with string key

for example;

magazine["word"] = 3
note["word"] = 1

would give a Yes answer since there is enougth word to use


texts: How can I make this StringToCollections method more generic?

texts:
I am new to C# and I have big functions that receives the following arguments:

(Package inPackage, string materialIDs, string functionIDs, string companyIDs)

Asides from the first argument, which is an object of type Package, all the other arguments are strings of IDs.

So, for example, a valid input for this function would be: myPackage, "1,2,3", ",2,3,4", ",45,2".

A package is an object that contains a list of materials, a list of functions and a list of companies.

The objective of this function, is to look up in the DB all the objects that contain those IDs, and add them to myPackage.

To achieve this objective, this is what I have created:

private Package StringToCollections(Package inPackage, string materialIDs, string functionIDs, string companyIDs)
        {
            //Check Materials Data - Case WITHOUT FORMAT PROTECTION
            var materialList = new List<Material>();
            var materialStringArray = materialIDs.Split(',');
            var materialIdsArray = materialStringArray.Where(x => x != "").Select(int.Parse);
            materialList.AddRange(DB.Materials.Where(x => materialIdsArray.Contains(x.MaterialId)));
            inPackage.GATE_Material = materialList;

            //Check Employee_Functions Data - HAS FORMAT PROTECTION ... KINDOFF?
            List<Function> functionsList = new List<Function>();
            string[] functionStringArray = functionIDs.Split(',');
            List<int> functionIdsArray = new List<int>();
            for (int i = 0; i < functionStringArray.Length; i++)
            {
                try
                {
                    functionIdsArray.Add(int.Parse(functionStringArray[i]));
                }
                catch (FormatException)
                {
                    //not a number, ignore - IS THIS A GOOD IDEA!?
                }
            }
            functionsList.AddRange(DB.Function.Where(x => functionIdsArray.Contains(x.FunctionId)));
            inPackage.Function = functionsList;

            //Check Company Data - ANOTHER WAY OF FORMAT PROTECTION ... KINDOFF?
            if (!companyIDs.IsNullOrWhiteSpace())
            {
                var companiesList = new List<Company>();
                var companyStringArray = companyIDs.Split(',');
                var companyIdsArray = companyStringArray.Where(x => x != "").Select(int.Parse);
                try
                {
                    companiesList.AddRange(DB.Companies.Where(x => companyIdsArray.Contains(x.ID)));
                    inPackage.Companies = companiesList;
                }
                catch (FormatException)
                {
                    //do nothing. If the string has an incorrect format, we add nothing and continue.
                }
            }

            return inPackage;
        }

I honestly believe this code is a mess and was hoping that it could be fixed by using C# generics like <T>, but I am not sure if this is possible due to the differences in getting each fields ID and Name.

Is it possible to optimize this function and make it more generic with protection from format exception? if so, how?


texts:
Please review the code:

    package com.gmail.practice;

import java.util.Arrays;

public class Queues {

    int head;
    int tail;
    int size;
    int[] queue;

    public Queues(int arraysize)
    {
        if(arraysize<0)
        {
            throw new IllegalArgumentException("size cannote be less than equals zero");
        }
        head = -1;
        tail = -1;
        size = arraysize;
        queue = new int[size];
    }

    public boolean isEmpty()
    {
        return(tail == -1 && head == -1);
    }

    public void enqueue(int value)
    {
        if((tail+1)%size == head)
        {
            System.out.println("the queue is full");
        }else if(isEmpty())
        {
            head++;
            tail++;
            queue[tail] = value;
        }else{
            tail = (tail+1)%size;
            queue[tail] = value;
        }
    }

    public int dequeue()
    {
        int value = 0;
        if(isEmpty())
        {
            System.out.println("the queue is empty cant dequeue");
        }else if(tail == head){
            value = queue[head];
            head = -1;
            tail = -1;
        }else{
            value = queue[head];
            head = (head+1)%size;
        }

        return value;
    }

    public void display()
    {
        System.out.println(Arrays.toString(queue) + " " + "tail is " + " "+ tail +" the head is" + " " + head);
    }

    public static void main(String[] args)
    {
        Queues q = new Queues(5);
        q.enqueue(3);
        q.enqueue(4);
        q.enqueue(2);
        q.enqueue(1);
        q.enqueue(5);
        q.display();
        q.dequeue();
        q.dequeue();
        q.display();
        q.enqueue(1);
        q.enqueue(5);
        q.dequeue();
        q.dequeue();

    }
}


texts: How to reduce number of hierarchical 'if statements'

texts:
<% @descriptions.each_with_index do |description, i| %>
  <% description.tale2.each do |tax_ref| %>
    <% if condition %>
      <% if condition %>
        <% if condition %>
          <%= $text_first_describe%> <%= $paren_author_yr %>
             <% ref_sp_uniq.each_with_index do |ref, i| %>
               <% if ref == tax_ref.ref_wo_brace%>
                  <% execution %>
               <% elsif i == (ref_sp_uniq.size - 1)%>
                  <%# @ref_desc = "#{@ref_desc_numb}. #{tax_ref.ref_wo_brace}" %>
               <% end %>
             <% end %>
          <% if condition %>
                  <% execution %>
          <% elsif condition %>
            <% execution %>
          <% elsif taxon_name.emend_author_year %>
             <%= print %>
          <% else %>
             <%= print %>
          <% end %>
        <% end %>
      <% else %>
        <% if condition %>
          <%= print %>
          <% ref_sp_uniq.each_with_index do |ref, i| %>
             <% if condition %>
                <% execution %>
             <% elsif condition %>
                  <% execution %>
             <% end %>
          <% end %>
          <% if condition %>
            <% execution %>
          <% elsif condition %>
            <% execution %>
          <% elsif condition %>
            <% execution %>
          <% else %>
            <% execution %>
          <% end %>
        <% end %>
      <% end %>
    <% end %>
  <% end %>
<% end %>


texts:
I'm fairly new to front end web development, but finally felt confident enough to create my own jQuery slider. I wish to receive constructive criticism about my code, how I can optimize any line of code, or ideas on how I can make this a bit more interesting.

$(document).ready(function(){
    /*
    =====================================
        THE SLIDER SCRIPT STARTS HERE
    =====================================
    */
    var i = 0;
    var images = ["Slide/bandera_OK%202.png","Slide/CARAVANA_carta.png","Slide/KANGOO.png","Slide/mochila.png","Slide/RADICAL_OH_03_alta.png","Slide/SILVER_final.png"];

    setInterval(function(){
        var topDiv = $('[data-slide='+'top'+']');
        var topImg = $('[data-slide='+'top'+'] > img');
        var bottomDiv = $('[data-slide='+'bottom'+']');
        var bottomImg = $('[data-slide='+'bottom'+'] > img');

        i++;

        if(i == images.length){
            i = 0;
             bottomDiv.animate({left:'100%'},1500);
            topImg.attr('src',images[i]);
            setTimeout(function(){
                bottomDiv.css('z-index','0');
                topDiv.css('z-index','1');
            },2000);

            setTimeout(function(){
                bottomDiv.css('left','0px');
                bottomImg.attr('src',images[i+1]);
            },2500);

        }
        else if(i % 2 != 0){
            topDiv.animate({left:'100%'},1500);
            bottomImg.attr('src',images[i]);
            setTimeout(function(){
                topDiv.css('z-index','0');
                bottomDiv.css('z-index','1');
            },2000);

            setTimeout(function(){
                topDiv.css('left','0px');
                topImg.attr('src',images[i+1]);
            },2500);
        }
        else if(i % 2 == 0){
            bottomDiv.animate({left:'100%'},1500);
            topImg.attr('src',images[i]);
            setTimeout(function(){
                bottomDiv.css('z-index','0');
                topDiv.css('z-index','1');
            },2000);

            setTimeout(function(){
                bottomDiv.css('left','0px');
                bottomImg.attr('src',images[i+1]);
            },2500)

        }

    },3000);

});
.slider {
position: relative;
}

.slider div {
position: absolute;
width: 100%;
height: 100%;
top: 0px;
left: 0px;
}

.slider div img {
width: 100%;
}

[data-slide='top'] {
z-index: 1;
}

.wrapper {
width: 100%;
height: 100%;
position: relative;
}


texts: Elegant approach to building unordered list from XML

texts:
How can I improve on this rather ugly method that builds an HTML unordered list from an XML file?

I maintain a collection of ASP.NET webforms that all need to pull in the same site navigation as our main website. The forms have a master page that mimics the main site template, and we want any changes to the main navigation to flow through to the forms automatically.

The main site uses an XML document to generate the navigation, and the document uses inconsistent formatting for the links (some have "http://mysite.com" hardcoded, and some are relative to the main site "/subsite").

Here's what I have right now:

private void LoadNavigation()
{
    string urlPrefix = "http://mysite.com";
    string xmlFilePath = ConfigurationManager.AppSettings["NavigationUrl"].ToString();
    XmlDocument doc = new XmlDocument();
    doc.Load(xmlFilePath);
    XmlNodeList navigationItems = doc.DocumentElement.FirstChild.ChildNodes;

    foreach (XmlNode item in navigationItems)
    {
        if (item.Attributes.GetNamedItem("url").Value.Contains("http://")) // link is hard coded
        {
            navList.InnerHtml += "
 " + item.Attributes.GetNamedItem("title").Value + "|
";
        }

        else
        {
            navList.InnerHtml += "
 " + item.Attributes.GetNamedItem("title").Value; //relative link

            if (item.NextSibling == null)
            {
                navList.InnerHtml += "
"; //last item in list
            }
            else
            {
                navList.InnerHtml += "|
"; //not the last item in list
            }
        }
    }
}

Believe it or not, this is an improvement over the original, which included a hardcoded URL for the XML file and got the values out of the XML document like this:

XmlNodeList nodeList = doc.ChildNodes[1].ChildNodes[0].ChildNodes;

But it still needs a lot of work. Please have at it.


texts: CoffeeScript implementation of A* algorithm

texts:
a_star =                        # returns the goal node (or null if path not found). To reconstruct path follow the node.__src till null
  (
    start,                       # starting node
    neighbors,                   # a function that takes in a node and returns list of neighbours
    h,                           # admissable A* heuristic distance from goal i.e. heurisitic(x) <= distance(x,y) + heuristic(y) for all x,y
    dist = (a,b) -> 1,           # takes two nodes and returns distance between them (optional - default is 1)
    isGoal = (x) -> h(x) is 0    # returns true iff node is goal (optional - assumes heurisitc(goal) = 0)
  ) ->

    closed = {}                # set of nodes already evaluated
    q = {}                     # set of tentative nodes to be evaluated, the value is the 'f_score' (F = G + H)
    g = []                     # 'g-score' - the exact cost to reach this node from start

    add = (node, parent) ->
      node.__src = parent
      g[node] = if parent? then g[parent] + dist parent, node else 0
      q[node] = g[node] + h(node)

    remove_best = ->
      best = null
      best = node for node,f of q when best is null or f < q[best]
      if best? then closed[best] = true; delete q[best]
      return best

     add start, null

     while true
      c = remove_best()
      if c is null or isGoal c then return c
      add n, c for n in neighbours c when not closed[n] and (q[n] is null or g[c] + dist(c, n) <= g[n])


texts:
I have very large data files (10 to 40 GB) which I want to plot as figures. A data file contains t matrices of size n x n. A data file of t=3 matrices of size n looks like:

1 2
3 6
1 2
3 3
4 2
5 1

Here is the code that does the job:

import itertools as it
import matplotlib.pyplot as plt
import time

def printImage(M, k):
    figobj = plt.figure()
    fig = plt.imshow(M, interpolation='nearest')
    fig.set_cmap('hot')
    fig.axes.get_xaxis().set_visible(False)
    fig.axes.get_yaxis().set_visible(False)
    plt.axis('off')
    plt.tight_layout()
    plt.savefig('%05d' % k + '.png', bbox_inches='tight', pad_inches=0, dpi=300)
    plt.close(figobj)

n = 1000
t = 1000

t0 = time.clock()
with open('data', 'r') as f:
    for i in range(t):
        try:
            items = [list(map(float, i.split())) for i in it.islice(f, n)]
        except:
            raise
        else:
            printImage(items,i)
        print(str(i) + '/' + str(t))

t1 = time.clock()
print(t1-t0)

The processing speed for 1000 matrices of size 1000 x 1000 of this code is shown below:

The time is increasing and it takes about one second per image. I would like to know if I can increase the processing speed if I don't want to decrease quality?


texts: Prevent a UITextField from being input with aphabetic characters

texts:
The goal is to disallow typing alphabetic characters as input in a UITextField.

Please tell me if this approach is convenient.

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        let charSet = CharacterSet.letters
        let existingTextHasDecimalSeparator = textField.text?.range(of: ".")
        let replacementTextHasDecimalSeparator = string.range(of: ".")
        let existingTextHasAlphabeticCharacters = textField.text?.rangeOfCharacter(from: charSet)
        let replacementTextHasAlphabeticCharacters = string.rangeOfCharacter(from: charSet)

        if existingTextHasDecimalSeparator != nil,
            replacementTextHasDecimalSeparator != nil {
            return false
        } else if existingTextHasAlphabeticCharacters != nil ||
                    replacementTextHasAlphabeticCharacters != nil {
                return false
        } else {
            return true
        }
    }


texts: Find whether two (or 'n') particular values are present in a binary tree

texts:
I have a solution to find if two values are present in a binary tree (not a BST).

I would like to know if there is

a more efficient way to do this?
a more elegant way to this?
specific improvement for the parts I've marked with comments?
a better way to generalize the solution if we have to check if some 'n'
values (all of them) are present in tree or not?

I have a working solution mentioned in the code below but I think the same could be achieved using a more elegant and efficient code.

Note : Please assume that CheckIfValuesPresentInTree() is an API that I need to implement, so I can't change the underlying data structure.

/*The structure of a Node is as follows:
struct Node {
    int data;
    Node * right, * left;
};*/

void IsPresent(Node* p, int n1, int n2, bool& f1, bool& f2);

bool CheckIfValuesPresentInTree(Node* root, int n1, int n2) {
    auto f1 = bool{false};
    auto f2 = bool{false};

    IsPresent(root, n1, n2, f1, f2);

    return f1&&f2;
}

void IsPresent(Node* p, int n1, int n2, bool& f1, bool& f2) {
// Too many arguments passed to the function.
    if (!p) {
        return;
    }

    if (p->data == n1) {
        f1 = true;
    }

    if (p->data == n2) {
        f2 = true;
    }

    IsPresent(p->left, n1, n2, f1, f2);
    IsPresent(p->right, n1, n2, f1, f2);
// Second recursive call might not be needed if both n1 and n2 are found
// in 1st call.
// We can write something like below : but is there a better way ?
/*
    IsPresent(p->left, n1, n2, f1, f2);
    if (f1 && f2) {
        return;
    }
    IsPresent(p->right, n1, n2, f1, f2);
*/
}


texts: Median of two sorted equal sized arrays on combination

texts:
The comprehensive description of the problem can be found here.  I'm looking for code review, clever optimizations, adherence to best practices. etc.

This code is also a correction of code previously posted here.

/**
 * @author javadeveloper
 */
public final class MedianOfTwoSortedArrays {

    private MedianOfTwoSortedArrays() {}

    private static boolean isMedian (int[] a1, int[] a2, int pos) {
        if (pos == 0 || pos == (a1.length - 1)) return true;
        return (a1[pos] >= a2[pos]) && (a1[pos] <= a2[pos + 1]);
    }

    private static double calculateMedian(int[] a1, int a1median, int[] a2, int a2median) {
        if (a1median == 0 || a2median == 0 || a1[a2median] < a1[a1median + 1]) return (a1[a1median] + a2[a2median])/2.0;
        return ((a1[a1median] + a1[a1median + 1])/2.0);
    }

    /**
     * Given two sorted arrays of same length it returns the median.
     * If arrays are not of equal length throws the IllegalArgumentException.
     * If arrays are not sorted the results can be unpredictable.
     *
     * @param a1    the first sorted array
     * @param a2    the second sorted array
     * @return      the median of the two integers or null if no such median is found due to illegal input.
     */
    public static Double median (int[] a1, int[] a2) {
        if (a1.length != a2.length) throw new IllegalArgumentException("The argument thrown is illegal");

        int lb = 0;
        int hb = a1.length - 1;

        while (lb <= hb) {
            int a1Median = (lb + hb)/2;
            int a2Median = (a2.length - 1) - a1Median;

            // is one of the element constituting the median in first array ?
            if (isMedian(a1, a2, a1Median)) {
                return calculateMedian(a1, a1Median, a2, a2Median);
            }

            // is one of the element constituting the median in second array ?
            if (isMedian(a2, a1, a2Median)) {
                return calculateMedian(a2, a2Median, a1, a1Median);
            }

            if (a1[a1Median] < a2[a2Median]) {
                lb = a1Median + 1;
            }

            if (a1[a1Median] > a2[a2Median]) {
                hb = a1Median - 1;
            }
        }
        return null;
    }

    public static void main(String[] args) {
        int[] a1 = {1, 3, 5, 7, 9};
        int[] a2 = {2, 4, 6, 8, 10};
        System.out.println("Expected 5.5, Actual " + median (a1, a2));

        int[] a3 = {1, 3, 5, 7, 9, 100};
        int[] a4 = {2, 4, 6, 8, 10, 200};
        System.out.println("Expected 6.5, Actual " + median (a3, a4));

        int[] a5 = {1, 2, 3, 4};
        int[] a6 = {5, 6, 7, 8};
        System.out.println("Expected 4.5, Actual " + median (a5, a6));

        int[] a7 = {5, 6, 7, 8};
        int[] a8 = {1, 2, 3, 4};
        System.out.println("Expected 4.5, Actual " + median (a7, a8));

        int[] a9 =  {1, 1, 10, 10};
        int[] a10 = {5, 5,  5,  5};
        System.out.println("Expected 5.0, Actual " + median (a9, a10));

        int[] a11 = {5, 5, 5, 5};
        int[] a12 = {1, 1, 10, 10};
        System.out.println("Expected 5.0, Actual " + median (a11, a12));
    }
}


texts: Function to skip assignments and apply multiple functions

texts:
This is the function:
/**
 * Apply 1..n one parameter functions to the given variable.
 *
 * @param array/mixed $callback: An array of Callback functions which accept one parameter.
 * @param $var: The variable to apply them to.
 */
function §($callback,&$var) {
    if(is_array($callback)) {
        foreach($callback as $c) {
            $var = $c($var);
        }
    } else {
        $var = $callback($var);
    }
}

$a = "4";

§('intval',$a);

var_dump($a);

§(['intval','exp','ceil'],$a);

var_dump($a);

Result:

int(4)
float(55)

What do you think? This functions saves typing a lot of assignments, but could it confuse users?


texts: Immuitable recursive linear search of an array of string

texts:
I am new to F#. Is the following code, which represents about three hours of work, a canonical way to achieve its goals. If not, how can it be improved?

For instance, can we provide a default value of zero for the index parameter? Also, how do we handle a search for a term that does not exist? Could we use something similar to tail::head instead of matching against array.[index]? It looks more verbose that it needs to be.

open System

let rec linearSearch (array: string[]) (target: string) (index: int) =
    match array.Length with
    | l when index >= l -> -1
    | _ ->
        match array.[index] with
        | x when x = target -> index
        | y -> linearSearch array target (index + 1)

[<EntryPoint>]
let main argv =
    let names = [|
        "erdnase"
        "vernon"
        "le paul"
        "scarne"
        "ireland"
    |]
    linearSearch names "le paul" 0 |> printfn "The target is at index: %A"
    linearSearch names "luttin" 0 |> printfn "The target is at index: %A"
    0

The goals for writing the code were:

Use an array instead of a list, because I would like to understand F# arrays.
Implement a linear search, because it is a simple algorithm.
Write in canonical F#, because canonical code is more maintainable.


texts:
The program here is simply supposed to tell you the shipping charge based off of the weight of the package. I am just wondering if there is any further way to concise it? At the moment, I do not think it can go any further than that. The only place where I'm unsure whether I could improve it, could be Booleans. Possibly use a while statement?

def main():

    weight = eval(input("Please enter the weight of the package: "))

    rate = 0

    if weight <= 2:
        rate += 1.25
    elif weight > 2 and weight <= 5:
        rate += 2.35
    elif weight > 5 and weight <= 10:
        rate += 4.05
    elif weight > 10:
        rate += 5.55

    charge = rate * weight

    print("The shipping charge is: $%s" % charge)

print(main())


texts: Adding  items dynamically to a to-do list

texts:
For a homework assignment, I have to create a "TO-DO" list, which will add a list item to the unordered list dynamically using JavaScript. The input element is also added using JavaScript, having to generate a unique id that changes with each site visit. I'm looking for any suggestions that will improve the efficiency of the code.

/*
 - get user input
 - create
 element
 - append that to
 list
*/

function Form_Processes() {

 this.count = 0;
 this.input_id = generate_id();

 this.addToList = function() {
  var itemToAdd = document.getElementById(this.input_id).value;
  if(!(itemToAdd === "")) {
   this.count += 1;
   var list_tag = document.getElementById('list');
   var li_tag = document.createElement('li');
   li_tag.id = "li_" + this.count;
   var li_text = document.createTextNode("- " + itemToAdd);
   li_tag.appendChild(li_text);
   list_tag.appendChild(li_tag);

   //clear textbox for next input
   document.getElementById(this.input_id).value = "";
  }
 }

 this.removeFromList = function() {
  var numsOfElements = document.getElementById('list').childElementCount;
  if(numsOfElements > 0) {
   var itemToRemove = document.getElementById('li_' + this.count);
   itemToRemove.outerHTML = "";
   this.count -= 1;
  } else {
   console.log('ERROR: Not Enough Child Elements to remove (script.js:25)');
  }
 }

 function generate_id() {
    var text = "";
    var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_";

    for (var i = 0; i < 8; i++){
      text += possible.charAt(Math.floor(Math.random() * possible.length));
    }
    return text;
 }

}

var f = new Form_Processes();

function execute(x) {
 if(x == 1) {
  f.addToList()
 } else if(x == 2) {
  f.removeFromList();
 }
}

function load_form() {
 var x = document.getElementById('in');

 //create input tag
 var input_tag = document.createElement('input');
 input_tag.type = "text";
 input_tag.name = "user_input";
 input_tag.id = f.input_id;
 input_tag.placeholder = "Enter here...";

 x.appendChild(input_tag);

 //insert line break
 var break_tag = document.createElement('br');
 x.appendChild(break_tag);

 var button1 = createButton("button", "add_list", 1, "Add To List");
 var button2 = createButton("button", "remove_list", 2, "Remove From List");

 x.appendChild(button1);
 x.appendChild(button2);

}

function createButton(type, name, e, text) {
 //create buttons
 var button_tag = document.createElement('button');
 button_tag.type = type;
 button_tag.name = name;
 button_tag.onclick = function() { execute(e); }

 var button_text = document.createTextNode(text);
 button_tag.appendChild(button_text);

 return button_tag;
}
* {
 font-family: "Times New Roman", Times, serif;
}

body {
 background-color: pink;
}

fieldset {
 border: none;
}

input[type=text] {
 padding: 12px 20px;
 border-radius: 5px;
 border: 1px solid grey;
 font-size: 25px;
 margin: 2px;
}

button {
 background-color: green;
 border: none;
 border-radius: 6px; /* rounded corner look */
 color: white; /* button text color */
 text-align: center;
 font-size: 16px;
 margin: 1px;
}

ul {
 list-style-type: none;
   margin: 0;
   padding: 0;
}

li {
 background-color: grey;
 margin: 3px;
 font-size: 50px;
 border-radius: 5px;
 color: white;
 padding-left: 15px;
}
<!DOCTYPE html>

  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>TO-DO</title>

  <link rel="stylesheet" type="text/css" href="style.css">

   <form action="">
    <fieldset id="in">

    </fieldset>
   </form>

TO-DO


texts:
I have some parameterized queries in Access 2010.
They are often used in VBA functions having the same parameters.
In such cases, I give the query and function the same name.
The following is such a function (from my actual project):

Public Function get_assignments(e_id As Long, yr As Integer, wk As Integer) As DAO.Recordset
    Dim db As DAO.Database
    Set db = CurrentDb
    Dim qd As DAO.QueryDef
    Set qd = db.QueryDefs!get_assignments
    qd.Parameters![e_id] = e_id
    qd.Parameters![year] = yr
    qd.Parameters![week] = wk
    Set get_assignments = qd.OpenRecordset
    qd.Close
End Function

Both the query and function are named get_assignments and things work fine.

Am I asking for trouble? While I don't usually add "type" suffixes to names, I could rename the query as get_assignments_qry or even rename the function as get_assignments_fn. What's best?

Feel free to give feedback on any aspects of this code.


texts: Generic comparitive array selection sort

texts:
My code works, but my IDE is giving me warnings for unchecked method invocation.  I have found useful information about Comparable arrays here.  I have found useful information about unchecked method invocation here.  Despite this, I just can't figure out how to please my IDE.  My intention is to have the method selectionSort sort an array of either Integers or Doubles using compareTo.

import java.util.Arrays;

class Main{
    public static void main(String[] args){

        Comparable[] data0 = {2, 8, -39, 904, 8, 0};
        Comparable[] data1 = {1.1, -5.68, 4.39, -0.01, 5.59};

        System.out.printf("Unsorted array: %s%n%n", Arrays.toString(data0));
        selectionSort(data0);
        System.out.printf("%nSorted array: %s%n", Arrays.toString(data0));

        System.out.printf("Unsorted array: %s%n%n", Arrays.toString(data1));
        selectionSort(data1);
        System.out.printf("%nSorted array: %s%n", Arrays.toString(data1));
    }

    private static <T extends Comparable<T>> void selectionSort(T[] data){
        for(int i = 0; i < data.length - 1; ++i){
            int smallest = i;

            for(int index = i + 1; index < data.length; ++index){
                if (data[smallest].compareTo(data[index]) > 0){
                    smallest = index;
                }
            }

            swap(data, i, smallest);
            printPass(data, i + 1, smallest);
        }
    }

    private static <T> void swap(T[] data, int first, int second){
        T temporary = data[first];
        data[first] = data[second];
        data[second] = temporary;
    }

    private static <T> void printPass(T[] data, int pass, int index){
        System.out.printf("after pass %2d: ", pass);

        for(int i = 0; i < index; ++i){
            System.out.printf("%s ", data[i]);
        }

        System.out.printf("%s* ", data[index]);

        for(int i = index + 1; i < data.length; ++i){
            System.out.printf("%s ", data[i]);
        }

        System.out.printf("%n               ");

        for (int j = 0; j < pass; j++){
            System.out.printf("-- ");
        }
        System.out.println();
    }
}


texts: Shell script to copy video files to another folder

texts:
I recently started running but hate running both in the quiet and with music, so i've been listening to podcasts.  Unfortunately, I've caught up with all my favorites and so I've started listening to some iTunesU courses, but unfortunately (again) very few of them have audio-only versions.

I wrote a shell script to copy any recently added iTunesU video files to another folder as m4a files (via ffmpeg) but since it's the first such script that i've ever written I am slightly worried to set it to run every morning ...

Anyway, I would appreciate some feedback from you expert types of what potential problems there might be with how I have it working now or suggestions of how I might improve part of it.  Also, as you'll see, I tried to set up a function to do the extension check but couldn't get it to work that way, is there a way to do that?

#!/bin/bash

oldIFS="$IFS" # allow for files/directories with spaces in the names
IFS=$'\n'

is_video_file ()
{
    ext=$1

    if ([ $ext = "m4v" ] || [ $ext = "mp4" ]);
        then
            return 1
        else
            return 0
    fi
} # couldn't get this to work right...

iTunesU_Source=~/Music/iTunes_U/
iTunesU_Destination=~/Music/iTunesU_audio/

cd $iTunesU_Source

for sub in */; do
    echo;
    echo $sub

    dest_sub=${iTunesU_Destination}/${sub}

    # create the sub folder if it doesn't exist
    does_not_exist=false
    [ -d $dest_sub ] || does_not_exist=true

    if $does_not_exist;
        then
            mkdir $dest_sub
    fi

    # get the modified times for the two subfolders
    source_sub_time=$(stat -f "%m" -t "%s" ${sub})
    dest_sub_time=$(stat -f "%m" -t "%s" ${dest_sub})

    if $does_not_exist || (( $source_sub_time > $dest_sub_time ));
        then
            cd $sub

            for file in *; do
                filename=$(basename $file)
                extension="${filename##*.}"
                filename="${filename%.*}"

                dest_file=$dest_sub$filename".m4a"

#               if ! [[ -f $dest_file ]] && (is_video_file $extension = 1);
                if ! [[ -f $dest_file ]] && ([ $extension = "m4v" ] || [ $extension = "mp4" ]);
                    then

                    ffmpeg -i $file -vn -acodec copy $dest_file
            fi
            done; # each file in source sub_folder

            cd ..
    fi # source sub_folder is new or recently modified

done

IFS="$oldIFS"


texts:
This is the code I've written to find the maximum-weight independent set of a graph path. It's a standard problem with a well-known dynamic programming solution of linear complexity. Since it's a graph path, it's simplified down to a sequence of vertex weights, and we need to find the subset of non-adjacent vertices having the maximum sum.

Basically, it does this:

Iterates the sequence forward to calculate max-weight
Stores the included vertices in vector<bool> of n
Iterates the included vertices backwards to reconstruct the max-set
(not strictly required) returns the reversed max-set, so it's in original order.

I wonder whether this code could be done more elegantly from the point of STL usage.
Specifically:

I'm using accumulate with pair to keep the previous state, this might be sloppy.
There is also a vector<bool> that I use to avoid duplicate comparisons when reconstructing the set, maybe this can be done better too.
copy_if could generate the vertices in the original-order if we had copy_backward_if, but we don't.

#include <algorithm>
#include <iostream>
#include <numeric>
#include <sstream>
#include <string>
#include <vector>

template<class W>
std::pair<W, std::vector<W>> max_weighted_independent_set(const std::vector<W> &verts)
{
    if (verts.empty())
        return std::make_pair(0, std::vector<W>());
    else if (verts.size() == 1)
        return std::make_pair(verts.front(), std::vector<W>{verts.front()});

    // Dynamic programming approach. The current max-weighted set either
    // excludes the prev vertex or includes it but skips the current one.
    // To pass along the previous weights a pair<prev-prev, prev> is used.
    std::vector<bool> includes(verts.size());
    auto inc = begin(includes); *inc++ = true;
    auto wmax = accumulate(++verts.cbegin(), verts.cend(), std::make_pair(0, verts[0]),
        [&](const std::pair<W, W> &p, const W weight) {
        const W new_weight = p.first + weight; // overflow check omitted for clarity
        return std::make_pair(p.second, (*inc++ = new_weight > p.second) ?
            new_weight : p.second);
    });

    // Reconstruct the set by skipping verts according to the includes vector.
    std::vector<W> result;
    auto i = includes.crbegin(); bool skip = false;
    copy_if(verts.crbegin(), verts.crend(), back_inserter(result),
        [&](const W &lhs) { return skip = skip ? i++, false : *i++; });

    // Reversing the copy is redundant and provided for convenience.
    return std::make_pair(wmax.second, std::vector<W>(result.crbegin(), result.crend()));
}

int main() {
    auto result = max_weighted_independent_set(std::vector<int>{1, 4, 5, 4});
    copy(result.second.begin(), result.second.end(),
        std::ostream_iterator<int>(std::cout, " "));
    std::cout << "weight: " << result.first << std::endl;
    return 0;
}

Note that I've skipped the overflow checking code and unit-tests for brewity. I also ignore negative weights and duplicate max-sets to keep the focus on STL application.


texts: 2D lattice random walk plots in functional style

texts:
To practice writing code in the functional programming style, I wrote a program to plot two-dimensional lattice random walks. I'd appreciate any feedback about how to improve its "functionaliness".

possibleSteps <- list(c(-1,0), c(0,-1), c(1,0), c(0,1))

step <- function(x) {
        return(unlist(sample(possibleSteps, 1)))
}

takeRandomWalk <- function(nSteps) {
        coordPairs <- Reduce(`+`, lapply(1:nSteps, step), accumulate = T)
        x <- sapply(coordPairs, `[`, 1)
        y <- sapply(coordPairs, `[`, 2)
        return(list(x, y))
}

plotRandomWalk <- function(nSteps, margins) {
        walkObj <- takeRandomWalk(nSteps)
        plot(seq(-margins,margins), seq(-margins,margins),
             type = 'n', xlab = "", ylab = "")
        lines(walkObj[[1]], walkObj[[2]])
}

Call plotRandomWalk(10000, 80) for an example.

EDIT

I have now compiled a far schnazier version as a shiny app:

Check it out!

Thanks for the help!


texts:
I'd love thoughts on how to make this more elegant. I'm planning to add some additional functionality, but basically this is just my first pass at creating a pythonic Slack bot from scratch.

You need Slack API token to run it. I am deploying to Heroku, so I have it looking for an environment variable called API_TOKEN which I set (in bash, anyway) export API_TOKEN='abc-1234xyzFakeTokenString'

There are two files, app.py:

from slackclient import SlackClient
import time
import re
import datetime

class Bot(object):

    def __init__(self, token, searches):
        self.searches = searches
        self.client = SlackClient(token)
        self.username = {}
        self.user_id = {}

    def run(self):
        if self.client.rtm_connect():
            try:
                self.user_id = self.client.api_call("auth.test")['user_id']
                self.username = self.client.api_call("auth.test")['user']
                self._log(self.username + ": " + self.user_id)
            except:
                print Exception
            while True:
                self.process_messages(self.client.rtm_read())
                time.sleep(0.25)
        else:
            self._log("Connection failed.")

    def _log(self, message, level=' DEBUG '):
        """
        TODO this should actually put logs somewhere useful;
        """
        print str(datetime.datetime.utcnow()) + level + message

    def filter_speak(self, room, message):
        """
        posts a message to a channel if it matches the call.
        """
        for call in self.searches:
            response = self.searches[call]
            if re.search(call, message):
                self.client.api_call("chat.postMessage", as_user="true",
                                     channel=room, text=response)

    def process_messages(self, messages):
        for msg in messages:
            # We're only interested in entries of type "message"
            if msg['type'] == "message":
                # TODO also check the text of expanded links.
                if 'text' in msg:
                    body = msg['text']
                elif 'subtype' in msg:
                    if msg['subtype'] == "message_changed":
                        body = msg['message']['text']
                else:
                    self._log(msg + " didn't appear to have text or subtype?")

                if 'user' in msg:
                    if msg['user'] != self.user_id:
                        self.filter_speak(message=body, room=msg['channel'])

And then in a separate run.py file I have:

from app import Bot
from os import environ

pairs = {}

pairs["[kK]nock[, -]*[kK]nock"] = "Who's there?"

pope_bot = Bot(environ['API_TOKEN'], pairs)
pope_bot.run()

I'm hoping to add a bit more functionality -- I'd like it to chirp a few more things when prompted by a DM, for instance, but this works so I wanted feedback on how I could streamline it or what you might have done differently.


texts: Entity Framework optimization when using transactions

texts:
I want to save NUnit local tests in a mysql database hosted in Amazon RDS, and

I'm wrapping up everything in a transaction like so :

using (var context = new StDbContext())
         {
            context.Database.Log = Console.Write;
            if (!context.Database.Connection.State.HasFlag(ConnectionState.Open))
            {
               context.Database.Connection.OpenAsync();
            }
            using (var transaction = context.Database.BeginTransaction())
            {
               try
               {
                  var unit_of_work = new UnitOfWork(context);
                  unit_of_work.Sessions.AddModelSession(Model, unit_of_work);
                  context.SaveChanges();

                  transaction.Commit();
               }
               catch (Exception ex)
               {
                  transaction.Rollback();
                  TestBaseCore.mNLogLoggerService.Error(ex.Message);
               }

            }
         }

Is there a better way of optimizing this code, in order to be sure that the connection or the current transaction is still open until all the data it is saved to the database? because when trying to save using this code to a local database everything works perfectly, but when saving to a database hosted by Amazon RDS, the code will crash with no exception.The only difference is the connection string


texts: Solution to Project Euler problem 5 (LCM of 1 to 20)

texts:
I'm an experienced C# developer trying to teach myself F#. I spent a day or 3 reading throught the F# wikibook trying to get to know the syntax and F# fundamentals.

As an exercise I'm trying to go through the Project Euler problems to get a better feeling of the syntax and working with the language.

I've just solved problem 5 (finding the least common multiple of 1, 2, 3, …, 20). But I'm not so happy about the hoops I had to jump through to get a data structure that represents my solution.
I've used this blogpost to get to the algorithm for solving the problem.

I was wondering if anyone could give me some pointers as to how this code could be improved? My guess is that the inherent immutability of F# values is causing me to have to perform a lot of steps to get the exact data I want...

This is my code:

let main argv =
//calculates the prime factors of a number
let findPrimeFactors x =
    let primes = [|2I;3I;5I;7I;11I;13I;17I;19I|]
    let rec loop acc counter = function
        | x when x = 1I -> failwith "A PRIME IS BY DEFINITION GREATER THAN 1"
        | x when primes |> Array.contains x -> x :: acc
        | x when counter = primes.Length -> failwith "MY LIST OF KNOWN PRIMES IS NOT BIG ENOUGH"
        | x when x%primes.[counter]=0I-> loop (primes.[counter]::acc) (counter) (x/primes.[counter])
        | x -> loop acc (counter + 1) x

    let primeFactor = loop [] 0 x |> List.rev
    primeFactor

//calculates the prime factors for each of the numbers between 2 and n
//then, for each of the prime factorizations it tries to find the highest power for each occurring prime factor
let findPrimeFactorsPowers n =
    //builds a map of all the prime factor powers for all prime factorizations
    let rec addCounterFactorPowers factorPowers = function
        | counter when counter = n -> factorPowers
        | (counter : int) -> addCounterFactorPowers ((findPrimeFactors (counter|>bigint) |> List.countBy (fun x-> x)) @ factorPowers) (counter + 1)
    let allFactorPowers = addCounterFactorPowers [] 2
    //group all the powers per prime factor
    let groupedFactorPowers = allFactorPowers |> List.groupBy (fun (factor, power) -> factor)
    //get the highest power per prime factor
    let maxFactorPowers = groupedFactorPowers |> List.map (fun (key, powers) -> (key, powers |> List.map (fun (factor, power) -> power) |> List.max))

    //return the result
    maxFactorPowers

let n = 20;
let primeFactorSet = findPrimeFactorsPowers n
printfn "%A" primeFactorSet

let smallestNumberDivisableByAllNumbersBelown =  (primeFactorSet |> List.fold (fun state (factor, power) -> state * pown factor power) 1I)
printfn "Result %A" smallestNumberDivisableByAllNumbersBelown

System.Console.ReadKey(true)|>ignore
0 // return an integer exit code


texts: Program to delete directories that do not contain a file

texts:
I'm an intern and have an ETL project I'm doing in python.

Part of it is to make sure after I move files I delete empty directories.

I wrote this code to clean up directories that are empty and in testing it works for me but I want to make sure it won't end up deleting folders full of files.

def folderCleanup(p_rootPath):
    for r, dirs, files in os.walk(p_rootPath):
        for folder in dirs:

            if len(os.listdir(os.path.join(r, folder))) == 0: #Checks if the folders have anything in them
                shutil.rmtree(os.path.join(r, folder))

            elif hasFile(os.path.join(r, folder)): #Checks if a subfolder will have a file in it
                    pass
            else:
                    shutil.rmtree(os.path.join(r, folder),ignore_errors=True)
            #end if
        #end for
    #end for
#end def

def hasFile(p_path): #Returns true if the given directory or any of its children directories have a file in them
    for r, d, f in os.walk(p_path):

        if len(f) > 0:
            if len(f) == 1 and f[0] == 'Thumbs.db':
                continue
            else:
                return True
            #end if
        #end if
    #end for
    return False
#end def

I am just looking for some feedback and whether there are any potential problems with this code.


texts:
I'm working on a script to backup S3 to GC everyday. I'm not sure if my script has any potential bug or error that might have destroyed anything from both sides? The data is quite sensitive and I don't want to mess it up. Anything is welcomed.

#!/bin/sh

if hash aws 2>/dev/null; then
    echo 'awscli is installed.'
else
    echo 'Please install awscli by running sudo pip install awscli'
    exit
fi

if hash gsutil 2>/dev/null; then
    echo 'gsutil is installed.'
else
    echo 'Please install gsutil by running sudo pip install gsutil'
fi

if env | grep -q ^BACKUP_TO_EMAIL=
then
    echo "After backup is done email will be send to $BACKUP_TO_EMAIL"
else
    echo "BACKUP_TO_EMAIL is not set please set it"
    exit
fi

if env | grep -q ^S3_BUCKET=
then
    echo "Checking if $S3_BUCKET exists"
    if aws s3 ls "s3://$S3_BUCKET" 2>&1 | grep -q 'AllAccessDisabled'
    then
        echo "bucket $S3_BUCKET doesn't exist please check again."
        exit
    fi
else
    echo 'S3_BUCKET is not set please set it'
    exit
fi

if env | grep -q ^GC_BUCKET=
then
    echo "Checking if $GC_BUCKET exists"
    if gsutil ls "gs://$GC_BUCKET" 2>&1 | grep -q 'AccessDeniedException'
    then
        echo "bucket $GC_BUCKET doesn't exist please check again."
        exit
    fi
else
    echo 'GC_BUCKET is not set please set it'
    exit
fi

echo "Backing up now..."
#`gsutil -m rsync -r s3://$S3_BUCKET gs://$GC_BUCKET`

echo "Creating new backup folder"
datestamp=$(date +%m%d%y)
mkdir $datestamp

echo "Downloading backup"
aws s3 sync "s3://$S3_BUCKET" $datestamp

echo "Compressing site backup"
tar -zcvf $datestamp.tar.gz $datestamp
file=$datestamp.tar.gz
rm -rf $datestamp

echo "Uploading to GC"
gsutil cp $file "gs://$GC_BUCKET"

echo "Deleting temporary files"
rm $file

echo "Sending email"
body="Backup is complete and the file is in gs://$GC_BUCKET/$file"

echo $body | mail $BACKUP_TO_EMAIL -s "S3 to GS backup"


texts:
The following codes generate table row dynamically. I wonder if there are better ways of generating the same data. Also instead of manually coding the heading and the table itself, is it possible to code them with less codes without using the innerHTML function.

            ID
            Name
            Mark Score

Data:

const students = {
        '24': {
            'id':'24',
            'Name':'Zuali',
            'mark':30,
        },
        '25': {
            'id':'25',
            'Name':'Famkima',
            'mark':52,
        },
        '27':{
            'id':'27',
            'Name':'Duha',
            'mark':77,
        },
        '28':{
            'id':'28',
            'Name':'Rema',
            'mark':81,
        },
        '29':{
            'id':'29',
            'Name':'Sanga',
            'mark':47,
        },
        '30':{
            'id':'30',
            'Name':'Dari',
            'mark':23,
        },
    };

JS code to create the table data:

const markObtained = Object.keys(students).reduce(function(names, name) {
if (students[name].mark>=20) {
    names[name] = students[name];
}
return names;
}, {});
const doc = document.createDocumentFragment();
const table = document.querySelector("table");
for(let i=0; i<Object.keys(markObtained).length; i++) {
    const data = Object.values(markObtained)[i];
    const tr = document.createElement("tr");
    for (const v in data){
         const td = document.createElement("td");
        td.textContent = data[v];
        tr.appendChild(td);
    }
  table.appendChild(tr);
 }
table.appendChild(doc);

I would highly appreciate if any expert in js can help me better optimize the codes and give me another workaround examples?


texts: Sass mixins vs Angular layout components

texts:
For a long time I've been using Angular "Layout" components so their role is basically to define layout, like padding, margin, fonts and so on.

For instance, page header component:

<my-header>My super page</my-header>

So now this component will have SCSS:

:host {
    width: 100%;
    display: block;
    padding:10px
}

But it's kind of the same I can achieve with SASS mixins:

@mixin page-header(){
        width: 100%;
        display: block;
        padding:10px
}

and then I can use it on the page:

My super page

and SCSS:

div.page-header{
  @include page-header();
}

I don't see much difference. The only benefit of components would be bundle size, since if mixins are "big" and used in many places then size will be bigger.

My question is, what is the best way to make structural/Layout components? I appreciate any thoughts/recommendation they usually lead to better decisions :)

It's not a question for components like <my-header [image]="cat.jpg" [header]="text"></my-header>. The questions how it's better to make components which contains mostly CSS.


texts:
This is a program to calculate the largest prime number.  Are there any possible improvements in style/speed/accuracy?

public static int? LargestPrime(int max)
{
    if (max < 0)
        return null;
    int largestPrime = 0;
    for (int i = 0; i <= max; i++)
    {
        bool? isPrime = IsPrime(i);
        if ((bool)isPrime)
            largestPrime = i;
        if (i % 100000 == 0)
            Console.WriteLine(largestPrime.ToString("N0"));
    }
    return largestPrime;
}
private static List<int> listPrimes = new List<int>() { 2, 3 };
private static int listPrimeMax;
private static int listPrimesCount = 100000;
private static bool firstA = true;
private static bool firstB = true;
public static bool? IsPrime(int n)
{
    if (listPrimes.Count < listPrimesCount)
    {
        // from wiki
        // function is_prime(n : integer)
        // if n ≤ 1
        //     return false
        // else if n ≤ 3
        //     return true
        // else if n mod 2 = 0 or n mod 3 = 0
        //     return false
        // let i ← 5
        // while i×i ≤ n
        //     if n mod i = 0 or n mod(i + 2) = 0
        //         return false
        //     i ← i + 6
        //return true
        if (n < 0)
            return null;
        if (n <= 1)
            return false;
        if (n <= 3)
            return true;
        if (n % 2 == 0 || n % 3 == 0)
            return false;
        for (int i = 5; i*i <= n; i += 6)
        {
            if (n % i == 0 || n % (i + 2) == 0)
                return false;
        }
        if (listPrimes.Count < listPrimesCount)
        {
            listPrimes.Add(n);
            listPrimeMax = n;
        }
        return true;
    }
    else
    {
        if(firstA)
        {
            Console.WriteLine("in listPrimes");
            firstA = false;
        }
        foreach (int i in listPrimes)
        {
            if (n % i == 0)
                return false;
            if (i * i > n)
                break;
        }
        for (int i = listPrimeMax + 2; i*i <= n; i += 2)
        {
            if (n % i == 0)
                return false;
        }
        if (listPrimes.Count < 100 * listPrimesCount)
        {
            listPrimes.Add(n);
            listPrimeMax = n;
        }
        else if(firstB)
        {
            Console.WriteLine("in 100*listPrimes");
            firstB = false;
        }
        return true;
    }
}


texts: Authorization - Create and unlock a User

texts:
I just wrote this, but I am not realy happy with that. I think there is an easier way to do this. First I am checking if a user has an ID (from a portal we are using, it is in the header). After that I have to check if the user exists in my application, if not a user will be created, if the user exists, the datetime lastlogon will be updated.
(here is my first problem, CheckIfUserExists always returns true, except on an Exception, is this ok?). After that I am checking if userExists is true. If a user is created it has to be unblocked by an admin. If this happened the user can access the page.
If the user is in Role Admin, Viewbag is true otherwise false. If userExists is false, he is getting the default error.

I think my chain of thought is realy complicated.

public ActionResult Index()
{
    bool userExists = false;
    if (HelperClass.UserId != "")
        userExists = CheckIfUserExists(HelperClass.UserId);
    else
        return RedirectToAction("AccessDenied", "Error");

    if (userExists)
    {
        bool unblocked = CheckIfUnblocked(HelperClass.UserId);
        if (unblocked)
        {
            if (User.IsInRole("Admin"))
                ViewBag.Admin = true;
            else
                ViewBag.Admin = false;
            return View("Index");
        }
        return RedirectToAction("AccessDenied", "Error");
    }
    else
    {
        return RedirectToAction("Index", "Error");
    }
}

EDIT: Adding Code

public bool CheckIfUserExists(string u_gvid)
{
    try
    {
        using (NpgsqlConnection con = new NpgsqlConnection(_Connection))
        {
            con.Open();
            using (NpgsqlCommand cmd = new NpgsqlCommand())
            {
                cmd.Connection = con;
                //qry check if user exists
                var result = cmd.ExecuteScalar().ToString().ToLower();
                if (result == "false")
                {
                    return CreateUser(HelperClass.UserId, HelperClass.Name);
                }
                else
                {
                    //Update lastlogonn time
                    //qry
                    cmd.ExecuteScalar();
                    return true;
                }
            }
        }
    }
    catch (NpgsqlException ex)
    {
        //log
        RedirectToAction("DatabaseError", "Error");
    }
    catch (Exception ex)
    {
        //log
        RedirectToAction("Index", "Error");
    }
    return false;
}

public bool CheckIfUnblocked(string u_gvid)
{
    try
    {
        using (NpgsqlConnection con = new NpgsqlConnection(_Connection))
        {
            con.Open();
            using (NpgsqlCommand cmd = new NpgsqlCommand())
            {
                //qry "SELECT unblocked FROM tbl.users WHERE uid = @uid";
                var result = (bool)cmd.ExecuteScalar();

                if (result)
                    return true;
                else
                    return false;
            }
        }
    }
    catch (NpgsqlException ex)
    {
        //log
        RedirectToAction("DatabaseError", "Error");
    }
    catch (Exception ex)
    {
        //log
        RedirectToAction("Index", "Error");
    }
    return false;
}


texts: Making PHP composable and look functional

texts:
I've found myself on numerous occasions needing to with large text-files, where joining this on that, and filtering this out on arbitrary conditions.

The first couple of times, this turned into a loop in a loop in a loop mess which was indented more times than I care to either remember or admit.

More recently, I've attempted to make something that looks and behaves more "functional". Below is the basic class and a simple example.

I'm primarily concerned with extensibility. I'm not sure the approach I use will lend itself to extensibility in the future. I though, for example, about trying to stream results to disc, and I'm not sure that's doable at all without a fundamental change. Similarly it would be useful to add a simple ->not() for negating a filter, which I also don't see easily doable here.

A secondary concern is performance. PHP is perhaps not the best choice for a functional style. I'm guessing the performance of all these function calls isn't fantastic. Anything obvious I can do to improve it? If "real" performance is a requirement, the obvious suggestion might just to be to not use PHP, but if there are cheap ways to stretch this further, it would be nice.

Code:

class Functional {
  protected $result;
  protected $extra_data;

  public function __construct($array = NULL) {
    $this->result = $array;
  }

  public function reduce($callback, $i = NULL) {
    if ($i === NULL) {
      $i = $this->result;
    }

    $result = array_reduce($i, $callback);
    $this->result = $result;
    return $this;
  }

  public function walk($callback, $i = NULL) {
    if ($i === NULL) {
      $i = $this->result;
    }

    array_walk($i, $callback);
    $this->result = $i;
    return $this;
  }

  public function filter($callback, $i = NULL) {
    if ($i === NULL) {
      $i = $this->result;
    }

    $this->result = array_filter($i, $callback);
    return $this;
  }

  public function result() {
    return $this->result;
  }

  public function gather($callback, $key) {
    $this->extra[$key] = $callback($this->result)
    return $this;
  }

  public function extra($key) {
    return $this->extra[$key];
  }
}

Example usage:

$a = [1, 2, 3, 4];

$f = new Functional($a);
$result = $f->walk(function(&$i) { return $i *= 2; })
  ->reduce(function($i, $j) { return $i + $j; })
  ->result();

var_dump($result);

int(20)


texts:
I recently asked this question about performance of an unordered_map, but I realize my question is probably more about this piece of code here.

I create a 8 x 10 x 30 x 30 x 24000 nested vectors of floats. This structure is used to keep track of votes in this 5D space. Many of the bins are never actually incremented, though (0 votes). The structure takes up 7.2GB of memory.

I initially thought to switch to a hash map (hence, my other question), but there's memory overhead in storing the 5D keys, and it's actually slower.

How can I improve this solution? I'd like to reduce the memory used, without giving up much speed.

Things I've thought of:

Switching to an unordered_map (was slower and used more memory)
Dropping to half-precision floats (I only need about 3-4 digits of precision, and the votes accumulated in any of the bins are in approximately [-3,3]) - haven't tried this
Replacing the inner vector<float> with map<float> - haven't tried this

I'd appreciate feedback about any of these ideas.

#include <random>
#include <vector>

int main(int argc, char** argv) {
  std::default_random_engine generator;
  std::uniform_int_distribution<int> random_z(1,24000);
  std::uniform_real_distribution<float> random_vote(0.0, 1.0);

  // This makes an 8 x 10 x 30 x 30 x 24000 vector of vectors... of vectors.
  std::vector<std::vector<std::vector<std::vector<std::vector<float> > > > > votes;
  for (size_t a = 0; a < 8; ++a) {
    std::vector<std::vector<std::vector<std::vector<float> > > > a_grid;
    for (size_t b = 0; b < 10; ++b) {
      std::vector<std::vector<std::vector<float> > > b_grid;
      for (size_t y = 0; y < 30; ++y) {
        std::vector<std::vector<float> > y_grid;
        for (size_t x = 0; x < 30; ++x) {
          y_grid.push_back(std::vector<float>(24000, 0));
        }
        b_grid.push_back(y_grid);
      }
      a_grid.push_back(b_grid);
    }
    votes.push_back(a_grid);
  }

  for (int i = 0; i < 200000; ++i) {
    int z = random_z(generator); // z in [1,24000]
    for (int a = 0; a < 8; ++a) {
      for (int b = 0; b < 10; ++b) {
        for (int x = 0; x < 30; ++x) {
          for (int y = 0; y < 30; ++y) {
            float this_vote = random_vote(generator);
            if (this_vote > 0.8) {
              votes[a][b][y][x][z] += this_vote;
            }
          }
        }
      }
    }
  }
  return 0;
}


texts:
Does this code fine for database reusability?

<?php
/**
 * Database
 *
 * Class for handling database connections
 *
 *
 * @category   Global Class
 * @copyright  ---
 * @license    ---
 * @version    1.0
 * @link       ---
 * @since      File available since Release 1.0
 * @created    ---
 * @modified   ---
 * @author     Original Author <--->
 * @author     Future Author <--->
 */

class Database
{
    private $database_connection = null;

    public function __construct( $database_id )
    {
        $database_host     = '';
        $database_name     = '';
        $database_username = '';
        $database_password = '';

        switch ( $database_id ) {
            case 'db1':
                $database_host     = 'host';
                $database_name     = 'name';
                $database_username = 'user';
                $database_password = 'pass';
                break;
            case 'db2':
                $database_host     = 'host';
                $database_name     = 'name';
                $database_username = 'user';
                $database_password = 'pass';
                break;
            default:
                trigger_error( 'Undefined database id', E_USER_ERROR );
        }

        try {
            $this->database_connection = new PDO( "mysql:host={$database_host};
                                                  dbname={$database_name}",
                                                  $database_username,
                                                  $database_password );

            $this->database_connection->setAttribute( PDO::ATTR_ERRMODE,
                                                      PDO::ERRMODE_EXCEPTION );
        } catch ( PDOException $pdo_exception ) {
            trigger_error( $pdo_exception, E_USER_ERROR );
        }

        if ( empty( $this->database_connection ) ) {
            trigger_error( 'Undefined database connection', E_USER_ERROR );
        }
    }

    public function execute_query( $query, $statement_id, $values )
    {
        $statement = $this->database_connection->prepare( $query );

        if ( $statement_id == 'db1' ) {
            $statement->bindParam( ':id', $values[ 0 ] );
        } else if ( $statement_id == 'db2' ) {
            $statement->bindParam( ':id1', $values[ 0 ] );
            $statement->bindParam( ':id2', $values[ 1 ] );
        } else {
            trigger_error( 'Undefined statement id', E_USER_ERROR );
        }

        $statement->execute();

        return $statement;
    }
}

?>

and call it here like this?

<?php
require once( "database.php" );

$database_1 = new Database( "db1" );
$database_2 = new Database( "db2" );

$database_1->execute_query( "SELECT * FROM user WHERE id = :id", "db1", array( 0 ) );
$database_1->execute_query( "SELECT * FROM user WHERE id = :id", "db1", array( 1 ) );
$database_2->execute_query( "SELECT * FROM user WHERE id = :id1 AND id2 = :id2", "db2", array( 0, 1 ) );
$database_2->execute_query( "SELECT * FROM user WHERE id = :id1 AND id2 = :id2", "db2", array( 2, 3 ) );

?>


texts: Converting audio to different file formats

texts:
I have this code that converts audio to different file formats:

import java.io.File;
import it.sauronsoftware.jave.AudioAttributes;
import it.sauronsoftware.jave.Encoder;
import it.sauronsoftware.jave.EncoderException;
import it.sauronsoftware.jave.EncodingAttributes;
import it.sauronsoftware.jave.InputFormatException;

/*  required jars(jave-1.0.2.jar)
 *  Handles Encoding and Decoding
 *  Audio to different file formats
 */
public class AudioEncoderDecoder {

    private static final Integer bitrate = 256000;//Minimal bitrate only
    private static final Integer channels = 2; //2 for stereo, 1 for mono
    private static final Integer samplingRate = 44100;//For good quality.

    /* Data structures for the audio
     *  and Encoding attributes
     */
    private AudioAttributes audioAttr = new AudioAttributes();
    private EncodingAttributes encoAttrs = new EncodingAttributes();
    private Encoder encoder = new Encoder();

    /*
     * File formats that will be converted
     * Please Don't change!
     */
    private String oggFormat = "ogg";
    private String mp3Format = "mp3";
    private String wavFormat = "wav";

    /*
     * Codecs to be used
     */
    private String oggCodec = "vorbis";

    /* Set the default attributes
     * for encoding
     */
    public AudioEncoderDecoder(){
        audioAttr.setBitRate(bitrate);
        audioAttr.setChannels(channels);
        audioAttr.setSamplingRate(samplingRate);
    }

    public void encodeAudio(File source, File target, String mimeType){
        //Change the hardcoded mime type later on
        if(mimeType.equals("audio/mp3")){
            this.mp3ToOgg(source, target);
        }
    }

    private void mp3ToOgg(File source, File target){
        //ADD CODE FOR CHANGING THE EXTENSION OF THE FILE
        encoAttrs.setFormat(oggFormat);
        audioAttr.setCodec(oggCodec);
        encoAttrs.setAudioAttributes(audioAttr);
        try{
        encoder.encode(source, target, encoAttrs);
        }catch(Exception e){
            System.out.println("Encoding Failed");
        }
    }

    private void oggToMp3(){
        //ADD CODE FOR CHANGING THE EXTENSION OF THE FILE
        encoAttrs.setFormat(mp3Format);
        audioAttr.setCodec(mp3Codec);
        encoAttrs.setAudioAttributes(audioAttr);
        try{
        encoder.encode(source, target, encoAttrs);
        }catch(Exception e){
            System.out.println("Encoding Failed");
        }
    }

    public static void main(String[] args){
        AudioEncoderDecoder aed = new AudioEncoderDecoder();
        File source = new  File("singelementsmp3.mp3");
        File target = new File("test.ogg");

        //Test Mp3 To Ogg Convertion
        String mimeType = "audio/mp3";
        aed.encodeAudio(source, target, mimeType);

        //Test Ogg To Mp3 Convertion
    }
}

Now, the xToX conversion basically the same throughout the whole code implementation. The only thing will change is the codec.

What is another way to make this code cleaner? From my point of view it repeats itself. What should I change? Or are there any design patterns I should implement?


texts: Optimizing jQuery table building by replacing appends with string concat

texts:
I've wrote some code to create a grid of data, however depending on the size of the grid being drawn, IE8 shows a warning message about a long running script.

I've read that multiple appends are a slow way of drawing a table, so I'm trying to concatenate a string and append it once at the end. I've been using this as a reference but not sure where to start. Any suggestions on how to go about it?

var drawgrid = function (tableName, data) {
         grid = {};
         var order = [];
         var orderCount = 0;
         for (var i = 0; i < data.length; i++) {
                 var exists = false;
                 var currentValue = data[i].masterVal;
                 if (typeof currentValue == 'undefined') {
                         currentValue = '';
                 }
                 for (var x = 0; x < order.length; x++) {
                         if (currentValue == order[x]) {
                                 exists = true;
                                 break;
                         }
                 }
                 if (!exists) {
                         order[orderCount] = currentValue;
                         orderCount++;
                 }
         };
         var table = $('#tb_' + tableName);
         var table_thead = table.find('thead');
         table_thead.empty();
         var tr_head = $('<tr>');
         var table_tbody = table.find('tbody');
         table_tbody.empty();
         $('<th>', {
                 'html': '&nbsp;'
         }).appendTo(tr_head);

         for (var i = 0; i < order.length; i++) {
                 var tr_body = $('<tr>');
                 var headerDefined = false;
                 $('<th>', {
                         "text": order[i]
                 }).appendTo(tr_head);
                 for (var j = 0; j < order.length; j++) {
                         var currentCell = {};
                         var wclass = '';
                         if (!headerDefined) {
                                 $('<td>', {
                                         'text': order[i]
                                 }).appendTo(tr_body);
                                 headerDefined = true;
                         }
                         for (var x = 0; x < data.length; x++) {
                                 if (data[x].masterVal == order[i] && data[x].subValue == order[j]) {
                                         currentCell = data[x];
                                         break;
                                 }
                         }
                         $('<td>', {
                                 'text': currentCell.value,
                                 'class': tableStyle,
                                 'data-hd': currentCell.subValue,
                                 'data-cl': currentCell.masterVal
                         }).appendTo(tr_body);
                 }
                 tr_body.appendTo(table_tbody);
                 tr_head.append().appendTo(table_thead);
         }
 };


texts:
Is this too much work for 1 touch listener? Is this bad for devices with slow CPU's?

@Override
     public boolean onTouch(View v, MotionEvent event) {
        int id = v.getId();
        switch(id){
                      case R.id.sound1:
                          if(event.getAction()==android.view.MotionEvent.ACTION_DOWN){

                          if(intLoop ==0){
                              mp1=MediaPlayer.create(MainClass.this, R.raw.item1);
                              mp1.start();
                              v.setPressed(true);
                              return true;
                          }
                          if(intLoop == 1){
                              mp1=MediaPlayer.create(MainClass.this, R.raw.item1);
                              mp1.start();
                              mp1.setLooping(true);
                              v.setPressed(true);
                              return true;
                          }
                          }else if
                              (event.getAction()==android.view.MotionEvent.ACTION_UP){
                              mp1.stop();
                              mp1.reset();
                              mp1.release();
                              v.setPressed(false);
                              clickCounter();
                              return false;
                              }
                         break;


texts:
I am using a recursive algorithm to find all of the file-paths in a given directory: it returns a dictionary like this: {'Tkinter.py': 'C:\Python27\Lib\lib-tk\Tkinter.py', ...}.

I am using this in a script to open modules by solely given the name. Currently, the whole process (for everything in sys.path) takes about 9 seconds. To avoid doing this every time, I have it save to a .pkl file and then just load this in my module-opener program.

The original recursive method took too long and sometimes gave me a MemoryError, so what I did was create a helper method to iterate through the subfolders (using os.listdir), and then call the recursive method.

Here is my code:

import os, os.path
def getDirs(path):
    sub = os.listdir(path)
    paths = {}
    for p in sub:
        print p
        pDir = '{}\{}'.format(path, p)
        if os.path.isdir(pDir):
            paths.update(getAllDirs(pDir, paths))
        else:
            paths[p] = pDir
    return paths

def getAllDirs(mainPath, paths = {}):
    subPaths = os.listdir(mainPath)
    for path in subPaths:
        pathDir = '{}\{}'.format(mainPath, path)
        if os.path.isdir(pathDir):
            paths.update(getAllDirs(pathDir, paths))
        else:
                paths[path] = pathDir
    return paths

Is there any way to make this faster? Thanks!


texts: JavaScript event handlers, scope, and the module design pattern

texts:
I've been using JavaScript for some time now, but mostly just jQuery to prettify web pages.  I've started doing some serious development with it in the last year.

So, I want to make sure I'm not doing something stupid.  I found a post about the module pattern, and it makes sense to me, so I'm going to attempt to use it on this project instead of keeping nearly everything global.

I'm just a little fuzzy on where I should put event listeners.  Is there going to be any issues with scope if the listener is instantiated inside a method?  If I'm building something like a toolbar with different functions (kind of like a paint program with 'move', 'select', 'paintbrush', and 'eraser' options), do I keep the onClick for all of those in global scope?

PROJ.namespace("easel");
PROJ.easel.canvas = function() {
  //private variable to store current state
  var current_mode = "select";

  return {
    enableSelect: function () {
      //disable other tools, enable 'select' event listeners
    }
    enablePaintbrush: function () {
      //disable other tools, enable 'paintbrush' event listeners
    }
    enableMove: function () {
      //disable other tools, enable 'move' event listeners
    }
    enableEraser: function () {
      //disable other tools, enable 'eraser' event listeners
    }
  };
}();

//event listeners for the tool pallete
$('#tools #paintbrush').on('click', function() { PROJ.easel.canvas.enablePaintbrush() };
$('#tools #move').on('click', function() { PROJ.easel.canvas.enableMove() };
$('#tools #select').on('click', function() { PROJ.easel.canvas.enableSelect() };
$('#tools #eraser').on('click', function() { PROJ.easel.canvas.enableEraser() };

Of course, once the specific tool is selected, it needs its own listeners.  For example, a paintbrush needs handlers for 'mousedown' (start painting), 'mousemove' (lay down paint), and 'mouseup' (stop painting).  Can those listeners be enabled inside of PROJ.easel.canvas?

EDIT: How are you supposed to pick an "answer" on codereview.stackexchange.com?  You're asking peoples' opinions...