Laravel dropdown list without empty values I'm creating dropdown list from all possible cities in database, all cities are distincted.

$city = DB::table('contacts')->distinct('city')->lists('id', 'city');

^ Extracts all possible cities, however it also extract empty string ['' => '95].

How I can forbid retrieving empty city ?

I tried using $city = DB::table('contacts')->whereNotNull('city')->distinct('city')->lists('id', 'city'); But didn't helped. My code looks like this now.

    $city = DB::table('contacts')->distinct('city')->lists('id', 'city');
    unset($city['']);
    array_unshift($city, 'Select city');

How can I improve it ?

I'm assuming that you are using the whereNotNull() because in addition to allowing empty strings, you allow null values?

That being said, you could always modify your code to use the specific where() clause. This can take an array as input and you can specify both the empty string and NULL.

$city = DB::table('contacts')->distinct('city')->lists('id', 'city')->where(function($query) {
    $query->where('contacts.city', '!=', '')
        ->orWhere('contacts.city', '!=', null);
})

There's a very good SO post here about multiple where clause queries.


Project Euler Problem 7: Find 10001st prime number I was able to complete the problem, but I would like to improve my code and make it more idiomatic.

Here is the challenge description:

  Problem 7 - 10001st prime

  By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th >prime is 13.
  What is the 10 001st prime number?

  http://projecteuler.net/problem=7

Here is my code:

let isDivibleBy num denum = num % denum = 0
let isPrime x previousPrimes = not (Seq.fold (fun acc y -> (isDivibleBy x y) || acc) false previousPrimes)
let getPrime n =
    let rec getPrimesInternal count num previousPrimes =
        match count with
        | 0 -> previousPrimes
        | _ -> let prime = isPrime num previousPrimes
               match prime with
               | true -> getPrimesInternal (count - 1) (num + 1) (num::previousPrimes)
               | false -> getPrimesInternal count (num + 1) previousPrimes
    match n with
    | n when n <= 0 -> 0
    | n -> List.head (getPrimesInternal (n - 1)  2 [2])

[<EntryPoint>]
let main argv =
    printfn "%i" (getPrime 10001)
    0 // return an integer exit code

One of the major problem I would like to address is performance.  An easy way to improve the performance would be to stop the fold when a prime number is found, but I couldn't find the appropriate technique or function.

Updated version of code:

let isPrime n =
    match n with
    | _ when n < 2 -> false
    | 2 -> true
    | _ when n % 2 = 0 -> false // even numbers greater than 2
    | _ -> // odd numbers greater than 2
        let limit = int(sqrt(float(n)))
        let rec check i =
            i > limit || (n % i <> 0 && check (i + 2))
        check 3

let getPrimes n =
    let rec getPrimeInternal found i =
        if found >= n
        then []
        else
            if isPrime i
            then i::getPrimeInternal (found + 1) (i + 1)
            else getPrimeInternal found (i + 1)
    getPrimeInternal 0 2

let getPrime n =
    Seq.last (List.toSeq (getPrimes n))

[<EntryPoint>]
let main argv =
    printfn "%i" (getPrime 10001)
    0 // return an integer exit code

One of the major problem I would like to address is performance.

When thinking about performance, the first question you should ask yourself is: could I use a better algorithm? Turns out there are better algorithms for generating primes, though they would be more difficult to implement (especially since they find all primes up to a certain number, which is not the same as finding the n-th prime).

It's probably not worth it in this case.

  An easy way to improve the performance would be to stop the fold when a prime number is found

You can use Seq.exists for that, which will also make your code simpler:

let isPrime x previousPrimes = not (Seq.exists (isDivibleBy x) previousPrimes)

(I'm using partial function application instead of a lambda, to make the code shorter.)

Other notes:

let isDivibleBy num denum = num % denum = 0

I think this function should be called isDivisibleBy.

match prime with
| true -> …
| false -> …

This is what if is for.

 getPrimesInternal count (num + 1) previousPrimes

If you start with num = 3 (and not 2), you can be sure that all primes that you test will be odd, so you can use num + 2 here, speeding up your code by about 50 %.


Median of 3 Quicksort in C I'm trying to re-implement the C stdlib function qsort using a median of 3 quicksort.

void qsort(void *base, size_t nitems, size_t size, int (*compar)(const void *, const void*))

This is my first major project in C, and I'd like to know how my style looks and what techniques I might be missing out on. Thanks for the help.

In sort.h, I have

/* returns > 0 if arg1 is greater than arg2, 0 if equal, < 0 if less*/
typedef int (*compare_func)(void *, void *);
/*Median of 3 quicksort Function*/
void quick_sort(void * arr, size_t nitems, size_t size,  compare_func compare);

And in quick_sort.c I have

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

void swap_mem(void * ptr1, void * ptr2, size_t size){
    /*
     * Swaps the values at the addresses pointed at by ptr1 and ptr2
     */
    void * tmp = malloc(size);
    memcpy(tmp, ptr1, size);
    memcpy(ptr1, ptr2, size);
    memcpy(ptr2, tmp, size);
    free(tmp);
}

void median_of_3(void * arr, size_t start, size_t stop, size_t size, compare_func compare){
    /*
     * Performs median of 3 partitioning on an array starting at start and ending
     * at stop
     */
    int mid;

    /*determine midpoint of array to nearest integer multiple of size*/
    mid = ((start + stop)>>1)/size * size;

    /*sort the 3 item array by comparing middle value to first and last value*/
    if(compare(arr + stop, arr + start) < 0)
        swap_mem(arr + stop, arr + start, size);
    if(compare(arr + mid, arr + start) < 0)
        swap_mem(arr + mid, arr + start, size);
    if(compare(arr + stop, arr + mid) < 0)
        swap_mem(arr + stop, arr + mid, size);

    /*swap the second to last value of arr with the median value*/
    swap_mem(arr + mid, arr + stop - size, size);
}

void quick_sort_aux(void * arr, size_t start, size_t stop, size_t size, compare_func compare){
    /*
     * Recursive median-of-3 quick sort
     */

    /*Base Case 1: 1 item in array (already sorted)*/
    if(start >= stop) return;

    /*Base Case 2: sort 2 or 3 item array*/
    median_of_3(arr, start, stop, size, compare);

    if(stop - start <=2*size) return;

    /*Recursively sort larger arrays*/
    int l_ptr = start;
    int r_ptr = stop - 2*size;

    /*move all values to the proper side of the pivot*/
    while(l_ptr <= r_ptr){
        while(compare(arr + l_ptr, arr + stop - size) < 0 && l_ptr <= r_ptr)
            l_ptr+=size;
        while(compare(arr + r_ptr, arr + stop - size) >= 0 && l_ptr <= r_ptr)
            r_ptr-= size;
        if(l_ptr <= r_ptr)
            swap_mem(arr + l_ptr, arr + r_ptr,size);
    }
    /*swap the pivot back into place*/
    swap_mem(arr + l_ptr, arr + stop - size,size);

    /*recursively sort the two halves*/
    quick_sort_aux(arr, start, l_ptr - size, size, compare);
    quick_sort_aux(arr, l_ptr + size, stop, size, compare);
}

void quick_sort(void * arr, size_t nitems, size_t size,  compare_func compare){
    /*
     * wrapper for recursive quick_sort_aux
     */
    quick_sort_aux(arr, 0, size*(nitems-1), size, compare);
}

This is my first time posting to StackExchange. Let me know how I can improve my question.

Your swap_mem will get called O(n log n) times. This makes it worth taking a closer look at for optimization.

One thing you can do is avoid repeated calls to malloc and free and instead preallocate the tmp buffer in the root function call and pass it around or use alloca to allocate the buffer on the stack.

void swap_mem(void * ptr1, void * ptr2, size_t size){
    /*
     * Swaps the values at the addresses pointed at by ptr1 and ptr2
     */
    void * tmp = alloca(size); //will get freed automatically on function exit.
    memcpy(tmp, ptr1, size);
    memcpy(ptr1, ptr2, size);
    memcpy(ptr2, tmp, size);
}


Building a SharePoint Search URL I'm trying to build a URL to call the SharePoint Search REST API in TypeScript. The interesting part is building the querytext, which is done by my buildQueryText method. In my case it takes two parameters: A content type to search for and a array of select properties.

buildQueryText(contentType: string, selectProperties: string[]): string {
    var contentTypeQuery = "'" + "SPContentType:" + contentType + "'";

    var selectPropertiesQuery = "";
    if (selectProperties.length !== 0) {
        selectPropertiesQuery = "&selectproperties=" + "'";
        selectProperties.forEach((property, index) => {
            if (index < selectProperties.length - 1) {
                selectPropertiesQuery += property + ",";
            } else {
                selectPropertiesQuery += property + "'";
            }
        });
    }

    return `${contentTypeQuery}${selectPropertiesQuery}&clienttype='Custom'`;
}

I'm calling the method like this:

buildQueryText("SearchItem", ["prop1", "prop2", "prop3"])

and expecting the following output:

"'SPContentType:SearchItem'&'selectproperties=prop1,prop2,prop3'&clienttype='Custom'"

I'm looking for a way to improve the selectPropertyQuery part and make it more readable, as it seems quite messy. And i'm aware that there is no real validation of the inputs.

It looks to me as you want to join the array. I don't know TypeScript, it it should have a join method on the array.

selectPropertyQuery = properties.join(",")


Validating a User via Save Method I'm fairly new to object oriented programming here and am trying to get my head around the best way to go about creating Users and Validating them in the system.

My first attempt is below and my main questions apart from does it all seem correct is in regards passing a validator class to the save function and pros/cons to this.

A lot of the functionality has been stripped back to enable you to read it a bit easier, including removing any getters and setters but please assume they are there:

User Model

class User implements Validateable {

    protected $name;
    protected $email;
    protected $validator;

    // getters and setters for name, email, validator here

    public function save( Validator $validator ) {

        $this->validator = $validator;
        if( $this->validator->validate( $this ) )
            return true;

        return false;

    }

    public function getRules() {

        return [
            'name' => new NameValidator( $this->name ),
            'email' => new EmailValidator( $this->email )
            ];

    }

}

Abstract Validator

abstract class ValidatorAbstract {

    protected $errors;

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

}

Name Validator

class NameValidator extends ValidatorAbstract {

    protected $name;
    protected $errors;

    public function __construct( $name ) {
        $this->name = $name;
    }

    public function validate() {

        if( empty( $this->name ) )
            $this->errors[] = 'Invalid Name';

        if( $this->errors )
            return false;

        return true;

    }

}

Email Validator

class EmailValidator extends ValidatorAbstract {

    protected $email;
    protected $errors;

    public function __construct( $email ) {
        $this->email = $email;
    }

    public function validate() {

        if( !filter_var( $this->email, FILTER_VALIDATE_EMAIL ) ) :
            $this->errors[] = 'Invalid Email';
        endif;

        if( $this->errors )
            return false;

        return true;

    }

}

User Validator

class UserValidater implements Validator {

    protected $data;
    protected $rules;
    protected $errors;

    public function validate( Validateable $obj ) {

        $this->rules = $obj->getRules();

        foreach( $this->rules as $rule ) :

            if( !$rule->validate() )
                $this->errors[] = $rule->getErrors();

        endforeach;

        if( $this->errors )
            return false;

        return true;

    }

    public function getErrors() {

        return $this->errors;

    }

}

Validator Interface

interface Validator {

    public function validate( Validateable $data );
    public function getErrors();

}

Validateable Interface

interface Validateable {

    public function getRules();

}

And finally some example code using all of the above:

$user = new User;
$user->setName( 'Peter' );
$user->setEmail( 'peter@email.com' );

if( $user->save( new UserValidater ) ) :
    // do some stuff
else :
    $errors = $user->getValidator()->getErrors();
    // do some stuff with the errors
endif;

It's better to separate the validation from the save operation and to use a constraint object to setup the rules which be applied to the entity. So you get a better separation of concern, which is one of the keys to good OOP architecture. I propose something like this:

$user = new User;
$user->setName( 'Peter' );
$user->setEmail( 'peter@email.com' );
$validator = new Validator(new UserConstrainte));
if( $validator->validate($user)){
    $databaseStuff->save($user)
} else {
    $error = $validator->getErrors()
}

I advise you to check the validator component from symfony2: https://github.com/symfony/Validator which is really well designed.


Memoizing in PostScript The pusherr and poperr procedures maintain an internal stack as a lisp-like
linked-list. It's a little slower than an earlier stackwise
version according to naive testing. It allocates lots of 2- and 3- element
arrays for its data. But the code using them becomes very readable IMO with this
approach.

The memo-func function generates a procedure body specified by the
template but with the DICT replaced by the dict argument.

The resulting procedure simply pushes the local dict, then pushes an error handler for the /undefined
error, then just does load, and pops the handler and the dict. If load does not find the needed value, it will signal an /undefined error which will be caught be our handler.

The error handler calls the procedure named /default and saves the input and output as a new definition in the local dict.

Improvements?

%!

<<
/errorstack null  % [ {errordict/errname{handler}} null ]

/pusherr {
    errordict 3 1 roll 3 copy pop 2 copy get    % ed /n {new} ed /n {old}
    3 array astore cvx  errorstack   2 array astore  /errorstack exch store
    put
}

/poperr {
    errorstack dup null ne {
        aload pop  /errorstack exch store
        exec put
    } if
}

/memo-func {
    {
        DICT begin
            /undefined { pop dup default dup 3 1 roll def } pusherr
                load
            poperr
        end
    }
    dup length array copy
    dup 3 2 roll 0 exch put cvx
}
>> begin

/fib <<
    0 1
    1 1
    /default { dup 2 sub fib  exch 1 sub fib  add }
>> 100 dict copy  memo-func  def

0 1 100 {  fib =  } for

The 100 dict copy allows you to also set the initial size of the dictionary to  determine how many entries you can add before it needs to rehash.

This code was previously posted in comp.lang.postscript at the end of a thread which includes the stackwise version mentioned above.

Bug

poperr leaves a null on the stack if errorstack is null. Better:

/poperr {
    errorstack null ne {
        errorstack aload pop  /errorstack exch store
        exec put
    } if
}

This leaves the stack clean and makes extra calls to poperr harmless. If desireable, some action could be put in the else case but since this code is mucking about with error handlers, it is unclear whether signalling an error is correct here.


Extract SSID and BSSID from a file I have file called Network.txt which contains SSID and BSSID as below:

  SSID                              BSSID               MODE             FREQ       RATE       SIGNAL   SECURITY   ACTIVE
'Bards Tale'                  30:DA:9B:70:EE:F4   Infrastructure   2412  MHz   54 MB/s    47       WPA2              no
'Alaskan Pale'                70:37:73:B7:3A:53   Infrastructure   2412 MHz   54 MB/s    44       WPA2             yes
'Abita Turbodog'              9C:1E:04:4C:59:FC   Infrastructure   2412 MHz   54 MB/s    7        WPA WPA2         no
'Alaskan Amber'               12:62:EB:2C:C0:06   Infrastructure   2422 MHz   54 MB/s    2        WPA WPA2         no

I want to get SSID and BSSID in safe and efficient way.  Here is my approach, which is working fine; can it be improved?

void GetSSIDAndBSSID(const std::string &temp)
    {
        if (temp.find("'") != std::string::npos)
        {

            std::string::size_type end_pos = temp.find_last_of(":");
            if (end_pos == std::string::npos)
                end_pos = temp.size();

     std::string FirstWord = temp.substr(1, end_pos+2);
    std::cout <<"SSID="<< FirstWord.substr(0,temp.find_last_of("'")-1) << std::endl;
   std::cout<<"BSSID=" << FirstWord.substr(temp.find_first_of(":")-2,temp.find_last_of(":")+2) << std::endl;
        }
    }

int main()
{
        ifstream fin("pathTO/Network.txt");
        std::string line;
        while(getline(fin,line))
        {

                GetSSIDAndBSSID(line);

        }

I see a number of things that may help you improve your code.

Use the required #includes

The code uses ifstream which means that it should #include <fstream>.  It was not difficult to infer, but it helps reviewers if the code is complete.  In this case, the code needs the following:

#include <string>
#include <iostream>
#include <fstream>

Separate concerns

Instead of having the single routine extract field and print them, I'd recommend separating those into separate functions.  It makes the code clearer and allows flexibility if, for example, you wanted to sort the entries before printing them.

Don't abuse using namespace std

Putting using namespace std at the top of every program is a bad habit that you'd do well to avoid.  I don't know that you've actually done that, but it seems so because the code within main omits the namespace in several places.

Fix the bug

Right now, the code reports the BSSID without the first character.  That's a bug caused because the first "-2" in the last line of GetSSIDAndBSSID should actually be -3.  Also, as pasted, your main is missing a closing }.

Be sure of your inputs

We are left to infer, from the sample and from your code, the format of the file that is to be parsed.  Perhaps you had to figure it out from samples yourself.  Either way, it's very helpful to document, as comments, just exactly what the code is expecting so that if any of those assumptions ever need to change, it will be clear what needs to be changed.  For example, it appears that there is an implicit assumption that the last ":" on the line is used to figure out the substring length that includes the two fields of interest.  However, it appears to me that the fields are of fixed width, which would make it very efficient to simply used a fixed index into the string.  Also, your code seems to assume but doesn't test that the first character on the line is "'".

Use consistent formatting

The code as posted has inconsistent indentation which makes it hard to read and understand. Pick a style and apply it consistently.


Unit Test case for services method in angular I want to write the test case for Service class.
My Service Class dynamic-form.service.ts
import { HttpClient, HttpBackend } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Router } from '@angular/router';

@Injectable({
  providedIn: 'root'
})
export class DynamicFormService {

  private http: HttpClient;

  constructor(private handler: HttpBackend
  ) {
    this.http = new HttpClient(handler);
  }

  async getDynamicFormData(paramName: any, data?: any): Promise<any> {
    return await this.http.get(this.HostUrl + paramName).toPromise();
  }

  async getTaskByWorkflowId(paramNameWithId): Promise<any> {
    return await this.http.get(this.HostUrl + paramNameWithId).toPromise();
  }

  async getAccontType(paramNameWithId): Promise<any> {
    return await this.http.get(this.HostUrl + paramNameWithId).toPromise();
  }
}

My dynamic-form.spec.ts are as follows
import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing';
import { TestBed} from '@angular/core/testing';
import { RouterTestingModule } from '@angular/router/testing';
import { of } from 'rxjs';

import { DynamicFormServiceService } from './dynamic-form-service.service';

describe('DynamicFormServiceService', () => {
  let service: DynamicFormServiceService;
  let httpMock: HttpTestingController;
  beforeEach(() => {
    TestBed.configureTestingModule({
      imports: [HttpClientTestingModule, RouterTestingModule.withRoutes([])]
    });
    service = TestBed.inject(DynamicFormServiceService);
    httpMock= TestBed.inject(HttpTestingController);
  });

  it('should be created', () => {
    expect(service).toBeTruthy();
  });
});

I have written one of service method test case as follows
it('should call getAccontType', ()=>{
    const data = [
      {
        "id": 4,
        "name": "24hrs"
      },
      {
        "id": 5,
        "name": "48hrs"
      }];
    service.getAccontType(`account-type`).then(res=> expect(res.length).toBeGreaterThan(0));
    const request = httpMock.expectOne(`http://localhost:8080/account-type`);
    expect(request.request.method).toBe('GET');
    request.flush(data);
    httpMock.verify();
  });

I want to know it is good way to write test-case this way or I can do better. Any suggestion.

Personally i would create an interface for the expected data from the backend. any is something i try to avoid, because then my IDE can´t help me finding my stupid mistakes.
For example
interface DynamicFormData {
   aValue: string,
   anotherValue: number,
}

async getDynamicFormData(paramName: string, data?: SomeDataType): Promise<DynamicFormData > {
  return await this.http.get(this.HostUrl + paramName).toPromise();
}

It gives you the benefit, that whereever you call that method, the IDE will know how the data will look like and what methods could be performed on it.
Also personally i like working with RxJS more than Promises, but thats a personal habit. But it allows to filter, modify, do stuff on the response. And i stay away from "async/await", because i do not like blocking tasks in my frontend if i can avoid them. But as i said, personal style.
About the init of the testcases, why do you need to import the RouterTestingModule? Its not used in the service at all.
About the test coverage:
When i see a method interface like getDynamicFormData(paramName: any, data?: any) then i would ask myself if "paramName" is mandatory or not. Also test cases are a kind of documentation, therefore i would add a testcase with an empty paramName (for example null).
From a Unit-testing perspective i would avoid hard coded strings like "account-type". You will surely use this strings also at other places in the regular code when you want to call the service. If those strings change, you have to find all places where they are used and replace them. Therefore i would create constants for those and us those constants. Then if the API changes ( e.g. "account-type" changes to "type-of-account") you just have to change it at one place and all (code and unit test) will adept automaticly.
You specificly asked in the comment for "code-coverage".
For that we have to think about what could be the possible results of each method. The Promise could be resolved or fail. Quite easy.
BUT your service is instantiated with a parameter
constructor(private handler: HttpBackend) {
    this.http = new HttpClient(handler);
 }

If you do not provide any input (as you do in your unit test), then its instantiated with this.http = new HttpClient();. I always use the HTTPClient provided directly by Angular, therefor i do not really know the effect of this. From the documentation it seems that this would circumvent the interceptors. But be it as it be, as its an input that may alter the behavior of your service, its something that should be covered by your testcases.
Hope you could use some of the mentioned things. :-)
warm regards
Jan


