texts:
While reading a data structure book, I have implemented a chained hash table. I want to share the code with you and get your opinion about it.

chained_hash_table.h

#ifndef CHAINED_HASH_TABLE_H_INCLUDED
#define CHAINED_HASH_TABLE_H_INCLUDED

#include <stdlib.h>
#include "../linked_list/linked_list.h"

typedef size_t hkey_t;

typedef struct ChainedHashTable_ {
    size_t buckets;
    List **table;
    hkey_t (*hash)(const void *key);
    void (*destroy)(void *data);
    int (*compare)(const void *fdata, const void *sdata);
}ChainedHashTable;

ChainedHashTable *chtb_init(size_t buckets,
        hkey_t (*hash)(const void *key),
        void (*destroy)(void *data),
        int (*compare)(const void *fdata, const void *sdata));
void chtb_destroy(ChainedHashTable *chtb);
int chtb_insert(ChainedHashTable *chtb, void *data);
int chtb_remove(ChainedHashTable *chtb, void **data);
int chtb_lookup(const ChainedHashTable *chtb, const void *data);

#endif

chained_hash_table.c

#include <string.h>

#include "chained_hash_table.h"

#define chtb_hash_key(chtb, data)   chtb->hash(data) % chtb->buckets

ChainedHashTable *chtb_init(size_t buckets,
        hkey_t (*hash)(const void *key),
        void (*destroy)(void *data),
        int (*compare)(const void *fdata, const void *sdata)) {

    ChainedHashTable *chtb;

    if( (chtb = malloc(sizeof *chtb)) != NULL ) {
        chtb->buckets = buckets;
        chtb->hash = hash;
        chtb->destroy = destroy;
        chtb->compare = compare;

        if( (chtb->table = malloc(buckets * sizeof *chtb->table)) == NULL) {
            free(chtb);
            return NULL;
        }

        int i;

        for(i = 0; i < buckets; ++i) {
            if( (chtb->table[i] = list_init(destroy, compare)) == NULL) {
                for(--i; i >= 0; --i)
                    free(chtb->table[i]);

                free(chtb);
                return NULL;
            }
        }
    }

    return chtb;
}

void chtb_destroy(ChainedHashTable *chtb) {
    size_t i;

    for(i = 0; i < chtb->buckets; ++i)
        if(chtb->table[i] != NULL)
            list_destroy(chtb->table[i]);

    free(chtb->table);
    free(chtb);
}

int chtb_insert(ChainedHashTable *chtb, void *data) {
    size_t bucket = chtb_hash_key(chtb, data);

    if(list_find(chtb->table[bucket], data) != NULL)
        return 1;

    if(list_prepend(chtb->table[bucket], data) != 0)
        return -1;

    return 0;
}

int chtb_remove(ChainedHashTable *chtb, void **data) {
    size_t bucket = chtb_hash_key(chtb, data);

    if(chtb->table[bucket] == NULL)
        return -1;
    return list_remove(chtb->table[bucket], data);
}

int chtb_lookup(const ChainedHashTable *chtb, const void *data) {
    size_t bucket = chtb_hash_key(chtb, data);

    return list_find(chtb->table[bucket], data) == NULL ? 0 : 1;
}


texts: Printing the PID of a program immediately before it runs

texts:
I need to know (for monitoring purposes) the PID of a program immediately before I start it. There could be multiple of the same program launched at the same time, so monitoring ps or top isn't really an option. It dawned on me as I was exploring various bash-related options that I could make use of C's exec functions to try and pull this off. With that in mind, I whipped up this little piece of code:

#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>

int main(int argc, char **argv)
{
    char **argv_copy;
    int i;

    if (argc >= 2)
    {
        argv_copy = malloc(argc * sizeof *argv_copy);

        for (i = 1; i < argc; i++)
        {
            argv_copy[i-1] = argv[i];
        }
        argv_copy[argc] = (char *) NULL;

        printf("%lu\n", (long unsigned) getpid());

        execvp(argv[1], argv_copy);
    }
    return 0;
}

It works as expected - it immediately prints out the PID of the process and then loads the actual process I want to run. What I'm not convinced of is the security or robustness of this little hack. I don't need it to be 100% bullet-proof security-wise, but if you can drive an SUV through it I'd like to know.

Could I get some advice on these two areas specifically?


texts:
This function sorts an array and returns the unique items. I'm trying to get it down to a readable 5 lines of code. So far I've renamed the variable cursor variable and inlined the assignments.
I'll appreciate fresh eyes.

Before

function uniques(array) {
    var result = [], val, ridx;
    outer:
    for (var i = 0, length = array.length; i < length; i++) {
        val = array[i];
        ridx = result.length;
        while (ridx--) {
          if (val === result[ridx]) continue outer;
        }
        result.push(val);
    }
    return result;
}

After

function uniques(array) {
    var result = [], val, cursor;
    outer:
        for (var i = 0, length = array.length; i < length; i++) {
        val = array[i], cursor = result.length;
        while (cursor--) {
          if (val === result[cursor]) continue outer;
        }
        result.push(val);
    }
    return result;
}


texts: Read and write data to/from Serial Port in C#

texts:
I am building a console application which will be scheduled in Task Scheduler of Windows to run my code every day at a set hour. Summing up, this application will read and write through serial port. When I send something to the Arduino, I need to receive something from it to finish up what I've sent and execute the command.

In other words, I will send something so see if the door is opened, if it is the application will run a code to close it. If the door is already closed I will send a bunch of characters to be displayed into the Arduino Led Display.

So I've developed a code but I am not sure if it's totally correct, if possible help me improve it. There is any changes I could make?

static void Main(string[] args)
{
    SerialPort comport = new SerialPort("COM1", 9600, Parity.None, 8, StopBits.One);
    comport.Open();

    string start = "?";
    string carriageReturn = "\r";
    string text = string.Empty;

    string mensage = "@" + "r" + "\r";
    string mensage2 = "@" + "{" + texto + "\r";

        try
            {
                while (true)
                {
                    //Send to the Arduino
                    comport.Write(start + "*" + carriageReturn);

                    //If the serial port have bytes to read
                    if (comport.BytesToRead > 0)
                    {
                        //Buffer with data
                        byte[] data = HexStringToByteArray(mensage);

                        //Handle data
                        comport.Read(data, 0, data.Length);

                        //Send again to execute the the command
                        comport.Write(start + "*" + carriageReturn);
                    }

                    if (comport.BytesToRead > 0)
                    {
                        comport.Write(start + "*" + carriageReturn);

                        byte[] data2 = HexStringToByteArray(mensage2);

                        comport.Read(data2, 0, data2.Length);

                        comport.Write(text);
                    }
                    comport.Close();
                }
            }

        catch(Exception ex)
        {
        }
}

private static byte[] HexStringToByteArray(string s)
{
    s = s.Replace(" ", "");
    byte[] buffer = new byte[s.Length / 2];

    for (int i = 0; i < s.Length; i += 2)
        buffer[i / 2] = (byte)Convert.ToByte(s.Substring(i, 2), 16);
        return buffer;
}


texts:
I've been experimenting more with webcrawling and hence have started to get a better understanding compared to my previous questions. Right now, my code scraps from a car forum on each page and iterates through every pages. What would you recommend to improve on?

import requests
from bs4 import BeautifulSoup, SoupStrainer
import pandas as pd

list_topic = []
list_time = []

SESSION = requests.Session()

def get_response(url):  # Gets the <html> structure from the website #
    response = SESSION.get(url)
    soup = BeautifulSoup(response.text, 'lxml',
                         parse_only=SoupStrainer('ul', {'class': 'posts posts-archive'}))
    return soup

def iteration(url, max_page=52):
    starting_page = 1
    while starting_page <= max_page:
        ## formats the new URL etc (https://paultan.org/topics/test-drive-reviews/page/1) ##
        new_url = url + f"page/{starting_page}"
        data = get_response(new_url)
        get_reviews(data)
        ## iteration starts ##
        starting_page += 1

def get_reviews(response):
    for container in response('article'):
        title = container.h2.a.text
        time = container.time.text
        list_topic.append(title)
        list_time.append(time)
    else:
        None

def create_pdReview():
    return pd.DataFrame({'Title': list_topic, 'Time': list_time})

if __name__ == '__main__':
    URL = 'https://paultan.org/topics/test-drive-reviews/'
    print(iteration(URL))
    print(create_pdReview())

I've been wondering; would using yield improve the efficiency and simplicity of the code? How would it be done? Because I've been trying to learn from my previous inquiries that has been answered on earlier. Here is a similar question and I'm trying to put to practice what has been recommended so far.


texts: Graph adjacency list implementation in C++

texts:
I have been playing around with an adjacency list implementation of a graph class, on which I'd like to be able to run a build and test several graph algorithms. The code I have below works and I have been able to implement BFS, DFS, Dijkstra and Prim's algorithms, but I'm not very satisfied with it and would very much appreciate criticism.

One of the key problems that I can see is that the neighbours of a node are private and therefore to traverse them inside a function (i.e. Dijkstra) I need to make this function a friend of the node class.  I suspect that I should implement smart pointers to solve this but before I do this I'd like to consider other suggestions (maybe custom iterators?).

I also think there is a problem with how the nodes are being initialised, as I would prefer not having to call setKey in the graph::addNode function.

The node class:

class node{
 public:
  node() {}
  node(int k) : key(k){}
  void addNeighbour(int k, int weight = 1){
    if (this->key == k) return;
    neighbours.push_back(std::make_pair(k,weight));
  }
  inline int getKey() const {return key;}
  inline void setKey(const int k){key = k;}

  void display() const{
    for (std::list<std::pair<int,int> >::const_iterator it = neighbours.begin(); it != neighbours.end(); ++it){
      std::pair<int,int> entry = *it;
      std::cout << entry.first << " ";
    }
    std::cout << std::endl;
  }

  friend void bfs(graph &g, int src);
  friend graph prim(graph &g);
  friend void dijkstra(graph &lg, int src);
 private:
  std::list<std::pair<int, int> > neighbours;  //first element in pair corresponds to vertex key, second to the edge weight between them
  int key;
};

The graph class:

class graph{
 public:
  graph(const int sz) : size(sz),
                        nodes(sz, node()),
                        directed(false) {}
  void addNode(int key, const std::vector<std::pair<int,int> > &input);
  void display() const;
  node &operator[](const int i){return nodes[i];}
  inline int getSize() const {return size;}
 private:
  std::vector<node> nodes;
  int size;
  bool directed;
};

void graph::addNode(const int key, const std::vector<std::pair<int,int> > &input){

  nodes[key].setKey(key);
  for (std::vector<std::pair<int,int> >::const_iterator it = input.begin(); it != input.end(); ++it){
    std::pair<int,int> entry = *it;
    nodes[key].addNeighbour(entry.first, entry.second);
    if (!directed){
      nodes[entry.first].addNeighbour(key, entry.second);
    }
  }
}


texts: Function to check if received message matches any of the expected messages

texts:
I have a message coming in and I need to match it against the expected messages. The program will eventually do something as a result of receiving those messages. I am not very experienced at programming, but surely there should be a better way to declare all those messages it can be in like a separate entity and then be able to use it within this HexSearch.cpp file?

I tried to search how to do that but I couldn't find the right words to ask about this using a search engine. There is many more messages than those show here which still need to be declared but this is just a sample, which I don't like to look at already.

