texts: Get a notification when questions get posted

texts:
I like to help people on StackOverflow, matter of fact nowadays it depends on how quick you are when answering question.
With that being said, I can't always keep a tab and an eye to refresh the browser to view new questions.

I made a very basic script to send me a notification (OSX) whenever there's a new question.

import requests, os, threading, time
from bs4 import BeautifulSoup
from timeloop import Timeloop
from datetime import timedelta

tl = Timeloop()

SE_REALTIME = "https://stackexchange.com/questions?tab=realtime"
WATCHED_TAG = "swift"
QUE_LI = []

# The notifier function
def notify(title, subtitle, message, link):
    t = '-title {!r}'.format(title)
    s = '-subtitle {!r}'.format(subtitle)
    m = '-message {!r}'.format(message)
    l = '-open {!r}'.format(link)
    os.system('terminal-notifier {}'.format(' '.join([m, t, s, l])))

def fetch():
    # The SOUP
    soup = BeautifulSoup(requests.get(SE_REALTIME).content, "html.parser")

    # List of Questions with the sid: Stackoverflow.com
    li = soup.find_all('div', {'data-sid': 'stackoverflow.com'})

    # Loop Through
    for child in li:
        id = child['class'][2]
        all_tags = child.find("span", attrs={'class': 'realtime-tags'}).text.strip()
        tags = all_tags.split()
        if WATCHED_TAG in tags:
            if id not in QUE_LI:
                question = child.find("a", attrs={'class': 'realtime-question-url realtime-title'})
                QUE_LI.append(id)
                notify(title = 'New Question {}'.format(' '.join([WATCHED_TAG])),
                subtitle = 'Stackoverflow.com',
                message  = question.text.strip(),
                link = question['href'])

@tl.job(interval=timedelta(seconds=2))
def fetch_questions_every_2s():
    fetch()

if __name__ == "__main__":
    tl.start(block=True)

Ok, This code works well. But I'm looking for:

A way to listen for changes on the div tree (without making a request every 2 second)
Less code.

Dependencies:

Terminal-Notifier
BeautifulSoup
TimeLoop
Requests


texts: Mapping a textual method name to a function

texts:
My program (a daemon hosting a Minecraft server) exposes a D-Bus interface to allow interaction with the server from other processes. To that end, and to avoid a chain of repetitive conditionals in the invocation handler, I'm using a map of Glib::ustring keys (the method invoked) to std::bind-created function objects (code abbreviated slightly; see end of question for link to full source):

std::unordered_map<Glib::ustring, std::function<void(Minecraftd1*, const Glib::RefPtr<Gio::DBus::MethodInvocation>&)>> handlerMap;
std::once_flag handlerMapInitFlag;

Minecraftd::Minecraftd1() {
    // Only initialise the method name/handler method map once. Placeholders are used for the "this" and invocation arguments.
    std::call_once(handlerMapInitFlag, []{
        using namespace std::placeholders;
        handlerMap.emplace("SaveAll", std::bind(&Minecraftd1::handleSimpleCommand, _1, _2, "save-all"));
        // Omitted: two similar mappings
        handlerMap.emplace("Stop", std::bind(&Minecraftd1::handleSimpleCommand, _1, _2, "stop"));
    });
}

// Called by the Glib main loop when a D-Bus method call is received
void Minecraftd1::onMethodCall(const Glib::ustring &methodName, const Glib::RefPtr<Gio::DBus::MethodInvocation> &invocation) {
    auto handler = handlerMap.find(methodName);
    if(handler != handlerMap.end()) {
        handler->second(this, invocation);
    } else {
        invocation->return_error(Gio::DBus::Error{Gio::DBus::Error::UNKNOWN_METHOD, "Method does not exist."});
    }
}

void Minecraftd1::handleSimpleCommand(const Glib::RefPtr<Gio::DBus::MethodInvocation> &invocation, std::string command) const {
    // Write value of command to standard input (rebound to a pipe)
    invocation->return_value(Glib::VariantContainerBase{});
}

I realise that, for the current set of methods, I could just as well use a map of methodName to the command string to write to the file descriptor, but this way of doing it allows me to create more complex handlers for commands that require more than just a simple pass-through without having to change the execution flow of onMethodCall. Of course, if a handler method requires access to e.g. the parameters of the D-Bus invocation, I would need to modify the signature of all the handlers to accept it as an argument, with a corresponding additional placeholder in the std::bind call.

Is this a good way of going about runtime dispatch based on a string identifier, or am I barking up the wrong tree here? Is there any way that it could be improved further?

The full source code may be found on GitHub.


texts:
I am building a small app for adopting different types of pets.

My API looks like this:

 [
       {category: 'dog', pets: [{breed: 'chihuahua', gender: 'm' }, ....]},
       {category: 'cat', pets: [{breed: 'tobby', gender: 'f'}, ....]},
       ....
 ]

In my app, I have a form for putting and removing pets to/from the adoption list. When the user clicks on the delete button, I dispatch the DELETE_PET action and my reducer deletes the selected pet and changes my state locally.

Everything works as expected, I am just wondering if there is a more efficient way to handle the action. Also, I need to get rid of the for-in since I am using ESLint and I get the error Using ForInStatement is not allowed.

My reducer looks like this:

[DELETE_PET]: (state, { payload }) => {
    for (const key in state) {
        state[key].pets.map((pet, keys) => {
            if (pet === payload) {
                delete state[key].pets[keys];
                return { ...state };
            }
        });
    }
    return { ...state };
}

What the values correspond to:

State = object version of pets API

 {
       {category: 'dog', pets: [{breed: 'chihuahua', gender: 'm' }, ....]},
       {category: 'cat', pets: [{breed: 'tobby', gender: 'f'}, ....]},
       ....
 }

Payload = selected pet for deletion:

{breed: 'chihuahua', gender: 'm'}


texts: Calculate the value of an arithmetic term written in Polish Notation

texts:
I have to create a program which calculates the result of an arithmetic term written in Polish Notation.

var parseNotation = parseNotation || {};

/**
 * Computes the result of an given arithmetic term which is written in
 *  Reverse Polish Notation (https://en.wikipedia.org/wiki/Reverse_Polish_notation).
 * @param { String } termInReversePolish - The operators / operands of
 *  the term have to be separated by colons. See usage example!
 * @return { number } Result of the given term.
 * @throws { Error } Will throw an error in case of no or invalid parameter
 *  is given.
 *
 * Usage example (will display 37 as result):
 *  console.log(parseNotation.computeFromReversePolish('5,6,2,+,*,12,4,/,-'));
 */

parseNotation.computeFromReversePolish = function(termInReversePolish) {
  var currentChar = '';
  var stack = [];
  var right = 0;

  if (typeof termInReversePolish !== 'string') {
    throw new Error(
      `No valid parameter given. String expected but ${typeof termInReversePolish} found.`);
  }

  if (termInReversePolish.search(/[^\d,+*\/-]/g) != -1) {
      throw new Error(
        'Given parameter contains illegal characters. Valid characters are: + - * / , 0-9');
  }

  termInReversePolish = termInReversePolish.split(',');

  termInReversePolish.forEach((currentChar, i) => {
    if (['+', '-', '*', '/'].indexOf(currentChar) === -1) {
      stack.push(currentChar);
    } else {
      right = stack.pop();

      stack.push(eval(stack.pop() + currentChar + right));
    }
  });

  return stack.pop();
}

// ---- Testing ------------------
console.log(parseNotation.computeFromReversePolish( '1,2,+,3,4,+,*' ));
console.log(parseNotation.computeFromReversePolish( '5,6,2,+,*,12,4,/,-' ));
console.log(parseNotation.computeFromReversePolish( '2,7,+3,/,14,3,-,4,*,+,2,/' ));

My first few test with the function have gone well. Nevertheless, I would like to read the opinion of other developer, especially regarding:

Is my documentation done in a proper way? Or does I have to improve it?
Is my parameter validation sufficient? Especially regarding the used regular expression.
Generally: Is everything done in a good way and fashion?

If someone sees an error or flaw then please let me know.


texts:
I have this code that reads in a "scrambles" and a "words" file. It compares both files using their canonical form and prints out the words from the "words" file that match a particular scrambled word. I'm looking for ways to make this quicker.

public class scramble
{

    public static void main(String[] args) throws Exception
    {
        if (args.length < 2 ) die( "Must pass name of input files on cmd line." );

        BufferedReader scrambles = new BufferedReader( new FileReader( args[1] ) );
        BufferedReader words = new BufferedReader ( new FileReader( args[0] ) );
        ArrayList<String> scramblesList= new ArrayList<String>();  // default initial capacity is 10
        ArrayList<String> wordList= new ArrayList<String>();

        long startTime = System.currentTimeMillis();  // like clicking START on your stopwatch

        while (scrambles.ready())
        {
             String scramble = scrambles.readLine();
             scramblesList.add( scramble );
         }

        Collections.sort( scramblesList );
        while (words.ready())
        {
            String word = words.readLine();
            dictionaryList.add( word );
        }
        Collections.sort( wordList );

        for(String scramble: scramblesList)
        {
            System.out.print(scramble + " ");
                for(String word: wordList)
                {
                if(toCanonical(scramble).equals(toCanonical(word)))
                    System.out.print(word + " ");
                }
        System.out.println();
        }
        long endTime = System.currentTimeMillis();  // like clicking STOP on your stopwatch
        long ms = endTime-startTime;
        System.out.println("Elapsed time in seconds: " + ms/1000.0 + "\n"); // 1 ms is a 1,000th of a second
    } // END MAIN

    private static void die( String errmsg )
    {
                System.out.println( "\nFATAL ERROR: " + errmsg + "\n" );
                System.exit(0);
    }

    private static String toCanonical( String word )
    {
        char[] array = word.toCharArray();
        // #1 declare a char[] array and assign into it the return value from word.toCharArray()

        Arrays.sort(array);
        // #2 pass that char[] into Arrays.sort(...)
        String C = new String (array);
        // #3 return a new a new String that is constructed using that char[]
            return C;

    }
}


texts: Add to a variable multiple in cells variables

texts:
I have code that is used to add all cells of a tab to a var:

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

#define NB 10000

// Instruction RDTSC du Pentium
static __inline__ unsigned long long RDTSC(void) {
    unsigned hi, lo;
    __asm__ __volatile__ ("rdtsc" : "=a"(lo), "=d"(hi));
    return ((unsigned long long) lo) | (((unsigned long long) hi) << 32);
}

// IS HERE TO CONTAIN THE TAB, IT WILL CONTAIN ALL THE NUMBERS I WILL HAVE TO ADD TO MY FINAL INT NAMES "somme" IN MY MAIN.
// Initialisation de la matrice d'entiers
void InitTab(int **tab) {
    int i, j;

    for (i = 0; i < NB; i++) {
        tab[i] = (int *) malloc(NB * sizeof(int));
        assert (tab[i] != NULL);
    }

    for (i = 0; i < NB; i++)
        for (j = 0; j < NB; j++)
            tab[i][j] = rand()%100000;
}

// IT WILL RETURN ME THE MINIMUM OF A COLUMN OF MY TABLE BECAUSE WHE WANT TO ADD THE MINIMUM OF ALL COLUMNS OF THE TABLE TO THE FINAL INT NAMES "somme" IN MY MAIN.
// Calcul du minimum d'une colonne
int MinColonne(int **tab, int colonne) {
    int i, min;

    min = tab[0][colonne];
    for (i = 1; i < NB; i++)
        if (min > tab[i][colonne]) min = tab[i][colonne];

    return (min);
}