Find the minimum number of coin change Description:
You are given coins of different denominations and a total amount of money amount. Write a function to compute the fewest number of coins that you need to make up that amount. If that amount of money cannot be made up by any combination of the coins, return -1.

coins = [1, 2, 5], amount = 11, return 3 (11 = 5 + 5 + 1)
coins = [2], amount = 3, return -1.

Code:
class Solution {
    public int coinChange(int[] coins, int amount) {
        if (amount == 0) return 0;
        if (amount <  0) return -1;

        int min = -1;
        for (int coin : coins) {
            int currentMin = coinChange(coins, amount - coin);

            // if amount is less than coin value
            if (currentMin >= 0) {
                min = min < 0 ? currentMin : Math.min(currentMin, min);
            }
        }

        return min < 0 ? -1 : min + 1;
    }
}

Questions:
This question has slight deviation from normal one where we just need to return 0, returning -1 got me confused and I found it really hard to think in terms of recursion and handling edge cases.
PS: The solution works perfectly.

I think part of your problem is, you aren't taking the recursion far enough.  I would suggest, that the loop be replaced by recursion.  This can be accomplished quite easily by making sure the array is sorted first, and advancing from highest to lowest.  Since this will require extra parameters and the addition of calling the sort function.  Making the recursive function private and using a  public helper overload, will neaten things quite a bit.  Something like this should work:

public class Solution
{

    public static int coinChange(int[] coins, int amount)
    {
        Arrays.sort(coins);
        return coinChange(coins, amount, coins.length - 1, 0);
    }

    private static int coinChange(int[] coins, int amount, int index, int numCoins)
    {
        if (amount == 0)
        {
            return numCoins;
        }
        if (amount < coins[0])
        {
            return -1;
        }
        if (amount >= coins[index])
        {
            int tempCoins = (int) (amount / coins[index]);
            int tempAmount = amount - (tempCoins * coins[index]);
            if (tempAmount == 0 || tempAmount >= coins[0])
            {
                amount = tempAmount;
                numCoins += tempCoins;
            }
        }
        index--;

        return coinChange(coins, amount, index, numCoins);
    }
}

The usage would still be the same(int numCoins = Solution.coinChange(new int[]{1,2,5},11);).

Your description of the problem didn't mention whether the array would be sorted.  If it is guaranteed to be sorted that line can be left out.

You'll notice that there are still 3 states to check for, but that each one is only checked for once per recursion.

I didn't like the idea of making the amount go below 0.  Simply stopping when the amount was either 0 or less than the smallest coin, seems a cleaner way of doing things, to me.


Solving an ODE numerically with forward Euler method The goal is to solve an ODE numerically with forward Euler method. The programs works well (numerical solution really near analytical one). The problem I see is that the Euler scheme don't jump to eyes, probably because of push_back() functions. This approach is the only one I found to let the time of simulation (number of steps) be variable (change only the t_max constant). Do you have any idea to improve the clarity of the program?

/*  R. M.
        20.08.2012
    Exercice 1.2 of Computational Physics, N. Giordano and H. Nakanishi
        Euler method to solve: dv/dt = a - bv
*/

#include <iostream>
#include <fstream>
#include <string>
#include <vector>

void calculate(std::vector<double>& time, std::vector<double>& velocity, const double t_max, const double dt, const double a, const double b)
{
    const int iterations(t_max / dt);

    for(int i(1); i < iterations; i++)
    {
        time.push_back( time[i-1] + dt );
        velocity.push_back( a * dt + (1 - b*dt) * velocity[i-1] );
    }
}

void save(const std::vector<double>& time, const std::vector<double>& velocity, const std::string& filename)
{
    std::ofstream file_out(filename);

    for(int i(0); i < time.size(); i++)
    {
        file_out << time[i] << ' ' << velocity[i] << std::endl;
    }

    file_out.close();
}

int main()
{
    // Constants
    constexpr double t_max(8);          // Time to end simulation
    constexpr double dt(0.01);          // Time step
    constexpr double a(10.);            // Acceleration
    constexpr double b(1.);             // Air friction

    std::vector<double> time({0});      // Initial time (t = 0)
    std::vector<double> velocity({0});  // Initial velocity (v = 0)

    calculate(time, velocity, t_max, dt, a, b);
    save(time, velocity, "veocity.dat");

    return 0;
}

The smallest change that might make it more readable is to resize the vectors first, so you can index the elements rather than calling push_back.

It's generally a good idea to reserve vectors before a loop anyway if you know how big they're going to end up, and resize will handle that too.

void calculate(std::vector<double>& time, std::vector<double>& velocity,
               const double t_max, const double dt, const double a, const double b)
{
    const int iterations(t_max / dt);
    time.resize(iterations, 0.);
    velocity.resize(iterations, 0.);

    for(int i(1); i < iterations; i++)
    {
        time[i] = time[i-1] + dt;
        velocity[i] = a * dt + (1 - b*dt) * velocity[i-1];
    }
}

if you're keeping two vectors synchronized like this, it's sometimes nicer to replace them with a single vector whose elements have two fields:

struct step {
    double time;
    double velocity;
};

void calculate(std::vector<step>& steps,
               const double t_max, const double dt, const double a, const double b)
{
    const int iterations(t_max / dt);
    steps.resize(iterations);

    for(int i(1); i < iterations; i++)
    {
        steps[i].time = steps[i-1].time + dt;
        steps[i].velocity = a*dt + (1 - b*dt) * steps[i-1].velocity;
    }
}

this is more of an aesthetic preference though, and it isn't clearly better in your case.


Linear Peano multiplication in Scheme? I've been running through The Little Schemer, and have hit the example of Peano multiplication.  The solution is given in TLS (reproduced below) -- however what interests me is the order of the algorithm.

(define mX
  (lambda (n m)
    (cond
      ((zero? m) 0)
      (else
        (+ n (mX n (1- m))))
      )))

My understanding is that this sort of operation is to be avoided, as the order of the operation is unnecessarily large.

To that end I've been trying to think of how to convert this to a linear operation (I was able to do so in the case of addition). Nesting two functions occurred to me, but once i do this i am unsure how to measure the order of the function.

(define (mX n m)
  (define (mX-aux n m product)
    (if (zero? m)
      product
      (mX-aux n (1- m) (+ product n))))
  (mX-aux n m 0))

Is this approach linear or recursive? Is there a another way to do this? In particular, is it possible to do this without setting variables?

Let's look at a simpler problem first: counting the length of a list. Here's the recursive way to do it:

(define (length lst)
  (if (null? lst)
      0
      (+ 1 (length (cdr lst)))))

Okay, so, what would it look like if instead of recursing, we kept a running count of the length instead?

(define (length lst)
  (length-aux lst 0))

(define (length-aux lst count)
  (if (null? lst)
      count
      (length-aux (cdr lst) (+ 1 count))))

Here, length-aux tail-recurses into itself over and over with a new running count until we hit the end of the list, at which point we return the count.

This idiom is common enough that Scheme has a concept called named let, which you can use like this:

(define (length lst)
  (let loop ((lst lst)
             (count 0))
    (if (null? lst)
        count
        (loop (cdr lst) (+ 1 count)))))

You can use a similar approach for solving your problem iteratively:

(define (mX n m)
  (let loop ((m m)
             (product 0))
    (if (zero? m)
        product
        (loop (- m 1) (+ product n)))))

Notice that we are not setting variables here. We are doing a tail recursion into loop, which is passed the new m and product values as arguments.


Toggle dropdown menus for different menu items with Jquery In a bigger project of mine I'm using angular to create a dropdown menu dynamically and then toggling a dropdown menu for some of the menu items. This is why I got a function that toggles the dropdown menus for only the items that should actually have one. However, I feel like I should try to DRY this out a bit since I'll be repeating the same function even more than what I've done so far. How can I improve this code? Should I create a self invoking function or something similar?

Here's the functions (they're part of a controller object that I left out):

    init: function() {

        menuController.toggleDropDown('msg');
        menuController.toggleDropDown('mypages');
        menuController.toggleDropDown('tools');
        menuController.toggleDropDown('administration');
        menuController.toggleDropDown('contactinfo');
        menuController.toggleDropDown('utbildning');
        menuController.toggleDropDown('surveys');
        menuController.toggleDropDown('help');
    },
    toggleDropDown: function (id) {

        $('#main-menu' + ' #' + id + '').hover(function() {
            $('#' + id + ' ul').stop().slideToggle();
        });
    }

I think you can use html attribute to group it.

eg.

 or
 or whatever

and then

$('#main-menu [data-toggle="dropdown"]').hover(function(e) {
    $(e.currentTarget).find('ul').stop().slideToggle();
});


Any way to optimize or improve this python combinations/subsets functions? I believe this is essentially the same method as the itertools.combinations function, but is there any way to make this code more more perfect in terms of speed, code size and readability :

def all_subsets(source,size):
        index = len(source)
        index_sets = [()]
        for sz in xrange(size):
                next_list = []
                for s in index_sets:
                        si = s[len(s)-1] if len(s) > 0 else -1
                        next_list += [s+(i,) for i in xrange(si+1,index)]
                index_sets = next_list
        subsets = []
        for index_set in index_sets:
                rev = [source[i] for i in index_set]
                subsets.append(rev)
        return subsets

Yields:

>>> Apriori.all_subsets(['c','r','i','s'],2)
[['c', 'r'], ['c', 'i'], ['c', 's'], ['r', 'i'], ['r', 's'], ['i', 's']]

There is probably a way to use generators or functional concepts, hopefully someone can suggest improvements.

This type of problems lend themselves very well to recursion. A possible implementation, either in list or generator form could be:

def all_subsets(di, i) :
    ret = []
    for j, item in enumerate(di) :
        if i == 1 :
            ret = [(j,) for j in di]
        elif len(di) - j >= i :
            for subset in all_subsets(di[j + 1:], i - 1) :
                ret.append((item,) + subset)
    return ret

def all_subsets_gen(di, i) :
    for j, item in enumerate(di) :
        if i == 1 :
            yield (j,)
        elif len(di) - j >= i :
            for subset in all_subsets(di[j + 1:], i - 1) :
                yield (item,) + subset

>>> all_subsets(range(4), 3)
[(0, 1, 2), (0, 1, 3), (0, 2, 3), (1, 2, 3)]
>>> list(all_subsets_gen(range(4), 3))
[(0, 1, 2), (0, 1, 3), (0, 2, 3), (1, 2, 3)]

If you are going to run this on large sets, you may want to memoize intermediate results to speed things up.


How to optimize the code to save data at GAE datastore? I have the following code (for Country and City classes key_name is numeric id with addition of 'i' at the beginning):

def add_country(country, country_name):
  if country and country_namef and country_name != '':
    return Country.get_or_insert('i'+str(country), country_name=country_name)
  else:
    return None