#include "HexSearch.h"

void searchFunction(int num, char msg[]) {

    static const char readReq[] = { 0x92 };
    static const char readResp[] = { 0x00, 0x02, 0x12, 0x34, 0xA1 };

    static const char writeReq[] = { 0x0A, 0xE0 };
    static const char writeResp[] = { 0x00, 0x02, 0x11, 0x01, 0x98 };

    static const char resetReq[] = { 0x00, 0xFF };
    static const char resetResp[] = { 0x00, 0x21, 0x23, 0x0E, 0xAE, 0x11, 0x3A };

    static const char verReq[] = {0x00, 0xA2};
    static const char verResp[] = {0x00, 0x03, 0x82, 0xAA, 0x07, 0x88, 0xA9};

    static const char typeReq[] = {0x00, 0x67};
    static const char typeResp[] = {0x00, 0x03, 0x00, 0x00, 0xC4, 0x77};

    static const char askReq[] = {0x00, 0x55};
    static const char askResp[] = {0x00, 0x01, 0xFE, 0xFF};

    if (num == 4) {
        replyMsg(msg, 2, 3,  readReq, readResp, sizeof(readResp) / sizeof(readResp[0]));
    }
    else if (num == 5) {
        replyMsg(msg, 2, 4, writeReq, writeResp, sizeof(writeResp) / sizeof(writeResp[0]));
        replyMsg(msg, 2, 4, resetReq, resetResp, sizeof(resetResp) / sizeof(resetResp[0]));
        replyMsg(msg, 2, 4, verReq, verResp, sizeof(verResp) / sizeof(verResp[0]));
        replyMsg(msg, 2, 4, typeReq, typeResp, sizeof(typeResp) / sizeof(typeResp[0]));
        replyMsg(msg, 2, 4, askReq, askResp, sizeof(askResp) / sizeof(askResp[0]));
    }
}

void replyMsg(char msg[], int startArr, int endArr, const char* receiv, const char* resps, int respL) {
    if (std::equal(msg + startArr, msg + endArr, receiv)) {
        for (int x = 0; x < respL; x++) {
            serialPC.putc(resps[x]);
        }
    }
}

The code works. I am interested in improving it only. num is the total number of bytes of a message. E.g. readReq has one byte of data, but has also got 2 start bytes and 1 end byte so a total of 4. readResp array has the 2 start bytes, 2 data bytes, and one end byte and so it has a total size of 5 bytes. The 2nd byte is the one which specifies the length of a message. msg[] is the message coming in from a serial connection essentially.

As an example, if msg[] = { 0x00, 0x01, 0x92, 0x56 } then num = 4 and replyMsg will compare the 3rd byte to see that it matches readReq and so output readResp...


texts: C# calculate total time worked with TimeSpan

texts:
So there is an existing codebase which calculates the total time worked per month.

What the code is doing:

iterates through all the working days entries
retreives the value of net work time which is in format: HH:mm
calculates the minutes out of the net work time string
formats the net work time to the report day row (back again)
adds the daily calculated minutes to monthly total
formats the total monthly minutes to the report totals row

Problem

The code randomly calculates the data properly.
When data is calculated properly:

the total is calculated properly,
the day rows adds up to the total value

When data is not properly calculated:

the total has always 1h less
every entry which does not have minutes part has 1h less which means that it does not even adds up to the wrongly calculated total

To resolve the problem we obviously need to get rid of type conversion from double (ts.TotalHours) to int

But the questions are:

Why the calculations are wrong randomly (or this is just my impression)?
How to mimic the wrong calculation behavour in unit tests?

Based on this SO thread: https://stackoverflow.com/q/47302758/1498401 it seems that floating point calculation might be platform specific so additional information about server configuration:

There are 2 fronted servers with win 2k12r2

static int totalMinutesCounter { get; set; }

public static string GetFormatedTime(string s, out int minutesCounter)
{
    minutesCounter = 0;

    if (s == null)
    {
        return string.Empty;
    }

    int workedTimeMinutes = GetNumberOfMinutes(s);

    if (workedTimeMinutes < 0)
    {
        throw new ArgumentOutOfRangeException("workedTimeHours", "Negative values not allowed");
    }

    minutesCounter = workedTimeMinutes;

    TimeSpan ts = new TimeSpan(0, workedTimeMinutes, 0);

    return ((int)ts.TotalHours).ToString() + ts.ToString(@"\:mm");
}

static string GetFormatedTimeFromMinutes(int minutes, ref int minutesCounter)
{
    TimeSpan ts = new TimeSpan(0, minutes, 0);

    minutesCounter += minutes;

    return ((int)ts.TotalHours).ToString() + ts.ToString(@"\:mm");
}

private static int GetNumberOfMinutes(string s)
{
    if (string.IsNullOrWhiteSpace(s))
    {
        return 0;
    }

    char[] charSeparators = new char[] { ':' };
    string[] result = s.Split(charSeparators, StringSplitOptions.None);
    string sh = result[0].ToString();
    string sm = result[1].ToString();
    int hh = int.Parse(sh);
    int mm = int.Parse(sm);

    return mm + 60 * hh;
}

My unit test i would like to see failing ;)