// MAIN
int main(void) {
    int somme = 0;
    int i,z;
    int **tab;

    unsigned long long t1, t2; // chronometrage
    srand(1);

    tab = (int **) malloc(NB * sizeof(int *));
    assert(tab != NULL); // exit si erreur d'allocation

    InitTab(tab);// permet aussi de mettre le processeur en pleine puissance

    t1 = RDTSC();
    for (z=0; z<10; z++) // pour avoir une moyenne du temps d'execution
    for (i = 0; i < NB; i++)
         somme += MinColonne(tab, i);
t2 = RDTSC();

    printf("Somme des minima de chaque colonne : %d \n", somme);

    printf("Temps en cycles d'horloge : %llu \n", (t2 - t1));

    return EXIT_SUCCESS;
}

I have to optimize this code but I don't find any for to break, while to optimize and no multiple if ... (These are the only things I know how to optimize)

Do you know how to?

I can't touch at InitTab(tab); line and the double for.


texts:
I need to randomly erase 33% of the non-zero elements in each line of a matrix.
Side note: The end goal is to train a denoising autoencoder to remove this noise.
My solution:
import numpy as np

matrix = np.random.rand(1000,3000)

for i in range(matrix.shape[0]):
    clean = matrix[i, :] # original matrix line
    # find non zero elements
    msk = np.nonzero(clean)
    assert sum(msk[0]) != 0

    # keep 66% of them
    idx = np.random.randint(0, len(msk[0]), size=max(1, len(msk[0])//3)) #erase at least 1
    msk = np.delete(msk, idx)

    dirty = clean
    dirty = [j if i in msk else 0 for i,j in enumerate(dirty)]
    assert sum(clean-dirty) != 0

    #save clean and dirty
    #...

My guess is that the bottleneck is drawing random numbers at each iteration.
Is there an alternative way to do this?


texts: Angular controller to handle showing or hiding multiple widgets

texts:
I have 7 variables controlling 7 widgets showing or hiding from the frontend. I want to put them together and control all of them using one function. Here is what I have. However, I feel like even though this way works, the code is really ugly and should have space for improvements.

$scope.showWidget = function(showA, showB, showC, showD, showE, showF, showG) {
                    if (showA !== null) {
                        $scope.showshowA = showA;
                    }
                    if (showB !== null) {
                        $scope.showshowB = showB;
                    }
                    if (showC !== null) {
                        $scope.showshowC = showC;
                    }
                    if (showD !== null) {
                        $scope.showD = showD;
                    }
                    if (showE !== null) {
                        $scope.showshowE = showE;
                    }
                    if (showF !== null) {
                        $scope.showshowF = showF;
                    }
                    if (showG !== null) {
                        $scope.showG = showG;
                    }
                }

E.G. I will use the following code snippet for controlling showG variable on the fly.

 $scope.showWidget(null, null, null, null, null, null, true);


texts:
For the problem given:

  Douglas Hofstadter’s Pulitzer-prize-winning book, Gödel, Escher, Bach, poses the following mathematical puzzle.

  Pick a positive integer \$n\$ as the start.
  If \$n\$ is even, divide it by 2.
  If \$n\$ is odd, multiply it by 3 and add 1.
  Continue this process until \$n\$ is 1.

  The thesis is: The number \$n\$ will travel up and down but eventually end at 1 (at
  least for all numbers that have ever been tried -- nobody has ever
  proved that the sequence will terminate). Analogously, hailstone
  travels up and down in the atmosphere before eventually landing on
  earth.

  The sequence of values of n is often called a Hailstone sequence, because hailstones also travel up and down in the atmosphere before falling to earth. Write a function that takes a single argument with formal parameter name \$n\$, prints out the hailstone sequence starting at \$n\$, and returns the number of steps in the sequence.

  Hailstone sequences can get quite long! Try 27. What's the longest you can find? Fill in your solution below:

def hailstone(n):
    """Print the hailstone sequence starting at n and return its length.

    >>> a = hailstone(10)  # Seven elements are 10, 5, 16, 8, 4, 2, 1
    10
    5
    16
    8
    4
    2
    1
    >>> a
    7
    """
    "*** YOUR CODE HERE ***"

Below is the solution written for above problem that performs hailstone sequence:

def hailstone(n):
    count = 1
    """Print the terms of the 'hailstone sequence' from n to 1."""
    assert n > 0
    print(n)
    if n > 1:
        if n % 2 == 0:
            count += hailstone(n / 2)
        else:
            count += hailstone((n * 3) + 1)
    return count

result = hailstone(10)
print(result)

With the above solution, I would like to confirm that this program follows functional paradigm instead of imperative paradigm with good abstraction.

I would like to understand if this program can still be improved from paradigm perspective.


texts: Checking all elements against each other for elements strictly worse

texts:
Consider the following function:

def test_func(all_copies, checker):
    bad_copies = set(c[0] for c in itertools.permutations(all_copies, 2) if not checker(*c))
    all_copies = [c for c in all_copies if c not in bad_copies]
    return all_copies

This function returns a list of elements that are not overshadowed by any other element. Considering the checker:

def checker(l, r):
    return l[0] < r[1] or l[1] < r[1]

and the input:

all_copies = [(2,3)(2,2),(3,3),(3,1),(1,3),(4,1)]

This will return:

[(2,2),(3,1),(1,3)]

Now this works in 3 steps:

First itertools.permutations creates all combinations to check against. Secondly set() - because it can only contain one of each element is basically an "any". And any(not(x)) is basically the complement of all(x). So if an element turns "strictly worse" against any other element it is added to the "bad_copies".
Finally the last line selects all elements that are not bad copies.

Now this seems nice, but it basically performs the check n2 - n times. And the takes another O(n) to create the list.

Can I optimize this? Can the code become more clear and direct?

A more elaborate function that does the same thing is (can this be optimized using list comprehensions):

def test_func(all_copies):
    out = []
    for i in all_copies:
        add = True
        for j in all_copies:
            if i != j:
                if not check_post(i,j):
                    add = False
        if add:
            out.append(i)
    return out


texts: Arranging words in sentences alphabetically

texts:
For an online contest whose problem is here, I wrote some code.

  In this problem the input will consist of a number of lines of English text consisting of the letters of the English alphabet, the punctuation marks ' (apostrophe), . (full stop), , (comma), ; (semicolon), : (colon) and white space characters (blank, newline).
  Your task is print the words in the text in lexicographic order (that is, dictionary order). Each word should appear exactly once in your list. You can ignore the case (for instance, "The" and "the" are to be treated as the same word.) There should be no uppercase letters in the output.

  For example, consider the following candidate for the input text:

This is a sample piece of text to illustrate this
problem.

  The corresponding output would read as:

a
illustrate
is
of
piece
problem
sample
text
this
to

  Input format

  The first line of input contains a single integer \$N\$, indicating the number of lines in the input. This is followed by \$N\$ lines of input text.

  Output format

  The first line of output contains a single integer \$M\$ indicating the number of distinct words in the given text. The next \$M\$ lines list out these words in lexicographic order.

  Test data

  You may assume that \$N ≤ 10000\$ and that there are at most 80 characters in each line. You may also assume that there are at the most 1000 distinct words in the given text.

  Example

  We now illustrate the input and output formats using the above example.

  Sample input

2
This is a sample piece of text to illustrate this
problem.

  Sample output

10
a
illustrate
is
of
piece
problem
sample
text
this
to

It is working perfectly as far as I know. When I run my code, it passes all tests.

import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;

/**
 * Created by aditya on 14-10-2014.
 */
public class Main {

    public static void main(String args[]) {

        Scanner scan = new Scanner(System.in);
        int n = Integer.parseInt(scan.nextLine());
        ArrayList<String> lines = new ArrayList<String>();
        ArrayList<String> words = new ArrayList<String>();
        ArrayList<String> words_2 = new ArrayList<String>();
        boolean once_entered = true;
        for (int i = 0; i < n; i++) {
            lines.add(i, scan.nextLine() + " ");
        }
        for (int i = 0; i < n; i++) {
            String word = "";
            for (int j = 0; j < lines.get(i).length(); j++) {
                char char_0 = lines.get(i).toLowerCase().charAt(j);
                if ((int) (char_0) >= (int) ('a') && (int) (char_0) <= (int) ('z')) {
                    word += char_0;
                    once_entered = false;
                } else if (!once_entered) {
                    words.add(word);
                    word = "";
                    once_entered = true;
                }
            }
        }
        for (int i = 0; i < words.size(); i++) {
            boolean contains =false;
            for(int j=0;j<words_2.size();j++){
                if(words_2.get(j).contentEquals(words.get(i)))
                    contains=true;
            }
            if(!contains)
                words_2.add(words.get(i));
        }
        Collections.sort(words_2);
        System.out.println(words_2.size());
        for (int i = 0; i < words_2.size(); i++) {
            System.out.println(words_2.get(i));
        }
    }
}


texts: is_palindrome function that ignores whitespace and punctuation

texts:
from string import punctuation, ascii_lowercase

def is_palindrome(string):
    """Return True if string is a palindrome,
    ignoring whitespaces and punctuation.
    """
    new = ""
    for char in string:
        lc = char.lower()
        for x in lc:
            if x in ascii_lowercase:
                new += x

    return new[::-1] == new

# string = "Was it a rat I saw?"
# print(is_palindrome(string))


texts: Rails controller method to create a customer with credit card info

texts:
I'm working on a Rails application that has a lot of logic in the controller that should be in the model. In the app/controllers/customers_controller.rb#create there is logic to create stripe cc info for the customer. I think this should be in the model.

How can I move this logic into the model and still handle any exceptions in the controller?

app/controllers/customers_controller.rb

def create
  ...
  card = {
        'object' => 'card', 'number' => card_number, 'exp_month' => card_expire_month, 'exp_year' => card_expire_year,
        'cvc' => card_cvc, 'address_zip' => parms['zipcode'], 'name' => "#{parms['first_name']} #{parms['last_name']}",
        'address_line1' => parms['street_address_1'], 'address_state' => parms['state'],
        'address_line2' => parms['street_address_2'], 'address_city' => parms['city']
      }

      begin
        resp = Stripe::Customer.create(
          description: 'Customer for DoctorNow',
          metadata: { customer_id: @customer.id },
          email: @customer.email,
          source: card)
        @customer.assign_attributes(
          stripe_customer_id: resp['id'],
          stripe_card_id: resp['sources']['data'][0]['id'],
          stripe_card_last4: resp['sources']['data'][0]['last4'],
          stripe_card_type: resp['sources']['data'][0]['brand']
        )

        event('card_preauth', 'customer_id', @customer.id)
      rescue Stripe::CardError => e
        @err = stripe_error(e, 'creating_card_card_error', 0)
        render :err_show, status: :payment_required, json: @err
        event('card_preauth_failed', 'customer_id', @customer.id)
        return
      rescue Stripe::InvalidRequestError => e
        @err = stripe_error(e, 'create_card_invalid', 0)
        event('card_preauth_failed', 'customer_id', @customer.id)
        render :err_show, status: :payment_required, json: @err
        return
      rescue Stripe::AuthenticationError => e
        @err = stripe_error(e, 'create_card_authentication', 0)
        event('card_preauth_failed', 'customer_id', @customer.id)
        render :err_show, status: :payment_required, json: @err
        return
      rescue Stripe::APIConnectionError => e
        @err = stripe_error(e, 'create_card_connect', 0)
        event('card_preauth_failed', 'customer_id', @customer.id)
        render :err_show, status: :payment_required, json: @err
        return
      rescue Stripe::StripeError => e
        @err = stripe_error(e, 'create_card_stripe', 0)
        event('card_preauth_failed', 'customer_id', @customer.id)
        render :err_show, status: :payment_required, json: @err
        return
      rescue => e
        @err = stripe_error(e, 'create_card_generic', 0)
        render :err_show, status: :payment_required, json: @err
        event('card_preauth_failed', 'customer_id', @customer.id)
        return
      end
  ...
end


texts:
I'm just starting to get along with threads in Java and I need some code review,
about interfaces, classes, managing threads, correct writing, secure threads, exposed objects etc.

Horse-Race Implementation:

package HorseRace;

public interface FinishingLine {

    public void arrive(Horse h);
}

package HorseRace;

import java.util.Vector;

public class FinishingLineImpl implements FinishingLine {

    Vector<String> Ranking = new Vector<String>(10);

    public FinishingLineImpl(){}
    @Override
    public void arrive(Horse h) {
        // TODO Auto-generated method stub
        Ranking.add(h.getId());
    }

    public void print()
    {
        for (int i = 0; i < 10 ; i++)
        {
            System.out.println("Place " + (i + 1)+ " is : " + Ranking.get(i));
        }
    }
}

package HorseRace;

public interface Horse {

    public void run();
    public String getId();
}

package HorseRace;
import java.util.Random;

public class HorseImpl implements Horse,Runnable {

    int _distance;
    String _id;
    FinishingLine _f;

    public HorseImpl(String id, FinishingLine f)
    {
        _id = id;
        _distance = 0;
        _f = f;
    }
    @Override
    public void run() {
        // TODO Auto-generated method stub
        Random rand = new Random();

        int n = rand.nextInt(10) + 1;

        while (_distance < 100)
        {
            try
            {
                Thread.sleep(n);
            }
            catch (Exception e)
            {
                e.printStackTrace();
            }
            _distance += 1;
        }

            _f.arrive(this);
    }

    @Override
    public String getId() {
        // TODO Auto-generated method stud
        return _id;
    }
}

package HorseRace;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

public class Main {

    public static void main(String[] args) throws InterruptedException {
        // TODO Auto-generated method stub

        ExecutorService e = Executors.newFixedThreadPool(10);
        FinishingLineImpl f = new FinishingLineImpl();

        for (int i = 0; i<10 ; i++)
        {
            System.out.println("Creating a horse with id = " + (i+1));
            String strI = Integer.toString(i+1);
            HorseImpl h = new HorseImpl(strI,f);
            e.execute(h);
        }

        e.shutdown();
        e.awaitTermination(60000, TimeUnit.SECONDS);

        f.print();
    }
}


texts: Create or update a row in a queue with the given new item

texts:
This works just as documented, but the code doesn't make it very clear that it does:

/**
 * Queues the given item and returns the success of this operation.
 *
 * @param newItem      The item to enqueue
 * @param rowUUID      The optional UUID of an existing row.
 *
 * @return @c YES iff the given item could be enqueued.
 */
- (BOOL) addToQueue:(id)newItem
            rowUUID:(NSString *)rowUUID
{
    // This wrapper method allows use of the old method signature and be guaranteed the old method behavior.
    return [self addToQueue:newItem rowUUID:rowUUID updateOldRow:YES];
}

/**
 * Queues the given item and returns the success of this operation.
 *
 * @param newItem      The item to enqueue
 * @param rowUUID      The UUID of an existing row if @c updateOldRow , else of a
 *                     new row.
 * @param updateOldRow If @c rowUUID is @c nil , does nothing. Else, if @c YES ,
 *                     requires a row with the UUID @c rowUUID to exist and updates
 *                     it with the new item. Else, creates a new row with that UUID.
 *
 * @return @c YES iff the given item could be enqueued.
 */
- (BOOL) addToQueue:(id)newItem
            rowUUID:(NSString *)rowUUID
       updateOldRow:(BOOL)updateOldRow
{
    // When updateOldRow == YES, the method behaves as it did before my changes.
    RowObject *row;
    if (rowUUID && updateOldRow)
    {
        row = [self getOldRowWithUUID:rowUUID];
        if (!row)
        {
            return NO;
        }
    }
    else
    {
        row = [self makeNewRow];
    }

    if (!rowUUID)
    {
        row.uuid = [self generateNewUUID];
    }
    else if (!updateOldRow)
    {
        row.uuid = rowUUID;
    }

    row.contents = newItem;

    return [self queueRow:row];
}

As the doc comment says, this is supposed to create or update a row in a queue with the given new item, based on the value of updateOldRow. If that is YES, then the method attempts to use rowUUID to pop an old row to update, but if it cannot find such a row, the method fails immediately. If updateOldRow is NO, then a new row is created with the given rowUUID, or a new one if none is given. After all that, the new item is saved in the row and the row is placed in the queue.

Please keep in mind, this is a genericized but working version of my code based on the real (proprietary) code; it behaves and is structured the same. Also, this has to be pored over to ensure it works just as documented, and even more-so if you don't trust/read the documentation.

How can I restructure this code so it works the same, but is easier to understand?


texts:
I am new to Django and added a vote duplicate check to the tutorial application. I set a cookie in the vote view:

cookie_name = 'voted'
cookie_pattern = '^(\d-?)+$'
# ...
def vote(request, question_id):
    question = get_object_or_404(Question, pk=question_id)
    # ...
    # Set duplicate vote cookie.
    half_year = timedelta(weeks=26)
    expires = datetime.utcnow() + half_year
    if cookie and re.match(cookie_pattern, cookie):
        redirect.set_cookie(cookie_name, "{}-{}".format(cookie, question.id), expires=expires)
    else:
        redirect.set_cookie(cookie_name, question.id, expires=expires)

And then check for the cookie in the detail and vote view:

def has_voted(cookie, question_id):
    """Checks for question_id in cookie"""
    return cookie and \
        re.match(cookie_pattern, cookie) and \
        question_id in list(map(int, cookie.split('-')))

class DetailView(generic.DetailView):
    model = Question
    template_name = 'polls/detail.html'

    # ...
    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        # Check duplicate vote cookie
        cookie = self.request.COOKIES.get(cookie_name)
        if has_voted(cookie, self.object.id):
            context['voted'] = True
        return context

def vote(request, question_id):
    question = get_object_or_404(Question, pk=question_id)
    cookie = request.COOKIES.get(cookie_name)
    if has_voted(cookie, question.id):
        return render(request, 'polls/detail.html', {
            'question': question,
            'voted': True,
        })

What can be improved in this implementation?


texts: The Miller-Rabin Primality Test in Clojure

texts:
I am new to clojure and I wanted to test out my skills by taking an existing implementation written in Python and writing it in Clojure.

Concerns

My main concerns are where I use cond and put an upto parameter in the function definitions of isWitness and probablyPrime. I am not sure if that's the best way to loop (I tried using the actual loop construct but found out, you couldn't break out of it).

Furthermore, on line 41 where I call the isWitness function from probablyPrime seems very messy. I am calling decompose twice when calling it once would be best (I don't know how to simulate local "variables" or use let properly).

Also I have separated a part of my isWitness into another function called checkWitness. I am not sure if that's the best way to do it.

(ns jeremy-kun.miller-rabin
  (:require [clojure.math.numeric-tower :as math]))

;; This is the clojure version of the original python code done on jeremykun website
;; https://jeremykun.com/2013/06/16/miller-rabin-primality-test/
(defn pow [x y & [z]]
  (if z
    (mod (math/expt x y) z)
    (math/expt x y)))

(defn rand-between [n]
  (rand-nth (range 2 n)))

(defn decompose [exponent-of-two n]
  (if (not= 0 (mod n 2))
    {:exponent exponent-of-two :n n}
    (decompose (+ 1 exponent-of-two) (/ n 2))))

(defn checkWitness [possibleWitness p exponent remainder upto]
  (cond (> upto exponent) true
    (= (- p 1) (pow possibleWitness 2 p)) false
    :else (checkWitness (pow possibleWitness 2 p) p exponent remainder (inc upto)))
  )

(defn isWitness [possibleWitness p exponent remainder upto]
  (cond
    (or (= (pow possibleWitness remainder p) 1) (= (pow possibleWitness remainder p) (- p 1))) false
    (zero? exponent) true
    :else (checkWitness (pow possibleWitness remainder p) p exponent remainder upto)))

(defn probablyPrime [p accuracy upto]
  (if (or (= p 2) (= p 3))
    true)

  (if (< p 2)
    false)

  (cond
    (> upto accuracy) true
    (isWitness (rand-between (- p 2)) p (:exponent (decompose 0 (- p 1))) (:n (decompose 0 (- p 1))) 0) false
    :else (probablyPrime p accuracy (inc upto))
    ))

;;(def test-witness [[10 5] [11 9] [12 5] [13 10] [14 11] [15 3] [16 13] [17 3] [18 7] [19 11]])

;;
;(prn
;  (map (fn [x] (isWitness (last x) (first x)
;                         (:exponent (decompose 0 (- (first x) 1))) (:n (decompose 0 (- (first x) 1)))
;                         0))
;       test-witness))

(prn (probablyPrime 25 100 0))                              ;; false
(prn (probablyPrime 100 100 0))                             ;; false
(prn (probablyPrime 151 100 0))                             ;; true
(prn (probablyPrime 97 100 0))                              ;; true

Test Cases

I have already included four test cases for primes. If you want to test more then just replace the first parameter and leave the rest as is, especially upto.

The block of code that is commented out tests the isWitness function. You can test it out by uncommenting the code and the value test-witness. The value test-witness is a list of lists. Each element in the list of list is the value to check and a random number between 2 and the value you want to test for primality minus 2.

For instance, [10 5], 10 is the value to check for primality and 5 is a random number between 2 and 10.

If you uncomment the block and run the code, it should return

(true false true false true true true false true false)

which is what the python code runs if you use the same values.


texts:
This is a byte stream implementation in C. Its usage and purpose should be evident from main.

Implementation is not finished; this is just start. Comments are still welcome.

.h:

#include <stdint.h>

typedef struct
{
    uint8_t * data;
    uint32_t length;
    uint32_t offset;
} ByteStream;

int32_t BSInitWithSize(ByteStream *bs, uint32_t len);
uint32_t BSNrOfRemainingBytes(ByteStream *bs);
int32_t BSFreeUnderlyingArray(ByteStream *bs);
void BSPrintContents(ByteStream *bs);
void BSRewind(ByteStream *bs);
int32_t BSPutU8(ByteStream *bs, uint8_t v);
int32_t BSGetU8(ByteStream *bs, uint8_t *out);
int32_t BSPutU16LE(ByteStream *bs, uint16_t v);

.c:

#include "ByteStream.h"
#include <stdlib.h>
#include <stdio.h>
#include <string.h>

int32_t BSInitWithSize(ByteStream *bs, uint32_t len)
{
    if (NULL == bs)
        return -1;

    // Allocate data array of sufficient length
    bs->data = (uint8_t*)malloc(len); // Note: Probably should check return value here
    memset(bs->data,0,len); // set values to nil

    bs->length = len;
    bs->offset = 0;

    return 0;
}

uint32_t BSNrOfRemainingBytes(ByteStream *bs)
{
    return bs->length - bs->offset;
}

void BSRewind(ByteStream *bs)
{
    bs->offset=0;
}

int32_t BSPutU8(ByteStream *bs, uint8_t v)
{
    if(BSNrOfRemainingBytes(bs)<1)
        return -1;

    bs->data[bs->offset]=v;
    bs->offset++;

    return 0;
}

int32_t BSGetU8(ByteStream *bs, uint8_t *out)
{
    if(BSNrOfRemainingBytes(bs)<1)
        return -1;

    bs->offset++;
    *out= bs->data[bs->offset-1];

    return 0;
}

int32_t BSPutU16LE(ByteStream *bs, uint16_t v)
{
    if(BSNrOfRemainingBytes(bs)<2)
        return -1;

    // This code compiles on LE machine, so
    // copying a integer to buffer will write
    // the integer into the buffer in a little endian way
    // exactly what this method is supposed to do
    // Note: Probably this is not portable
    memcpy(&bs->data[bs->offset],&v,2);
    bs->offset+=2;

    return 0;

}

void BSPrintContents(ByteStream *bs)
{
    int i = 0;
    for(i=0; i<bs->offset; i++)
    {
        printf("%02X ",bs->data[i]);
    }
}

int32_t BSFreeUnderlyingArray(ByteStream *bs)
{
    // Free underlying data array of BS object if it is not NULL
    if(NULL != bs->data)
    {
        free(bs->data);
        bs->data=NULL; // Set to NULL
        return 0;
    }

    return -1;
}

main:

#include "stdafx.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

extern "C"
{
#include "ByteStream.h"
}

int _tmain(int argc, _TCHAR* argv[])
{
    ByteStream b;
    memset(&b,0,sizeof(b));

    // Init bs
    BSInitWithSize(&b,14);

    // Add values
    for(int i=0;i<12;i++)
    {
        if(-1 == BSPutU8(&b, (uint8_t)i))
            printf("Error putting data \n");

        printf("Remaining Free Bytes: %d\n",BSNrOfRemainingBytes(&b));
    }

    // Rewind
    printf("---\n");
    BSRewind(&b);

    // Print values
    for(int i=0;i<12;i++)
    {
        uint8_t t;

        if(-1 == BSGetU8(&b, &t))
        {
            printf("ERROR Getting value \n");
        }
        else
            printf("Value at %d is %d \n", i, t);
    }

    // Put short integer in a little endian way
    if(-1 == BSPutU16LE(&b,765))
        printf("Error putting short \n");

    BSPrintContents(&b);

    // Free underlying buffer
    BSFreeUnderlyingArray(&b);

    return 0;
}

In many cases I decided to return error code from functions, and pass return values as out parameters.


texts:
Goproxy is a Go package implementing an HTTP proxy.
I am using it to store requests from a client (eg: a web browser) for further processing.

In an http.Request struct, the Body is an io.ReadCloser, it can only be read once.

The problem I faced is that I need to read the Body to store it, but still make it accessible to goproxy so that it can be sent to the server.

I solved it by reading the body with ioutil.ReadAll, and then creating a   ReadCloser with the byte slice I got. I then assign this ReadCloser to the request Body.

package main

import (
    "bytes"
    "flag"
    "fmt"
    "io/ioutil"
    "log"
    "net/http"
    "net/url"
    "regexp"
    "sync"

    "github.com/elazarl/goproxy"
)

var requests map[string][]Request
var mutex sync.Mutex

type Request struct {
    Method        string
    URL           url.URL
    Proto         string // "HTTP/1.0"
    ProtoMajor    int    // 1
    ProtoMinor    int    // 0
    Header        http.Header
    Body          []byte
    ContentLength int64
    Host          string
    PostForm      url.Values
    RequestURI    string
}

type RequestBody struct {
    *bytes.Reader
}

func (r RequestBody) Close() error {
    return nil
}

func storeRequest(r *http.Request, ctx *goproxy.ProxyCtx) (*http.Request, *http.Response) {
    body, err := ioutil.ReadAll(r.Body)
    if err != nil {
        // only print error for now
        log.Println(err)
        return r, nil
    }
    r.Body.Close()
    r.Body = RequestBody{bytes.NewReader(body)}
    fmt.Println(string(body))
    mutex.Lock()
    requests[r.URL.Host] = append(requests[r.URL.Host], Request{
        Method:        r.Method,
        URL:           *r.URL,
        Proto:         r.Proto,
        ProtoMajor:    r.ProtoMajor,
        ProtoMinor:    r.ProtoMinor,
        Header:        r.Header,
        Body:          body,
        ContentLength: r.ContentLength,
        Host:          r.Host,
        PostForm:      r.PostForm,
        RequestURI:    r.RequestURI,
    })
    mutex.Unlock()
    return r, nil
}

func main() {
    proxy := goproxy.NewProxyHttpServer()
    proxy.OnRequest(goproxy.ReqHostMatches(regexp.MustCompile("^.*$"))).
        HandleConnect(goproxy.AlwaysMitm)
    proxy.OnRequest().DoFunc(storeRequest)

    requests = make(map[string][]Request)

    addr := flag.String("addr", ":8080", "proxy listen address")
    flag.Parse()
    log.Fatal(http.ListenAndServe(*addr, proxy))
}

I would like to know if this is a correct way of solving this problem.


texts:
I would like to get a feedback about the code below. Is there any way to improve its performance? Maybe you know input values that might print bad output? The idea of the code is to count unique characters from s2 that are not listed in s1.

Ideone.com URL

class Combine {
    public static void main(String[] args) throws IOException {
        BufferedReader bi = new BufferedReader(new InputStreamReader(System.in));
        String s1 = bi.readLine();
        String s2 = bi.readLine();

        String usedCharacters = "";

        for(int i = 0; i < s2.length(); i++) {
            String c = Character.toString(s2.charAt(i));
            if(!usedCharacters.contains(c) && !s1.contains(c))
                usedCharacters += c;
        }

        System.out.println(usedCharacters.length());
    }
}


texts:
I'm trying to find the best solutions for operations on the following database:

  Employee (EmployeeId, Surname, Salary, DepartmentId)
  Department (DepartmentId, DeptName, City, Director)
  Project (ProjectId, ProjectName, Budget, Director)
  Works (EmpoyeeId, ProjectId)

My queries:

1 SQL query to find the surname of the employees who are directors of a department.

SELECT Surname
FROM Employee
WHERE Employee.EmployeeId IN (
SELECT Department.Director
FROM Department
);

2 SQL query to find the employee surname and salary of all employees who work in Haarlem.

SELECT Surname, Salary, City
FROM Employee,Department
WHERE Department.City = ‘Haarlem’;

3 SQL query to find the names of the projects whose budget is higher than 100 and the surnames of the employees who work on them.

SELECT ProjectName, Budget, Surname
FROM Project, Employee, Works
WHERE Project.Budget > 100
AND Works.EmployeeId = Employee.EmployeeId
AND Works.ProjectId = Project.ProjectId;

Are there any better ways to get the information needed?


texts: Using object oriented PHP to display users in a database

texts:
I'm new to object oriented PHP, so I'm sure of the good or bad practices. The below code is working perfectly, I just don't know if it is a bad or good approach to use most of the methods as static and declare class properties as public.

Could someone provide me some advise?

In users.php

<?php

class Users{

  public $user_id, $user_name, $user_email, $user_fname, $user_lname, $user_role;

  public static function display_users(){
      $display_users[] = self::find_all_query("SELECT * FROM users");
      return (!empty($display_users)) ? array_shift($display_users) : false;
  }

  public static function find_all_query($sql){
    global $database;
    $result = $database->query($sql);
    $db_result = array();
    while($row = mysqli_fetch_assoc($result)){
      $db_result[] = self::instantiation($row);
    }

    return $db_result;

  }

  public static function instantiation($row){

    $the_users_object = new Users();

    foreach ($row as $attribute => $data) {
      if($the_users_object->has_the_attribute($attribute)){
        $the_users_object->$attribute = $data;
      }
    }
    return $the_users_object;
  }

  private function has_the_attribute($attribute){
     $users_properties = get_object_vars($this);
     return array_key_exists($attribute , $users_properties);
  }

}
?>

In admin-users.php

<?php
$display_users = Users::display_users();

foreach ($display_users as $users) {
  echo "
";
    echo " $users->user_id    	";
    echo " $users->user_name   	";
    echo " $users->user_email 	";
    echo " $users->user_fname 	";
    echo " $users->user_lname 	";
    echo " $users->user_role 	";
  echo "
";
}
?>

In database.php

<?php
// require_once("init.php");

class Database{

  private $connection;

      function __construct(){
        $this->open_db_connection();

      }

      public function open_db_connection(){
        $this->connection = new mysqli(DB_HOST,DB_USER,DB_PASS,DB_NAME);

          if($this->connection -> connect_error){
            die('
Database Connection Failed!!!!
.'. $this->connection -> connect_error);
          }

      }

      private function checkQuery($query){
        if(!$query){
          die("
Query Failed!!!!
 ". $this->connection -> error);
        }
      }

      public function query($sql){
        $result = mysqli_query($this->connection , $sql);
        $this->checkQuery($result);
        return $result;

      }

}

      $database = new Database();

?>


texts: Should I Move Methods To A Different Class

texts:
The following code is part a class called class db_tables. All the other getTbl* methods other than getTblHerd pull information based on the ID of the animal that is passed to them.

My question is while the following code works would it be better to move all the other getTbl methods into the Animal class and pass them the ID stored in the Animal class.

Thanks,

public static ArrayList<Animal> getTblHerd() throws Exception {
    CC_H2 db = new CC_H2();
    db.Connect(Variables.getStrConn(), Variables.getStrUser(),
            Variables.getStrPassword(), "Embedded");
    ResultSet rs = db
            .query("Select HERD_ID FROM tblHerd ORDER BY HERD_ID ASC");

    ArrayList<Animal> alAnimals = new ArrayList<Animal>();

    while (rs.next()) {
        int i = rs.getInt("HERD_ID");
        alAnimals.add(new Animal(i));
    }
    db.Disconnect();
    return alAnimals;
}

public static ArrayList<Note> getTblNotes(int intID) throws Exception {
    CC_H2 db = new CC_H2();
    db.Connect(Variables.getStrConn(), Variables.getStrUser(),
            Variables.getStrPassword(), "Embedded");
    ResultSet rs = db
            .query("Select NOTE_ID FROM tblNotes WHERE NOTE_HERD_ID = "
                    + intID + " ORDER BY Note_Date DESC");

    ArrayList<Note> alNotes = new ArrayList<Note>();

    while (rs.next()) {
        int i = rs.getInt("NOTE_ID");
        alNotes.add(new Note(i));
    }
    db.Disconnect();
    return alNotes;
}

public static ArrayList<Vaccination> getTblVaccination(int intID) throws Exception {
    CC_H2 db = new CC_H2();
    db.Connect(Variables.getStrConn(), Variables.getStrUser(),
            Variables.getStrPassword(), "Embedded");
    ResultSet rs = db
            .query("Select Vac_ID FROM tblVaccination WHERE VAC_HERD_ID = "
                    + intID + " ORDER BY Vac_Date DESC");

    ArrayList<Vaccination> alVaccinations = new ArrayList<Vaccination>();

    while (rs.next()) {
        int i = rs.getInt("VAC_ID");
        alVaccinations.add(new Vaccination(i));
    }
    db.Disconnect();
    return alVaccinations;
}

public static ArrayList<Owner> getTblOwners(int intID) throws Exception {
    CC_H2 db = new CC_H2();
    db.Connect(Variables.getStrConn(), Variables.getStrUser(),
            Variables.getStrPassword(), "Embedded");
    ResultSet rs = db
            .query("Select Owner_ID FROM tblOwners WHERE Owner_ID = "
                    + intID + " ORDER BY Owner_Last_Name ASC");

    ArrayList<Owner> alOwners = new ArrayList<Owner>();

    while (rs.next()) {
        int i = rs.getInt("Owner_ID");
        alOwners.add(new Owner(i));
    }
    db.Disconnect();
    return alOwners;
}


texts: Summing all parameters, except the last, which should be subtracted instead

texts:
Working on some python koans and got one which states:

def f(a, b, z):

    """Rewrite this function to take an arbitrary number of arguments.

    It should add up all but the last argument and then subtract the
    last argument from the total.

    If no arguments are provided then return 0.
    """
    return a + b - z

My solution:

def f(*args):
    return sum(args[:-1]) - args[-1] if args else 0

This gives 2 out of 3 stars for a solution. I am not asking for help to get 3 stars specifically, but, rather for a review of what I have, and to see if there is perhaps something I am missing, or even if you consider my solution to be good as it is.

Out of interest, I've have also tried:

try:
    return sum(args[:-1]) - args[-1]
except IndexError:
    return 0

but that did not get 3 stars either.

What I am looking for is whether there is or isn't a more 'Pythonic' way of doing this, maybe reduce it even further than what I had there.

If there is only 1 value then the logic should give you the negative of your element.


texts: Sequence Generator from previous max sequence based on certain conditions

texts:
I'm new to VBA programming so the following code may look terrible which is why I want ways to understand how to better optimize it and other future codes.

Sub Sequence()
Application.ScreenUpdating = False
Application.Calculation = xlCalculationManual
Application.DisplayAlerts = False
Dim unique_string1, unique_string2, unique_string3 As String

Dim arrj() As String
Dim arrk() As String
Dim arro() As String
Dim a, b, c As Long

'ARRAYj

jr = Sheets("Docs").Cells(Sheets("Docs").Rows.Count, 1).End(xlUp).Row
Set range1 = Sheets("Docs").Range("J2:J" & jr)
For Each cel In range1
    If Not InStr(unique_string1, cel.Value) > 0 Then
        unique_string1 = unique_string1 & cel.Value & ","
    End If
Next
arrj = Split(unique_string1, ",")

'ARRAYk

kr = Sheets("Docs").Cells(Sheets("Docs").Rows.Count, 1).End(xlUp).Row
Set range2 = Sheets("Docs").Range("K2:K" & kr)
For Each cel In range2
    If Not InStr(unique_string2, cel.Value) > 0 Then
        unique_string2 = unique_string2 & cel.Value & ","
    End If
Next
arrk = Split(unique_string2, ",")

'ARRAYo

pr = Sheets("Docs").Cells(Sheets("Docs").Rows.Count, 1).End(xlUp).Row
Set range3 = Sheets("Docs").Range("o2:o" & pr)
For Each cel In range3
    If Not InStr(unique_string3, cel.Value) > 0 Then
        unique_string3 = unique_string3 & cel.Value & ","
    End If
Next
arro = Split(unique_string3, ",")

'ForLoop

For a = LBound(arrj) To UBound(arrj)
    For b = LBound(arrk) To UBound(arrk)
        For c = LBound(arro) To UBound(arro)
            If Not (arrj(a) = "" Or arrk(b) = "" Or arro(c) = "") Then

                Dim x, y, z As String
                x = Trim(arrj(a))
                y = Trim(arrk(b))
                z = Trim(arro(c))

                Dim lRow   As Long, i As Long
                Dim ws     As Worksheet
                Dim nextn  As Long
                Dim getAddress As String
                Set ws = ActiveSheet

                With ws
                    lRow = .Cells(.Rows.Count, 1).End(xlUp).Row

                    For i = 2 To lRow
                        If .Cells(i, 10).Value = x And .Cells(i, 11).Value = y And .Cells(i, 15).Value = z And .Cells(i, 23).Value = "" Then
                            getAddress = .Cells(i, 23).Address
                            nextn = 1 + Application.Evaluate("MAX(IF((J2:J20000=""" & x & """)*(K2:K20000=""" & y & """)*(O2:O20000=""" & z & """),INT(w2:20000)))")
                            Range(getAddress).Value = nextn
                        End If
                    Next i
                End With
            End If
        Next c
    Next b
Next a
Application.ScreenUpdating = True
Application.DisplayAlerts = True
Application.Calculation = xlCalculationAutomatic
End Sub

So the code gets the distinct value from the columns and stores it in an array. Then those 3 arrays containing the distinct value combination is used to check for the max of the sequence and assigned a plus 1 to the max sequence if found. Else a 1.

How could I make this run faster considering there are a lot of rows and combinations to check?

P.s: If you have a code for getting distinct value from a column and store it into and array it would be great.

Mock-DATA

   J     K     O         W
1jobid  dep  job_no   Sequence
2 aaa   FJ     1         1      <existing data>
3 aaa   FJ     1         2
4 aaa   FJ     1         5
5 aaa   RJ     1         1
6 aaa   RJ     1         9
7 aaa   RJ     1         10     <existing data>
-----------------------------------------------------
8 aaa   RJ     1         11     <after the code is run, 11 is assigned>
9 aaa   FJ     1          6     <after the code is run, 6 is assigned >

columns J,K,O are strings and column W is number.

EDIT : As mentioned in the comments changed Range("J2:J20000" & jr) to Range("J2:J" & jr)


texts: Counting lowercase and uppercase letters in a string in Python

texts:
I am writing a program to count the number of uppercase and lowercase letters in a string. I came up with something that works, but as I am still a beginner I have a feeling writing the code this way is probably considered "clumsy."

Here is what I have:

stri = input("Give me a phrase:")
stri_up = 0
stri_lo = 0
for i in stri:
    if i.isupper():
        stri_up += 1
    if i.islower():
        stri_lo += 1
print("The number of uppercase letters in your phrase is:", stri_up)
print("The number of lowercase letters in your phrase is:", stri_lo)

Output:

Give me a phrase: tHe Sun is sHininG
The number of uppercase letters in your phrase is: 4
The number of lowercase letters in your phrase is: 11

I would like to learn how to write neat, beautiful code so I am wondering if there is a more efficient and elegant way to code this.


texts:
I have functions of permutation :

function permutations($letters,$num)
{
   $last = str_repeat($letters[0],$num);
   $result = array();
   while($last != str_repeat($this->lastchar($letters),$num))
   {
       $result[] = $last;
       $last = $this->char_add($letters,$last,$num-1);
   }
   $result[] = $last;
   return $result;
}

function char_add($digits,$string,$char)
{
    error_reporting(0);

    if($string[$char] < $this->lastchar($digits))
    {
       $string[$char] = $digits[strpos($digits,$string[$char])+1];
       return $string;
    }
    else
    {
       $string = $this->changeall($string,$digits[0],$char);
       return $this->char_add($digits,$string,$char-1);
    }
}

function lastchar($string)
{
   return $string[strlen($string)-1];
}

function changeall($string,$char,$start = 0,$end = 0)
{
   if($end == 0) $end = strlen($string)-1;
   for($i=$start;$i<=$end;$i++){
       $string[$i] = $char;
   }
   return $string;
}

Example to run this :

print_r($this->permutations('1234',2));

And results will be:

Array(
[0] => 11
[1] => 12
[2] => 13
[3] => 14
[4] => 21
[5] => 22
[6] => 23
[7] => 24
[8] => 31
[9] => 32
[10] => 33
[11] => 34
[12] => 41
[13] => 42
[14] => 43
[15] => 44)

It can run well. However, when I run with greater number of permutation like : $this->permutations('1234',5) , the script will cause memory exhaustion.

What can I change to optimize the functions ?


texts:
After a long break I have to return to programming in C. As an exercise I wrote this simple linked list thing. Please just have a look, any comments are appreciated. Just shoot.
#include <stdlib.h>
#include <stdio.h>

typedef struct
{
  int iNumber;
} TData;

typedef struct TLinkedList
{
  struct TLinkedList* iNext;
  TData iData;
} TLinkedList;

TLinkedList* Create(TData* aData)
{
  TLinkedList* ptr = (TLinkedList*) malloc(sizeof(TLinkedList));
  ptr->iData = *aData;
  ptr->iNext = NULL;

  return ptr;
}

void AddToLinkedList(TLinkedList** aLinkedListStart, TData* aData)
{
  printf("%s: aData->iNumber %i\n", __FUNCTION__, aData->iNumber);

  TLinkedList* newItem = Create(aData);

  if (*aLinkedListStart == NULL)
  {
    *aLinkedListStart = newItem;
  }
  else
  {
    TLinkedList* runner = *aLinkedListStart;

    while((*runner).iNext != NULL)
    {
      runner = runner->iNext;
    }

    runner->iNext = newItem;
  }
}

void FreeLinkedList(TLinkedList** aLinkedListStart)
{
  TLinkedList* runner = *aLinkedListStart;

  while((*runner).iNext != NULL)
  {
    TLinkedList* freePtr = runner;
    runner = runner->iNext;
    free(freePtr);
  }
}

void DisplayLinkedList(TLinkedList* aLinkedList)
{
  while(aLinkedList != NULL)
  {
    printf("%s: iNumber %i\n", __FUNCTION__, aLinkedList->iData.iNumber);
    aLinkedList = aLinkedList->iNext;
  }
}

int main()
{
  TLinkedList* firstPtr = NULL;

  TData myData_1 = {1};
  TData myData_2 = {2};
  TData myData_3 = {3};

  AddToLinkedList(&firstPtr, &myData_1);
  DisplayLinkedList(firstPtr);

  AddToLinkedList(&firstPtr, &myData_2);
  DisplayLinkedList(firstPtr);

  AddToLinkedList(&firstPtr, &myData_3);
  DisplayLinkedList(firstPtr);

  FreeLinkedList(&firstPtr);

  return 0;
}

```


texts: SQL Query that pulls rows in current table based on parent id optimization

texts:
I am creating a user permission system. I will have my user permissions set up off of "objects" and not pages. For example, I have an EVENTS section. Within that section, there are FORMS, FEES, etc. I want to be able to handle permissions down to the child levels.

Here is my permission_objects table:

| id | object | parent_id |
+----+--------+-----------+
| 1  | EVENTS | NULL      |
| 2  | FORMS  | 1         |
| 3  | FEES   | 1         |

Here is my current query:

SELECT `up`.*
FROM `permission_objects` `po`
INNER JOIN `user_permissions` `up` ON `up`.`object`=`po`.`id` AND (`up`.`user_group`=2 OR `up`.`user_id`=17)
WHERE `po`.`object`='EVENTS' OR `po`.`parent_id`=(
  SELECT `id` FROM `permission_objects` WHERE `object`='EVENTS'
)

I really want to avoid doing a subquery. I thought that instead of having a parent_id I could have parent_object and have that contain the parent's object value. i.e. | 2 | FORMS | EVENTS |. That way I could change my WHERE clause to:

WHERE `po`.`object`='EVENTS' OR `po`.`parent_object`='EVENTS'

However I feel that keeping it as parent_id is a better approach. Is there a way to keep that but not have to have a subquery in my sql?


texts:
I am currently using the following to convert [url=][/url] to an HTML link:

s = message.replace(/\[url=([^\]]+)\]\s*(.*?)\s*\[\/url\]/gi, "$2")

That work's fine.

I then added on another replace function using a regular expression to replace www with http://www like so:

s = message.replace(/\[url=([^\]]+)\]\s*(.*?)\s*\[\/url\]/gi, "$2")
.replace(/www/g, "http://www");

This is probably not the best/efficient method and also does not support https:// which is not a priority at the moment, but it is something I would like to include at some point. What could I do to improve the regular expression?

I asked this on Stack Overflow. However, I was informed that the type of question was not really fit for there, which I understand.


texts: Filtering data on basis of attribute values

texts:
I am writing code to filter data on basis of attribute values. It is possible that the user can select multiple values.

How can this be better?

Models.Products filter(ViewModel.Filter search,IEnumerable<Models.Products> product)
{
    if (search.filter!= null && search.filter.Count>0)
        {
             var f = search.First();
             var tempProducts = products
                               .Where(c => c.productattributes
                                            .Where(a => a.AttributeId == f.Id && f.Value.Contains(a.Value))
                                            .Any());
             search.filter.Remove(f);
             foreach (var fs in search)
             {
                var p = products.Where(c => c.productattributes.Where(a => a.AttributeId == fs.Id && fs.Value.Contains(a.Value)).Any());
                tempProducts = tempProducts.Union(p);
             }
             products = tempProducts;
        }
}

Filter View Model:

public class Filters
{
    public long Id { get; set; }

    public IEnumerable<string> Value { get; set; }
}


texts: Co-inductive hypothesis for transitivity of stream bisimulation

texts:
Catalin Hritcu published some notes on coinduction in Coq, including a discussion of coinduction principles in the style of Giménez and Castéran. One of the exercises is to show that stream bisimulation is transitive using the following coinduction principle:

stream_eq_coind
     : forall (A : Type) (R : stream A -> stream A -> Prop),
       (forall s1 s2 : stream A, R s1 s2 -> head s1 = head s2) ->
       (forall s1 s2 : stream A, R s1 s2 -> R (tail s1) (tail s2)) ->
       forall s1 s2 : stream A, R s1 s2 -> stream_eq s1 s2

The "hard part", if any, is finding a coinduction hypothesis. Here is mine:

Definition stream_eq_trans_principle {A : Type} (t1 t3 : stream A) :=
  exists t2, stream_eq t1 t2 /\ stream_eq t2 t3.

The proof follows naturally.

My question: is this the "canonical" induction hypothesis for this problem, or is there a different one which is considered more elegant?

Here is some stand-alone code for experimenting with.

Require Import Relations RelationClasses.

Set Implicit Arguments.

CoInductive stream (A : Type) : Type :=
  | scons : A -> stream A -> stream A.

CoInductive stream_eq (A : Type) {eqA : relation A} `{EQ : Equivalence A eqA} : stream A -> stream A -> Prop :=
| eqstep : forall h1 h2 t1 t2, eqA h1 h2 -> stream_eq t1 t2 -> stream_eq (scons h1 t1) (scons h2 t2).

Section stream_eq_coind.
  Variable A : Type.
  Variable eqA : relation A.
  Context `{EQ : Equivalence A eqA}.
  Variable R : relation (stream A).

  Hypothesis H1 : forall h1 h2 t1 t2,
    R (scons h1 t1) (scons h2 t2) -> eqA h1 h2.
  Hypothesis H2 : forall h1 h2 t1 t2,
    R (scons h1 t1) (scons h2 t2) -> R t1 t2.

  Theorem stream_eq_coind : forall s1 s2 : stream A,
    R s1 s2 -> stream_eq s1 s2.
  Proof.
    cofix. intros s1 s2 H0.
    destruct s1, s2.

    specialize (H1 H0). simpl in H1. subst.
    specialize (H2 H0). simpl in H2.
    specialize (stream_eq_coind _ _ H2) as H3. clear stream_eq_coind.
    apply (eqstep a a0 H1 H3).
  Qed.

End stream_eq_coind.

Check stream_eq_coind.

Lemma stream_eq_refl : forall {A : Type} (s : stream A),
  stream_eq s s.
Proof.
  intros.
  apply stream_eq_coind with (R := fun s1 s2 => s1 = s2).
  - intros. inversion H. reflexivity.
  - intros. inversion H. reflexivity.
  - reflexivity.
Qed.

Lemma stream_eq_sym : forall {A : Type} (s1 s2 : stream A),
  stream_eq s1 s2 -> stream_eq s2 s1.
Proof.
  intros.
  apply stream_eq_coind with (R := fun s1 s2 => stream_eq s2 s1).
  - intros. inversion H0. subst. reflexivity.
  - intros. inversion H0. apply H6.
  - assumption.
Qed.

Definition stream_eq_trans_principle {A : Type} (t1 t3 : stream A) := exists t2, stream_eq t1 t2 /\ stream_eq t2 t3.

Lemma stream_eq_trans : forall {A : Type} (s1 s2 s3 : stream A),
  stream_eq s1 s2 -> stream_eq s2 s3 -> stream_eq s1 s3.
Proof.
  intros A s1 s2 s3 Eq1 Eq2.
  apply stream_eq_coind with (R := stream_eq_trans_principle).
  - intros h1 h3 t1 t3 [t2 [Eq1' Eq2']].
    inversion Eq1'. subst.
    inversion Eq2'. subst.
    reflexivity.
  - intros h1 h3 t1 t3 [t2 [Eq1' Eq2']].
    inversion Eq1'. subst.
    inversion Eq2'. subst.
    exists t4. repeat split; assumption.
  - unfold stream_eq_trans_principle. eauto.
Qed.


texts:
The task
is taken from leetcode

  Given an array A of strings made only from lowercase letters, return a
  list of all characters that show up in all strings within the list
  (including duplicates).  For example, if a character occurs 3 times in
  all strings but not 4 times, you need to include that character three
  times in the final answer.

  You may return the answer in any order.

  Example 1:

  Input: ["bella","label","roller"]

  Output: ["e","l","l"]

  Example 2:

  Input: ["cool","lock","cook"]

  Output: ["c","o"]

  Note:

  1 <= A.length <= 100

  1 <= A[i].length <= 100

  A[i][j] is a lowercase letter

My imperative solution:

function commonChars(A) {
  const [first, ...rest] = A.sort((a,b) => -(a.length - b.length));
  const duplicates = [];
  [...first].forEach(e => {
    let isDuplicate = true;
    for (let x = 0, len = rest.length; x < len; x++) {
      let letters = rest[x];
      const i = letters.search(e);
      if (i !== -1) {
        letters = letters.slice(0, i) + letters.slice(i + 1);
        rest[x] = letters;
      } else {
        isDuplicate = false;
      }
    }
    if (isDuplicate) {
      duplicates.push(e);
    }
  });
  return duplicates;
}

const arr = ["cool","lock","cook"];
console.log(commonChars(arr));

My declarative solution

const commonChars2 = A => {
  const [first, ...rest] = A.sort((a,b) => b.length - a.length));
  return [...first].reduce((duplicates, e) => {
    let isDuplicate = true;
    for (let x = 0, len = rest.length; x < len; x++) {
      const letters = rest[x];
      const i = letters.search(e);
      if (i !== -1) {
        rest[x] = letters.slice(0, i) + letters.slice(i + 1);
      } else {
        isDuplicate = false;
      }
    }
    if (isDuplicate) { duplicates.push(e); }
    return duplicates;
  }, []);
};

const arr = ["cool","lock","cook"];
console.log(commonChars2(arr));

Is there also a good functional approach?


texts:
Here is my solution to the Tower of Hanoi problem using Python

def helper(number_rings: int, origin: int, target: int, spare: int, list_result=[])->list:
    """Helper function works out which ring to move"""
    if number_rings == 1:
        list_result.append([origin, target])
    else:
        #Move all but 1 ring from ORIGIN tower to SPARE tower
        helper(number_rings - 1, origin=origin, target=spare, spare=target)
        #MOVE the last ring from ORIGIN tower to TARGET tower
        helper(1, origin=origin, target=target, spare=spare)
        #MOVE the remaining rings from the SPARE tower to TARGET tower
        helper(number_rings - 1, origin=spare, target=target, spare=origin)
        return list_result

def move_rings(number_rings: int)->int:
    """Function prints the ring move required"""
    dict_rings = {0: "A", 1: "B", 2: "C"}
    if number_rings == 1:
        print("Move from A to C")
        return 1
    list_result = helper(number_rings, 0, 2, 1)
    for item in list_result:
        print("Move from", dict_rings[item[0]], "to", dict_rings[item[1]])
    return len(list_result)

if __name__ == "__main__":
    counter = move_rings(1)
    print(f"Solution possible in {counter} moves")


texts:
I'm working on prepared statements for my website and I'm wondering if it's possible to have multiple prepared statements one after another.  In this example, I have 2 select statements. I'm hoping that the question marks I have as placeholders won't be overwriting one another.  After that's been answered, I was wondering if this code was still open to SQL injection.

function getHomeUploads($conn) {
        $userName = $_GET["user"];
        $sqluserid = "SELECT * FROM users WHERE userName = ?;";
        $useridstmt = mysqli_stmt_init($conn);
        if (!mysqli_stmt_prepare($useridstmt, $sqluserid)) {
            echo "SQL statement failed";
        }
        else {
            mysqli_stmt_bind_param($useridstmt, "s", $userName);
            mysqli_stmt_execute($useridstmt);

            $useridresult = mysqli_stmt_get_result($useridstmt);
            while ($useridrow = mysqli_fetch_assoc($useridresult)) {

                if($useridrow['userid'] > 0) {
                    $userid = $useridrow['userid'];
                    $sqlusercontent = "SELECT * FROM posts WHERE hostid = ? AND userid = ? AND commentid = 0;";
                    $stmtusercontent = mysqli_stmt_init($conn);
                    if (!mysqli_stmt_prepare($stmtusercontent, $sqlusercontent)) {
                        echo "SQL statement failed";
                    }
                    else {
                        mysqli_stmt_bind_param($stmtusercontent, "ss", $userid, $userid);
                        mysqli_stmt_execute($stmtusercontent);
                        $usercontent = mysqli_stmt_get_result($stmtusercontent);
                        $postid = 1;

                        echo "
";
                        echo "
";
                        while ($row = mysqli_fetch_assoc($usercontent)) {
                            // Text fileid
                            if ($row['fileid'] == 1) {
                                echo "
";
                                echo "
";
                                echo $row['title']."
";
                                echo $row['date']."
";
                                echo $row['description']."
";
                                echo "
";
                                echo "
 •••
";
                                echo "
";
                            }
                            // Picture fileid
                            else if ($row['fileid'] == 2) {
                                $filename = "posts/".$userid."/".$postid."*";
                                $fileinfo = glob($filename);
                                $fileext = explode(".", $fileinfo[0]);
                                $fileactualext = $fileext[1];

                                echo "
";
                                echo "
";
                                echo $row['title']."
";
                                echo $row['date']."
";
                                echo "
";
                                echo $row['description']."
";
                                echo "
";
                                echo "
 •••
";
                                echo "
";
                            }
                            else {
                                echo '';
                            }

                            $postid++;
                        }
                        echo "
";
                        echo "
";
                    }
                }
            }
        }
    }
```


texts: Android RecyclerView Adapter: Passing normal clicks and menu clicks over the same activity

texts:
I am unsure about my approach here. As you can see, I want to send normal clicks and 2 different menu item clicks back to the underlying activity over an interface. Now I wonder if it is bad practice to send it over the same interface. I couldn't find an answer online. Also, any suggestions about what to change here?

public class ImageAdapter extends RecyclerView.Adapter<ImageAdapter.ImageViewHolder> {
private Context mContext;
private List<Upload> mUploads;
private OnItemClickListener mListener;

public ImageAdapter(Context context, List<Upload> uploads) {
    mContext = context;
    mUploads = uploads;
}

@Override
public ImageViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View v = LayoutInflater.from(mContext).inflate(R.layout.image_item, parent, false);
    return new ImageViewHolder(v);
}

@Override
public void onBindViewHolder(ImageViewHolder holder, int position) {
    Upload uploadCurrent = mUploads.get(position);
    holder.textViewName.setText(uploadCurrent.getName());
    Picasso.with(mContext)
            .load(uploadCurrent.getImageUrl())
            .placeholder(R.mipmap.ic_launcher)
            .fit()
            .centerCrop()
            .into(holder.imageView);
}

@Override
public int getItemCount() {
    return mUploads.size();
}

public class ImageViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener,
        View.OnCreateContextMenuListener, MenuItem.OnMenuItemClickListener {
    public TextView textViewName;
    public ImageView imageView;

    public ImageViewHolder(View itemView) {
        super(itemView);

        textViewName = itemView.findViewById(R.id.text_view_name);
        imageView = itemView.findViewById(R.id.image_view_upload);

        itemView.setOnClickListener(this);
        itemView.setOnCreateContextMenuListener(this);
    }

    @Override
    public void onClick(View v) {
        if (mListener != null) {
            int position = getAdapterPosition();
            if (position != RecyclerView.NO_POSITION) {
                mListener.onItemClick(position);
            }
        }
    }

    @Override
    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
        menu.setHeaderTitle("Select Action");
        MenuItem doWhatever = menu.add(Menu.NONE, 1, 1, "Do whatever");
        MenuItem delete = menu.add(Menu.NONE, 2, 2, "Delete");

        doWhatever.setOnMenuItemClickListener(this);
        delete.setOnMenuItemClickListener(this);
    }

    @Override
    public boolean onMenuItemClick(MenuItem item) {
        if (mListener != null) {
            int position = getAdapterPosition();
            if (position != RecyclerView.NO_POSITION) {

                switch (item.getItemId()) {
                    case 1:
                        mListener.onWhatEverClick(position);
                        return true;
                    case 2:
                        mListener.onDeleteClick(position);
                        return true;
                }
            }
        }
        return false;
    }
}

public interface OnItemClickListener {
    void onItemClick(int position);

    void onWhatEverClick(int position);

    void onDeleteClick(int position);
}

public void setOnItemClickListener(OnItemClickListener listener) {
    mListener = listener;
}
}


texts:
I have finished a program, and it does what I want it to do, but I feel I am "doing it wrong", even though it's seemingly efficient enough. I have prepared a small example of what I feel I am handling wrong with the backgroundworker class and would like to see if I could have handled this any more cleanly.

First, I have a form with 1 button, 1 statusstrip, 1 toolstripprogressbar, and 1 toolstriplabel. I update the statusstrio items while the backgroundworker is running, as well as show messageboxes across classes. See below.

Form1.cs

namespace StatusStripTest
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void prepareToRun()
        {
            if (!backgroundWorker1.IsBusy)
            {
                backgroundWorker1 = new BackgroundWorker();
                backgroundWorker1.DoWork += delegate
                {
                    Looping.loop(statusStrip1);
                };
                backgroundWorker1.RunWorkerAsync();
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            prepareToRun();
        }

    }
}

Looping.cs

namespace StatusStripTest
{
    public class Looping
    {
        public static void loop(StatusStrip strip)
        {
            Form1 Form1 = new Form1();
            string alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
            while (true)
            {
                MessageBox.Show("Time to loop");
                foreach (char c in alphabet)
                {
                    StripHandler.UpdateProgress(strip, alphabet.IndexOf(c), alphabet.Length);
                    StripHandler.UpdateStatus(strip, c.ToString());
                }
            }

        }
    }

}

StripHandler.cs

namespace StatusStripTest
{
    public class StripHandler
    {
        public static void UpdateStatus(StatusStrip ss, String Status)
        {
            ss.Invoke((MethodInvoker)delegate
            {
                if ((ss.Items[1] as ToolStripStatusLabel) != null)
                {
                    ss.Items[1].Text = Status;
                }
            });
        }

        public static void UpdateProgress(StatusStrip ss, long position, long len)
        {
            ss.Invoke((MethodInvoker)delegate
            {
                if ((ss.Items[0] as ToolStripProgressBar) != null)
                {
                    ToolStripProgressBar tspb = (ToolStripProgressBar)ss.Items[0];
                    tspb.Minimum = 0;
                    tspb.Maximum = (int)len;
                    tspb.Value = (int)position;
                }
            });
        }
    }
}

Am I passing the statusstrip incorrectly?


texts: Euler Project 12# - highly divisible triangular number

texts:
I'm an amateur programmer, new to Java and while attempting the Project Euler Archive 12 (Highly divisible triangular number) I ran into extremely long run time, with no result as of yet.

Is it efficient and what should I do to improve it? Is there a special method to follow when sorting factors of numbers?

Basically I need to find the first triangle number with over 500 divisors.

public class Divisor {

    public static void main(String[] args) {
        int f = 0; //divisors
        int m = 500; //max divisors
        int j = 1; //current number
        int z = 0; //sum (last run achieved: 135878572)
        int a = 1; //current denominator
        String t = ""; //total divisors

            while (f<=m) {
                f = 0;
                z += j;
                j++;
                System.out.println("------");
                System.out.println("t: " + z);
                //Now get factors of each, the first to have over 500 is the answer
                while (a <= z){
                    if ((z % a) == 0) {
                        t += (String.valueOf(a) + "|");
                        f++;
                    }
                    a++;
                }
                System.out.println("f: " + t);
                t="";
                System.out.println("d: " + f);
                a = 1;
            }
            System.out.print("Answer: " + z);
    }

}

Here is an example of my output (first 3 triangle numbers):

------
t: 1   <--- Triangle Number
f: 1|  <--- Factors (Divisors)
d: 1   <--- Total Factors (Total Divisors)
------
t: 3
f: 1|3|
d: 2
------
t: 6
f: 1|2|3|6|
d: 4
------

Also please note: I'm using NetBeans IDE 7.3.1, with Java 1.7


texts: Which way of writing a conditional test is the most readable?

texts:
I have three conditions like the following:

if (IsAllTriggersRequired && meterFlag && workFlag && timeFlag)
{
    result.Add(new TodayTaskTest { Code = item1.Code, Id = item1.Id, Title = item1.Title });
}
else if (!IsAllTriggersRequired && (meterFlag || workFlag || timeFlag))
{
    result.Add(new TodayTaskTest { Code = item1.Code, Id = item1.Id, Title = item1.Title });
}

if ((IsAllTriggersRequired && meterFlag && workFlag && timeFlag) ||(!IsAllTriggersRequired && (meterFlag || workFlag || timeFlag)))
{
    result.Add(new TodayTaskTest { Code = item1.Code, Id = item1.Id, Title = item1.Title });
}

bool isAdd = false;

if (IsAllTriggersRequired && meterFlag && workFlag && timeFlag)
    isAdd = true;
else if (!IsAllTriggersRequired && (meterFlag || workFlag || timeFlag))
    isAdd = true;

if (isAdd)
    result.Add(new TodayTaskTest { Code = item1.Code, Id = item1.Id, Title = item1.Title });

In the second one, can I avoid repeating the same code?


texts: Regular Expression to remove blank lines

texts:
This is basically my first Ruby class, which is to remove all empty lines and blank times from a .txt file. A simple test case is also included.

I tested the code and it works fine. But I did not have much idea about if the code style is good, or if there are some potential issues. Can someone please do a quick review and kindly provide some feedback?

Is there any potential issue in the code? did I miss some boundary check?
Is the code style good in general? e.g, name convention, indent, etc.
what can I do if I want to make it more professional? e.g., better choice of functions, error-handling, object-oriented, test-driven,  etc.

require 'test/unit'

class  BlankLineRemover
  def initialize()
    puts "BlankLineRemover initialized."
  end

  def generate(input_filename, output_filename)

    reader = File.read(input_filename)

    f = File.new(output_filename, "w")

    f.puts remove(reader)

    f.close

  end

  def  remove(stringToremove)

    regEx = /^[\s]*$\n/

    stringToReturn = stringToremove.gsub(regEx, '')
    stringToReturn.strip!

    if stringToReturn.length >= 1
      return stringToReturn
    else
      return ""
    end
  end

end

class TestCleaner < Test::Unit::TestCase
  def test_basic

    sInput1 = "line1\n\t\nline4\n\tline5\n"
    sExpectedOutput1 = "line1\nline4\n\tline5"

    sInput2=""
    sExpectedOutput2 = ""

    sInput3="\n\t\t\n"
    sExpectedOutput3 = ""

    testCleaner = BlankLineRemover.new
    assert_equal(sExpectedOutput1, testCleaner.remove(sInput1))
    assert_equal(sExpectedOutput2, testCleaner.remove(sInput2))
    assert_equal(sExpectedOutput3, testCleaner.remove(sInput3))

  end
end

unless ARGV.length == 2
  puts "Usage: ruby Blanker.rb input.txt output.txt\n"
  exit
end

simpleRemover = BlankLineRemover.new

simpleRemover.generate(ARGV[0],ARGV[1])


texts:
I recently took a test. One of the questions was to find problems in the following code and suggest refactoring which can provide adding new formats of data:

public class FileProcessor
{
    enum FileType
    {
        Html, Text
    }

    public void ProcessFile(string fileName)
    {
        StreamReader fileStream = new StreamReader(File.OpenRead(fileName));
        string fileContent = fileStream.ReadToEnd();

        if (fileContent.IndexOf("<html") != -1)
            ProcessHtmlFile(fileContent);
        else ProcessTextFile(fileContent);

        ProcessFile(fileContent,fileContent.IndexOf("<html")!= -1?
                                     FileType.Html:FileType.Text);
        fileStream.Close();

    }

    private void ProcessFile(string content,  FileType fileType)
    {

        switch(fileType)
        {
            case FileType.Html:
                ProcessHtmlFile(content);
                break;
            case FileType.Text:
                ProcessTextFile(content);
                break;
            default:
                throw new Exception("Unknown file format");
        }
    }

    private void ProcessHtmlFile(string content){...}

    private void ProcessTextFile(string content){...}

}

What I've suggested:

I've suggested to use open closed principle and my implementation is:

public class FileProcessor
{
   public void ProcessFile(string fileName, IFile file)
   {
      StreamReader fileStream = new StreamReader(File.OpenRead(fileName));
      string fileContent = fileStream.ReadToEnd();

      file.ProcessFooFile(fileContent);
      fileStream.Close();
   }
}

public interface IFile
{
    void ProcessFooFile(string fileContent);
}

public class HtmlFile : IFile
{
   public void ProcessFooFile(string fileContent)
   {
      //Process HTML File
   }
}

public class TextFile : IFile
{
   public void ProcessFooFile(string fileContent)
   {
      //Process Text File
   }
}

My questions are:

Is it appropriate to use open closed principle in this case?
Is my implementation correct? Especially, please, see that I deleted a row ProcessFile(fileContent,fileContent.IndexOf("<html")!= -1?FileType.Html:FileType.Text); from public void ProcessFile(string fileName) as there is no need in the row.
Is there some drawbacks in my implementation. Please, provide improvements.


texts:
I have an array of file names. For example:

string[] files= { "one.zip", "two.txt", "one.zip", "three.txt", "three.txt", "one.zip" };

And I've developed the following method to correct duplicate names. What the method does is just change duplicate names. I am just adding incremented value for the next duplicated value. For example, my developed method ChangingDuplicateNames(string[] files)correct the previous array to:

string[] files= { "one.zip", "two.txt", "one1.zip", "three.txt", "three1.txt", "one2.zip"};

And implementation of ChangingDuplicateNames(string[] files) is:

private string[] ChangingDuplicateNames(string[] files)
{
    //Creating a dicitonary to store duplicated values. "Key" of dictionary
    //is duplicated name, "Value" of dictionary is number to add for name
    Dictionary<string, int> duplicateNames = files.GroupBy(x => x)
        .Where(group => group.Count() > 1)
        .ToDictionary(grouped => grouped.Key, grouped => 0);

    if (duplicateNames.Count == 0)
        return files;

    int namesLength = files.Length;
    string actualName = string.Empty;
    for (int indexArray = 0; indexArray < namesLength; indexArray++)
    {
        int incrementedValue;
        bool isDuplicate = duplicateNames.TryGetValue(files[indexArray],
            out incrementedValue);
        if (isDuplicate)
        {
           actualName = files[indexArray];
           if (incrementedValue == 0)
              files[indexArray] = files[indexArray];
           else
           {
               //Adding increment to the mext duplicate name
               string fileNameWithoutExtension = Path
                    .GetFileNameWithoutExtension(files[indexArray]);
               string fileExtension = Path
                   .GetExtension(files[indexArray]);
               files[indexArray] = fileNameWithoutExtension +
                   "(" + incrementedValue + ")" + fileExtension;
           }
           duplicateNames[actualName] = ++incrementedValue;
        }
    }
    return files;
}

And my question is: Is it possible to improve this algorithm? I mean could be this code smaller?

Maybe I should not iterate through the all array of names, but I cannot figure out how I can change names in files without iterating through all array. Thanks in advance.


texts:
I started reading about JavaScript patterns, and I really liked module pattern.
So I created some module:

var App = (function (parent, $) {
    function myPrivateFunc () {
        // Some private stuff
    }

    return {
        myPubFunc: myPrivateFunc,
        publicFunction: function () {
            // Do some stuff
        }
    };
})(App || {}, jQuery);

Now I want to call some functions on page but only functions I need on that specific page. I got idea to add data-modules attribute to body, and then load modules I demanded on that attribute. I did that this way:

var modules = $('body').data('modules').split(" ");

for (var i = modules.length - 1; i >= 0; i--) {
    App[modules[i]]();
}

My question is: Is this a good way to achieve what I wanted? I tested, it's working fine, but I'm a little suspicious about this dynamic calling. Is there better solutions (preferably not libraries) out there? If this is not good, why it isn't?


texts: Looping over text boxes and editing values

texts:
I wrote this code to check if a text box is empty. If it is I put the current date into it with a score and loop over the six boxes.
Once it fills the boxes it will then loop over checking the dates and it finds the oldest and overrides it with the new value.

I feel what I have done here may be a bit crude and or long winded, this there a better way I could have done this?

<input type="textbox" id="bank1" value="19990112" class="bank" /> 1

<input type="textbox" id="bank2" value="19980112" class="bank" /> 2

<input type="textbox" id="bank3" value="19970112" class="bank" /> 3

<input type="textbox" id="bank4" value="19960112" class="bank" /> 4

<input type="textbox" id="bank5" value="19950112" class="bank" /> 5

<input type="textbox" id="bank6" value="19940112" class="bank" /> 6

<input type="button" value="Click Me" id="btn" />

var idAndValues = {};
var Time = [];
var oldest = "";
var formatDateMili = "";
var ids = "";
var m = false;
var now = new Date();
var a = now.getFullYear();
var b = now.getMonth();
var c =now.getDate();
var FullDateNow = a.toString() + "0"+b.toString() + c.toString();

$('#btn').click(function() {

  $('.bank').each(function() {

    if ($(this).val() != "") {

      var StoredDate = $(this).val();
      var formatDateMili = DateStringSort(StoredDate).getTime();
      Time.push(formatDateMili);
      ids = $(this).attr('id');
      idAndValues[ids] = formatDateMili;

    } //end if

    if ($(this).val() === "") {

      $(this).val("19980214" + "_" + "score");
      m = true;

      return false;

    } else {

      m = false;
    }

  }); // end loop

  if (m != true) {
    oldest = Math.min.apply(null, Time);

    for (var key in idAndValues) {
      if (idAndValues.hasOwnProperty(key)) {

        //   alert(idAndValues[key]+ " key checking" + " oldest checking "+ oldest);
        if (idAndValues[key] === oldest) {
          $('#' + key).val(FullDateNow + "_" + "score");
          Time = [];

        }

        //   alert(key + " -> " + idAndValues[key]);
      }
    }

  }

});

function DateStringSort(Stored) {

  var StoredDayTrim = Stored.substring(6, 8);

  var StoredmonthTrim = Stored.substring(4, 6);

  var StoredYearTrim = Stored.substring(0, 4);

  var FormatDate = new Date(StoredYearTrim, StoredmonthTrim, StoredDayTrim);

  return FormatDate;

}

here is a fiddle


texts: Find a serial port device through WMI (windows management instrumentation)

texts:
The idea here is to be able to find a USB serial port device connected during runtime, thus not knowing its port number, and use it in the application to retrieve information from the device.

string comportInfo = string.Empty;

using (var entitySearcher = new ManagementObjectSearcher("root\\CIMV2", "SELECT * FROM Win32_PnPEntity WHERE Caption LIKE '%" + SerialPortToFind + "%'"))
{
    using (var serialPortSearcher = new ManagementObjectSearcher("root\\WMI", "SELECT * FROM MSSerial_PortName"))
    {
        //testBase.SamplerWithCancel is like a for loop with exception control, a time between interations and amount of iterations to be made. It expects a true or false value to determine whether a desired condition is met. Failing to return a true value in the specified iterations throws an exception.
        testBase.SamplerWithCancel(() =>
            {
            var portList = serialPortSearcher.Get().Cast<ManagementBaseObject>().ToList();
            var matchingEntities = entitySearcher.Get().Cast<ManagementBaseObject>().First();

            if (portList.Count != 0 && matchingEntities != null)
            {
                foreach (ManagementBaseObject port in portList)
                {
                    if (port["InstanceName"].ToString().Contains(matchingEntities["DeviceID"].ToString()))
                    {
                        comportInfo = port["PortName"].ToString();
                    }
                }
                return true;
            }
            else
                return false;
        }, "Serial port not found", 3, 1500, 500, false, false);
    }
}

The code works well, but I want to know where I can improve it to make it more resilient and less error prone.

I feel like using LINQ would be way more appropiate than what I did.


texts: Specialized template methods with complex numbers class

texts:
Suppose I have a class of complex numbers called Complex and I wish to implement a class of generic matrices with transpose operation.

doubles and ints don't require special care, but you have to calculate the conjugate of complex numbers to transpose. Therefore, I implemented a "specialized transpose()".

template <class T>
Matrix<T> Matrix<T>::transpose() const
{
    Matrix<T> matrix(_cols, _rows);

    unsigned int i, j;

    for (i = 0; i < _rows ; ++i)
    {
        for (j = 0; j < _cols; ++j)
        {
            matrix(j, i) = (*this)(i, j);
        }
    }

    return matrix;
}

template <>
Matrix<Complex> Matrix<Complex>::transpose() const
{
    Matrix<Complex> matrix(_cols, _rows);

    unsigned int i, j;

    for (i = 0; i < _rows ; ++i)
    {
        for (j = 0; j < _cols; ++j)
        {
            matrix(j, i) = (*this)(i, j).conj();
        }
    }

    return matrix;
}

As you can see, there's a severe code repetition. Is there any way I can deal with it (like using helper methods)?

References from Wikipedia:

Transpose
Conjugate transpose


texts:
In the situation where I am looping through a collection looking for an item, is it better practice to break before I return or should I break and then return?

Return during loop:

foreach(string item in items)
{
    string[] split = item.Split('|');
    if(split[0] == searchFor)
        return split[1];
}
return null;

Break then return:

string result = null;
foreach(string item in items)
{
    string[] split = item.Split('|');
    if(split[0] == searchFor)
    {
        result = split[1];
        break;
    }
}
return result;


texts:
The point of this method is to emulate Java hashCode().

In order for this to work the project must have arithmetic overflow allowed under:

  project --> compiler options --> advanced.

    Public Shared Function GetHashCodeStr(value As String) As Integer
        Dim finalCode As Integer = 0

        For i As Integer = 0 To value.Length - 1
           Dim powerValue = (Convert.ToInt32(value(i)) * Math.Pow(31, value.Length - 1 - i))

        If powerValue > Integer.MaxValue Then
            Dim timesGreaterThanInt = Math.Floor(powerValue / Integer.MaxValue)
            powerValue = powerValue - timesGreaterThanInt - (timesGreaterThanInt) * Integer.MaxValue
        End If

        finalCode += CInt(powerValue)
    Next

    Return finalCode
End Function


texts:
I'm fixed on the save file format. There are only three types of data:

long (NumPy int32 array, independent of platform)
double (NumPy double array)
string (UTF-8, but ord(c) < 128 for all characters)

whereby the first two get saved in their binary representation. Strings get saved as string and are preceded with an int32 with its length (not fixed along one column).

I have input data of the form:

bun = {'x': np.zeros(n_col),
       'y': np.zeros(n_col, dtype=np.int32),
       'z': np.zeros(n_col),
       'u': ['abc'] * n_col}

And I need to save it line-by-line.

Pseudo code:

for i in range(n_col):
     for col in ordered_colum_names:
           save(bun[col][i])

As so many file IO's can get costly (yes, I tried it first and I have up to 1M lines) and the files are limited to be below 150MB I decided to write everything into a bytes buffer and then write in one go to the disk. But I feel my code could be simplified. Please let me know what your thoughts about it.

import io
from collections import OrderedDict

import numpy as np

###############################
### Functions to comment on ###
###############################

def join(*args):
    return b''.join(args[0])

def array2binary_list(bin):
    """ Converts an numpy array into an list of bytes.
    !!! Note returns generator !!! """
    return map(bytes, zip(*[iter(bin.tobytes())] * bin.itemsize))

def write_binary_col(fid, bun, col):
    """ Write down the data in the variable space format.
    For int32 and double this means just the binary.
    For str this means ascii representation preceded with the str length in
    int32 """
    raw = []

    for key, val in col.items():
        if (val['type'] == 'double') or (val['type'] == 'long'):
            raw.append(array2binary_list(bun[key]))
        elif val['type'] == 'string':
            str_len = np.array([len(line) for line in bun[key]], dtype=np.int32)
            raw.append(array2binary_list(str_len))
            raw.append(line.encode('ascii') for line in bun[key])
        else:
            raise TypeError('Unknown Type {}'.format(val['type']))

    # Transpose and serialize it first
    fid.write(b''.join(map(join, zip(*raw))))

#########################################################
### Some helper functions to illustrate the problem ###
#########################################################

def create_data(n_col):
    """ This generates just some fake data """
    bun = {'x': np.zeros(n_col),
           'y': np.zeros(n_col, dtype=np.int32),
           'z': np.zeros(n_col),
           'u': ['abc'] * n_col}

    col = OrderedDict()
    col['x'] = {'type': 'double'}
    col['y'] = {'type': 'long'}
    col['z'] = {'type': 'double'}
    col['u'] = {'type': 'string'}

    return (bun, col)

if __name__ == '__main__':
    fid = io.BytesIO()
    bun, col = create_data(100)

    write_binary_col(fid, bun, col)

    print(fid.getvalue())


texts: Switch questions using JavaScript and CSS

texts:
I am writing a Q&A wap page and want to switch questions in one page. This is my first time to write JS and CSS code, so I think there must be some improvement.

$(function(){
    $("#parent").on('click','.children', function(e){
        var that = e.currentTarget;
        var wid = parseInt($(that).parent().css('width'));
        var margin = parseInt($(that).parent().css('marginLeft'));
        margin -= wid;
        $(that).parent().css('marginLeft', margin + "px");
    });
});
#wrap {
  width: 100%;
  height: 30px;
  overflow: hidden;
}
#parent {
  width: 100%;
  -webkit-transition: all .2s linear;
  white-space: nowrap;
}
#parent div {
  background-color: gray;
  width: 100%;
  height: 30px;
  display: inline-block;
}
<!DOCTYPE html>

    <meta charset="UTF-8">
    <title></title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=no" />
    <meta name="apple-touch-fullscreen" content="yes" />
    <meta name="apple-mobile-web-app-capable" content="yes" />
    <meta name="apple-mobile-web-app-status-bar-style" content="black" />
    <meta name="format-detection" content="telephone=no" />

    <link rel="stylesheet" href="../css/change.css"/>

NO.1

NO.2

NO.3

NO.4

result

Running example

I don't want to my last result div to switch, so there is no event listener on my last result div.