def add_city(city, city_name, country):
  if country and city and city_name and city_name != '':
    return City.get_or_insert('i'+str(city), city_name=city_name, parent=country)
  else:
    return None

Is it correct code or can it be optimized somehow?

def add_country(country, country_name):
  if country and country_namef and country_name != '':

I assume that country_namef is a typo. If so, there is no point in checking country_name != '' because empty strings are already considered False

    return Country.get_or_insert('i'+str(country), country_name=country_name)
  else:
    return None

def add_city(city, city_name, country):
  if country and city and city_name and city_name != '':

As before, empty strings are false, so you are checking that twice

    return City.get_or_insert('i'+str(city), city_name=city_name, parent=country)
  else:
    return None


Improve this function that compares jQuery versions Please help me improve this function that compares the jQuery version currently available (or not) with the one required.

function(need) {
    if (typeof(jQuery) != 'undefined') {
        if (!need) return true;
        var re = /(\d+)\.(\d+)\.(\d+)/,
            cur = re.exec(jQuery.fn.jquery),
            need = re.exec(need);
        return (need[1] <= cur[1] && need[2] <= cur[2] && need[3] <= cur[3]);
    } else return false;
}

I'm sorry, but that code is completely broken.

It doesn't work if either version contains only two numbers such as the current "1.6".
It uses string comparison instead of integer comparison, so that it will return true if you "need" (theoretical) version "1.4.10" but only "1.4.2" is included, because "10" < "2" is true.
It doesn't stop comparing minor version numbers, if the major number is already bigger. For example it will return false if "1.4.2" is "needed", but "1.5.1" is included, because "2" > "1"
And finally you should keep in mind that "newer" isn't necessarily better. For example, the new 1.6 version changes how .attr() works, and scripts that rely on the old functionality of .attr() may break.


Generate unique string permutations recursively Objective

Write a recursive method for generating all permutations of an input string. Return them as a set.

See: Recursive String Permutations - Interview Cake
 Questions
1: How does the problem change if the string can have duplicate characters?

The solution below works with duplicate characters because the index of the original input is used to generate unique combinations of the original input minus the character at the given index. Therefore, there may be duplicate characters, however, their unique indexes will generate the correct solution.

2: What is the space and time complexity?

Time Complexity: \$O(n^2)\$ because there is one iteration through the input for which index to examine, and a second iteration, placing the character at each position of the input to generate various combinations. Therefore, \$n x n\$. This follows the rule, do X for each time of Y. See: Time complexity of all permutations of a string - GeeksforGeeks

Space Complexity: Is the space complexity also quadratic \$O(n^2)\$ because the unique permutations stored in a Set would grow quickly based on the size of the initial input?

3: How to optimize the time and space complexity?

Time Complexity: I do not see further time complexity optimizations.

Space Complexity: I do not see further space complexity optimizations because the solution syntactically is recursive, but performs iteratively. The recursive part of the code, allPerm performs after each iteration through the input. Therefore, there are no methods saved onto the JVM's call stack.

 Code

Iterate through each char and move the char to each position of the input String.
Add each version to a Set.

fun allPerm(input: String, lookAtIndex: Int, set: HashSet<String>): HashSet<String> {
    if (lookAtIndex <= input.length - 1) {
        for (i in 0 .. input.length - 1) {
            val combo = input.substring(0, lookAtIndex) +
                    input.substring(lookAtIndex + 1)
            set.add(combo.substring(0, i) + input.get(lookAtIndex) +
                    combo.substring(i))
        }
        allPerm(input, lookAtIndex + 1, set)
    }
    return set
}

See: GitHub

✅ Solution
 Fix - Missing Combinations

Recursively generate each permutation of characters.
For every permutation, iterate through each index and move the last character to each position of the permutation.
Add each permutation to the Set.

fun getPerms(input: String): HashSet<String> {
    val perms = hashSetOf<String>()
    if (input.length <= 1)
        return hashSetOf(input)
    val allCharsExceptLast = input.substring(0, input.length - 1)
    val permsOfAllCharsExceptLast = getPerms(allCharsExceptLast)
    val lastChar = input.substring(input.length - 1)
    for (s in permsOfAllCharsExceptLast) {
        for (i in 0.. allCharsExceptLast.length) {
            perms.add(s.substring(0, i) + lastChar + s.substring(i))
        }
    }
    return perms
}

 Questions
1: How does the problem change if the string can have duplicate characters?
Considering the input aaaaaaaaaaaaaaaaaaaaaa, it would return one combination. However, the algorithm would check each possible combination at every index which is highly inefficient. For example, with input aaa, the algorithm would run 9 times for the character at index 0, 1, and 2 for all 3 positions, so 3 x 3 iterations.
2: What is the space and time complexity?
Considering the input abcdefghijklmnopqrstuvwxyz, it seems like the space complexity grows larger than O(n^2) and closer to O(n^n), exponential growth.
3: How to optimize the time complexity?
If we take a simple example with one repeated character, a, in the input abac, the second combinations of a at index 2 are entirely repeated throughout the rest of the iterations.
Therefore, if a character value is a repeat value the iterations for the repeated value should be skipped. The algorithm may be adjusted to store an instance variable set of characters already searched for to improve the time efficiency.
Index 0
abac
baac
baac
baca
Index 1
baac
abac
aabc
aacb
Index 2: This is the second time using character a, therefore, we can skip these iterations.
aabc
aabc
abac
abca
Index 3
caba
acba
abca
abac


Basic OS login program I have just finished the sololearn C++ course and wanted to create a basic login program in the vein of a basic operating system.

#include "ubuntu_login"
#include <iostream>
#include <string>
using namespace std;

Ubuntu_Login::Ubuntu_Login()
{
    cout << "\t Welcome to Ubuntu!\n" << endl;
}

void Ubuntu_Login::usr_login()
{

cout << "Please enter a username" << endl;
getline(cin,username);

cout << "Please enter a password" << endl;
getline(cin,password);

while(username_input != username || password_input != password)
  {
    cout << "\n|Ubuntu Login|" << endl;

    cout << "Please enter your username" << endl;
    getline(cin, username_input);

    cout << "Please enter your password" << endl;
    getline(cin, password_input);

    if(username_input != username || password_input != password)
      {
        cout << "Incorrect username or password" << endl;
      }
  }
}

#include "ubuntu_login.h"
#include <iostream>
#include <string>
using namespace std;

int main()
{
  Ubuntu_Login UO;
  UO.usr_login();
}

Header file:

#ifndef UBUNTU_LOGIN_H
#define UBUNTU_LOGIN_H
#include <string>
using namespace std;

class Ubuntu_Login
{
public:
  Ubuntu_Login();
  void usr_login();
private:
  string username;
  string password;
  string username_input;
  string password_input;
};

#endif // UBUNTU_LOGIN_H

Any help on improving my code by getting rid of useless code or replacing it with better code would be greatly appreciated.

Never write login code

This is much harder than you think. Leave it to the experts you will get some security piece wrong.

Code Review

Don't use this:

using namespace std;

See Why is “using namespace std;” considered bad practice?.

The reason the "standard namespace" is called std is so that it is not a big deal to type std:: before each standard object/function/type. Don't be lazy type the extra 5 characters.

I don't see declarations for username or password I hope they are not global variables.

cout << "Please enter a username" << endl;
getline(cin,username);

cout << "Please enter a password" << endl;
getline(cin,password);

You have used a while loop.

while(username_input != username || password_input != password)
{
}

You may want to look at a do while loop. As the test is not done till the end of the input code. If somebody had an empty username and password then it would match before the loop was entered and you would never get asked.

do
{
}
while(username_input != username || password_input != password);

Hint

Passwords should NEVER be stored (or encrypted). You should only ever store the hash of the password (properly salted). When a user enters a password hash it with the appropriate salt and compare it to the stored hash of the password.

A hash can be though of as one way encryption. You can encrypt it, but because it is lossy you can not decrypt the hash back to a password. So if people get hold of the your password file all they have is a set of hashes and no passwords.


Find all single elements in an array I am interested in printing all numbers that do not have a match in an array.
Example: 1,3,4,5,3,4,5,5,6 result 1,5,6
Please review my solution bellow. What would be a much better way for this? Any input on how to improve this is welcome

public static Integer[] outputSinglePair(Integer[] numbers){
        if(numbers == null)
            throw new IllegalArgumentException();

        Arrays.sort(numbers);
        ArrayList<Integer> result = new ArrayList<Integer>();
        for(int i = 0; i < numbers.length - 1; ){
            if(numbers[i] != numbers[i + 1]){
                result.add(numbers[i]);
                i++;
            }
            else
                i+=2;
            if(i == numbers.length - 1)result.add(numbers[i]);//we hit last element of array which is unpaired
        }
        return result.toArray(new Integer[0]);
    }

I think this is the sort of thing for which HashSet is perfect. Your implementation would look something like I have shown below. The advantage is that you don't need a sort so your running time is strictly linear.

(Updated to fix syntax errors)

public static Integer[] outputSinglePair(Integer[] numbers){
    if(numbers == null)
        throw new IllegalArgumentException();

    HashSet<Integer> result = new HashSet<Integer>();
    for (int next: numbers) {
        if (result.contains(next)) {
            result.remove(next);
        }
        else {
            result.add(next);
        }
    }
    return result.toArray(new Integer[result.size()]);
}


Duplicates in array elements and sorting I've been given this little test exercise for an interview as php developer, and I'd like to hear from you if my solution is good (enough) or if the problem could have been solved in a better way. Please keep in mind that I've no academic training in CS or equivalent (rather the opposite) and my career started as a self-taught developer.

Given the array:

$numbers = array(
   1,  68,86, 52, 35, 86, 1, 24, 13, 72, 1
);

Take the duplicates and print them out in a string separated by a comma (ex. "a,b,c,d"), ordered in ascendent way.

$holder = [];  // holder for the duplicates
$prev = 0; // previous number
sort($numbers); // sorted them now, so the loop is one-time only

foreach($numbers as $num) {
   if ($prev == $num) {
      $holder[$num] = $num;
      /*I put the $num as index of the array so any double occurrence will overwrite any similar one, to avoid dupes on the $holder that would have compelled me to scan it again.*/
   }
   $prev = $num;  // assign the current number so on the next iteration
                  // i will compare with the next
}

echo implode(',', $holder); //print them out comma separated

I'm not sure if this is an optimal way or could be optimized / made better further. I'm guessing it's an \$O(n)\$ algorithm but again, I admit I have poor theoretical knowledge...

EDIT

My mistake, the requirements were for results sorted, I'm sorry for not pointing it out (I thought I did)

Since it's an interview, they're probably looking for one of two things:

You show that you understand logic
You know PHP

It's never advisable to "recreate the wheel", and PHP has built-in methods to do what you're looking for - for example:

// Count how many times each array value occurs in the array
$occurrences = array_count_values($numbers);
// Filter out any that aren't duplicates
$duplicates = array_filter($occurrences, function($count) { return $count > 1; });
// Format the output as requested
$output = implode(',', array_keys($duplicates));

I note you don't say you have a requirement to sort anything, so don't bother.

If I were hiring you I'd obviously prefer you had both of the points above, but I'd rather that you used PHP to its ability as much as possible. Aside from that, this is a code review site, so the same answer would stand in that case. Example.


Random String Chooser I was tasked with creating the class RandomStringChooser that prints the strings in the passed array in a random order, based on the for loop in the tester. If the number of iterations in the for loop is larger than the size of the array passed, then "NONE" should be returned. Look at the tester in the program for an example of how this is run.

I'm looking for feedback on code efficiency, neatness, and other nitpicks that can improve the look of my code. I'd very much like to kick bad habits to the curb.

import java.util.List;
import java.util.ArrayList;
import java.util.Random;

// Declare the RandomStringChooser class

public class RandomStringChooser {

    /** Declare any fields (instance variables) **/
    private ArrayList<String> wordArray;
    private Random r;

    /** Declare any constructors */
    public RandomStringChooser(String[] wordArray) {
        this.wordArray = convert(wordArray);
        this.r = new Random();
    }

    /**Convert array to arraylist**/
    private ArrayList<String> convert(String[] array) {
        ArrayList<String> arraylist = new ArrayList<String>();
        for(String string : array) {
            arraylist.add(string);
        }
        return arraylist;
    }

    /** Write the getNext method */
    public String getNext() {
        if(this.wordArray.size() != 0) {
            int index = r.nextInt(this.wordArray.size());
            String word = this.wordArray.get(index);
            if(word != null) {
                this.wordArray.remove(index);
                return word;
            }
            return "NONE";
        }
        return "NONE";
    }

    /** This is a main method for testing the class */
    public static void main(String[] args) {
        System.out.println("It should print the words in the array in a random order and then NONE twice");
        String[] wordArray = {"wheels", "on", "the", "bus"};
        RandomStringChooser sChooser = new RandomStringChooser(wordArray);
        //This loop will output the words in `wordArray` in random order, then "NONE" twice
        for (int k = 0; k < 6; k++) {
            System.out.println(sChooser.getNext() + " ");
        }
        //This loop will output the words in `wordArray` in random order, then stop
        for (int k = 0; k < 4; k++) {
            System.out.println(sChooser.getNext() + " ")
        }

     } // end of main

} // end of class

Interface

When I see a method named get…(), I expect it to behave like a getter method: it should retrieve data, with no side-effects.  Your getNext(), though, has the side-effect of consuming one random element from the list.  Therefore, next() would be a more appropriate name than getNext().

Once you rename it, you'll see that your RandomStringChooser should probably just implement the Iterator<String> interface.  Java programmers instantly recognize an Iterator and know how one should behave.

Then, you'll see that the Iterator interface says that next() should throw NoSuchElementException when the elements have been exhausted — and that is what you should do too.  In fact, returning "NONE" as a special string to indicate a missing value is a bad practice.

Furthermore, if one of the input strings is in fact null, it shouldn't be the job of your RandomStringChooser to translate it to "NONE".

Consider changing the signature of the constructor to public RandomStringChooser(String... words).  The code will continue to work the same way, but you would also have the option of invoking it as new RandomStringChooser("wheels", "on", "the", "bus"), with multiple string arguments.

Efficiency

Whenever you extract a random element from the list, you call this.wordArray.remove(index).  Removing an element causes all of the subsequent elements to be copied over to fill the gap.  Therefore, if you randomly go through an n-element list, you will perform O(n2) copy operations, which is quite poor for efficiency.

A better idea would be to implement a Fisher-Yates shuffle, which just swaps one pair of elements per output string.

Miscellaneous

wordArray is poorly named: it's actually a java.util.List, not an array.

Your signposting comments are annoying noise to anyone who knows Java.

Suggested implementation

import java.util.Arrays;
import java.util.Iterator;
import java.util.NoSuchElementException;
import java.util.Random;

public class RandomStringChooser implements Iterator<String> {

    private Random r;
    private String[] words;
    private int n;

    public RandomStringChooser(String... words) {
        this.r = new Random();
        this.words = Arrays.copyOf(words, words.length);
        this.reset();
    }

    /**
     * Makes all words eligible to be chosen again, even if they have been
     * previously returned by next().
     */
    public void reset() {
        this.n = this.words.length;
    }

    public boolean hasNext() {
        return this.n > 0;
    }

    public String next() {
        if (!this.hasNext()) {
            throw new NoSuchElementException();
        }

        // Fisher-Yates shuffle
        int index = r.nextInt(this.n--);
        String word = this.words[index];
        this.words[index] = this.words[this.n];
        this.words[this.n] = word;
        return word;
    }

    /** This is a main method for testing the class */
    public static void main(String[] args) {
        System.out.println("It should print the words in the array in a random order and then NONE twice");
        RandomStringChooser sChooser = new RandomStringChooser(
            "wheels", "on", "the", "bus"
        );
        //This loop will output the words in `wordArray` in random order, then "NONE" twice
        for (int k = 0; k < 6; k++) {
            System.out.println(sChooser.hasNext() ? sChooser.next() : "NONE");
        }
        //This loop will output the words in `wordArray` in random order, then stop
        sChooser.reset();
        for (int k = 0; k < 4; k++) {
            System.out.println(sChooser.hasNext() ? sChooser.next() : "NONE");
        }
     }

}


Constructor function for persons with hobbies I'm trying to write a constructor function that generates instances of a user. One of the properties of the user class is an array of the user's hobbies. I'd like my constructor to have a method that generates a string representation of the array of hobbies provided to the constructor function. The goal is to create a grammatically correct sentence containing the hobbies of the Person instance, so if interests = ['hiking', 'biking', 'skiing'] the Person.bio() method will alert something like: This person's interests are: hiking, biking and skiing. I am trying to account for an array of unknown length being passed to the constructor.

I haven't used .reduce() much but from the little bit of testing I've done, this seems to do what I want it to do. I'm just looking for any critiques on how to make things more readable or performant!

Below is a stripped down version of the constructor function (missing things like name, age, etc. for clarity).

function Person(interests = []) {
  this.interests = interests;
  this.hobbiesSentence = interests.reduce((hobbyString, hobby, index, interests) => {
    switch(index) {
      case (interests.length - 1):
        return hobbyString += `${hobby}.`
      case (interests.length - 2):
        return hobbyString += `${hobby} and `
      default:
        return hobbyString += `${hobby}, `
    }
  }, '');

  this.bio = function () {
    alert(`This person's interests are: ${this.hobbiesSentence}`)
  };
}

As I'm writing this, I could see a case for making the function exist but not necessarily creating/storing the sentence unless the bio() method is called. Any other ideas? Thanks in advance.

Performance

Strings are immutable, so using accumulator += stuffToAppend in a loop can traditionally impact performance. The problem is that we're creating a new string every iteration, leading to quadratic time complexity for an operation that should be linear. It turns out that modern browsers optimize this heavily using an internal array to represent string parts and make it quite fast over using an explicit array, so this post is focused on style rather than performance.

Design

On first thought, reduce seems like the right function from a semantic standpoint since we want to boil the array of interests down to one string. However, since avoiding string concatenation requires an intermediate array in reduce, we might as well just skip the intermediate array and use map and join. It's pretty common that reduce can be replaced with map or filter, which are more specific and succinct.