[TestMethod]
public void TestMethod1()
{
    List<string> times = new List<string>()
    {
        "11:30","12:00","08:00","09:30","07:00","11:00","09:30","11:00","11:30","07:00","08:00","09:30","10:30","09:00","09:45","08:00","10:15","11:00","10:00"
    };

    for (int i = 0; i < 10000; i++)
    {
        foreach (var s in times)
        {
            int minutesCounter = 0;

            var rowValue = GetFormatedTime(s, out minutesCounter);

            totalMinutesCounter += minutesCounter;
        }

        int temp = 0;
        var result = GetFormatedTimeFromMinutes(totalMinutesCounter, ref temp);
        totalMinutesCounter = 0;

        Assert.AreEqual("184:00", result);
    }
}
```


texts: SQL/PHP Laravel - Looping through records to find relationships

texts:
I have two tables in my database, which contains a big list of organisations. They are called orgs_main and orgs_sub.  This is the structure:

orgs_main:

id | code | name | address |
----------------------------

orgs_sub:

id | code | name | address | merged |
-------------------------------------

orgs_main contains "main" organisations, which are identified by that they have a code starting with "64"

orgs_sub contains "sub" organisations, which are identified by they don't have a code starting with "64".

I need to find all the sub organisations, which have matching address to the main organisations, and then list them.

Example:

Broadway Avenue 110 (orgs_main)

Company 1 (orgs_main)
Company 2 (orgs_main)
Company 3 (orgs_main)
Sub company 1 (orgs_sub)
Sub company 2 (orgs_sub)

The way I am doing this now, is like this:

MergerController.php:

public function merger()
{
        //Select main organisations, that have matching addresses on sub-organisations and that is not already merged together.
        $MainOrganisations = DB::table("orgs_main AS j")
        ->selectRaw("DISTINCT j.address, (SELECT COUNT(*) FROM orgs_sub i WHERE i.address = j.address) AS SubCount")
        ->whereRaw("(SELECT COUNT(*) FROM orgs_sub i WHERE i.address = j.address AND i.merged=0) > 0")
        ->simplePaginate(10);

        //Loop through the main companies, so we get all main companies with the same address.
        foreach($MainOrganisations as $key => $SameAddress){
                $CompaniesSameAddress = DB::table('orgs_main')
                ->select('name', 'code')
                ->where('address', $SameAddress->address)
                ->where('code', 'LIKE', '64%')
                ->get();
                $SameAddress->Companies = $CompaniesSameAddress;
        }

        //Foreach found Main Organisation Address, list all the sub companies with this address.
        foreach($MainOrganisations as $key => $MainOrganisation){

            $SubOrganisations = DB::table('orgs_sub')
            ->select('name', 'code', 'id')
            ->where('address', $MainOrganisation->address)
            ->get();
            $MainOrganisation->SubOrganisations = $SubOrganisations;

        }
            //Return the data to our view.
            $data = [
              'MainOrganisations'            => $MainOrganisations,
            ];
            return $data;
}

My view file:

merger.list.blade.php:

    @foreach ($MainOrganisations as $Main)

            {{ $Main->address }}

            @foreach($Main->Companies as $Companies)
                {{$Companies->name}} (Code: {{ $Companies->code }})

            @endforeach

         @foreach($Main->SubOrganisations as $Sub)

                {{ $Sub->name }}
                {{ $Sub->code }}

        @endforeach

    @endforeach

Which shows something like this:

Any comments or alternatives methods is highly appreciated, as above code does function as intended, but it's quite slow and feel a bit "hackish" to me.

Thank you in advance!


texts: Finding the nth element of generalized Fibonacci sequences

texts:
I solved the Fibonacci Golf problem on checkio.org:

  The Fibonacci numbers or Fibonacci sequence are the numbers in the
  following integer sequence: 0, 1, 1, 2, 3, 5, 8, 13, 21...

  This is not the only interesting integer sequence however; there are
  many various sequences like the Fibonacci numbers, where each element
  is calculated using the previous elements. Let's take a look at a few
  of them. Described below are several integer sequences which you
  should try to implement:

fibonacci:
f(0)=0, f(1)=1, f(n)=f(n-1)+f(n-2)

tribonacci:
f(0)=0, f(1)=1, f(2)=1, f(n)=f(n-1)+f(n-2)+f(n-3)

lucas:
f(0)=2, f(1)=1, f(n)=f(n-1)+f(n-2)

jacobsthal:
f(0)=0, f(1)=1, f(n)=f(n-1)+2*f(n-2)

pell:
f(0)=0, f(1)=1, f(n)=2*f(n-1)+f(n-2)

perrin:
f(0)=3, f(1)=0, f(2)=2, f(n)=f(n-2)+f(n-3)

padovan:
f(0)=0, f(1)=1, f(2)=1, f(n)=f(n-2)+f(n-3)

  You are given the name of a sequence and a number "n". You should find
  the n-th element for that given sequence. In this mission the main
  goal is to make your code as short as possible. The system will check
  the length of your compiled code and assign a point value. The shorter
  your compiled code, the better. Your score for this mission is dynamic
  and directly related to the length of your code.

  For reference, scoring is based on the number of characters used. 1000
  bytes is the maximum allowable.

  Input: Two arguments. The name of a sequence as a string and a number
  "n" as a positive integer.

  Output: The n-th element of the sequence as an integer.

Who can make this better? My code is some bytes larger than it's supposed to be.

def fibgolf(type, n):
    if type=="fibonacci":
        a,b=0,1
        for i in range(n):
            a,b=b,a+b
        return a
    elif type == "tribonacci":
        a,b,c=0,1,1
        for i in range(n):
            a,b,c=b,c,a+b+c
        return a
    elif type == "lucas":
        a,b=2,1
        for i in range(n):
            a,b=b,a+b
        return a
    elif type == "jacobsthal":
        a,b=0,1
        for i in range(n):
            a,b=b,a*2+b
        return a
    elif type == "pell":
        a,b=0,1
        for i in range(n):
            a,b=b,b*2+a
        return a
    elif type == "perrin":
        a,b,c=3,0,2
        for i in range(n):
            a,b,c=b,c,a+b
        return a
    elif type == "padovan":
        a,b,c =0,1,1
        for i in range(n):
            a,b,c=b,c,a+b
        return a


texts:
This program prints odd numbers by thread1 and even numbers by thread2 sequentially. Can this code be optimized or made more efficient?

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

pthread_mutex_t count_mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t condition_var = PTHREAD_COND_INITIALIZER;

void *function_count1();
void *function_count2();

int count = 1;

int main()
{
    pthread_t thread1, thread2;
    int ret;

    if( (ret=pthread_create( &thread1, NULL, &function_count1, "thread1")) )
    {
        printf("Thread 1 creation failed: %d\n", ret);
        exit (EXIT_FAILURE);
    }

    if( (ret=pthread_create( &thread2, NULL, &function_count2, "thread2")) )
    {
        printf("Thread 2 creation failed: %d\n", ret);
        exit (EXIT_FAILURE);
    }

    pthread_join( thread1, NULL);
    pthread_join( thread2, NULL);

    exit(EXIT_SUCCESS);
}

void *function_count1(void *arg)
{
    while(count <= 10)
    {
        pthread_mutex_lock( &count_mutex );
        if (count % 2 != 0)
        {
            pthread_cond_wait(&condition_var, &count_mutex);
            printf("%s : counter = %d\n", (char *)arg, count++);
        }
        else
        {
            pthread_cond_signal(&condition_var);
        }
        pthread_mutex_unlock( &count_mutex );
    }
}

void *function_count2(void *arg)
{
    while(count <= 10)
    {
        pthread_mutex_lock( &count_mutex );

        if (count % 2 == 0)
        {
            pthread_cond_wait(&condition_var, &count_mutex);
            printf("%s : counter = %d\n", (char *)arg, count++);
        }
        else
        {
            pthread_cond_signal(&condition_var);
        }
        pthread_mutex_unlock(&count_mutex);
    }
}


texts: Calculate grades based on pass/fail percentage

texts:
Our school grading scale is from 1..10 with one decimal. If you do nothing you still get a grade of 1.0. A passing grade equals 5.5. A 'cesuur' percentage defines at what percentage of correct answers the 5.5 will be given to a student.

Examples:

List item
Grade(0,100,x) should always result in 1.0
Grade(100,100,x) should always results in 10.0
Grade(50,100,0.5) should result in 5.5

Questions: how can I simplify the code? How can I make it more robust?

Public Function Grade(Points As Integer, MaxPoints As Integer, Cesuur As Double) As Double
    Dim passPoints As Integer
    Dim maxGrade As Integer
    Dim minGrade As Integer
    Dim passGrade As Double
    Dim base As Double
    Dim restPoints As Integer
    Dim restPass As Double

    passPoints = Cesuur * MaxPoints
    maxGrade = 10
    minGrade = 1
    passGrade = (maxGrade + minGrade) / 2
    base = maxGrade - passGrade
    If Points < passPoints Then
        Grade = 1 + (passGrade - minGrade) * Points / passPoints
    Else
        restPoints = MaxPoints - Points
        restPass = MaxPoints * (1 - Cesuur)
        Grade = maxGrade - restPoints * base / restPass
    End If
    Grade = Round(Grade, 1)
End Function


texts:
I've made a JavaScript library that retrieves a Google Spreadsheet. It's something like Sheetrock.js, while mine is just a less powerful prototype.

I've uploaded the source code and example in GitHub. But you can just see the implementation and demo in JSFiddle. A sample spreadsheet is here.

Since I am not not a JavaScript professional, it just works, but I have no idea whether there is a misuse of JavaScript or a potential risk.

Can anyone give me a useful advice? I am focusing on a sort of violation of JavaScript standard or mechanism rather than a logical error on a flow.

spreadcell.js (My library)

function SpreadCell(params) {
  var is_undef = function(a) {
    return typeof(a) == "undefined"
  }
  if (is_undef(window.jQuery)) throw "jQuery must be loaded."
  if (is_undef(params.id)) throw "ID of the Google Spreadsheet must be specified."
  if (typeof(params.callback) != "function") throw "Callback must be a function."
  var table = {contain_header: !!params.contain_header}
  $.ajax({
    url: ("https://spreadsheets.google.com/feeds/cells/"
        + params.id + "/" + (params.sheet || "od6")
        + "/public/basic?alt=json"),
    success: function(response) {
      if (is_undef(response.feed)) throw "Invalid response. Maybe API changed."
      var get_RC = function(entry) {
        var idx = entry.id.$t.lastIndexOf("/");
        if (idx == -1) throw "Malformed entry. Maybe API changed.";
        return entry.id.$t.substr(idx + 2).split("C").map(Number);
      }
      var data = response.feed.entry
      var len = data.length
      table.dim = get_RC(data[len - 1])
      var raw = [];
      for (var i = 0; i < table.dim[0]; i++) {
        raw[i] = new Array(table.dim[1])
      }
      for (var i = 0; i < len; i++) {
        var RC = get_RC(data[i]);
        raw[RC[0] - 1][RC[1] - 1] = data[i].content.$t;
      }
      table.name = response.feed.title.$t
      if (table.contain_header) table.header = raw.slice(0, table.contain_header)
      table.body = raw.slice(table.contain_header)
      table.dim[0] -= table.contain_header
      delete table.contain_header
      params.callback(table)
    }
  })
  return table
}

index.html (Test sample)

<head>
<title>spreadcell.js</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script src="https://gsongsong.github.io/spreadcell-js/js/spreadcell.js"></script>
<script>
var callback = function(obj) {
  console.log(obj)
  console.log(news)
}
</script>
</head>

<body>

<script>
var news = new SpreadCell({id: "17EwNIgGf9YqVUgl0WQftCJybGy2cYlKk7PKeJi0T3qU",
                          contain_header: false,
                          callback: callback});
</script>

</body>


texts: Using events together with interfaces in VBA

texts:
Introduction
Because of the limitation of VBA in using events in interfaces I was searching for a kind of workaround.
For sure I also read this which also provides an approach, but I was searching for an easier way.
I ended up with the following solution.

The idea behind
Instead of defining the events directly in an interface - because it is not possible to use them in an implementing class in VBA - I use an additional 'event' class, where all necessary events will be placed in, and which will be injected into the interface implementing classes.

Naming of the event class
I'm aware of that this class is not really used as an interface, but it only should be used with the regarding interface.
So I named it also with an I prefix.
Another benefit of this is that it will be listed beneath the regarding interface.

Circular references
The worker object is provided with the event on purpose.
As long as it is used in the event handler with care, that means, it should not be stored anywhere else, there shouldn't be any risk regarding circular references.

The interfaces

IWorker

Option Explicit

Public Property Set Events(ByRef value As IWorkerEvents)
End Property

Public Sub Work()
End Sub

IWorkerEvents

Option Explicit

Public Event Notify(ByRef worker As IWorker, message As String)

Public Sub Notify(ByRef worker As IWorker, message As String)
    RaiseEvent Notify(worker, message)
End Sub

The implementations

Worker1

Option Explicit

Implements IWorker

Private Type TWorker
    Events As IWorkerEvents
End Type

Private this As TWorker

Private Property Set IWorker_Events(RHS As IWorkerEvents)
    Set this.Events = RHS
End Property

Private Sub IWorker_Work()
    Debug.Print "Worker 1 works hard."
    Notify "is working..."
End Sub

Sub Notify(ByVal message As String)
    If Not this.Events Is Nothing Then
        this.Events.Notify Me, message
    End If
End Sub

Worker2

Option Explicit

Implements IWorker

Private Type TWorker
    Events As IWorkerEvents
End Type

Private this As TWorker

Private Property Set IWorker_Events(RHS As IWorkerEvents)
    Set this.Events = RHS
End Property

Private Sub IWorker_Work()
    Debug.Print "Worker 2 works hard."
    Notify "is working..."
End Sub

Sub Notify(ByVal message As String)
    If Not this.Events Is Nothing Then
        this.Events.Notify Me, message
    End If
End Sub

Building it together

TestClass

Option Explicit

Dim WithEvents workerEvents As IWorkerEvents

Sub Test()
    Dim worker As IWorker

    Set workerEvents = New IWorkerEvents

    Set worker = New worker1
    Set worker.Events = workerEvents
    worker.Work

    Set worker = New worker2
    Set worker.Events = workerEvents
    worker.Work
End Sub

Private Sub workerEvents_Notify(worker As IWorker, message As String)
    Debug.Print "TestClass says:", TypeName(worker), message
End Sub

TestModule

Option Explicit

Sub Test()
    With New testClass
        .Test
    End With
End Sub

Output

Worker 1 works hard.
TestClass says:             Worker1       is working...
Worker 2 works hard.
TestClass says:             Worker2       is working...


texts: Calculating the biggest number of consecutive ones in a binary number

texts:
The following code calculates the biggest number of consecutive ones in a binary representation of a number. For example 6 -> 2 (110), 5 -> 1 (101):

String numberAsBinaryString = Integer.toBinaryString(number);
List<String> listOfConsecutiveOneStrings = Arrays.asList(numberAsBinaryString.split("0"));

System.out.println(listOfConsecutiveOneStrings.stream()
                                                  .max(Comparator.comparing(String::length))
                                                  .map(onesSequence -> onesSequence.length())
                                                  .get());

I wonder if there is a more elegant way of writing this especially since this solution involves quite a few conversions. Any opinions are appreciated.


texts:
I've been trying to write a really basic function to determine the difference (in days) between two dates. I am very new to C++ so as you can imagine I am very happy with my work.
This function is part of a much larger code so I have missed off my includes, but the function does compile without warnings.

Just looking for some constructive criticism that a reasonable beginner can take on board.

I should add, this function takes two dates as strings in British format DD/MM/YYYY.

int dateDiffs(std::string date1, std::string date2){

    int startYear, endYear;
    int startMonth, endMonth;
    int startDay, endDay;

    int startInDays, endInDays;

    std::map<int,int> daysInMonth;

    daysInMonth[1]=31;
    daysInMonth[2]=28;
    daysInMonth[3]=31;
    daysInMonth[4]=30;
    daysInMonth[5]=31;
    daysInMonth[6]=30;
    daysInMonth[7]=31;
    daysInMonth[8]=31;
    daysInMonth[9]=30;
    daysInMonth[10]=31;
    daysInMonth[11]=30;
    daysInMonth[12]=31;

    startYear = atoi(date1.substr(6,4).c_str());
    startMonth = atoi(date1.substr(3,2).c_str());
    startDay = atoi(date1.substr(0,2).c_str());

    endYear = atoi(date2.substr(6,4).c_str());
    endMonth = atoi(date2.substr(3,2).c_str());
    endDay = atoi(date2.substr(0,2).c_str());

    startInDays = (startYear * 365) + (startMonth * daysInMonth[startMonth]) + startDay;
    endInDays = (endYear * 365) + (endMonth * daysInMonth[endMonth]) + endDay;

    return (endInDays - startInDays);
}


texts:
I have this grouping thing, which is would be a switch case if it weren't for the ranges or a Counter of some sorts, but as there are those ranges I don't know how to implement this any more efficiently.

def getGroups(user_array):
    # group1 is group 1-10 x
    group1 = 0
    # group2 is group 10-50 x
    group2 = 0
    # group3 is group 50-100 x
    group3 = 0
    # group4 is group 100-200 x
    group4 = 0
    # group5 is group 200-500 x
    group5 = 0
    # group6 is group 500 - 1000 x
    group6 = 0
    # group7 is group 1000+ x
    group7 = 0

    for user in user_array:
        if user.x_count == 0:
            pass
        elif user.x_count <= 10:
            group1 += 1
        elif user.x_count <= 50:
            group2 += 1
        elif user.x_count <= 100:
            group3 += 1
        elif user.x_count <= 200:
            group4 += 1
        elif user.x_count <= 500:
            group5 += 1
        elif user.x_count <= 1000:
            group6 += 1
        else:
            group7 += 1
    return [group1, group2, group3, group4, group5, group6, group7]


texts: Generic pass_many(vals, pass_one) to unroll and call pass_one(val)

texts:
I'm trying to create a generic function that takes a data structure as input and then sends each non-empty item—e.g.: str, int—individually:

def print_this(v, delim1="", delim2=""):
    print v, delim1, delim2

def pass_many(vals, some_funct, args=None):
    if vals:
        if type(vals) == list or type(vals) == tuple:
            for v in vals:
                if v:
                    pass_many(v, some_funct, args)
        else:
            if args:
                some_funct(vals, *args)
            else:
                some_funct(vals)

>>> pass_many([['foo'],['',(5,3)]], print_this, ["newline","notnewline"])
foo newline notnewline
5 newline notnewline
3 newline notnewline

My current implementation works reasonably well, but feels hacky...

How could I generalise it to unroll all data-structures (except strings), and make it less hacky?


texts: Idiomatic Ruby if/else in a Sinatra route

texts:
Apologies if this question doesn't fit the format here, seemed more appropriate here than SO due to the more nebulous nature of the question.
Think mini tinyURL clone: POST to service to save the url + hash, then look up the mapping when visiting /anything. It's been a while since I've touched Ruby, and the resulting code snippet is not easy on the eyes:
require 'sinatra'
require 'mongoid'
require 'digest'

class MinifiedUrl
  include Mongoid::Document

  field :code, type: String
  field :original_url, type: String
end

# Redirect to the actual url, like tinyurl.com/abcdefg
get '/:code' do
  link = MinifiedUrl.where(:code => params[:code]).first # .first is falsy if there is no mapping
  if link
    puts "Found minified link"
    redirect link[:original_url], 302
  else
    puts "No minified link"
    redirect '/404', 404
  end
end

# Create a mapping from a POST request like { url: 'https://google.com/ '}
post '/' do
  incoming_url = params[:url]

  link = MinifiedUrl.where(:code => params[:code]).first
  # Reassign link if link is falsy
  link = MinifiedUrl.create(:target_url => incoming_url, :code => Digest::MD5.hexdigest(incoming_url)[0..5]) unless link

  link[:slug]
end

Is there an obvious way to make the code more idiomatic? My concern is multiple calls to MinifiedUrl model / reassigning value of link. I can't put my finger on it, but it doesn't feel ruby-like.


texts: Finding the two largest three digit numbers missing from a text file

texts:
Hear this problem: Write a C/C++ program that reads all the values from the "BAC.TXT" file and determines which are the two largest three digit numbers that are missing from the file using a time-efficient algorithm. This is the code that I wrote and it returned good values for all the input sets I tried:

#include <iostream>
#include <fstream>

using namespace std;

int main()

{   ifstream in("BAC.TXT");

    unsigned int a[1000], missing_numbers[2];
    unsigned int data, i = 0, j = 0, found_missing_numbers = 0;

    while(!in.eof())
    {   in >> data;

        if (data >= 100 && data <= 999)
            a[data] = 1;
    }

    for(i=999;i>=100;i--)
    {if(a[i]!=1)
    {   missing_numbers[j] = i;
        found_missing_numbers++;
        j++;
    }
    if (found_missing_numbers == 2)
        break;
    }

    if (found_missing_numbers == 2)
    {
        cout << "The two largest numbers of three digits that are missing from the file are:";
        cout << missing_numbers[0] << " and " << missing_numbers[1];
    }
    else if (found_missing_numbers == 1)
        cout << "Only one three digit number is missing from the file:" << missing_numbers[0];
    else
        cout << "There are no three digit numbers missing from the file.";

    cin.get();

    in.close();

    return 0;
}

Example of Input:

  125 88556 2534 12 456668 12 56324 4521 3 652 999 94 24521 6524 1112 125 997 12315 122 54 9 5546 754 998 12312 12152 745 2354 856 124 956 125 88556 2534 12 456668 12 56324 4521 3 652 999 94 24521 6524 1112 125 997 12315 122 54 9 5546 754 998 12312 12152 745 2354 856 124 956 125 88556 2534 12 456668 12 56324 4521 3 652 999 94 24521 6524 1112 125 997 12315 122 54 9 5546 754 998 12312 12152 745 2354 856 124 956 125 88556 2534 12 456668 12 56324 4521 3 652 999 94 24521 6524 1112 125 997 12315 122 54 9 5546 754 998 12312 12152 745 2354 856 124 956 125 88556 2534 12 456668 12 56324 4521 3 652 999 94 24521 6524 1112 125 997 12315 122 54 9 5546 754 998 12312 12152 745 2354 856 124 956 125 88556 2534 12 456668 12 56324 4521 3 652 999 94 24521 6524 1112 125 997 12315 122 54 9 5546 754 998 12312 12152 745 2354 856 124 956 125 88556 2534 12 456668 12 56324 4521 3 652 999 94 24521 6524 1112 125 997 12315 122 54 9 5546 754 998 12312 12152 745 2354 856 124 956 125 88556 2534 12 456668 12 56324 4521 3 652 999 94 24521 6524 11

Output:

  The two largest numbers of three digits that are missing from the file are:996 and 995

I consider the code quite efficient because the file is read a single time and it selects and works only with the data that could help to find the solution. I would like to hear your opinion, other suggestions, all that you consider that could make this solution more efficient.

P.S. I am a beginner in programming, don't know any OOP for the moment. I know the code I wrote is something like C with cout and cin...not C++. Don't kill me. This question is based on the same problem that I was solving here, but now I have a working solution. Now it's only a matter of optimisation.


texts: Function to represent an integer in a base

texts:
This function represents an integral type and represents it in a base.

#include <type_traits>
#include <limits>
#include <array>
#include <iterator>

namespace detail {

template <class Integral>
char n_to_digit(Integral n) {
    static const char * digits = "0123456789abcdefghijklmnopqrstuvwxyz";
    return digits[n];
}

/// This implementation is called if Integral is unsigned
template <unsigned Base, class Integral, class OutputIterator>
std::size_t integral_to_base_impl(Integral n, OutputIterator dst_it, std::true_type) {
    /// Length of str is the minimum number of bits to store Integral which is
    /// the number of chars required to store the maximum value of in base 2
    /// representation
    std::array<char, (sizeof(Integral) << 3)> str;
    auto it = str.begin();

    do {
        *it++ = n_to_digit(n % Base);
        n /= Base;
    } while (n != 0);

    while (it != str.begin()) {
        *dst_it++ = *(--it);
    }

    return std::distance(str.begin(), it);
}

/// This implementation is called if Integral is signed
template <unsigned Base, class Integral, class OutputIterator>
std::size_t integral_to_base_impl(Integral n, OutputIterator dst_it, std::false_type) {
    std::size_t length = 0;

    if (n < 0) {
        *dst_it++ = '-';
        ++length;
    }

    length += integral_to_base_impl<Base>(std::abs(n), dst_it, std::true_type());
    return length;
}

}

/// Represents an integral in a certain base
///
/// @tparam Base The base that the integral will be represented as
///
/// @param n The number that will be represented
/// @param dst_it A char OutputIterator that the representation will be written to
///
/// @return The length of the representation
template <unsigned Base, class Integral, class OutputIterator>
std::size_t integral_to_base(Integral n, OutputIterator dst_it) {
    static_assert(2 <= Base && Base <= 36, "Base must be >= 2 and <= 36");
    static_assert(std::is_integral<Integral>::value, "n must be an integral type");

    return detail::integral_to_base_impl<Base>(n, dst_it,
        std::integral_constant<bool, std::is_unsigned<Integral>::value>());
}

My implementation is like the C's non standard function itoa however it takes the base is taken as a template parameter which allow the compiler to make optimizations with operations involving the base such as modulo and divide however it must be known at compile time. This allows integrals to represented as binary and hexadecimal with the Base template parameter being 2 and 16 respectively.

The function integral_to_base has implementation specializiations for unsigned and signed integral types and has static assertions to check that the base is valid at compile time for safety.

Example usage:

int main() {
    std::string test;

    integral_to_base<10>(123343, std::back_inserter(test));
    std::cout << test << std::endl; //prints 123343
}


texts: Threadsafe get method on queue that draws values from other queues?

texts:
I have a class that implements Queue and draws values from other queues which may still be referenced outwith it. I want my method to draw values from the contained queues, using synchronized locks on them to ensure thread safety with other code that uses synchronized locks on the queues.

The way I've tried to achieve this is by having my method loop through all values indefinitely, storing the value if it's the next one, updating the stored values if it reaches the same queue again and the variables the queues are being measured by have changed since the list iteration, and returning the next value of the queue if it's unchanged since the last time it was checked and evaluated to have the next value - my logic being that at that point, all queues have been checked and the currently stored value/queue was checked earliest and has been reconfirmed to be the next value.

Is this the ideal way to create a thread-safe version of this method? Or would there be a better way?

http://pastebin.com/TSkiJFh0

Collection<Queue<T>> memberQueues;
final Lambda<T, Comparable> keyGetter;

public T get(boolean remove)
{
    // workaround to ensure thread-safety when synchronized locks can't extend past the block they're declared in.

    // Work on a copy of memberQueues
    List<Queue<T>> memberQueuesCopy;

    synchronized(memberQueues)
    { memberQueuesCopy = new ArrayList<Queue<T>>(memberQueues); }

    // Declare variables and initialise with last member of memberQueuesCopy.
    // If it checks every variable and the last one is next, then I don't think I need to check again.
    Queue<T> nextQueue = memberQueuesCopy.get(memberQueuesCopy.size() - 1);
    T nextValue = nextQueue.peek();
    Comparable nextValueComparable = keyGetter.getMember(nextValue);

    // Check all members of memberQueuesCopy. Find the lowest and hold the value until it gets to it again incase
    // any values have changed. When it gets back to the current lowest value, check whether the value it's being
    // sorted by has changed - and if it has, use its new values and run through all members again. If it hasn't,
    // return it.

    // I want a less contrived method. Suggestions that maintain thread safety?
    for(;;)
    {
        for(Queue<T> i : memberQueuesCopy)
        {
            synchronized(i)
            {
                T iValue = i.peek();
                Comparable iComparable = keyGetter.getMember(iValue);

                if(i == nextQueue)
                {
                    if(nextValue == iValue && nextValueComparable.equals(iComparable))
                    {
                        if(remove)
                            return nextQueue.remove();
                        else
                            return iValue;
                    }

                    nextValue = nextQueue.peek();
                    nextValueComparable = keyGetter.getMember(nextValue);
                }
                else
                {
                    if(iComparable.compareTo(nextValueComparable) < 0)
                    {
                        nextQueue = i;
                        nextValue = iValue;
                        nextValueComparable = iComparable;
                    }
                }
            }
        }
    }
}


texts:
Here's my JavaScript file that queries data from Parse and then updates my Handlebars.js template to display them. The code has 3 async calls using a Promise. It still feel like it could be improved, specifically in the Promises results loop where I check which i value it is. I'm not guaranteed that the bar we're on in the first loop is the same as in the second or third loop, which is why I have the nested loop checking if the names are the same to ensure it's the right one. Could I order them all alphabetically or something so that I can eliminate that? It seems like a lot of repeated code.

$(document).ready(function(){

google.maps.event.addDomListener(window, 'load', initialize);

function initialize() {

  Parse.initialize("ID","ID");
  var latlng = new google.maps.LatLng(42.035021, -93.645);

  var mapOptions = {
    center: latlng,
    scrollWheel: false,
    zoom: 13
  };

  var map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);

  // The Handlebars template for a bar item
  var source = $("#barTemplate").html();
  var template = Handlebars.compile(source);

  // Object containing the list of bars
  var data = new Object();
  var barList = new Array();

  // Build an array of Parse queries
  var queries = [];

  var Bar = Parse.Object.extend("Bars");
  var Deals = Parse.Object.extend("Deals");
  var Photos = Parse.Object.extend("BarPhotos");

  queries.push(new Parse.Query(Bar).find())
  queries.push(new Parse.Query(Deals).find())
  queries.push(new Parse.Query(Photos).find())

  // Wait for them all to complete
  Parse.Promise.when(queries).then(function() {

      // The results of each query are returned as arguments to the callback
      for(var i = 0, l = arguments.length; i < l; i++) {
          if (i == 0) {

            // Add the retrieved bars to the map
            for (var j = 0; j < arguments[i].length; j++) {
              var bar = arguments[i][j];
              var latlng = new google.maps.LatLng(bar.get('lat'), bar.get('long'));

              var marker = new google.maps.Marker({
                position: latlng,
                map: map,
                animation: google.maps.Animation.DROP
              });

              barList.push({"name": bar.get('name'), "deals": [], "img": ""});
            }

            // Add the retrieved deals to the bar
            for (var j = 0; j < arguments[i+1].length; j++) {
              var bar = arguments[i+1][j];
              var barName = bar.get('name');
              var dealsArr = new Array();
              var arr = bar.get('Monday');

              for (var k = 0; k < arr.length; k++) {
                dealsArr.push({"deal": arr[k]});
              }

              // Loop through bars to find match
              for (var l = 0; l < barList.length; l++) {
                if (barList[l].name == barName) {
                  // Update the deals array property
                  barList[l].deals = dealsArr;
                }
              }
            }

            // Add the retrieved images to the bar
            for (var j = 0; j < arguments[i+2].length; j++) {
              var bar = arguments[i+2][j];
              var barName = bar.get('barName');
              var imageFile = bar.get('imageFile');
              var imageURL = imageFile.url();

              // Loop through bars to find match
              for (var l = 0; l < barList.length; l++) {
                if (barList[l].name == barName) {
                  // Update the image property
                  barList[l].img = imageURL;
                }
              }
            }
          }

      }

      // Update template with bars
      data = {bars: barList};
      $("#barList").html(template(data));
  });
};
});


texts: Sorting 10,000 unique randomly-generated numbers

texts:
I have to write this program in java.

  Write a program name sorting.java that will use an array to store 10,000 randomly generated numbers (ranging from 1 to 10,000 no repeat number).

Here is what I have so far:

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

        Random rgen = new Random();  // Random number generator
        int[] nums = new int[10,000];  //array to store 10000 random integers (1-10,000)

        //--- Initialize the array to the ints 1-10,000
        for (int i=0; i<nums.length; i++) {
            nums[i] = i;
        }

        //--- Shuffle by exchanging each element randomly
        for (int i=0; i<nums.length; i++) {
            int randomPosition = rgen.nextInt(nums.length);
            int temp = nums[i];
            nums[i] = nums[randomPosition];
            nums[randomPosition] = temp;
        }

        //Print results
        for (int i = 0; i < nums.length; i++){
        System.out.println(nums[i]);
        System.out.println("\n");
    }
}


texts:
I have the following model:

namespace Site.Models.Country
{
    public class Country
    {
        public string CountryCode { get; set; }
        public string CountryName { get; set; }
        public string CountryUrl { get; set; }
    }
}

In a separate model folder for a different view and controller, I have a different model like this:

namespace Site.Models.Directory
{
    public class DirectoryProfileView
    {
        public List<Country> Countries { get; set; }

        public DirectoryProfileView()
        {
            this.Countries = new List<Country>(Country.GetCountryRegions());
        }
    }
}

Is it correct for me to use the Country model from a different model ?  I tried adding using Site.Models.Country;

However for the following to work:

public List<Country> Countries { get; set; }

I need to call by

public List<Country.Country> Countries { get; set; }

My two questions are:

Is this correct?  I don't really want to be creating another model exactly like my first Country model.
Also, any feedback on my naming conventions would be appreciated too.


texts: Vertically and horizontally center these HTML elements

texts:
I have an image and a text title that I'm trying to center in a div.  I would like the image to be to the left of the title, and for both of these elements to be centered both horizontally and vertically in the div.

I've found one way to do it, by nesting the image inside of a paragraph.  I'm assuming this is not the proper way to do it, but I haven't been able to figure out any other way.

Here is a jsfiddle:  http://jsfiddle.net/FvpV3/

And here is the code:

Title

message

Does anyone know of a better way to position the image and title?


texts:
I am learning how to do object-orientated programming in JS. In particular, I am learning about the constructor pattern.

In an attempt to exercise what I have been learning, I made this:

var assert = require("assert");

var Book = (function() {
  // private static variable (why this exhibits static behaviour, I have no clue)
  var books = [];

  var constructor = function(doc) {
    // guard clauses
    assert.ok(doc.title, "title cannot be undefined");
    assert.ok(doc.author, "author cannot be undefined");
    assert.ok(doc.genre, "genre cannot be undefined");

    // public properties
    this.title = doc.title;
    this.author = doc.author;
    this.genre = doc.genre;
    this.read = doc.read || false;
    this.id = books.length;
    this.description = this.title + " is a " + this.genre + " by " + this.author;

    // public function
    this.save = function() {
      books.push(this);
    };
  };

  // public static functions
  constructor.findById = function(id, callback) {
    function cloneBook(book) {
      return {
        id: book.id,
        title: book.title,
        author: book.author,
        genre: book.genre,
        read: book.read
      };
    }
    var book = books.filter(function(book) {
      return book.id === id;
    })[0];
    var clone = cloneBook(book);
    clone.save = function() {
      book.title = this.title;
      book.author = this.author;
      book.genre = this.genre;
      book.read = this.read;
    };
    callback(clone);
  };

  constructor.find = function(conditions, callback) {
    function areNoConditions(obj) {
      return Object.keys(obj).length === 0;
    }
    if (areNoConditions(conditions)) {
      callback(books);
      return;
    }
    var foundBooks = [];
    for (var prop in conditions) {
      books.forEach(function(book) {
        if (book[prop] === conditions[prop]) {
          foundBooks.push(book);
        }
      });
      callback(foundBooks);
    }
  };

  // return the function (the constructor)
  return constructor;
}());

...

var book = new Book("The Great Gatsby", "F. Scott Fitzgerald", "Novel");
book.save();
var books = Book.find();
book.read = false;
book.save();
console.log(books);

My aim was to emulate the Mongoose Model API.

My particular concerns are:

Is the constructor pattern the most applicable pattern here?
Is my code idiomatic?

I have decorated my code with comments for the purposes of this answer so you can know what I am thinking. I come from a C# background.


texts:
I am just trying to convert each list of values to String by index one by one. My Code is running fine. But I am thinking that I can write better code than this. I Need your good coding possibilities here to convert from list to String.

I am using the code below to convert:

CarComment[] list = form.getCarDataJaxb().getCarCommentList();
JSONObject obj = new JSONObject();
JSONArray comments = new JSONArray();
for (int i=0;i<list.length;i++){
    if (notEmpty(list[i].getText())){
        JSONArray commObj = new JSONArray();

        String str = list[i].getText();
        str = str.replaceAll("<", "&lt;");
        commObj.put(str);

        comments.put(commObj);
    }
}
obj.put("carcomm", comments);
response.setContentType("text/json");
response.getWriter().write(obj.toString());

I am trying to write good coding technique while converting from list to String at line
String str = list[i].getText();


texts:
This is an interview question from here. Specifically, the second asked for a function that took in two sorted arrays of integers with no duplicate values within a single array and which returned an array of the duplicates between the two arrays.

Here is my solution (with tests):

public class ArrayDuplicates {
     public static void main(String[] args) {
          int[] sorted1 = {1, 2, 3, 5, 7};
          int[] sorted2 = {2, 4, 5, 6};
          Integer[] duplicates = duplicates(sorted1, sorted2);
          for(Integer d: duplicates) {
            System.out.println(d.intValue());
           }
      }
     public static Integer[] duplicates(int[] sorted1, int[] sorted2) {
            List<Integer> duplicates = new ArrayList<Integer>();
            for(int count = 0; count < sorted1.length; count ++) {
                  for(int counter = 0; counter < sorted2.length; counter ++) {
                       if(sorted1[count] == sorted2[counter]) {
                            duplicates.add(sorted1[count]);
                       } else if(sorted1[count] < sorted2[counter]) {
                          break;
                       }
                   }
             }
    return duplicates.toArray(new Integer[duplicates.size()]);
    }
}

The code runs fine but I am trying to make it more efficient. I did a runtime analysis of the duplicates method and found the runtime to be in \$O(N^2)\$ (general nested for loop, etc). To me, there always seems to be some optimization to get the algorithm to \$O(n)\$. For this problem, the only optimization, I found was to break out of the while loop if the value in the second array is greater than the first (because you know it's sorted, so there's no way that value is present in the second array).

Is there another optimization that could get this code down to \$O(n)\$?


texts: Infinitely iterable list class in Python

texts:
itertools.cycle is cool, but it has an internal "storage" that uses up memory. And I wanted to practice "tampering" with built-in methods of classes, which is a new field for me. I tried to implement a class which mostly behaves like a list, but when we try to iterate over it (with for loop, for example), it would jump back to the beginning when it reaches the end, therefore cycling indefinitely. Here's what I've come up with:

class InfiniteListEmptyError(Exception):
    pass

class InfiniteList(list):
    """
    Pretty much a regular list, but when iterated over, it does not stop in the end.
    Instead, it iterates indefinitely.
    """

    def __init__(self, arg):
        super(InfiniteList, self).__init__(arg)

    def __getattr__(self, name):
        if name == "it":
            # get iterator
            result = object.__getattribute__(self, name)
        else:
            try:
                result = super(InfiniteList, self).__getattribute__(name)
            except AttributeError:
                try:
                    result = self.it.__getattribute__(name)
                except AttributeError:
                    # Initialize iterator cuz it's not initialized
                    self.__iter__()
                    result = self.it.__getattribute__(name)
        return result

    def __iter__(self):
        it = super(InfiniteList, self).__iter__()
        self.it = it
        return self

    def __next__(self):
        try:
            result = next(self.it)
        except StopIteration:
            self.__iter__()
            try:
                result = next(self.it)
            except StopIteration:
                raise InfiniteListEmptyError("Could not iterate. List is empty!")

        return result

# TESTS

a = InfiniteList(tuple()) #empty list

print(a)
print(a.__length_hint__()) #testing iterator attributes
print(a.__eq__([1,3,5])) # false

# should raise exception, since the list is empty
try:
    for i in a:
        print(i)
except InfiniteListEmptyError:
    print("List is empty!")

a.append(1)
a.extend([3,5])
print(a)
print(a.__eq__([1,3,5])) #true

# infinite loop
for i in a:
    print(i)

It works fine, it does not store an auxiliary list, so it does not consume twice as much memory, like itertools.cycle. But I'm not sure about the possible caveats when it comes to handling attributes. And yeah, I had to implement iterator within the InfiniteList class itself, so I had to redirect the calls to iterator's methods (like __length_hint__) to the saved iterator self.it.


texts: Draft version of wind farm design software

texts:
I'm currently working on a wind farm design software and basically I have to analyze the incidence of certain wind turbines on other downwind, in order to calculate the velocity drop in the wind once the downstream turbine "sees" the flow.

I have sorted out most of the code and it works, yet this particular piece of it is extremely slow to compute.

for wd in wind_direction_index:
        self.list_for_speed.append([])
        for ws in wind_speed_index:
            self.list_for_speed[wd].append([])
            wind_speed = self._wind_speeds[ws]
            #For every wind turbine, remember this list is still ordered from up to dow
            dummylist=copy.deepcopy(self.list_for_direction[wd])
            for WT in dummylist:
                #Replace No deficit with 0
                if WT[6]=='NO_deficit':
                    WT[6]=[0.0]
                else:
                    pass
                #For every WT that causes a wake effect on current one
                for upWT in WT[3]:
                    #Define current turbine and rotating upwind turbine
                    for ready in dummylist:
                        if upWT[0]==ready[0]:
                            upWT[6]=ready[6]
                        else:
                            pass
                    current_turbine=WT
                    upwind_turbine=upWT
                    #Calculate wind speeds deficits in every current WT due to every upwind WT to it only if here are upwind WTS
                    if len(current_turbine[3])!=0:
                        self.calculate_deficits(current_turbine,upwind_turbine,wind_speed)
                    else:
                        pass
                #Now we have appended all deficits in current_turbine(6) Time to add them up, find the speed and replace
                #First, I square the list of deficits
                WT[6]=[i**2 for i in WT[6]]
                #Now, i add the squares of the deficits
                deficit_squared=sum(WT[6])
                #Take the square root
                deficit_current=sqrt(deficit_squared)
                #Finally calculate wind speed at the rotor
                U=wind_speed*(1-deficit_current)
                #And I replace the list of wind speed deficits with the wind speed at the rotor
                WT[6]=U
                _Ct=self.team.rna_analysts.get_Ct(U)
                #Save results to local wind speeds array
                self.local_wind_speeds[WT[0]][wd][ws]=[U,_Ct]
            self.list_for_speed[wd][ws].append(dummylist)

I know it's a bit messy, but you can see more or less how my data structures are arranged. I have to calculate a wind speed "deficit" for every turbine, based on the wind direction and the wind speed (evidenced by local_wind_speeds). Can anyone spot how to make this piece of code much much faster?


texts:
I have an array of objects arr. One object looks like this:

obj = {
  name: 'name'
  email: 'email'
}

And then I have an array with strings (emails)

var excludedEmails = ['email1','email2',...]

I want to filter the excluded emails out of the arr.

Is there a better/faster way than this in VanillaJS (I am assuming the strings in excludedEmails are all upper case:

var filteredPersons = []
arr.forEach(function(person){
      if(!excludedEmails.includes(person.email.toUpperCase())){
        filteredPersons.push(person);
      }
})


texts: Script for adding a set of form fields on clicking an Add More button

texts:
This is a script that I use to add a set of form fields on clicking an Add More button:

This is the form:

                    Add More Field

                    Item:	Quantity:	Price:	Discount %	VAT %:	Final Price:

                    <input class='item form-control' id="find" type='text'  name='item[]' required>
                    <input class='qty form-control' id="find" type='number' name='qty[]' required>
                    <input class='price form-control' id="find" type='number' name='price[]' required>
                    <input class='discount form-control' id="find" type='number'  name='discount[]' required>
                    <?php $query = mysqli_query($con, "SELECT * FROM `tax_vat` "); echo '<select name="vat" id="find" data-required="true"><option value="">Select Vat</option>"';while ($row = mysqli_fetch_array($query)) {echo '<option value="' . $row['vat_rate'] . '">' . $row['vat_description'] . '</option>
';}echo '</select>';?>
                    <input class='total form-control' id="find" type='number' name='total[]' readonly required>

            Total : <input id='totaldp' class="form-control" type='number' name='totaldp' readonly required>
            <input type="hidden" id="name_id" name="name_id" />

In the form, there is a dropdown box which fetch certain details from the database. The PHP code to fetch and display the dropdown box is coded in the form so that it is displayed on the initial load of the page, and then, the same code is coded in the append function the script so that the same set of input fields are displayed on clicking the Add More button.

The whole thing works perfectly fine. But the code looks terribly ugly. Is there a better way to do it?


texts:
I have implemented the "Sum All Numbers in a Range" challenge from Free Code Camp quoted below.
The code works like a charm, but I don't think it's idiomatic. The challenge hints imply I should be using Math.max(), Math.min() and Array.reduce(). In addition I used the spread operator from ES6 to simplify both Math calls.
I'm looking for a more idiomatic way to solve this. I think it can be done in a one-liner, something like:
return arr.sort((function(a, b) { return a - b; })).reduce(function(a, b) { /* */ });

But I'm pretty sure I'm heading the wrong way with the above.
The challenge:

We'll pass you an array of two numbers. Return the sum of those two numbers and all numbers between them.
The lowest number will not always come first.

The code:
function sumAll(arr) {
  var out = 0;
  for (var i = Math.min(...arr); i <= Math.max(...arr); i++) {
    out += i;
  }
  return out;
}

Test cases:
sumAll([1, 4])
sumAll([4, 1])
sumAll([5, 10])
sumAll([10, 5])

Expected output:
10
10
45
45


texts: Julia RPN calculator algorithm ported from Python version

texts:
I've just finished the Reverse Polish Notation task in Julia from rosettacode.com by porting the existing Python code.

There are only a few lines I don't get how to port:

maxcolwidths = [max(len(y) for y in x) for x in zip(*rp)]

and the subsequent lines that use maxcolwidths.

I managed to pretty print the test output anyway, but I'd really love to hear any opinions from you.

ops = [
    :^ => :op_pow,
    :* => :op_mul,
    :/ => :op_div,
    :+ => :op_add,
    :- => :op_sub
]

for (op, func) in ops
    @eval function ($func)(stack)
        b = pop!(stack)
        a = pop!(stack)
        push!(stack, ($op)(a, b))
    end
end

input(prompt::String="") = (print(prompt); inp = chomp(readline()))
get_input(inp::String=input("Expression: ")) = (tokens = split(inp, ' '))

function rpn_calc{T<:String}(tokens::Vector{T}=get_input())
    stack = {}
    table = ["TOKEN" "ACTION" "STACK"]
    for token in tokens
        sym = symbol(token)
        if sym in keys(ops)
            action = "Apply op to top of stack."
            @eval $(ops[sym])($stack)
        else
            action = "Push num onto top of stack."
            push!(stack, parse(token))
        end
        table = [table; token action  join([string(s) for s in stack], ' ')]
    end
    return table
end

function test_rpn(rpn::String="3 4 2 * 1 5 - 2 3 ^ ^ / +")
    println("For RPN expression: $rpn")
    table = rpn_calc(get_input(rpn))
    i = 1
    n_rows = length(table[:, 1])
    while i <= n_rows
        if i == 1
            println(join(table[i, 1:2], '\t'), "\t"^4, table[i, 3])
        else
            println(join(table[i, :], '\t'))
        end
        i += 1
    end
    println("\nThe final output value is: $(table[end, 3])")
end

test_rpn()

Output:

For RPN expression: 3 4 2 * 1 5 - 2 3 ^ ^ / +
TOKEN   ACTION                           STACK
3       Push num onto top of stack       3
4       Push num onto top of stack       3 4
2       Push num onto top of stack       3 4 2
*       Apply op to top of stack         3 8
1       Push num onto top of stack       3 8 1
5       Push num onto top of stack       3 8 1 5
-       Apply op to top of stack         3 8 -4
2       Push num onto top of stack       3 8 -4 2
3       Push num onto top of stack       3 8 -4 2 3
^       Apply op to top of stack         3 8 -4 8
^       Apply op to top of stack         3 8 65536
/       Apply op to top of stack         3 0.0001220703125
+       Apply op to top of stack         3.0001220703125

The final output value is: 3.0001220703125


texts: Grab Facebook Graph share count and abbreviate it

texts:
I have this code that requests the graph API from Facebook to respond with a shared count for a particular URL (could be multiple on the page). Graph returns a full number (135934) and I take that number and abbreviate it into more friendly numbers (135K). Basically I'm looking for any help on improving the code to be more concise or if there's a better way to do something then to learn how.

 Some Article

 Some Article 2

 Some Article 3


texts:
I'd like this code to be minimized, while displaying the exact same stuff.

Specifically, on how to remove some of the repetitions made within the code (such as "if, else if") etc. using other statements or making the compiler go through it faster, as I feel like I lack the experience and the knowledge to do this without messing up everything (such as using switch & case).

For example, when I test for "tf", I'd like not to be forced to repeat the "average" depending on whether or not we add the "TEZA" grade.

#include <iostream>
using namespace std;
int main()

{
    string sub, tf;
    int m1, m2, m3, m4, sum, TEZA;
    double avg, tzm;

    cout << "SIMPLE AVERAGE CALCULATOR";
    cout << "\n" << "\n" << "Subject at hand?: ";
    cin >> sub;
    cout << "\n" << "Input the FOUR marks you'd like verified: " << "\n";
    cout << "\n" << "M1: ";
    cin >> m1;
    cout << "\n" << "M2: ";
    cin >> m2;
    cout << "\n" << "M3: ";
    cin >> m3;
    cout << "\n" << "M4: ";
    cin >> m4;
    cout << "\n" << "Would you like to include the TEZA grade?(Y/N): ";
    cin >> tf;

    sum = m1 + m2 + m3 + m4;
    avg = (double) sum / 4;

    if (tf == "Y" | tf == "y")
    {
        cout << "What is the TEZA grade?: ";
        cin >> TEZA;
        int tzm = ((double) avg * 3 + TEZA) / 4;
        cout << "\n" << "Your average grade at " << sub << " is " << tzm << "\n"
             << "\n";

        cout << "You got the following mark: ";
        if (tzm >= 9 && tzm <= 10)
            cout << "A" << "\n";
        else if (tzm >= 8 && tzm <= 9)
            cout << "B" << "\n";
        else if (tzm >= 7 && tzm <= 8)
            cout << "C" << "\n";
        else if (tzm >= 6 && tzm <= 7)
            cout << "D" << "\n";
        else if (tzm >= 5 && tzm <= 6)
            cout << "E" << "\n";
        else if (tzm < 5)
            cout << "F" << "\n";

        if (tzm >= 5)
        {
            cout << "DO YOU PASS: " << "\n";
            cout << "Yes." << "\n";
        }
        else
            cout << "No." << "\n";
    }

    else

    {
        cout << "\n" << "Average at " << sub << " is " << avg << "\n" << "\n";

        cout << "You got the following mark: ";
        if (avg >= 9 && avg <= 10)
            cout << "A" << "\n";
        else if (avg >= 8 && avg <= 9)
            cout << "B" << "\n";
        else if (avg >= 7 && avg <= 8)
            cout << "C" << "\n";
        else if (avg >= 6 && avg <= 7)
            cout << "D" << "\n";
        else if (avg >= 5 && avg <= 6)
            cout << "E" << "\n";
        else if (avg < 5)
            cout << "F" << "\n";

        cout << "\n" << "DO YOU PASS?: " << "\n";

        if (avg >= 5)
            cout << "Yes." << "\n";
        else
            cout << "No." << "\n";

    }
}


texts:
I am relatively new to C++ coming from languages such as Java and would like tips to make my code more C++ like and doing things in the C++ way.
The header file:
#pragma once

#include <string>
#include <memory>

class Expression
{
public:
    std::string symbol;
    std::shared_ptr<Expression> left;
    std::shared_ptr<Expression> right;

    float eval();
    static Expression parse(std::string s);

private:
    Expression(std::string symbol, Expression *left, Expression *right);
    static Expression parseRec(std::string s);
    static float evalRec(const Expression &e);
};

cpp file:
#include "Expression.hpp"
#include <unordered_map>

Expression::Expression(std::string symbol, Expression *left, Expression *right)
    : symbol(symbol), left(left), right(right) {}

float Expression::eval()
{
    return Expression::evalRec(*this);
}

float Expression::evalRec(const Expression &e)
{
    switch (e.symbol[0])
    {
    case '+':
        return evalRec(*e.left) + evalRec(*e.right);
    case '-':
        return evalRec(*e.left) - evalRec(*e.right);
    case '*':
        return evalRec(*e.left) * evalRec(*e.right);
    case '/':
        return evalRec(*e.left) / evalRec(*e.right);
    default:
        return std::stoi(e.symbol);
    }
}

Expression Expression::parse(std::string s)
{
    //Remove whitespace
    std::string output;
    for (auto &i : s)
    {
        if (i != ' ')
            output += i;
    }
    return parseRec(output);
}

Expression Expression::parseRec(std::string s)
{
    const std::unordered_map<char, int> precedence = {{'+', 1}, {'-', 1}, {'*', 10}, {'/', 10}};
    int indexOfLowest = -1;
    int i = 0;
    for (auto &&j : s)
    {
        switch (j)
        {
        case '+':
        case '-':
        case '*':
        case '/':
            if (indexOfLowest == -1)
                indexOfLowest = i;
            else if (precedence.at(j) <= precedence.at(s[indexOfLowest]))
                indexOfLowest = i;
            break;
        default:
            break;
        }
        i++;
    }
    if (indexOfLowest == -1)
    {
        return Expression(s, NULL, NULL);
    }
    else
    {
        return Expression(std::string(1, s[indexOfLowest]),
                          new Expression(parseRec(s.substr(0, indexOfLowest))),
                          new Expression(parseRec(s.substr(indexOfLowest + 1, s.length() - indexOfLowest - 1))));
    }
}

and a simple main:
#include <iostream>
#include "Expression.hpp"

int main(int argc, char const *argv[])
{
    //Parsed expression tree
    Expression e = Expression::parse("5 + 10 * 2 + 6 / 3");
    std::cout << e.eval() << std::endl;
    return 0;
}


texts: Making an atomic transaction out of several operations

texts:
I'm looking for a design pattern or suggestions that can help refactor my code into something a bit less repetitive. I have a method that has several sequential steps (10-15) that if any of them fail must record detail about the failure to a log and rollback all previous portions of the transaction. The example is below.

I have thought about taking each try catch and turning it into an individual method but then I have to pass around my undo stack (among several other variables) and I still have to conditionally abort the method and process the undo stack. I've briefly looked into the Momento and Command patterns but both seemed to grow the line count by a fair margin.

EnumResult TransactionThatRollsBack()
{
        var undoLog = new Stack<Action>();
        try
        {
            MoveInventory(inv, src, dest);
            undoLog.Push(() => MoveInventory(inv,dest,src));
        }
        catch (Exception ex)
        {
            RecordError("InventoryError", ex, inv, src, dest);
            Undo(undoLog);
            return EnumResult.FailedInventoryMove;
        }

        try
        {
            NotifyReportingOfMove(inv, user);
            undoLog.Push(() => NotifyReportingOfUnMove(inv, user));
        }
        catch (Exception ex)
        {
            RecordError("NotifyReportingOfMove", ex, inv, user);
            Undo(undoLog);
            return EnumResult.FailedReportingMove;
        }

        try
        {
            AddUserToSweepstakes(user);
            undoLog.Push(() => RemoevUserFromSweepstakes(user));

        }
        catch (Exception ex)
        {
            RecordError("AddUserToSweepstakes", ex, user);
            Undo(undoLog);
            return EnumResult.FailedSweepstakesAdd;
        }

        ...
        return EnumResult.Success
}


texts: Harvard CS50 Problem Set 1: greedy change-making algorithm

texts:
The goal of this code is to take dollar or cents input from the user and give out minimum number of coins needed to pay that between quarters, dimes, nickels and pennies. If this code can be shortened, how would one do it?

#include <stdio.h>
#include <cs50.h>
#include <ctype.h>
#include <math.h>

int main(void)
{
float b;
do
    {
    printf("please give balance owing: ");
    b = GetFloat();
    }
while (b<0);

int v;
int q = 25;
int d = 10;
int n = 5;
int p = 1;
int count=0;

b=b*100;
int c=round(b);
int balance = c;
printf("%i\n", balance);
//printf("%.2f\n", round(c));

while(balance>=q)
    {
    v=balance/q;
    count=count+v;
    balance=balance-(q*v);
    }
while(balance>=d)
    {
    v=balance/d;
    count=count+v;
    balance=balance-(d*v);
    }
while(balance>=n)
    {
    v=balance/n;
    count=count+v;
    balance=balance-(n*v);
    }
while(balance>=p)
    {
    v=balance/p;
    count=count+v;
    balance=balance-(p*v);
    }

printf("the number of coins needed is: %i\n", count);
printf("balance after coins paid: %i\n", balance);

}


texts: Remove (not extract) timestamp from HTML string

texts:
I've got strings coming from irregularly and ugly formatted HTML sites, that contain a timestamp. I am interested in removing the timestamp entirely and get all the rest.

from bs4 import BeautifulSoup

date1 = '
10:15 AM  ARVIND KRISHNAMURTHY, Northwestern University
'
date2 = """

 8:45 a.m.<o:p></o:p>

RICARDO  CABALLERO, MIT and NBER<o:p></o:p>

"""

soup1 = BeautifulSoup(date1)
print repr(soup1.text.strip())
# "u'10:15 AM  ARVIND KRISHNAMURTHY, Northwestern University'"
soup2 = BeautifulSoup(date2)
print repr(soup2.text.strip())
# "u'8:45 a.m.RICARDO  CABALLERO, MIT and NBER'"

Now, to get the text following the timestamp, I split along whitespaces to join all elements, except the first two:

def remove_date(aString):
    cleaned = aString.replace("\t", " ").replace(".m.", " ").strip()
    return " ".join(cleaned.split(" ")[ 2:]).strip()

string1 = remove_date(soup1.text.strip())
print repr(string1)
# u'ARVIND KRISHNAMURTHY, Northwestern University'
string2 = remove_date(soup2.text.strip())
print repr(string2)
# u'RICARDO  CABALLERO, MIT and NBER'

It delivers the desired result, but this is arguably very ugly. Is there something better? Maybe something that works like dateutil.parser.parse(), but in reverse?


texts: Solution for swapping ArrayList data members with another

texts:
Two possible solutions but which one? Or is there a Better?

I have a class MP3Track with members: Track number (int), track name (String), artist (String), in faourites (boolean) etc. My catalogue class contains two ArrayLists, one containing all tracks (vectorMain) and the other containing favourites (vectorFav) which are copies of the tracks in the main catalogue.

I want the user to have the option of swapping two track numbers (which are unique in both arrays).

Sample printout of the main catalogue below:

Both samples get the desired result but:

(Solution 1) deleted as didn't work in reverse.
(Solution 2) Below Seems rather cumbersome!
(Solution 3) Below Seems more elegant but very long winded!

getMainIndex() - returns the index position in the ArrayList for a given track number or -1.

Here is Solution 2 (overcame problem of solution 1 - but ugly)

Here is start of method:

public void swapTrack(){
    int t1 = -1, t2 = -1;
    System.out.println(face.getSwapTrackMenu());
    System.out.print("1) Please enter first track number to swap: ");
    t1 = scan.readInt();
    System.out.print("2) Please enter second track number to swap: ");
    t2 = scan.readInt();
    MP3Track mp31 = null;
    MP3Track mp32 = null;

Now solution 2

if((getMainIndex(t1)!=-1)&&(getMainIndex(t2)!=-1)){
    String s1 = null;
    String s2 = null;
    for(MP3Track track : vectorMain){
        if(track.getTrackNo() == t1){
            s1 = track.getTitle();
        }
        if(track.getTrackNo() == t2){
            s2 = track.getTitle();
        }
    }

    for(MP3Track track : vectorMain){
        if(track.getTitle().equals(s1)){
            track.setTrackNo(t2);
        }
        if(track.getTitle().equals(s2)){
            track.setTrackNo(t1);
        }
    }

    for(MP3Track track : vectorFav){
        if(track.getTitle().equals(s1)){
            track.setTrackNo(t2);
        }
        if(track.getTitle().equals(s2)){
            track.setTrackNo(t1);
        }
    }
}

Here is Solution 3

    //Loop thorugh main (ArrayList) looking for both track numbers
    for(MP3Track track : vectorMain){
        if(track.getTrackNo() == t1){
            //If track 1 found assign it to temp var
            mp31 = vectorMain.get(getMainIndex(t1));
        }
        if(track.getTrackNo() == t2){
            //If track 2 found assign it to temp var
            mp32 = vectorMain.get(getMainIndex(t2));
        }
    }

    //Check if we found track 1
    if(vectorMain.contains(mp31)){
        //Set temp var new track number
        mp31.setTrackNo(t2);
    }
    //Check if we found track 2
    if(vectorMain.contains(mp32)){
        //Set temp var new track number
        mp32.setTrackNo(t1);
    }

    mp31 = null;                //Remove pointer reference
    mp32 = null;                //Remove pointer reference

    //loop thorugh Fav (ArrayList) looking for track numbers
    for(MP3Track track : vectorFav){
        if(track.getTrackNo() == t1){
            //Assign it to temp var
            mp31 = vectorFav.get(getFavIndex(t1));
        }
        if(track.getTrackNo() == t2){
            //Assign it to temp var
            mp32 = vectorFav.get(getFavIndex(t2));
        }
    }
    //Check if we found it first
    if(vectorFav.contains(mp31)){
        mp31.setTrackNo(t2);
    }
    //Check if we found it first
    if(vectorFav.contains(mp32)){
        mp32.setTrackNo(t1);
    }

Is there something I'm missing here? I've hit a wall as to a better solution!!

I'm new to Java so any suggestions, improvements & comments appreciated.

Many thanks


texts:
Is it bad to do return render? I am doing this to NOT also allow a redirect.

def create
    @patient = Patient.new(params[:patient])
    if  !@patient.save
      @patient.user.password = ''
      @patient.user.password_confirmation = ''
      return render is_admin? ? 'new_admin' : 'new'
    else
      #Fire off an e-mail
      PatientMailer.welcome_email(@patient).deliver
    end

    if current_user == @patient
      sign_in @patient
    else
      redirect_to patients_path
    end
  end


texts: Printing 80 (or more) times the same character

texts:
I want to print a lot of the same characters and I don't want to use a for loop and I'm also looking for a way to do it as less lines as possible. Even better I would like to be able to store that string in a static variable to use again and again.

This is how I currently do it (ugly but at least no for loop):

System.out.println("----------------------------------------"
                + "----------------------------------------"
                + "----------------------------------------");

What's a better way (aesthetically wise)?


texts: Showing statistics of popular JavaScript frameworks from GitHub API

texts:
I am currently working on a simple app to check the stats of popular javascript frameworks. For this I am using the Github API to get certain data sets and have come close to finishing my project.

const frameworks = [
  {
    name: "angular",
    logo: "img/angular.png",
    url: "https://api.github.com/repos/angular/angular.js"
  }
  /*
  {
    name: "ember",
    logo: "img/ember.png",
    url: "https://api.github.com/repos/emberjs/ember.js"
  },
  {
    name: "react",
    logo: "img/react.png",
    url: "https://api.github.com/repos/facebook/react"
  },
  {
    name: "vue",
    logo: "img/vue.png",
    url: "https://api.github.com/repos/vuejs/vue"
  }
  */
];

const frameworkData = url => {
  return fetch(url)
    .then(resp => {
      return resp.json();
    })
    .then(data => {
      return {
        data: {
          name: data.name,
          forks: data.forks_count,
          stars: data.stargazers_count,
          issues: data.open_issues_count
        }
      };
    });
};

const setup = () => {
  let now = new Date();
  const row = document.getElementById("row");

  frameworks.forEach(framework => {
    const promises = [];
    promises.push(frameworkData(framework.url));

    Promise.all(promises).then(data => {
      const obj = data[0].data;
      console.log(obj);
      const card = `

${framework.name}

Watchers: ${obj.forks}

Stars: ${obj.stars}

Commits: ${obj.issues}

`;
      row.innerHTML += card;
    });
  });
};

setup();

Being this is one of my first javascript 'apps' I feel it was done to the best of my ability. However, I feel there is a code smell in here that I have been trying to figure out how to fix but have not.

As you may be able to see in the frameworks for each loop, I am settings this variable const obj = data[0].data;. To me this is strange and I could not seem to find away around it. This is done because the single object for that API call is being returned in an array and I was not sure how to get that data other than calling the first index on the array since it will always be 0. Is there a better way to do this? How was my first javascript app?


texts: Using generator for buffered read of large file in Python

texts:
I have a large file that I need to parse - and since it will be regenerated from external queries every time script runs so there is no way to parse it once and cache the results.

I want to save memory footprint and read and parse only logical "chunks" of that file everything between open 'product' and closing curly bracket.
Not sure what is the canonical way in Python (I am new to the language).

Here's what I tried so far:

def read_chunk(file_name, pattern_open_line, pattern_close_line):
    with open(file_name,"r") as in_file:
        chunk = []
        in_chunk = False
        open_line = re.compile(pattern_open_line);
        close_line = re.compile(pattern_close_line)
        try:
            for line in in_file:
                line = line.strip()
                if in_chunk:
                    chunk.append(line)
                if close_line.match(line):
                    yield chunk
                if open_line.match(line):
                    chunk = []
                    chunk.append(line)
                    in_chunk = True
                    continue
        except StopIteration:
            pass

def get_products_buffered(infile):
    chunks = read_chunk(infile, r'^product\s*$', r'^\s*\}\s*')
    products = []
    for lines in chunks:
        for line in lines:
            if line.startswith('productNumber:'):
                 productNumber = line[len('productNumber:'):].strip().rstrip(';').strip('"')
                 products.append(productNumber)
                 continue
    return products

def get_products_unbuffered(infile):
    with open(infile) as f:
        lines = f.readlines()
        f.close()
    products = []
    for line in lines:
        if line.startswith('productNumber:'):
             productNumber = line[len('productNumber:'):].strip().rstrip(';').strip('"')
             products.append(productNumber)
             continue
    return products

I profiled both runs and while unbuffered reading is faster:

Buffered reading
Found 9370 products:
Execution time: 3.0031037185720177
Unbuffered reading
Found 9370 products:
Execution time: 1.2247122452647523

it also incurs a much bigger memory hit when file is essentially read into memory:

Line #    Mem usage    Increment   Line Contents
================================================
    29     28.2 MiB      0.0 MiB   @profile
    30                             def get_products_buffered(infile):
    31     28.2 MiB      0.0 MiB       chunks = read_chunk(infile, '^product\s*$', '^\s*\}\s*')
    32     28.2 MiB      0.0 MiB       products = []
    33     30.1 MiB      1.9 MiB       for lines in chunks:

versus:

Line #    Mem usage    Increment   Line Contents
================================================
    42     29.2 MiB      0.0 MiB   @profile
    43                             def get_products_unbuffered(infile):
    44     29.2 MiB      0.0 MiB       with open(infile) as f:
    45    214.5 MiB    185.2 MiB           lines = f.readlines()

I would be grateful for any pointers/suggestions.


texts:
Objective: The objective of the program is to create a JIRA ticket using a REST API.  It's working perfectly fine without any issue. However I am not sure if it's up to good Scala standards.

I would be delighted if someone could let me know what I can do to improve it.

import org.apache.http.HttpResponse
import org.apache.http.auth.UsernamePasswordCredentials
import org.apache.http.client.methods.HttpPost
import org.apache.http.entity.StringEntity
import org.apache.http.impl.auth.BasicScheme
import org.apache.http.impl.client.HttpClients
import org.apache.http.util.EntityUtils

object JIRAUtil{

  private def getJiraID(response: HttpResponse): String ={
    val entity = response.getEntity
    val content = EntityUtils.toString(entity)
    val id = "DPPR-\\d{4}".r
    val jiraID = id.findFirstIn(content)
    assert(jiraID.isDefined, s"Failed to create JIRA: ${content}")
    jiraID.get
  }

  def createJIRA(project: String, summary: String, description: String, assigneeName: String,
                 assigneeEmail: String): String = {
    val data = s"""{
      "fields": {
         "project":{
            "key": "${project}"
         },
         "summary": "[Automation] - ${summary}",
         "customfield_10118": "DPPR-1109",
         "assignee": {
            "name": "${assigneeName}",
            "emailAddress": "${assigneeEmail}"
         },
         "description": "${description}",
         "issuetype": {
            "name": "Bug"
         }
     }
    }"""

    val url = "https://acosta-it.atlassian.net/rest/api/latest/issue/"
    val post = new HttpPost(url)
    val httpClient = HttpClients.createDefault()

    val credential = new UsernamePasswordCredentials("gaurang.shah@abc.com", "CoddadEhptnDfU18F")
    post.addHeader("Content-type", "application/json")
    post.addHeader(new BasicScheme().authenticate(credential, post, null))
    post.setEntity(new StringEntity(data))
    val response = httpClient.execute(post)
    val jiraId = getJiraID(response)
    jiraId
  }

}


texts: Linear search algorithm template implementation

texts:
This template class is a linear search algorithm with a simple search function. I have tested it with int and char and it seems to be working fine. I would like pointers on how I can make it more efficient and on my coding technique. I do know that the standard library provides this algorithm, i am just doing it for fun and practice

sLinear.h

//Linear search template

#ifndef SLINEAR_H
#define SLINEAR_H

namespace fm
{
    template <typename T>
    class sLinear
    {
        T *_list;
        T _item;
        int _sizeOfList;

    public:
        sLinear();
        sLinear(T *myArray, T item, int size);

        ~sLinear();

        int findItem();

    };

    //------public methods------
    template <typename T>
    sLinear<T>::sLinear()
    {
        _list = nullptr;
        _sizeOfList = 0;
    }

    template <typename T>
    sLinear<T>::sLinear(T *myArray, T item, int size)
    {
        _list = myArray;
        _item = item;
        _sizeOfList = size;
    }

    template <typename T>
    sLinear<T>::~sLinear()
    {
        _list = nullptr;
        _sizeOfList = 0;
    }

    template <typename T>
    int sLinear<T>::findItem()
    {
        while (_list != nullptr)
        {
            for (int i = 0; i < _sizeOfList; i++)
            {
                if (_list[i] == _item)
                {
                    return i + 1;
                }

            }

            return -1;

        }
    }
}
#endif

main.h

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

using namespace fm;

int main()
{

    /* Linear search with integer */
    int iList[] = { 1,9,2,6,5,3,7,4,8,0 };
    int size = (sizeof(iList) / sizeof((iList[0])));

    sLinear<int> mySearch(iList, 8, size);
    int k = mySearch.findItem();

    if (k == -1)
        std::cout << "Item not found!" << std::endl;
    else
        std::cout << "Item found:" << k << std::endl;

    return 0;
}


texts: Throwing the Exception But Using the Finally Block

texts:
Does this piece of code make sense? The idea is to throw any exceptions that may occur but always run the finally block to close the streams.

private void streamToFile(HttpResponse transferResponse) throws Exception {
    OutputStream output = null;
    InputStream input = null;
    try {
        input = new BufferedInputStream(transferResponse.getEntity().getContent());
        output = new FileOutputStream(transferFile);
        final int BUFFER_SIZE = 1024*10;
        byte data[] = new byte[BUFFER_SIZE];
        int count;
        while ((count = input.read(data)) != -1) {
            output.write(data, 0, count);
            publishProgress(count);
            remainingBytes = remainingBytes - count;
        }
    } finally {
        input.close();
        output.close();
    }
}


texts: Async/await and Task vs Task.Factory.StartNew and Result

texts:
I am working on creating some libraries for a project at work and I wanted to make sure I have this pattern correct. Assuming that the GetWidgets method is what I am going to be exposing, which is the preferred method for this? Is there any fundamental difference in these two methods?

public async Task<List<Widget>> GetWidgets(DateTime date)
{
    using (var httpClient = new HttpClient())
    {
        var feed = "http://example.org/feed";
        var response = await httpClient.GetStringAsync(feed);
        var items = await SomeOtherAsyncMethod(response);

        return items.Where(item => item.StartDate.Date == date).ToList();
    }
}

public Task<List<Widget>> GetWidgets(DateTime date)
{
    return Task.Factory.StartNew(() =>
    {
        using (var httpClient = new HttpClient())
        {
            var feed = "http://example.org/feed";
            var response = httpClient.GetStringAsync(feed).Result;
            var items = SomeOtherAsyncMethod(response).Result;

            return items.Where(item => item.StartDate.Date == date).ToList();
        }
    });
}

And if the second example is correct, should I be naming it GetWidgetsAsync?