Switch statements are also generally not used much in JS (but often used in C...). You can replace many switch statements in JS with an object (particularly if you're choosing between a number of similar functions), or at least an if statement. Either way, the nature of the commas and "and" in this example makes it a bit awkward, so there doesn't seem to be any clear-cut win.

Additionally, this routine of "prettifying" a list is generic and can be moved to a separate function to keep Person clean.

As an aside, instead of switching between "interests", "hobbies" and "bio", it seems best to pick one term and stick with it throughout.

Here's my attempt. This might seem a bit abstract, but it's typical in JS to avoid conditional/switch stuff as much as it is to avoid loops (which is the idea with reduce). If you prefer a more traditional approach, replace the joins array and indexing with an if statement and I'd still endorse it.

const prettyList = (a, sep=", ", endSep=[" and ", "."]) =>
  a.map((e, i) => e + (endSep[endSep.length-a.length+i] || sep)).join("")
;

const Person = function (interests=[]) {
  this.interests = interests;
  this.interestsSentence = prettyList(interests);

  this.interestsStr = () =>
    "This person's interests are: " + this.interestsSentence
  ;
};

const interests = ["foo", "bar", "baz", "quux"];

for (let i = 1; i <= 4; i++) {
  console.log(new Person(interests.slice(0, i)).interestsStr());
}

Now the function is reusable and we can change its behavior without much effort at all:

const prettyList = (a, sep=", ", endSep=[" and ", "."]) =>
  a.map((e, i) => e + (endSep[endSep.length-a.length+i] || sep)).join("")
;

const activities = ["biking", "running", "walking", "skipping", "driving"];
console.log("I love", prettyList(activities, "; ", [", sometimes ", " but not ", "!"]));
console.log("I love", prettyList(activities, " and ", [" while ", " :-o"]));


Class initialisation of fields I have a the beginnings of a class (in this case for a NeuralNet).
I'm not very happy with how I am initializing self.ws, seems a bit off.
What is the pythonic way to do this?

import numpy as np
class NeuralNet:
    def __init__(self,layerSizes):
        self.ws = self._generateStartingWeights(layerSizes)

    def _generateStartingWeights(self,layerSizes):
        def randMatrix(szThis,szNext): return np.matrix(np.random.normal(0,0.01,(szThis,szNext)))
       return [randMatrix(szThis,szNext) for (szThis,szNext) in pairwise(layerSizes)]

I think the primary question here is one of whether _generateStartingWeights or randMatrix are reusable; the secondary question is of naming conventions.

If _generateStartingWeights is not reusable, there's little reason not to write __init__ without the layers of helpers (and that's assuming there's not some better way to use numpy for this). Oh, and if it is reusable, you can just return this from it, instead of using a locally defined helper function:

def __init__(self, layerSizes):
    self.ws = [np.matrix(np.random.normal(0, 0.01, pair)) for pair in pairwise(layerSizes)]

On the flip side, if randMatrix is reusable, it needs to be somewhere other than local to another function.

As for naming conventions, a potentially heated subject, lots of people refer to PEP-8 (which I want to clarify is not a requirement for third party code unless you want to make it one). However due to its prevelance in the Python community, there seems to be a general preference for underscore_separated instead of camelCase names. Since it's not even always followed in the standard library, your project's preferences can overrule it. I only bring it up since I personally find camelCase names to be less in line with my view of "pythonic."


Count the number of vowels and consonants So I needed to write a function that takes a string and returns a javascript object with vowels and consonants properties that maps to the number of vowels and consonants in the string

function getCount(words) {
  let answer = {vowels: 0, consonants: 0};
  if( typeof words !== 'string') { return answer }

  let vowel  = 'aeiouAEIOU'

  for(char of words){
    if(char === ' ') { continue }
    if(vowel.indexOf(char) === -1){  // not a vowel
      answer.consonants += 1
    }
    else if(vowel.indexOf(char) !== -1){  // is a vowel
      answer.vowels += 1
    }
  }
  return answer
}

Is there a better way of going about it? Preferably a functional approach

This avoids loops completely and expresses your intent more clearly, I think.

Also, note that you should explicitly define the valid consonants, so that you will properly ignore numbers, punctuation, etc.

function getCount(words) {
  var words      = (typeof words == 'string') ? words : '',
      count      = re => (words.match(re) || []).length,
      vowels     = count(/[aeiou]/ig),
      consonants = count(/[bcdfghjklmnpqrstvxzwy]/ig);

  return {vowels, consonants};
}


Text extraction of document files I have this script that pulls text out of .docx, .doc and .pdf files and uploads that text to an Azure SQL Server. This is so users can search on the contents of those documents without using Windows Search / Azure Search.

The filenames are all in the following format:

firstname surname - id.extension

The id is incorrect though, the ID is from an outdated database and the new database that I am updating holds both (newID and oldID).

COLUMNS:

ID - New ID of the candidate record
OldID - Old ID of the candidate record (old database schema)
OriginalResumeID - Document link ID for the candidate table to the document table
CachedText - The field I am updating (holds the document text) at the moment this will mostly be NULL

Here is the script:

## Get resume list
$params = @{
    'Database' = $TRIS5DATABASENAME
    'ServerInstance' = $($AzureServerInstance.FullyQualifiedDomainName)
    'Username' = $AdminLogin
    'Password' = $InsecurePassword
    'query'    = "SELECT id, OldID, OriginalResumeID FROM Candidate WHERE OriginalResumeID IS NOT NULL"
}
$IDCheck = Invoke-Sqlcmd @params

## Word object
$files = Get-ChildItem -force -recurse $documentFolder -include *.doc, *.pdf, *.docx
$word = New-Object -ComObject word.application
$word.Visible = $false
$saveFormat = [Enum]::Parse([Microsoft.Office.Interop.Word.WdSaveFormat], "wdFormatText")

foreach ($file in $files) {
    Write-Output "Processing: $($file.FullName)"
    $doc = $word.Documents.Open($file.FullName)
    $fileName = $file.BaseName + '.txt'
    $doc.SaveAs("$env:TEMP\$fileName", [ref]$saveFormat)
Write-Output "File saved as $env:TEMP\$fileName"
    $doc.Close()

    $4ID = $fileName.split('-')[1].replace(' ', '').replace(".txt", "")
    $text = Get-Content "$env:TEMP\$fileName"
    $text = $text.replace("'", "''")

    $resumeID = $IDCheck | where {$_.OldID -eq $4id} | Select-Object OriginalResumeID
    $resumeID = $resumeID.OriginalResumeID

    <# Upload to azure #>
    $params = @{
        'Database' = $TRIS5DATABASENAME
        'ServerInstance' = $($AzureServerInstance.FullyQualifiedDomainName)
        'Username' = $AdminLogin
        'Password' = $InsecurePassword
        'query'    = "Update Document SET CachedText = '$text' WHERE id = $ResumeID"
    }
    Invoke-Sqlcmd @params -ErrorAction "SilentlyContinue"
    Remove-Item -Force "$env:TEMP\$fileName"
}

$word.Quit()

The problem is that running this on a large dataset, let's say 750000 documents takes far too long per document. I'm fairly certain that this is because it has to search through the entire $IDCheck object of 750000 records before it can get the originalResumeID of the record to upload to.

Running this on a smaller database is quite quick (around 200000 per 24 hours). I was thinking I could check the documents table and only pull rows where the CachedText field is null and loop that to run every 50000 documents so it would get quicker as it goes. Problem is the documents table will be massive and will take a long time to search through every time this is called.

Any help on speeding this up would be much appreciated.

EDIT:

Looks like it is the upload to azure causing the delay:

<# Upload to azure #>
$params = @{
    'Database' = $TRIS5DATABASENAME
    'ServerInstance' = $($AzureServerInstance.FullyQualifiedDomainName)
    'Username' = $AdminLogin
    'Password' = $InsecurePassword
    'query'    = "Update Document SET CachedText = '$text' WHERE id = $ResumeID"
}
Invoke-Sqlcmd @params -ErrorAction "SilentlyContinue"

I would try to use bulkcopy to load all of the IDs and their CachedText at once into a staging table in Azure, and then do a single update on your document table.

 CREATE TABLE document
(docKey     BIGINT IDENTITY(1, 1) PRIMARY KEY,
 CachedText NVARCHAR(MAX),
 id         INT
);
CREATE TABLE document_stage
(CachedText NVARCHAR(MAX),
 id         INT
);

As you iterate over the files, you create a PSObject with the properties you want in your sql table and add it to an collection. Then after all files are done, or at set batching limits you can use Out-DataTable to convert the collection into a data table, and then let SqlBulkCopy upload to the stage table in one batch, and a single UPDATE will update your primary table.

UPDATE Document
  SET
      CachedText = stg.CachedText
FROM document_stage stg
WHERE document.id = stg.id;

PS script

$files = Get-ChildItem -force -recurse $documentFolder -include *.doc, *.pdf, *.docx

$stagedDataAsArray = @()
foreach ($file in $files) {

    $fileName = $file.name
    $4ID = $fileName.split('-')[1].replace(' ', '').replace(".txt", "")
    $text = Get-Content "$($file.FullName)"
    $text = $text.replace("'", "''")

    $resumeID = $IDCheck | where {$_.OldID -eq $4id} | Select-Object OriginalResumeID
    $resumeID = $resumeID.OriginalResumeID

    <# create the row and add it to our  #>
     $fileInstance = New-Object -TypeName psobject
    $fileInstance | add-member -type NoteProperty -Name cachedText -Value $text
    $fileInstance | add-member -type NoteProperty -Name resumeID -Value $resumeID
    $stagedDataAsArray += $fileInstance
    Remove-Item -Force "$env:TEMP\$fileName"

    }
    $stagedDataAsTable = $stagedDataAsArray | Out-DataTable
    $cn = new-object System.Data.SqlClient.SqlConnection("YOUR AZURE DB CONNECTION STRING");
    $cn.Open()
    $bc = new-object ("System.Data.SqlClient.SqlBulkCopy") $cn
    $bc.DestinationTableName = "dbo.document_stage"
    $bc.WriteToServer($stagedDataAsTable)
    $cn.Close()

    $params = @{
        'Database' = $TRIS5DATABASENAME
        'ServerInstance' = $($AzureServerInstance.FullyQualifiedDomainName)
        'Username' = $AdminLogin
        'Password' = $InsecurePassword
        'query'    = "UPDATE Document
  SET
      CachedText = stg.CachedText
FROM document_stage stg
WHERE document.id = stg.id;"
    }
    Invoke-Sqlcmd @params -ErrorAction "SilentlyContinue"


Instantiate multiple classes in another class, invoke method from multiple classes The goal here is to pull all alerts from a single iterable:
obj = Alerts(db, args)
for alert in obj.alerts()
    pass

Now, I need to add a few more sources and I'm not sure if this is a good approach to instantiate all classes in the AllAlerts constructor? I also don't like the fact that I'll have to add them to the self.sources attribute each time there is a new one (achieving loose coupling).
Based on the code snippet provided below could you recommend some different, perhaps a better approach?
Code:
from itertools import chain

from . import mappings
from .utils import converter

class BaseSource(object):
    def __init__(self, db, args):
        self.args = args
        self.db = db

    def alerts(self):
        raise NotImplementedError

    def _data(self, mapping, source):
        """
        This method do the parsing based on data source.
        """
        for entry in self._raw_data():
            yield converter(source, mapping, entry)

class NagiosSource(BaseSource):
    def __init__(self, *args, **kwargs):
        ...
        super().__init__(*args, **kwargs)

    def _raw_data(self):
        """
        The logic to get the data from Nagios.
        """

    def alerts(self):
        mapping = mappings.nagios
        return self._data(mapping, "nagios")

class ZabbixSource(BaseSource):
    def __init__(self, *args, **kwargs):
        ...
        super().__init__(*args, **kwargs)

    def _raw_data(self):
        """
        The logic to get the data from Zabbix.
        """

    def alerts(self):
        mapping = mappings.zabbix
        return self._data(mapping, "zabbix")

class AllAlerts(BaseSource):
    def __init__(self, db, args):
        self.sources = (
            NagiosSource(db, args),
            ZabbixSource(db, args),
        )
        super().__init__(db, args)

    def alerts(self):
        return chain.from_iterable(s.data() for s in self.sources)

I though about adding a class decorator that will register all sources but then again, I would have to use a global variable and not sure how I could pass args when creating objects...
test.py:
sources = set()

def register(cls):
    sources.add(cls())
    return cls

@register
class NagiosSource:
    pass

@register
class ZabbixSource:
    pass

Test:
$ python test.py
{<__main__.ZabbixSource object at 0x7f1a3b1d26d0>, <__main__.NagiosSource object at 0x7f1a3b1d2760>}

Recording Subclasses
As of Python 3.6, there is an easy way to gather all your subclasses together, without having to risk the error-prone method of manually creating an AllAlerts subclass and listing all of the subclasses in it.  The key is object.__init_subclass__(cls).  It is called when a subclass is defined.
class BaseSource:
    subclasses = []

    def __init_subclass__(cls, **kwargs):
        super().__init_subclass__(**kwargs)
        cls.subclasses.append(cls)
        print("Registered", cls)

Now, whenever a subclass of BaseSource is defined, that subclass will be added to the BaseSource.subclass list.
Of course, AllAlerts did more than this.  It created one instance of each source subclass and passed the same arguments in the constructor of each.  We'll have to do that in a @classmethod of the base class.  It also used itertools to chain together all of the alerts from each of those source instances, so we'll have to record those source instances, and provide a @classmethod for getting that chain of alerts.
from itertools import chain

class BaseSource:
    subclasses = []

    def __init_subclass__(cls, **kwargs):
        super().__init_subclass__(**kwargs)
        cls.subclasses.append(cls)
        print("Registered", cls)

    @classmethod
    def init_all(cls, db, args):
        """
        Create one instance for each subclass, constructed using the given
        'db' and 'args' values.
        """
        cls.sources = (subclass(db, args) for subclass in cls.subclasses)

    @classmethod
    def all_alerts(cls):
        """
        Return an iterable of all alerts from all subclass sources
        """
        return chain.from_iterable(src.alerts() for src in cls.sources)

    def __init__(self, db, args):
        self.db = db
        self.args = args

    def alerts(self):
        """
        Return an iterable of alerts for this class
        """
        raise NotImplementedError()

With this base class, you just need to define the source subclasses, as many as you like.  There is no need to remember all of the classes; the base class does that for you:
class NagiosSource(BaseSource):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        print("Constructed Nagios Source")

    def alerts(self):
        yield "Alert 1"
        yield "Alert 2"

class ZabbixSource(BaseSource):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        print("Constructed Zabbix Source")

    def alerts(self):
        yield "Alert A"
        yield "Alert B"

After all of the subclass definitions have been read in, you will have to initialize them with the appropriate db and args, like you created an AllAlerts instance, which created all of the source objects.  And then you can request all alerts from the base class:
BaseSource.init_all("mydb", (1, 2, 3))

print(list(BaseSource.all_alerts()))

Output of above:
Registered <class '__main__.NagiosSource'>
Registered <class '__main__.ZabbixSource'>
Constructed Nagios Source
Constructed Zabbix Source
['Alert 1', 'Alert 2', 'Alert A', 'Alert B']
>>>

Raise objects, not classes
Your BaseSource had the method:
    def alerts(self):
        raise NotImplementedError

This appears to be raise a class instead of an instance of a class.  You should write:
    def alerts(self):
        raise NotImplementedError()

Using instances allows you to have arguments, which helps describe the error.  What does "Not Implemented" mean?  Does it mean "Not Implemented Yet", as in a later version of the library is expected to provide an implementation?  No!  We need subclasses to provide the implementation.
    def alerts(self):
        raise NotImplementedError("This method must be overridden in derived classes")

Public methods need docstrings
You provide docstrings for _data() and _raw_data(), but not for alerts().  This is backwards.
The leading underscore represents private methods.  An external caller does not need to know how to call them, because they are private.
On the other hand, public functions (without the leading underscore) are expected to be called by external callers.  And someone writing the code which uses these Source objects may want to know how to call the methods.  So they may type:
>>> help(NagiosSource)

and would reasonable expect to get information about how to use the class and its public method.  The docstring for _data and _raw_data would not be provided, because of the leading underscore.
You may provide docstrings for private methods (the expectation is the public methods would all have been documented first), but code comments may be just as useful.


I'm torn between conditionals and abrupt return functions Which one of these two is better?

This one:

middleware.response_redirect = function(){
   return function (req, res, next){
       var redirect = function(){
           if(req.form.redirect) return url.parse(req.form.redirect);
           return {
               protocol: "http",
               hostname: config.domain,
               pathname: "thanks",
           }
       }();
       redirect.query = querystring.stringify({
           "status": "success",
           "message": req.form.message
       });
       return res.redirect(url.format(redirect);
   }
}

Or this one:

middleware.response_redirect = function(){
   return function (req, res, next){
       var redirect;
       if(req.form.redirect){
           redirect = url.parse(req.form.redirect);
       }else{
           redirect = {
               protocol: "http",
               hostname: config.domain,
               pathname: "thanks",
           }
       }
       redirect.query = querystring.stringify({
           "status": "success",
           "message": req.form.message
       });
       return res.redirect(url.format(redirect);
   }
}

The function within function thing bothers me a little. But so does setting redirect in two places.

How about a ternary operator?

var redirect = req.from.redirect
  ? url.parse(req.from.redirect)
  : {
    protocol: 'http',
    hostname: config.domain,
    pathname: 'thanks'
  };

Looks cleaner in my opinion.


Counting which numbers fall in a certain bracket I'm taking a text file that looks like this:

77, 66, 80, 81
40,  5, 35, -1
51, 58, 62, 34
 0, -1, 21, 18
61, 69, 58, 49
81, 82, 90, 76
44, 51, 60, -1
64, 63, 60, 66
-1, 38, 41, 50
69, 80, 72, 75

and I'm counting which numbers fall in a certain bracket:

f = open("//path to file", "r")
text = f.read()
split = text.split()

greater70=0
sixtys=0
fiftys=0
fortys=0
nomarks=0

for word in split:
    temp = word.replace(',', '')
    number = int(temp)
    if number > 70:
        greater70+=1
    if number >= 60 and number <= 69:
        sixtys+=1
    if number >= 50 and number <= 59:
        fiftys+=1
    if number >= 40 and number <= 49:
        fortys+=1
    if number == -1:
        nomarks+=1

print greater70
print sixtys
print fiftys
print fortys
print nomarks

Have I done it in an efficient way sensible way or do experienced Python users think it looks a little convoluted?

Notes:

Creating so many variables is a warning sign that they should be grouped  somehow (an object, a dictionary, ...). I'd use a dictionary here.
Consider learning some functional programming (as opposed to imperative programming) to apply it when it improves the code (IMO: most of the time). Here it means basically using collections.counter and generator expressions.
Don't read whole files, read them line by line: for line in file_descriptor.
There are programmatic ways of detecting intervals of numbers (simple loop, binary search). However, since you have here only 5 intervals it's probably fine just to write a conditional as you did. If you had, let's say 20 intervals, a conditional branch would be a very sad thing to see.
Conditional branches are more clear when you use non-overlapping conditions with if/elif/else (effectively working as expressions instead of statements).

I'd write:

from collections import Counter

def get_interval(x):
    if x > 70:
        return "greater70"
    elif 60 <= x < 70:
        return "sixtys"
    elif x >= 50:
        return "fiftys"
    elif x >= 40:
        return "fortys"
    elif x == -1:
        return "nomarks"

with open("inputfile.txt") as file:
    counter = Counter(get_interval(int(n)) for line in file for n in line.split(","))
# Counter({'sixtys': 10, 'greater70': 10, None: 7, ..., 'fortys': 4})


External bottom up merge sort too slow My external sort function works but it is way too slow. I think the bottleneck is the merge function. How can I make it faster. Is there a better merge function I can use for merging into a file using random access file objects and buffers?

private static void merge(String a, String b,
int l, int m, int r)throws FileNotFoundException, IOException
{
    RandomAccessFile a1f = new RandomAccessFile(a,"rw");
    RandomAccessFile b1f = new RandomAccessFile(b,"rw");
    a1f.seek(l*4);
    b1f.seek(l*4);

    for(int i = l; i<m;i++){
        a1f.seek(i*4);
        b1f.seek(i*4);
        int num = a1f.readInt();
        b1f.writeInt(num);
    }

    for(int j=m; j<r; j++){
        a1f.seek((m + r - j - 1)*4);
        b1f.seek(j*4);
        int num = a1f.readInt();
        b1f.writeInt(num);
    }
    int i = l;
    int j = r - 1;

    //for (int i = l; i < m; i++) b[i] = a[i];
    //for (int j = m; j < r; j++) b[j] = a[m + r - j - 1];
    //if (b[j] < b[i]) a[k] = b[j--];
    //else a[k] = b[i++];

    for (int k = l; k < r; k++){
        b1f.seek(j*4);
        int b_j = b1f.readInt();
        b1f.seek(i*4);
        int b_i = b1f.readInt();
        if(b_j<b_i){
            b1f.seek((j--)*4);
            a1f.seek(k*4);
            a1f.writeInt(b1f.readInt());
        }
        else{
            b1f.seek((i++)*4);
            a1f.seek(k*4);
            a1f.writeInt(b1f.readInt());
        }

    }

    a1f.close();
    b1f.close();
}

The most glaring problem in your code here, is that you open and close the file on each call to the merge function. You should instead open it once in the calling function, and pass in the already-open files to the merge method. The open and close operaions are both slow, and should be minimized.

I recommend that you re-work that part of the solution, then re-post as a 'follow on', but then also include the calling part of the function in to your question so that more of the overall structure of your solution can be reviewed.

The variables a, b, l, r, m i, j, and k are also all horrible names... you should rename them to be 'self-documenting'. They should be called what they are. The variable l is particularly problematic because it is so easy to confuse with 1.

I struggle to understand the difference between the a and b files. It appears that you are copying the first chunk of data from the a-file to the b-file, and then merging from two different places in the b file back to the a-file.

I would recommend instead having two read-poitns on the b file and then write back to the A. The extra copy is slowing you down too. There's no need to copy from a-to b if you can jsut swap them...


Calculates the number of hours and days left, where the total number of hours is 486 I'm new here and this is my first simple console application that calculates the number of hours left. There's a lot to improve and if you have any suggestions on what things to add or refactor that would be awesome!  It's 486 because it's the usual number of hours an internship has.

The user presses 1 to enter the number of days, and 2 gets the current date. The output shows the accumulated number of hours, the remaining hours and days left before the 486 hours are up.

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

namespace Reuseable
{
    //calculates the accumulated hours, remaining hours, and remaining days, where total hours = 486.
    public static class ReuseableClass
    {
        static int AccumulatedHours(int dayhours, int input)
        {
            int result = dayhours * input;
            Console.WriteLine("Accumulated hours: " + result);
            return result;
        }

        static int RemainingHours(int totalhours, int accumulatedhours)
        {
            int result = totalhours - accumulatedhours;
            Console.Write("Remaining hours: " + result);
            return result;
        }

        static int RemainingDays(int remaininghours, int dayhours)
        {
            int result = remaininghours / dayhours;
            Console.Write("\nRemaining days: " + result);
            return result;
        }

        /// <returns>Number of business days during the 'span'</returns>
        public static double GetBusinessDays(DateTime startD, DateTime endD)
        {

            double calcBusinessDays =
                1 + ((endD - startD).TotalDays * 5 -
                (startD.DayOfWeek - endD.DayOfWeek) * 2) / 7;

            if (endD.DayOfWeek == DayOfWeek.Saturday) calcBusinessDays--;
            if (startD.DayOfWeek == DayOfWeek.Sunday) calcBusinessDays--;

            return calcBusinessDays;
        }

        public static void NumberOne()
        {
            //sets the hours
            int dayHours = 9;
            int totalHours = 486;
            int input;

            Console.WriteLine("\nEnter days");

            bool isNumeric = int.TryParse(Console.ReadLine(), out input);

            if (isNumeric == false) //checks if input is ok or not
            {
                Console.WriteLine("Invalid input");
                Console.ReadLine();
                System.Environment.Exit(1);
            }

            //gets input from user
            int accumHours = AccumulatedHours(dayHours, input);
            int remainingHours = RemainingHours(totalHours, accumHours);
            RemainingDays(remainingHours, dayHours);
        }

        public static void NumberTwo()
        {
            int dayHours = 9;
            int totalHours = 486;

            DateTime startDate = new DateTime(2016, 06, 20);
            DateTime endDate = DateTime.Today;

            int input = Convert.ToInt32(GetBusinessDays(startDate, endDate));

            int accumHours = AccumulatedHours(dayHours, input);
            int remainingHours = RemainingHours(totalHours, accumHours);
            RemainingDays(remainingHours, dayHours);

        }
        public static void Main()
        {
            Console.WriteLine("1. Enter No. of Days \n2. Use current day");
            ConsoleKeyInfo button = Console.ReadKey();
            if (button.Key == ConsoleKey.D1)
            {
                NumberOne();
            }
            else if (button.Key == ConsoleKey.D2)
            {
                NumberTwo();
            }
            else
            {
                Console.WriteLine("Invalid input");
            }

            Console.ReadLine();
        }
    }
}

ReuseableClass

Each class is (ok, might be) reusable so naming it like this does not have much value. It calculates something... name it simply IntershipCalculator.

And... it's not really reusable either because you write to the console there. You should write to the console somewhere else and let the methods just calculate the results.

NumberOne

This looks to me like a class but it's a method. You should name it appropriatly ie ReadNumberOne.

        //gets input from user
        int accumHours = AccumulatedHours(dayHours, input);
        int remainingHours = RemainingHours(totalHours, accumHours);
        RemainingDays(remainingHours, dayHours);

The comment is misleading. You are not getting here anything from the user but writing results.

Console.WriteLine("1. Enter No. of Days \n2. Use current day");

Why not like so?

Console.WriteLine("1. Enter No. of Days");
Console.WriteLine("2. Use current day");


Stripping formatting from text - Am I using an efficient jQuery selector? I'm making a comment box using a contenteditable div, but I want to remove formatting from text a user might copy/paste into it (also no CTRL+B or CTRL+I shortcuts allowed either). Only "approved" formatting ("tagged" names, URLs, etc).

Originally I went the regex route but was informed regex + html is not a good approach, so I then tried using jQuery/DOM manipulation and found a solution there as well.

I am worried though, that my jQuery selector used in $nodesToReplace is too long and possibly inefficient although it basically describes what I want returned. I'm just wondering if there was another more elegant/shorter/more efficient way to do this that I may have overlooked. Here's the code:

Two utility functions (for reference)

// Change an Element's type (change it's html tags) to "newType"
jQuery.fn.changeElemTypeTo = function(newType){
  // just make sure it's a plain element name
  newType.replace(/[<\/>]/ig,'');

  var newElemStr = '<' + newType + '>' + this.html() + '</' + newType + '>';
  console.log('*Nodes with tags replaced: ',newElemStr);
  return this.replaceWith(newElemStr);
};

// Remove/strip the html tags from an element
jQuery.fn.removeElemTags = function(){
  var tmp = this.replaceWith(this.html());
  console.log('*Node with tags Removed: ',this.html());
  return tmp;
};

main handler with super long selector in $nodesToReplace...

$('#input').on('paste', function() {
  var $inputDiv = $(this);
  setTimeout(function() {
    var oldHTML = '', newHTML = '';
    // look through the commentbox for headings and other (mostly) block
    // elements
    var $nodesToReplace = $inputDiv.find('h1,h2,h3,h4,h5,h6,address,article,aside,blockquote,div,p,pre,dd,dt');
    var $nodesToRemove = $inputDiv.find('*').not($nodesToReplace);

    $nodesToRemove.each(function(){
      console.log('Nodes with tags to remove: ',$(this).outerHtml());
      $(this).removeElemTags();
    });

    $nodesToReplace.each(function(){
      console.log('Nodes with tags to replace: ',$(this).outerHtml());
      $(this).changeElemTypeTo('p');
    });
  }, 10);
});

I also have a demo on JSBin: http://jsbin.com/adazel/10/edit

I struggled with the same issue in the past, and decided to simply use a disposable DOM element to convert the HTML to plaintext:

var message = "..."; // Contains HTML markup
var tmp = document.createElement("DIV");
tmp.innerHTML = message;
var message = tmp.textContent||tmp.innerText;
// message now contains plaintext, and tmp can be disposed of

With this approach, we still needed to allow the user to enter a single tag. For this, we simply implemented a microformat where the user enters "placeholders" with bracket symbols:

  Hello [[person]], having a good day?

Since this is just plain text, it will not be removed by the above conversion process, and can simply be replaced with the appropriate HTML tags:

message.replace('/\[\[person\]\]/g', 'some name');


File I/O, SHA1 sum and compression The function hash_blog is inspired by "how git stores its objects". It is supposed to take a String, append a header to it, compute the SHA1 of it, then compress it and write it to a file. The first two characters of SHA1 is a directory name, and the rest of the characters are the file name.

Since I am learning the language, I am looking for general review. Is my code idiomatic Java code? Are there parts where I could make the code better?

package yas;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.zip.DeflaterOutputStream;
// import java.util.zip.Inflater;

public class Yas {

    public static void main(String[] args) {
        try {
            hash_blob("yasar arabaci");
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
    }

    /**
     * @param args
     * @throws NoSuchAlgorithmException
     */
    public static String hash_blob(String content) throws NoSuchAlgorithmException {

        String hash_string; // hold sha1 hash
        String input = "blob " + content.length() + '\0' + content;

        // Step 1 is to compute sha1
        MessageDigest mDigest = MessageDigest.getInstance("SHA1");
        byte[] result = mDigest.digest(input.getBytes());
        { // to create namespace for StringBuilder
            // This code block was borrowed from internet ;)
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < result.length; i++) {
                sb.append(Integer.toString((result[i] & 0xff) + 0x100, 16).substring(1));
            }
            hash_string = sb.toString();
        }
        System.out.println("hash string is " + hash_string);
        // Step 3 is to write to a file

        File dest_file;
        {
            File yas_dir = new File(System.getProperty("user.dir"), ".yas");
            File object_dir = new File(yas_dir, "objects");
            File dest_dir = new File(object_dir, hash_string.substring(0, 2));
            dest_dir.mkdirs();
            dest_file = new File(dest_dir, hash_string.substring(2));
            System.out.println("dest file = " + dest_file);
        }
        try {
            if (!dest_file.exists()) {
                dest_file.createNewFile();
            }
            try (OutputStream out = new DeflaterOutputStream(new FileOutputStream(dest_file))) {
                out.write(input.getBytes());
            }

        } catch (IOException e) {
            e.printStackTrace();;
        }
        return "Dummy Return";

    }
}

Problems :

methods mkdirs() and createNewFile() return booleans to indicate whether they are successful. You should check and handle if they return false.
IOException gets ignored, you print the stacktrace but clients have no way of knowing the method failed.

Style :

This is one procedural block in which different concerns ( finding and creating files, directories, computing hash, converting byte[] to a String, ... ) are handled. Despite an attempt to limit the of variables scope with a block statement, variable scope is unclear and often wider than strictly needed. There is but one cure : refactor : extract method.
variable naming does not follow Java conventions.
Don't return a dummy return value, declare the method to have void as return value, and you don't need to return a value.
Comments : step 1, step 3 what happened to step 2?
printStackTrace() statement ends with ;; only one is needed. (probably a typo)
loop over the byte array can be a foreach loop :

like this :

for (byte aResult : computeSha1Hash(input)) {
    builder.append(Integer.toString((aResult & 0xff) + 0x100, 16).substring(1));
}

coupling should be reduced. The hashing algorithm (sha1), output mechanism (files) and byte[] to String encoding are all hardwired.
use of magic numbers; replace with explaining constants.


Abstract Factory Pattern in Python I have been reading today about the Abstract Factory Pattern, and tried to make the following implementation.
I have seen a lot of implementations in the internet, where they use switch statements, but I must say that I didn't like that much, since the more factories you make, it seems to me that it makes very difficult to add new products, if needed.
Anyways, I was hoping you to take a look at it and let me know your opinions. Thanks in advance for taking your time to review it.
Factories
from abc import ABC, abstractmethod

class PlayerFactory(ABC):
    """
    This class is meant to be an interface
    """
    @abstractmethod
    def create_goalkeeper(self):
        pass

    @abstractmethod
    def create_defender(self):
        pass

class FootballPlayerFactory(PlayerFactory):
    def create_goalkeeper(self):
        return FootballGoalkeeper()

    def create_defender(self):
        return FootballDefender()

class HockeyPlayerFactory(PlayerFactory):
    def create_goalkeeper(self):
        return HockeyGoalkeeper()

    def create_defender(self):
        return HockeyDefender()

Football players
class FootballPlayer:
    def __init__(self, uses_hands):
        self.uses_hands = uses_hands

    def play(self):
        print("I'm playing football!")

class FootballGoalkeeper(FootballPlayer):
    def __init__(self):
        super(FootballGoalkeeper, self).__init__(uses_hands=True)

class FootballDefender(FootballPlayer):
    def __init__(self):
        super(FootballDefender, self).__init__(uses_hands=False)

Hockey players (my creativity stopped here, so I didn't include any difference between goalkeepers and defenders)
class HockeyPlayer:
    def play(self):
        print("I'm playing hockey!")

class HockeyGoalkeeper(HockeyPlayer):
    pass

class HockeyDefender(HockeyPlayer):
    pass

As your code presently stands, you don't need the derived Factory classes.  They don't do anything different from each other, so they can all be handled by a concrete base class.
class PlayerFactory:

    def __init__(self, goal_keeper_class, defender_class):
        self._goal_keeper_class = goal_keeper_class
        self._defender_class = defender_class

    def create_goalkeeper(self):
        return self._goal_keeper_class()

    def create_defender(self):
        return self._defender_class()

player_factory = {
    "Football": PlayerFactory(FootballGoalkeeper, FootballDefender),
    "Hockey": PlayerFactory(HockeyGoalkeeper, HockeyDefender),
}

Example Usage:
>>> player = player_factory["Hockey"].create_defender()
>>> type(player)
<class '__main__.HockeyDefender'>
>>> player.play()
I'm playing hockey!
>>>

If there is some aspect of the factories which actually do something different, and thus necessitate separated derived classes, you'll need to include that in your question.


Plotting many images at once in matplotlib I am using numpy and  matplotlib to do a statistical simulation.  The simulation itself is pretty fast thanks to numPy vectorizatio, however the plotting is slow since I still use a for loop.

Here is the result:

Right now, I call matplotlib.pyplot.plt 10000 times - once for each tile in 100 × 100 square which can't possibly be optimal, but I can't think of how to do it better:

N = 100
for x in range(N):
    for y in range(N):
        plt.fill( myPath[x,y,0] ,myPath[x,y,1])

Let's say I stored all the varaibles in an numPy array myPath with shape (N,N,2,4) so that myPath[x,y,0] and myPath[x,y,1] give the x and y coordinates of the path.

How do I reduce the number of calls to plt in my visualization?

Try using matplotlib's LineCollection class. Here's an example.

In your case, you might do:

from matplotlib import pyplot as plt
from matplotlib.collections import LineCollection

ax = plt.gca()
pts = myPath.reshape((-1,2))  # make a matrix of (x,y) pairs
edges = LineCollection(pts)
ax.add_collection(edges)
plt.show()