texts: Spring autowiring in managed beans with support for serialization - is this safe?

texts:
Im trying to solve two problems I see with JSF2 and Spring.
First

@Autowired in @ManagedBean does not work
Nor does @ViewScoped with @Controller
@ManagedProperty is not type safe and requires setter

Second

You can not serialize singleton spring beans without hassle
Managed beans must be serializable so the container can serialize the session

So I enabled @Autowired in managed beans and fixed serialization with this common base class which all managed beans (at least @SessionScoped and @ViewScoped ones) derive from.
public abstract class Handler implements Serializable {
    private static final long serialVersionUID = 1L;

    @PostConstruct
    private void init() {
        Spring.appCtx.getAutowireCapableBeanFactory().autowireBean(this);
    }

    private void readObject(ObjectInputStream ois) throws ClassNotFoundException, IOException {
        ois.defaultReadObject();
        Spring.appCtx.getAutowireCapableBeanFactory().autowireBean(this);
    }
}

Handlers are now implemented like that:
@ManagedBean
@RequestScoped
public class Index extends Handler implements Serializable {
    private static final long serialVersionUID = 1L;

    @Autowired
    SampleService ss;

    public String hello() {
        return ss.sayHello();
    }
}

First tests seem fine, but I'm curious if I'm causing any problems I don't know of.


texts:
I've been given the following PHP code:

if(empty($search)){
        $_SESSION['keyword_exists'] = "no";
    }else{
        if(isset($_SESSION['old_keyword']) && $_SESSION['old_keyword'] != $search){
            $_SESSION['keyword_exists'] = "no";
        }
    }
    if(isset($_REQUEST['limitstart']) && $_REQUEST['limitstart'] > 0){
        if (!empty($search)) {
            if(isset($_SESSION['keyword_exists']) && $_SESSION['keyword_exists'] === "yes"){
                //intentionally left blank?
            }else{
                $limitstart = "0";
                $_SESSION['keyword_exists'] = "yes";
                $_SESSION['old_keyword'] = $search;
            }
        }
    }else{
            $limitstart = "0";
    }

I'm not entirely sure what this code does, as I'm fairly new to PHP and webdev.  The one comment is mine.  Is there any way to clean this up so that the next guy to see this is less confused than I am?


texts:
I have made an effect that has the h1 move and then reveals p using .addClass, .removeClass and CSS3 transition. It works perfectly but I think I am repeating too much of the code and I think there may be a way to write it better. I need postShow and postHide to be different because I need setTimeout to be in postShow for timing. Please review the code below and give me any pointers.

jQuery(document).ready(function($){

    var post          = $('div.post');

    var postShow = function(item) {
            $(item).closest('a').find('img.postimg').addClass('imggrow');
            $(item).closest('a').find('h1').addClass('bannerhover');
            setTimeout(function(){
                $(item).closest('a').find('p.excerpt').addClass('phover');
            },500);
        };

    var postHide = function(item) {
            $(item).closest('a').find('img.postimg').removeClass('imggrow');
            $(item).closest('a').find('h1').removeClass('bannerhover');
            $(item).closest('a').find('p.excerpt').removeClass('phover');
    };

//-----------------------------------------------------------

    if ($(window).width() > 1000) {

        post.hover(function() {
            $(this).find('a').find('p.excerpt').show(0, function() {
                postShow(this);
            });
        },function() {
            $(this).find('a').find('p.excerpt').hide(0, function() {
                postHide(this);
            });
        });

    }

//--------------------------------
});


texts: Python function that returns statistics based on copy file action

texts:
I wrote a function that returns a dictionary with statistics (memory usage, time, speed) based on another function that copies files/folders. I want to check if this is a good method or if you have any other suggestions or methods to improve it.

def get_copy_stats(funct, args):
    stats = {}
    mem_usg_bef = get_process_memory_usage("process.exe") #process of the app I am testing
    time_bef = timer()
    size = funct(*args) #calls the function that copies the file and returns the file/folder size
    time_aft = timer()
    mem_usg_aft = get_process_memory_usage("process.exe")
    stats['copy_time'] = time_aft-time_bef
    stats['copy_speed'] = size/(time_aft-time_bef)
    stats['mem_usg_bef'] = mem_usg_bef
    stats['mem_usg_aft'] = mem_usg_aft
    return stats

Example on how to call it:

get_copy_stats(copy_files,("C:\Users\me\Desktop\Source","C:\Users\me\Desktop\Dest"))


texts:
For answering this question of stackoverflow I have written the code
https://stackoverflow.com/questions/12033188/how-would-you-implement-your-own-reader-writer-lock-in-c11

Can someone review it - so that I can understand the possible problems in the code.

#include <condition_variable>
#include <iostream>
#include <shared_mutex>
#include <thread>
#include <unistd.h>
#define NR_THREADS 10
#include <mutex>

class MySharedLock {
 public:
  void read_lock() {
    std::unique_lock<std::mutex> lk(rw_mutex);
    std::cout << "\nReader Lock Writers are  " << writers << std::flush;
    if (writers != 0) {
      rw_cv.wait(lk, [this]() { return (this->writers == 0); });
    }
    readers++;
    lk.unlock();
  }

  void write_lock() {
    std::unique_lock<std::mutex> lk(rw_mutex);

    std::cout << "\nWriter Lock Writers are  " << writers << " Readers are "
              << readers << std::flush;
    if (readers == 0 && writers == 0) {
      std::cout << "\nWriter Lock Writers are  " << writers << std::flush;
    } else {
      rw_cv.wait(
          lk, [this]() { return (this->writers == 0 && this->readers == 0); });
    }
    writers++;
    lk.unlock();

  }

  void write_unlock() {
    std::lock_guard<std::mutex> lk(rw_mutex);
    writers--;
    rw_cv.notify_all();
  }

  void read_unlock() {
    std::lock_guard<std::mutex> lk(rw_mutex);
    if (readers == 1) {  // I am the last one.
      rw_cv.notify_all();
    }
    readers--;
  }

  explicit MySharedLock() {}

 private:
  std::mutex rw_mutex;
  std::condition_variable rw_cv;
  uintmax_t readers = {0}, writers = {0};
};


texts: Use predefined vs. custom enums to return appropriate message from service layer

texts:
In my project I used N Layer Architecture.

In the service layer I return  an enum  for each action, for example for Add action I have an enum like this :

  public enum AddStatus
{
    AddSuccessful,
    Faild,
    Exists
}

And for Edit I have this :

    public enum EditStatus
{
    Successful,
    Faild,
    NotFound,
    Exists
}

But sometimes I need a custom enum like this one :

    public enum AddAssetFunctionStatus
{
    AddSuccessful,
    Faild,
    Exists,
    ValueIsLess,
    ItIsNotStatistical
}

and with custom enum I can show the appropriate message to the end user.

Another way I use, which I think is good, is to pass an out string param to each action, like :

   AddStatus Add(AddAccessDeviceViewModel accessDeviceViewModel,out string message);

And in the controller I have :

 switch (result)
        {
            case AddStatus.AddSuccessful:
                _uow.SaveChanges();
                this.AddNotification(Messages.SaveSuccessfull, NotificationType.Success);
                return RedirectToAction(MVC.Admin.AccessDevice.Index());
            case AddStatus.Faild:
                this.AddNotification(Messages.SaveFailed, NotificationType.Warning);
                break;
            case AddStatus.Exists:
                this.AddNotification(Messages.DataExists, NotificationType.Info);
                break;

        }

Which one is better?

Use custom enum for each action that I need.
pass an out param to the action that I need.


texts:
I have this function:

int sort(book *data, int books, char mode, char sortBy) {

  int i, j;
  book aux;
  aux.cat = malloc(sizeof *(aux.cat));

  if(sortBy == 'n') {
    for(i = 0; i < books; i++) {
      for(j = i; j < books; j++) {
        if(mode == 'a') {
          if(strcmp((data + i)->fname, (data + j)->fname) > 0) {
            aux = *(data + i);
            *(data + i) = *(data + j);
            *(data + j) = aux;
          }
        }
        else {
          if(strcmp((data + i)->fname, (data + j)->fname) < 0) {
            aux = *(data + i);
            *(data + i) = *(data + j);
            *(data + j) = aux;
          }
        }
      }
    }
  }
  else {
    for(i = 0; i < books; i++) {
      for(j = i; j < books; j++) {
        if(mode == 'a') {
          if(strcmp((data + i)->categ, "Fictiune") == 0) {
            if(((data + i)->cat)->price > ((data + j)->cat)->price) {
              aux = *(data + i);
              *(data + i) = *(data + j);
              *(data + j) = aux;
            }
          }
        }
        else {
          if(strcmp((data + i)->categ, "Fictiune") == 0) {
            if(((data + i)->cat)->price < ((data + j)->cat)->price) {
              aux = *(data + i);
              *(data + i) = *(data + j);
              *(data + j) = aux;
            }
          }
        }
      }
    }
  }

  free(aux.cat);

  return 0;
}

I need to sort the data array in two modes: ascending and descending, and by two criteria: name and price.

The question is: is there a way to write another, more compact function that will do the same thing?

And, what do you think about line 5 (aux.cat = malloc(sizeof *(aux.cat));)? Is it a right way to initialize the cat pointer?

These are the structures:

typedef struct {
  int price, edition;
  char favCharacter[SMAX];
} category;

typedef struct {
  char title[SMAX], fname[SMAX], lname[SMAX], categ[SMAX];
  category *cat;
} book;


texts:
I would like to improve everything that can be improved. I don't understand regex a lot and what could be wrong. The main improve that I am looking for is related with errors. I want make the code robust to deal well with all kinds of errors. I could try to run in production and wait to see the errors, but I can't. At my company, I need to try to imagine all possible scenarios, good or bad.

Codepen

'use strict';

var sum = function(text, regex) {

  var match;
  var regex = regex || /(\d+)/g;

  var result = []
  while (match = regex.exec(text)) {
    result.push(match[1]);
  }

  return result.reduce(function(prev, curr) {
    return parseInt(prev) + parseInt(curr);
  }, 0);
};

console.log(sum('1 12 40'));
console.log(sum('10 12 40'));
console.log(sum('1 12 510'));
console.log(sum('LLLLLLLL'));
console.log(sum('10 1'));


texts:
This is working as expected, except in the speed area + I need to make it more readable and shorter if possible, I probably have lot's of things I don't need :).

Edit it is working now

charset = dict(opening='{[(<',\
    closing='}])>',\
    string = ('"', "'"),\
    comment=(('<!--', '-->'), ('"""', '"""'), ('#', '\n')))

allowed = ''.join([x[0][0] + x[1][0] for x in charset['comment']])
allowed += ''.join(charset['string'])
allowed += charset['opening']
allowed += charset['closing']

def brace_check(text):
    o = []
    c = []
    notr = []
    found = []
    busy = False
    last_pos = None
    for i in xrange(len(text)):
        ch = text[i]
        if not busy:
            cont = True
            for comment in charset['comment']:
                if ch == comment[0][0]:
                    como = text[i:len(comment[0])]
                    if como == comment[0]:
                        busy = comment[1]
                        if ch in charset['opening']:
                            last_pos = i
                        cont = False
                        break
            if cont:
                if ch in charset['string']:
                    busy = ch
                elif ch in charset['opening']:
                    o.append((ch, i))
                elif  ch in charset['closing']:
                    c.append((ch, i))
        else:
            if ch == busy[0]:
                if len(busy) == 1:
                    comc = ch
                else:
                    comc = text[i:i + len(busy)]
                if comc == busy:
                    if last_pos is not None:
                        if busy[-1] in charset['closing']:
                            found.append((last_pos, i))
                        last_pos = None
                        text = text[:i] + '\n' * len(comc) +\
                            text[i + len(comc):]
                    busy = not busy
            elif busy in charset['string']:
                if ch == '\n':
                    busy = not busy
    for t, e in reversed(o):
        try:
            n = next((b, v) for b, v in c\
                if b == charset['closing'][\
                    charset['opening'].find(t)] and v > e)
            c.remove(n)
            n = n[1]
            if found != []:
                if e < found[-1][0] and n > found[-1][0] and n < found[-1][1]\
                or e < found[-1][1] and n > found[-1][1] and e > found[-1][0]:
                    found.append((n, False))
                    n = False
        except StopIteration:
            n = False
        found.append((e, n))
    for t, e in c:
        found.append((e, False))
    return found


texts:
This is a question about best practices. I have a project I am building and I have the following base Exception class:

Namespace Project;
class Exception extends \Exception{

    //=============== BASE EXCEPTIONS 0 - 1000 ===============//
    /**
     * placeholder for unknown exeptions - the default type
     * @var number
     */
    const UNKNOWN_ERROR                 = 0;

    //===================== GENERAL =======================//

    const NOT_YET_IMPLIMENTED           = 1001;
    const NON_UNIQUE_EXCEPTION          = 1002;

    /**
     *
     * @param string $message
     * @param number $code
     * @param \Exception $previous
     */
    public function __construct( $message="", $code = 0, \Exception $previous = null ){

        if( $previous && $previous->getCode() == $code ){
            //we do some appending we don't wan't to re-append when re-throwing with the same code
            $message = $previous->getMessage();
        }else{
            $message = $this->getCustomMessage($code, $message);
        }
        parent::__construct($message, $code, $previous);
    }

    /**
     * Convert the __CLASS__::* constants into a basic error message and add
     * the extra bit for some more granularity
     * @param int $code
     * @param string $extra
     * @return string
     */
    public function getCustomMessage( $code, $extra ){
        $extra = trim( $extra );
        //get an array of class constants
        $ReflectionObj = new \ReflectionObject( $this );
        $constants = $ReflectionObj->getConstants();
        //find the constant by value ( values must be unique )
        $message = array_search($code, $constants);
        //format the message
        $message = ucwords( strtolower( str_replace("_", " ", $message)));
        $message .=  ( $extra == '' ) ? '' : ': '.$extra  ;
        return $message;
    }

}

This all works as desired and allows me to use the error constants as the message, such as:

 throw new Exception();
 throw new Exception('', Exception::UNKNOWN_ERROR);
 throw new Exception('I know what this error is', Exception::UNKNOWN_ERROR);

Which for the $e->message is:

- 'Unkown Error';
- 'Unkown Error';
- 'Unkown Error: I know what this error is';

Etc...

What I would like to do is by employing the magical power of eval (with the appropriate safeguards of course):

eval( "
    namespace Project\Exception;
    class $classname extends \Project\Exception{}
");

Where $classname would also be the error constant.  So that I could essentially throw exceptions with an appropriate class for each without having to actually create the minimalistic class for each one.

An example would be:

try{
    $error = Exception::UNKNOWN_ERROR; // I know this is a number but for example sake we will say it equates to 'UNKNOWN_ERROR'
    throw new $error;
}catch( \Project\Exception\UNKNOWN_ERROR $e ){

}

Thus I would be able to catch the errors by checking the class names, not the error codes, while still maintaining a small code-base for the exception handler (I plan to have a lot of exceptions).  My fear is that when extending exceptions I may lose track of the error numbers and may have some exception classes with conflicting error numbers, which I want to be unique for the whole project.  So by employing this method, I have only the one main class to store my constants in but still get the benefits of having many exception classes.

Here is a little update on a new test I just ran.  It seems that it is quite possible to throw a dynamic exception from the controller of the parent exception.  This is pretty fantastic. To achieve this, a few special steps must be taken but nothing to radical.


texts: Expanding a map into an infinite sequence

texts:
I have a map that I want to 'expand' into an infinite sequence in the following manner:

{0 'zero 3 'three 10 'ten}
=>
('zero 'zero 'zero 'three 'three 'three 'three 'three 'three 'three 'ten 'ten 'ten ...)

The indexes of the map indicating the index of the sequence where the value should change.

The following code works, but it does not please me.  Can this be written in a smarter way?

(defn expand-map
  [m]
  (letfn [(em
           [last-value indexes]
           (let [value (m (first indexes))]
                (if value
                  (lazy-seq (cons value (em value (rest indexes))))
                  (lazy-seq (cons last-value (em last-value (rest indexes)))))))]
    (em 'zero (iterate inc 0))))

(take 20 (expand-map {0 'zero 3 'three 10 'ten}))


texts:
I have implemented the following code:

class A
{
    abstract void f1(Object obj, Object data);
}

class A1:A
{
    void f1(Object obj, Object data)
    {
        m1(obj,data);
    }

    void m1(Object obj, Object data)
    {
    }
}

class A2:A
{
    void f1(Object obj, Object data)
    {
        m2(obj, data);
    }
    void m2(Object obj, Object data)
    {
    }
}

static class Factory
{
    public static A GetInstance(int i)
    {
        if (i == 1)
            return new A1();
        else if (i == 2)
            return new A2();
        else
            return null;
    }
}

Methods are being called from some other part of the application, as following:

var a = Factory.GetInstance(1);
a.f1(obj, data);

In the above code, the abstract method f1() has two parameters obj and data. While I reviewed the code, I found the parameter data can be determined from the first parameter obj itself. The area of the application from where the method f1() is being called, there the Libraries for getting data are not available. So I refactored the code further as following in order to send one parameter obj. Following is the implementation:

class A
{
    public Object data { get; set; }
    abstract void f1(Object obj);
}

class A1:A
{
    void f1(Object obj)
    {
        m1(obj,data);
    }

    void m1(Object obj, Object data)
    {
    }
}

class A2:A
{
    void f1(Object obj)
    {
        m2(obj, data);
    }
    void m2(Object obj, Object data)
    {
    }
}

static class Factory
{
    public static A GetInstance(int i)
    {
        if (i == 1)
            return new A1();
        else if (i == 2)
            return new A2();
        else
            return null;
    }
}

Now, I am calling the method as following:

var a = Factory.GetInstance(1);
a.data = GetData();
a.f1(obj);

Please let me know whether or not the refactoring is correct. Also, please suggest some ways for better refactoring.


texts:
I've done a test for a job (which I failed) and I'd like to know in which ways my code could've been better.

Here are the questions and my answers, it's not very long.

  1) Make a program that checks if a string has balanced parentheses or
  brackets.

  Braces: (), [], <>
  For every closing brace, there must've been an opening, and for every open there must be a closure
  return 1 if it's balanced, or 0 if it isn't

My code:

const verify = (string) => {

    // Array of the type of braces
    var braces = ["(", ")", "[", "]", "<", ">"];
    // Array half the length of braces Array
    var balanced = Array.apply(null, {length: braces.length/2}).map(function() { return 0; });

    for(let i = 0; i < string.length; ++i) {
        let char = string[i], braceIndex = braces.indexOf(char);

        if ( braceIndex == -1 ) {
            // If current char is not any type of brace, continue.
            continue;
        }

        // Get the index of the brace found halved and floored
        let braceBalancingIndex = braceIndex / 2, braceFloor = Math.floor( braceBalancingIndex );

        // If the halved index is equal to the index, then it must be an opening, else it must be a closing
        if (braceBalancingIndex == braceFloor) {
            balanced[braceFloor]++;
        }
        else {
            balanced[braceFloor]--;
        }

        // If at any type being, the balance is negative, there was a closing without opening
        for(let j = 0; j < balanced.length; ++j) {
            if (balanced[j] < 0) return 0;
        }

    }

    // If at the end the string is not balanced, there where more openings than closings
    for(let i = 0; i < balanced.length; ++i) {
        if (balanced[i] != 0) return 0;
    }

    return 1;
}


texts:
I am working on a project right now, where we need to search different APIs, then clean & persists data to database and finally pushing to Elasticsearch.

The high level code looks like this:

class BaseParser(object):

    def __init__(self, source):
        self.url = source.url
        self.api_key = source.api_key

    def _prepare_auth_header(self):
        headers = {
        "Authorization": "Basic {}".format(self.api_key)
        }
        return headers

    def get_response(self):
        raise NotImplementedError()

class UnitedexchangeParser(BaseParser):

    def get_response(self):
        headers = self._prepare_auth_header()
        response = requests.get(self.url, headers=headers)
        return response.json()

class DubaiParser(BaseParser):

    def get_response(self):
        headers = self._prepare_auth_header()
        response = requests.get(self.url, headers=headers)
        return response.json()["data"]

class ParserFactory(object):

    def parse(self, source):
        if source.name == "Unitedexchange":
            parser = Unitedexchange(source)

        elif source.name == "Dubai":
            parser = DubaiParser(source)

        return parser.get_response()

The application is working fine, but we are adding more and more new sources which leads to change ParserFactory with same block of code.

How can I improve the layout and design such a way so we do minimal change for adding new parser? Performance is also an issue, and right now we are loading lots of individual classes which basically doing the same thing. It would be great if you can give some hint on that, too.


texts:
I'm trying to create a custom div scroller.  I got it working, but it's still a little rough around the edges. Please take a look..

DEMO

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html>

    <title></title>

    <form id="form1" runat="server">

    </form>


texts: Handling exceptions and executing code if one was found

texts:
I have this code:

try
{
    Console.WriteLine("Input number {0}", i + 1);
    int number = ReadNumber(start, end);
}
catch (Exception ex)
{
    if (ex is ArgumentException)
    {
        Console.WriteLine("The input number wasn't in the alowed range. Please try again.");
    }
    else if (ex is FormatException)
    {
        Console.WriteLine("The input isn't an integer number. Please try again.");
    }
    else
    {
        Console.WriteLine("An unknown error occured. Please try again.");
    }

    i--;
}

I am wondering if there is a better way to do this - catch all exceptions and handle them and then, if any exception was caught, I want to reduce i by 1.


texts: ConvertAll Methods Implementation for Multidimensional Array in C# - follow-up

texts:
This is a follow-up question for ConvertAll Methods Implementation for Multidimensional Array in C#. Thanks to aepot's answer and Olivier's answer. In order to match the usage of the build-in API Array.ConvertAll, the input /output array types of the implemented methods below are similar to [], [,], [,,] and etc. style.
The experimental implementation
The experimental implementation is as below.
public static TOutput[,] ConvertAll<TInput, TOutput>(TInput[,] array, Converter<TInput, TOutput> converter)
    where TInput : unmanaged
    where TOutput : unmanaged
{
    return (TOutput[,])ConvertArray(array, converter);
}

public static TOutput[,,] ConvertAll<TInput, TOutput>(TInput[,,] array, Converter<TInput, TOutput> converter)
    where TInput : unmanaged
    where TOutput : unmanaged
{
    return (TOutput[,,])ConvertArray(array, converter);
}

public static TOutput[,,,] ConvertAll<TInput, TOutput>(TInput[,,,] array, Converter<TInput, TOutput> converter)
    where TInput : unmanaged
    where TOutput : unmanaged
{
    return (TOutput[,,,])ConvertArray(array, converter);
}

public static TOutput[,,,,] ConvertAll<TInput, TOutput>(TInput[,,,,] array, Converter<TInput, TOutput> converter)
    where TInput : unmanaged
    where TOutput : unmanaged
{
    return (TOutput[,,,,])ConvertArray(array, converter);
}

public static TOutput[,,,,,] ConvertAll<TInput, TOutput>(TInput[,,,,,] array, Converter<TInput, TOutput> converter)
    where TInput : unmanaged
    where TOutput : unmanaged
{
    return (TOutput[,,,,,])ConvertArray(array, converter);
}

public static TOutput[,,,,,,] ConvertAll<TInput, TOutput>(TInput[,,,,,,] array, Converter<TInput, TOutput> converter)
    where TInput : unmanaged
    where TOutput : unmanaged
{
    return (TOutput[,,,,,,])ConvertArray(array, converter);
}

public static TOutput[,,,,,,,] ConvertAll<TInput, TOutput>(TInput[,,,,,,,] array, Converter<TInput, TOutput> converter)
    where TInput : unmanaged
    where TOutput : unmanaged
{
    return (TOutput[,,,,,,,])ConvertArray(array, converter);
}

public static TOutput[,,,,,,,,] ConvertAll<TInput, TOutput>(TInput[,,,,,,,,] array, Converter<TInput, TOutput> converter)
    where TInput : unmanaged
    where TOutput : unmanaged
{
    return (TOutput[,,,,,,,,])ConvertArray(array, converter);
}

public static TOutput[,,,,,,,,,] ConvertAll<TInput, TOutput>(TInput[,,,,,,,,,] array, Converter<TInput, TOutput> converter)
    where TInput : unmanaged
    where TOutput : unmanaged
{
    return (TOutput[,,,,,,,,,])ConvertArray(array, converter);
}

static Array ConvertArray<T, TResult>(Array array, Converter<T, TResult> converter)
    where T : unmanaged
    where TResult : unmanaged
{
    if (array is null)
    {
        throw new ArgumentNullException(nameof(array));
    }

    if (converter is null)
    {
        throw new ArgumentNullException(nameof(converter));
    }

    long[] dimensions = new long[array.Rank];
    for (int i = 0; i < array.Rank; i++)
        dimensions[i] = array.GetLongLength(i);

    Array result = Array.CreateInstance(typeof(TResult), dimensions);
    TResult[] tmp = new TResult[1];
    int offset = 0;
    int itemSize = System.Runtime.InteropServices.Marshal.SizeOf(typeof(TResult));
    foreach (T item in array)
    {
        tmp[0] = converter(item);
        Buffer.BlockCopy(tmp, 0, result, offset * itemSize, itemSize);
        offset++;
    }
    return result;
}

All suggestions are welcome.
The summary information:

Which question it is a follow-up to?
ConvertAll Methods Implementation for Multidimensional Array in C#

What changes has been made in the code since last question?
Trying to perform higher dimensional overloadings and exception handling based on aepot's answer.

Why a new review is being asked for?
If there is any possible improvement or any other potential defect, please let me know.


texts:
I have only recently started learning python and the below is my attempt to create an 'interest rate' object which, given one of several types of interest/discount rate, gives the user access to all of the other corresponding rates that are equivalent to this. This looks as follows:

import math

class InterestRate:
    def __init__(self, effectiveInterestRate=0, nominalInterestRate=0, effectiveDiscountRate=0, nominalDiscountRate=0, discountFactor=0, forceOfInterest=0, paymentsPerPeriod=1):

        self.effectiveInterestRate = effectiveInterestRate
        self.nominalInterestRate = nominalInterestRate
        self.effectiveDiscountRate = effectiveDiscountRate
        self.nominalDiscountRate = nominalDiscountRate
        self.discountFactor = discountFactor
        self.forceOfInterest = forceOfInterest
        self.paymentsPerPeriod = paymentsPerPeriod

        numberOfRatesProvided = 0
        for attr, value in vars(self).items():
            if value != 0 and attr != 'paymentsPerPeriod':
                numberOfRatesProvided += 1
                rateGiven = attr
        if numberOfRatesProvided != 1:
            raise Exception("Incorrect number of inputs passed to InterestRate object")

        if rateGiven == 'nominalInterestRate': self.effectiveInterestRate = (nominalInterestRate/paymentsPerPeriod + 1)**paymentsPerPeriod - 1
        elif rateGiven == 'effectiveDiscountRate': self.effectiveInterestRate = effectiveDiscountRate / (1 - effectiveDiscountRate)
        elif rateGiven == 'nominalDiscountRate': self.effectiveInterestRate = (1 - nominalDiscountRate/paymentsPerPeriod)**-paymentsPerPeriod - 1
        elif rateGiven == 'discountFactor': self.effectiveInterestRate = 1/discountFactor - 1
        elif rateGiven == 'forceOfInterest': self.effectiveInterestRate = math.exp(forceOfInterest) - 1

        self.nominalInterestRate = self.paymentsPerPeriod*((1+self.effectiveInterestRate)**(1/self.paymentsPerPeriod) - 1)
        self.effectiveDiscountRate = self.effectiveInterestRate/(1+self.effectiveInterestRate)
        self.nominalDiscountRate = self.paymentsPerPeriod*(1 - (1 + self.effectiveInterestRate)**(-1/self.paymentsPerPeriod))
        self.discountFactor = 1 / (1 + self.effectiveInterestRate)
        self.forceOfInterest = math.log(1 + self.effectiveInterestRate)

    def outputInterestRateData(self):
        print("\n  ----------------------------------------------------")
        print("                   Interest Rate Data                 ")
        print("  ----------------------------------------------------")
        print("   Payments per Period:        ", self.paymentsPerPeriod)
        print("   Effective Interest Rate:    ", self.effectiveInterestRate)
        print("   Effective Discount Rate:    ", self.effectiveDiscountRate)
        print("   Nominal Interest Rate:      ", self.nominalInterestRate)
        print("   Nominal Discount Rate:      ", self.nominalDiscountRate)
        print("   Discount Factor:            ", self.discountFactor)
        print("   Force Of Interest:          ", self.forceOfInterest)
        print("  ----------------------------------------------------")

    def shiftedPaymentPV(paymentAmmount, periodsShifted):
        return paymentAmmount*(1 + self.effectiveInterestRate)**periodsShifted

Assuming that it is clear enough what I have attempted to do here, can anyone offer some constructive criticism on my first attempt at a python class module?


texts:
Here is my first attempt to create an simple drop down menu with CSS and Java Script.
This is the HTML code.

    <button>Menu 1</button>

        Option 1
        Option 2

    <button>Menu 2</button>

        Option 1

    <button>Menu 3</button>

        Option 1
        Option 2
        Option 3

CSS

div.dropdown {
    display: inline-block;
}
div.dropdown button {
    background-color:#fff;
    border:0px;
    color:#424242;
    cursor:pointer;
    padding:5px 0 5px 0;
}
div.menu1, div.menu2 {
    margin:0 0 0 20px;
}
div.menu1 button {
    border-bottom:2px solid #00BCD4;
}
div.menu2 button {
    border-bottom:2px solid #4CAF50;
}
div.menu3 button {
    border-bottom:2px solid #9FA8DA;
}
div.dropdown-content {
    display: none;
}
div.dropdown-content-active {
    margin-top:5px;
    display: block;
    background-color: #fff;
    border:1px solid #EEEEEE;
    box-shadow: 0px 0px 2px 1px #dcdcdc;
    position:absolute;
    border-radius:3px;
    z-index: 10;
}
div.dropdown-content a {
    display: block;
    width:100%;
    text-decoration: none;
    color:#3d3d3d;
    padding:4px;
    box-sizing: border-box;
    font-size:0.9em;
}
div.dropdown-content a:hover {
    background-color: #f0f0f0;
}

JavsScript

document.addEventListener('DOMContentLoaded', function() {
    [].forEach.call(document.querySelectorAll('div.dropdown button'), function(dropdown) {
        dropdown.addEventListener('click', function() {

            if(getComputedStyle(this.nextSibling).display === 'none') {

                [].forEach.call(document.querySelectorAll('div.dropdown div.dropdown-content-active'), function(dropdown_active) {
                    dropdown_active.classList.remove('dropdown-content-active');
                });

                this.nextSibling.classList.add('dropdown-content-active');
            } else {
                this.nextSibling.classList.remove('dropdown-content-active');
           }

        });
    });
});

The JavaScript is really simple but I am not sure that this is the best way I can achieve this. Would appreciate your comments.


texts:
I'm creating a dictionary app using Win32 API. I stored the word meaning in a file called dictionary.dic in the following format:

Word  Meaning
A     The first letter
B     The second letter
... and so on

As my window is created, I load the dictionary file into the std::map object using this code:
std::map<wstring, wstring> dict;
...
std::wifstream stream(L"dictionary.dic");
std::wstring temp, fileContent = L"";
while (std::getline(stream, temp)) {
    fileContent += temp;
    fileContent.push_back(L'\n');
}
std::vector<wstring> lines = split(fileContent, L'\n');
for (std::wstring line : lines) {
    std::vector<wstring> word = split(line, L'\t');
    dict.insert(dict.end(), make_pair(word[0], word[1]));
}

And when the user search the word, I'm using this code to display the meaning:
std::wstring enteredWord;
map<wstring, wstring>::iterator mi;
mi = dict.find(toLower(enteredWord));
if (mi != dict.end()) {
    //display meaning
}
else {
    //word not found
}

I used these functions to convert text to lowercase and split text:
I'm using this function to split the text:
std::vector<std::wstring> &split(const std::wstring &s, WCHAR delim, std::vector<std::wstring> &elems) {
    std::wstringstream ss(s);
    std::wstring item;
    while (std::getline(ss, item, delim)) {
        elems.push_back(item);
    }
    return elems;
}

std::vector<std::wstring> split(const std::wstring &s, WCHAR delim) {
    std::vector<std::wstring> elems;
    split(s, delim, elems);
    return elems;
}

std::wstring toLower(std::wstring val) {
    std::wstring temp = val;
    std::transform(temp.begin(), temp.end(), temp.begin(), tolower);
    return temp;
}

Is there a more efficient way to create a dictionary in Win32 / C++?


texts: Shortest path algorithm in 0-1-unoriented graph

texts:
I have an unoriented graph with n vertices and m edges, 1 <= n, m <= 100000. All edges have 0 or 1 weights (two vertices are connected even if the corresponding edge has 0 weight). Vertices indexing starts with 1. I need to find length of the shortest path from vertex A to vertex B.

Input data example:

4 5 1 3
1 2 1
2 3 0
3 4 1
4 1 1
1 3 0

From the first line I get: n = 4, m = 5, A = 1, B = 3. Then I get the elements of the adjacency list. The first number in each line is from-vertex, the second - to-vertex, and the last is the weight of current edge. 0 or 1.

In the output I must receive the length of the shortest path or -1 if the path doesn't exist.

Here is my solution using Dijkstra's algorithm:

#include <iostream>
...

using std::cout;
using std::cin;
using std::endl;
using std::vector;
using std::pair;
using std::string;
using std::map;

size_t INF = 200000;

int main() {
    size_t nVert,
        mEdges,
        start,
        end;
    cin >> nVert >> mEdges >> start >> end;
    vector<vector<pair<size_t, size_t>>> ajList(mEdges);
    size_t edStart, edEnd, weight;
    for (size_t vert = 0; vert < mEdges; ++vert) {
        cin >> edStart >> edEnd >> weight;
        ajList.at(edStart - 1).push_back(pair<size_t, size_t>(edEnd, weight));
    }

    vector<size_t> minLen(nVert, INF),
        pred(nVert);
    minLen[start - 1] = 0;
    vector<char> used(nVert);
    for (size_t vert = 0; vert < nVert; ++vert) {
        size_t currentVert = -1;
        for (size_t j = 0; j < nVert; ++j) {
            if (!used[j] && (currentVert == -1 || minLen[j] < minLen[currentVert]))
                currentVert = j;
        }
        if (minLen[currentVert] == INF)
            break;
        used[currentVert] = true;

        for (size_t j = 0; j < ajList[currentVert].size(); ++j) {
            int to = ajList[currentVert][j].first - 1,
                len = ajList[currentVert][j].second;
            if (minLen[currentVert] + len < minLen[to]) {
                minLen[to] = minLen[currentVert] + len;
                pred[to] = currentVert;
            }
        }
    }

    if (minLen[end - 1] == INF)
        cout << -1;
    else
        cout << minLen[end - 1];
    return 0;
}

I know that Dijkstra is the fastest algorithm for searching the shortest path from one vertex to all other vertices, but in my case it takes too long.

How can I optimize this code to make it working faster (this is the main problem)?
If you see some bugs in this snippet, please, let me know.


texts: Find the next multiple of N that is a perfect square number

texts:
Given a number \$t\$, (\$1 \leq t \leq 1000\$) that represent
  testcases and \$t\$ numbers \$n\$ (\$1 \leq n \leq 10^9\$). Show the
  next multiple of \$n\$ that is a perfect square number.

  Example of input:

5
5 9 10 12 13

  Example of output:

Case #1: 25
Case #2: 9
Case #3: 100
Case #4: 36
Case #5: 169

My solution iterates over all the next perfect squares of \$n\$ (using this formula \$ \left(\lfloor \sqrt{x} \rfloor + 1\right) ^ 2 \$ until it's a multiple of \$n\$.

#include <stdio.h>
#include <string.h>
#include <math.h>

unsigned long long myPow(unsigned long long x){
    return x*x;
}

int main(){

    unsigned int j;

    unsigned int t;
    scanf("%u",&t);

    for(j = 1; j <= t; j++){
        unsigned long long n;
        scanf("%llu",&n);
        double sqrtn = sqrt(n);
        if(sqrtn == (unsigned long long) sqrtn) //test if N is a perfect square
            printf("Case #%d: %llu\n",j,n);
        else{
            unsigned long long i = n;
            while((i = myPow(floor(sqrt(i))+1)) % n != 0);//find the next perfect square multipe of n
            printf("Case #%d: %llu\n",j,i);
        }
    }
}

This solution encounters "Time limit exceeded". Is there a faster way of finding the solution?


texts:
I have two 2D arrays of doubles a and b. Both have two rows and different numbers of columns.

a [[ 1,2,3][4,5,6]]

The list b represents a number of bins of numbers and the list is a list of numbers I'm trying to sort into these bins.

I need to go through each of the numbers in b to look for its corresponding bin. Here's the code I have, which works perfectly but I need to optimize it. Any ideas?

        int k = 0;
        for (int i = 0; i < a.GetLength(1); i++) {
            for (int j = 0; j < b.GetLength(1); j++) {

                //if fragment falls in bin, add it to the new object
                if (a[0, i] <= (b[0, j] + binSize / 2) &&
                    a[0, i] > (b[0, j] - binSize / 2)) {

                    c[0, k] = a[0, i];
                    c[0, k] = b[0, j];

                    c[1, k] = a[1, i];
                    c[1, k] = b[1, j];
                    k++;

                }
                if (k >= a.GetLength(1)) {
                    break;
                }
            }
        }


texts:
I have script for get three values (minimal numbers) from array :

$(document).ready(function(){
    var _array = [1,2,3,4];
    var save = 0;
    var _new_array = [];
    var nearDistance = [];
    $.each(new Array(3),function(n){
        if (_new_array.length < 1){
            save = Math.min.apply(Math,_array);
            _new_array = jQuery.grep(_array, function(value) {
              return value != save;
            });
            nearDistance.push(save);
        } else {
            save = Math.min.apply(Math,_new_array);
            _new_array = jQuery.grep(_new_array, function(value) {
              return value != save;
            });
            nearDistance.push(save);
        }
    });
    console.log(nearDistance);
});

This script works to get 3 minimal values,

scenario script : Do each 3 times, first each get minimal value (save) from first array (_array), delete minimal value from the first array (_array) and then put resudial values to new array (_new_array), minimal value push to nearDistance, next each get minimal value from new array.

I think my script too less performance if I want to get more values from an array, what do you think about my script?


texts:
The task is to print the following series

1 2 1 3 2 5 3 7...

The elements at odd positions are Fibonacci series terms and the elements at even positions are prime numbers. Given an input 'n' the element at the nth position in the series has to be printed.
eg. when n = 4, output will be 3. n = 7, output will be 3

I've tried to solve the problem by returning nth prime number or nth fibonacci term. I am looking for any improvements that can be  made to the code to optimize it further.

#include <bits/stdc++.h>
using namespace std;

int retPrime(int n)
{
    //Using sieve of Eratosthenes to generate primes
    int size = n + 1;
    bool Primes[100];
    int count = 0;
    memset(Primes, true, sizeof(Primes));
    for (int i = 2; i<sqrt(100); ++i)
    {
        if (Primes[i] == true)
        {
            for (int j = i * 2; j <= 100; j = j + i)
            {
                Primes[j] = false;
            }
        }
    }
    int primeIndex=0;
    int i = 2;
    while (count != n)
    {
        if (Primes[i] == true)
        {
            count++;
            primeIndex = i;
        }
        ++i;
    }
    return primeIndex;
}

int retFib(int n)
{
    if(n<=1){
        return n;
    }
    return retFib(n-1)+retFib(n-2);
}
int main()
{
    int n;
    cin >> n;
    if(n%2==0)
        cout << retPrime(n/2)<<" ";
    else
        cout << retFib((n/2)+1)<<" ";
    return 0;
}


texts: Qt foreach-like alternative to iterate over value AND key of an associative container

texts:
The Qt documentation recommend an iterator-based solution to iterate over an associative container like QMap and QHash, and I always wondered if there really isn't a (nice) solution using a foreach loop like in PHP:

foreach($container as $key => $value)

I looked into the source code of the foreach macro and extended it by a key variable. The following code is only the GCC version of the loop (it doesn't work with all compilers, see Q_FOREACH macro definition in qglobal.h for other versions).

#define foreachkv(keyvar, variable, container)                        \
for (QForeachContainer<__typeof__(container)> _container_(container); \
     !_container_.brk && _container_.i != _container_.e;              \
     __extension__  ({ ++_container_.brk; ++_container_.i; }))        \
    for (keyvar = _container_.i.key();; __extension__ ({break;}))     \
        for (variable = *_container_.i;; __extension__ ({--_container_.brk; break;}))

Now you can do the following:

QVariantHash m;
m.insert("test", 42);
m.insert("foo", true);
foreachkv(QString k, QVariant v, m)
    qDebug() << k << "=>" << v;

The output will be:

"foo" => QVariant(bool, true)
"test" => QVariant(int, 42)

Tests I've done so far:

examples from above
foreachkv works as expected with break and continue statements within the loop.

What did I do? I just added another for loop to introduce the key variable (called keyvar in the macro). Maybe I don't need this loop?


texts:
Question: Is there anything you could do in order to improve the test?

I am using Spring Framework 4, Hibernate 4, JUnit 4. All DAO unit tests inherit from TestDaoSetup class:

@ContextConfiguration(locations={
        "classpath:/config/test/spring.xml",
        "classpath:/config/test/hibernate.xml"
})
@TransactionConfiguration
@Transactional
public class TestDaoSetup {
}

One of unit tests:

@RunWith(SpringJUnit4ClassRunner.class)
public class CityDaoImplTest extends TestDaoSetup {
    @Rule
    public ExpectedException exception = ExpectedException.none();

    @Autowired
    private CityDao cityDao;

    @Autowired
    private CountryDao countryDao;

    @Test
    public void create_Created(){
        CountryEntity countryEntity = countryDao.find(1L);

        CityEntity cityEntity = new CityEntity();
        cityEntity.setName("Košice");
        cityEntity.setCountryEntity(countryEntity);

        cityDao.create(cityEntity);

        Assert.assertNotNull("Expected not null value.",cityDao.find(cityEntity.getId()));
    }

    @Test
    public void create_NoCountryAssociation_ExceptionThrown(){
        exception.expect(ConstraintViolationException.class);

        CityEntity cityEntity = new CityEntity();
        cityEntity.setName("Košice");

        cityDao.create(cityEntity);
        cityDao.flush();
    }

    @Test
    public void create_ExistingNameSameCountry_ExceptionThrown() {
        exception.expect(ConstraintViolationException.class);

        CountryEntity countryEntity = countryDao.find(1L);

        CityEntity cityEntity = new CityEntity();
        cityEntity.setName("Bratislava");
        cityEntity.setCountryEntity(countryEntity);

        cityDao.create(cityEntity);
        cityDao.flush();
    }

    @Test
    public void create_ExistingNameDifferentCountry_Created(){
        CountryEntity countryEntity = countryDao.find(2L);

        CityEntity cityEntity = new CityEntity();
        cityEntity.setName("Bratislava");
        cityEntity.setCountryEntity(countryEntity);

        cityDao.create(cityEntity);

        Assert.assertNotNull("Expected not null value.", cityDao.find(cityEntity.getId()));
    }

    @Test
    public void update_ExistingNameSameCountry_ExceptionThrown(){
        exception.expect(ConstraintViolationException.class);

        CityEntity cityEntity = cityDao.find(2L);
        cityEntity.setName("Bratislava");

        cityDao.update(cityEntity);
        cityDao.flush();
    }

    @Test
    public void update_ExistingNameDifferentCountry_Updated(){
        CityEntity cityEntity = cityDao.find(3L);
        cityEntity.setName("Bratislava");

        cityDao.update(cityEntity);

        Assert.assertEquals("Expected different value.", "Bratislava", cityDao.find(3L).getName());
    }

    @Test
    public void delete_NotUsed_Deleted() {
        CityEntity cityEntity = cityDao.find(4L);

        cityDao.delete(cityEntity);

        Assert.assertNull("Expected null value.", cityDao.find(cityEntity.getId()));
    }

    @Test
    public void delete_Used_ExceptionThrown(){
        exception.expect(ConstraintViolationException.class);

        CityEntity cityEntity = cityDao.find(1L);

        cityDao.delete(cityEntity);
        cityDao.flush();
    }
}

Question: Is there anything you could improve in the test?

EDIT:

To make test conditions more clear:

There are separated configurations, one is specifically for testing purposes.
There is database script which prepopulates the test database with test data before tests actually start.
Data are the same for each test, because there is a rollback after each test.
Test data are not prepopulated in each test class, but they are prepopulated in separate SQL file, which is executed before tests actually start.


texts:
I was trying to write a code from scratch for Chi-square test.This is the code that I had written in python using pandas.I had a doubt whether the code can produce the desired output or can be written in a more compacted way.

import pandas as pd
from scipy import chisqprob
from scipy import stats

def chi_square_of_df_cols(main_frame,column1,column2):
    grouped_data=pd.DataFrame(main_frame.groupby([column1,column2])[column1].count())
    grouped_data.columns=["count"]
    grouped_data.reset_index(inplace=True)
    pivoted_data=grouped_data.pivot(column1,column2,"count")
    pivoted_data.fillna(0,inplace=True)
    frame = pivoted_data.copy(deep="True")
    cols=pivoted_data.columns
    sum_row = {col: pivoted_data[col].sum() for col in pivoted_data}
    dof=(len(pivoted_data.columns)*len(pivoted_data))-1
    pivoted_data["Total_row"] = pivoted_data.sum(axis=1)
    grid_total=pivoted_data["Total_row"].sum(axis=0)
    for col in cols:
        for i in pivoted_data.index:
            frame.ix[i,col]= (pivoted_data.ix[i,"Total_row"])*(sum_row[col])/grid_total

    sum1=0
    for col in cols:
        for i in pivoted_data.index:
            sum1+=(pivoted_data.ix[i,col]-frame.ix[i,col])**2/frame.ix[i,col]

    p_value=chisqprob(sum1,dof)

    return p_value


texts:
For web-uploading of Cyrillic-named images, I've written the script below:

#!/usr/bin/python
# coding=utf-8

import os
import argparse
import shutil

class Error: pass
class FolderError(Error): pass

def copytranstree (src, dst):
   names = os.listdir( src )

   try:
       os.makedirs( dst )
   except WindowsError:
       pass

   errors = []

   for name in names:

       srcname = os.path.join( src, name )

       dstname = os.path.join( dst, ''.join([translit.get(x, x) for x in name.decode( input_parametres.encoding ).lower()]).encode( input_parametres.encoding ) )

       try:
           if os.path.isdir( srcname ):
               copytranstree( srcname, dstname )
           else:
               shutil.copy2( srcname, dstname )
       except (IOError, os.error), why:
           errors.append( ( srcname, dstname, str( why ) ))
       except Error, err:
           errors.extend( err.args[0] )

   try:
       shutil.copystat( src, dst )
   except WindowsError:
       pass
   except OSError, why:
       errors.extend( (src, dst, str(why) ) )
   if errors:
       raise Error( errors )

parser = argparse.ArgumentParser(description='Copy directory tree with transliterated pathnames')
parser.add_argument('-e','--encoding', help='File system encoding', default='utf-8')
parser.add_argument('-s','--src', help='Source folder name', default='./' )
parser.add_argument('-d','--dst', help='Destination folder name', default='./')

input_parametres = parser.parse_args()

translit = dict(zip(u"абвгдеёзийклмнопрстуфхьъ", "abvgdeeziyklmnoprstufh'~"))
translit.update({u'ц': 'tz', u'ч': 'ch', u'ш': 'sh', u'ы': 'yi',
                u'э': 'ye', u'ю': 'ju', u'я': 'ja', u' ': '_'})

src = os.path.abspath( input_parametres.src )
dst = os.path.abspath( input_parametres.dst )

if not os.path.exists( dst ):
   dstname = ''.join([translit.get(x, x) for x in dst.decode( input_parametres.encoding ).lower()]).encode( input_parametres.encoding ).lower()
   os.makedirs( dstname )
   dst = os.path.abspath( dstname )

if not os.path.exists( src ) or os.path.isfile( dst ):
   raise FolderError()

copytranstree( src, dst )

The script transliterates and copies a tree of files from a source folder to destination, considering encoding passed to the script (UTF for Ubuntu, CP121 for Windows).

Any ideas for common improvement of structure for Linux OS?


texts: Determine if a word can be constructed from list of subsets

texts:
The question is explained well by examples in the comments below. Also I request verifying complexity:  O( n * n!), where n is the number of words in the subsets. Review my code for optimizations, best practices etc.

/**
 * Question is better explained by examples:
 * 1. given
 *    i/p subsets  - ["un", "xy", "te", "i", "d"]
 *    and i/p string is : united should result in true.
 *    and i/p string of : union should result in false.
 *
 * 2. i/p subsets - ["tonyl", "pqr", "pqrbri",]
 *    and i/p string of : briton should be true.
 *    and i/p string of : japan should result in false.
 *
 * Complexity: O( n * n!) where n is numnber of subset words.
 *
 */
public final class StringFromSubSets {

    private StringFromSubSets() {}

    private static int getFactorial (int length) {
        int factorial = 1;
        for (int i = 1; i <= length; i++) {
            factorial = factorial * i;
        }
        return factorial;
    }

    private static void swapWithNext (List<String> subStrings, int i) {
        assert subStrings != null;
        assert i >= 0 && i < subStrings.size() - 1;

        String str = subStrings.get(i);
        subStrings.set(i, subStrings.get(i + 1));
        subStrings.set(i + 1, str);
    }

    private static String join (List<String> list) {
        assert list != null;

        final StringBuffer sb = new StringBuffer();
        for (String str : list) {
            sb.append(str);
        }
        return sb.toString();
    }

    private static Set<String> getPermutations(List<String> subStrings) {
        assert subStrings != null;

        final Set<String> set = new HashSet<String>();
        int factorial = getFactorial(subStrings.size());
        int counter = 0;

        while (counter < factorial) {
            for (int i = 0; i < subStrings.size() - 1; i++) {
                swapWithNext (subStrings, i);   // O(1)
                String joinedString = join (subStrings); // O(n)
                set.add(joinedString);
                counter++;
            }
        }
        return set;
    }

    public static boolean stringGotFromSubSets(List<String> subStrings, String wordToFind) {
        if (subStrings == null) {
            throw new NullPointerException("The substring provided is null.");
        }

        final Set<String> joinedStrings = getPermutations(subStrings);
        for (String joinedString : joinedStrings) {
            if (joinedString.contains(wordToFind)) return true;
        }

        return false;
    }

    public static void main(String[] args) {
        List<String> listOfString = new ArrayList<String>();
        listOfString.add("sachin");
        listOfString.add("tendulkar");
        listOfString.add("rahul");
        listOfString.add("dravid");
        System.out.println("Expected true, Actual " + stringGotFromSubSets(listOfString, "int"));
        System.out.println("Expected true, Actual " + stringGotFromSubSets(listOfString, "idsa"));
        System.out.println("Expected true, Actual " + stringGotFromSubSets(listOfString, "sachindravid"));

        System.out.println("Expected false, Actual " + stringGotFromSubSets(listOfString, "sehwag"));
        System.out.println("Expected false, Actual " + stringGotFromSubSets(listOfString, "ganguly"));
    }

}


texts:
This actually works nicely (we have > 2k repos) but I would really like it to start producing results right away as soon as it has any. Mostly so it seems faster than it is (by being more responsive).

   bbrepos(){
        #clone[1] is ssh using a filter made the escaping really ugly.
        #If it becomes necessary we can use a jq arg
        # get max number of repos, ceil(repos / 50), then create a page
        #sequence and curl them all
        local url=https://api.bitbucket.org/2.0/repositories/twengg
        local project=${1:+"q=project.key=\"$1\""}
        curl -snL  "$url?pagelen=0&page=1" | jq '"$(((\(.size) / 50) + 1 ))"' \
            | xargs bash -c 'eval "echo $1"' _ | xargs seq 1 | xargs -L 1 printf "?pagelen=50&page=%s&${1:-$project}\n" \
            | xargs -I {} -L 1 -P 20 -I {} bash -c 'curl -snL  "$1/$2" | jq -er .values[].links.clone[1].href' _ $url {} \ #clone[1] is ssh
            | sort -u
    }

Sample workflow:

bbsearch something | xargs -P 20 git clone

Alternatively, it might also be handy to have these other workflows:

bbsearch something other thing | xargs -P 20 git clone

cat things-to-find.txt | bbsearch | xargs -P 20 git clone

Sample payload (it's normally huge, so I stripped it down to what is needed):

{
  "pagelen": 1,
  "size": 3054,
  "values": [
    {
      "links": {
        "clone": [
          {
            "href": "https://chb0bitbucket@bitbucket.org/twengg/development-process.git",
            "name": "https"
          },
          {
            "href": "git@bitbucket.org:twengg/development-process.git",
            "name": "ssh"
          }
        ],
        "self": {
          "href": "https://api.bitbucket.org/2.0/repositories/twengg/development-process"
        }
      }
    }
  ],
  "page": 1,
  "next": "https://api.bitbucket.org/2.0/repositories/twengg?page=2"
}


texts:
I made a method that takes 2 DateTimes as a parameter, a startDate and a stopDate.

The routine should return a list of DateTime ranges by checking if the range in the parameters is above one year TimeSpan. If it is, it should separate the range into smaller ranges of one year, starting form startDate and adding a year until reaching the limit, and then adjusting the last range accordingly (as it might only contain a few months).

Can this method be made better or even recursive?

// startDate = 2016-01-01
// endDate = 2020-06-01

List<Tuple<DateTime,DateTime>> list = GetYearsBetweenDates(startDate, endDate);

//list = 2016-01-01 2016-12-31
//       2017-01-01 2017-12-31
//       2018-01-01 2018-12-31
//       2019-01-01 2019-12-31
//       2020-01-01 2020-06-01

private List<Tuple<DateTime, DateTime>> GetYearsBetweenDates(DateTime startDate, DateTime stopDate)
{
    var list = new List<Tuple<DateTime, DateTime>>();
    var oneYear = TimeSpan.FromDays(365);
    var tempStopDate = startDate + oneYear;
    var tempStartDate = startDate;
    bool first = true;

    if (stopDate - startDate < oneYear)
    {
        list.Add(new Tuple<DateTime, DateTime>(startDate, stopDate));
        return list;
    }

    while (tempStopDate != stopDate)
    {
        list.Add(new Tuple<DateTime, DateTime>(tempStartDate, tempStopDate));
        if (first)
        {
            tempStartDate += oneYear.Add(TimeSpan.FromDays(1)); // We should not have the same date twice
            first = false;
        }
        else
            tempStartDate += oneYear;

        tempStopDate += oneYear;

        if (tempStopDate > stopDate)
        {
            tempStopDate = stopDate;
            list.Add(new Tuple<DateTime, DateTime>(tempStartDate, stopDate));
        }
    }

    return list;
}


texts: JavaScript (multiple) inheritance / mixins

texts:
I'm quite new to JavaScript, and I'm trying to understand the idea behind inheritance in JavaScript. I've read a bit about it, and I don't want to mess with prototypes (which I don't yet fully understand) so, I wrote this code using the xtend module for node.js.

var xtend = require("xtend");

// Human constructor.
// Human is a base class, it can introduce itself, and knows it's age.
function createHuman(name, age) {

    function getName() {
        return name;
    }

    function getAge() {
        return age;
    }

    return {
        getName : getName,
        getAge : getAge,
    };

}

// Boy constructor
// Boy *is a* Human
// Boy can play football (but not yet)
function createBoy(name, age) {

    function playFootball() {
        console.warn("Football skills not implemented yet, but trying", "-", this.getName());
        // TODO: implement this
    }

    return xtend(createHuman(name, age), {
        playFootball: playFootball,
    })

}

// Girl constructor
// Girl *is a* Human
// Girl can sing (well, almost)
function createGirl(name, age) {

    function singASong() {
        console.warn("Singing not implemented yet, but trying", "-", this.getName());
        // TODO: implement this
    }

    return xtend(createHuman(name, age), {
        singASong: singASong,
    })

}

// Hermaphrodite constructor
// Hermaphrodite *is a* Girl **and** Hermaphrodite *is a* Boy, so we have multiple inheritance?
// Hermaphrodite can do what boys and girls can
function createHermaphrodite(name, age) {
    return xtend(createGirl(name, age), createBoy(name, age));
}

// Tests:
var boy = createBoy("John", 12);
var boy2 = createBoy("Frank", 10);
var girl = createGirl("Daisy", 7);

var herm = createHermaphrodite("Mel", 24);

console.info("Boy:  ", boy.getName(), boy.getAge());
console.info("Boy:  ", boy2.getName(), boy2.getAge());
console.info("Girl: ", girl.getName(), girl.getAge());
console.info("Hermaphrodite: ", herm.getName(), herm.getAge());

boy.playFootball();
boy2.playFootball();
girl.singASong();

herm.playFootball();
herm.singASong();

As you can see, I'm not using the usual Class approach, but instead have a kind of constructors that create objects. The inheritance is made using the xtend module, which copies properties from another objects. This - I think - also allows for multiple inheritance (see Hermaphrodite).

Questions:

Can this code be considered good practice? I always thought of JS as a more functional (than OO) language, so not trying to imitate classes, not using the new keyword and so on sounded good to me.
Is this fast / memory-efficient? I mean - there is an additional object created every time the sub-class instance is created, just to copy the properties (for example, if I create a Boy instance, there is a Human created just to copy the properties to Boy).
Is there a better / faster / more efficient (or simply: proper) way of doing this? (Pointing to one, remember that I'm a beginner, so be descriptive or I might not understand the answer.)


texts: Subset pandas DataFrame based on two columns ignoring what order the match happens in

texts:
I have two Pandas DataFrames and I want to subset df_all based on the values within to_keep.  Unfortunately this isn't straight forward pd.merge() or df.join() because I have multiple columns that I want to match on, and I don't care what order the match happens.

I don't care if df_all['source'] matches in either to_keep['from'] OR 'to_keep['to']
And then df_all['target'] matches in either to_keep['from'] OR to_keep['to'].

What I have below currently works, but it seems like a lot of work and hopefully this operation could be optimized.

import pandas as pd
import numpy as np

# create sample dataframe
df_all = pd.DataFrame({'from': ['a', 'a', 'b', 'a', 'b', 'c', 'd', 'd', 'd'],
                       'to': ['b', 'b', 'a', 'c', 'c', 'd', 'c', 'f', 'e'],
                       'time': np.random.randint(50, size=9),
                       'category': np.random.randn(9)
                       })

# create a key based on from & to
df_all['key'] = df_all['from'] + '-' + df_all['to']

df_all

    category    from    time    to  key
0   0.374312    a   38  b   a-b
1   -0.425700   a   0   b   a-b
2   0.928008    b   34  a   b-a
3   -0.160849   a   44  c   a-c
4   0.462712    b   4   c   b-c
5   -0.223074   c   33  d   c-d
6   -0.778988   d   47  c   d-c
7   -1.392306   d   0   f   d-f
8   0.910363    d   34  e   d-e

# create another sample datframe
to_keep = pd.DataFrame({'source': ['a', 'a', 'b'],
                        'target': ['b', 'c', 'c']
                       })

to_keep

    source  target
0   a   b
1   a   c
2   b   c

# create a copy of to_keep
to_keep_flipped = to_keep.copy()

# flip source and target column names
to_keep_flipped.rename(columns={'source': 'target', 'target': 'source'}, inplace=True)

# extend to_keep with flipped version
to_keep_all = pd.concat([to_keep, to_keep_flipped], ignore_index=True)

to_keep_all

    source  target
0   a   b
1   a   c
2   b   c
3   b   a
4   c   a
5   c   b

# create a key based on source & target
keys = to_keep_all['source'] + '-' + to_keep_all['target']

keys

0    a-b
1    a-c
2    b-c
3    b-a
4    c-a
5    c-b
dtype: object

df_all[df_all['key'].isin(keys)]

    category    from    time    to  key
0   0.374312    a   38  b   a-b
1   -0.425700   a   0   b   a-b
2   0.928008    b   34  a   b-a
3   -0.160849   a   44  c   a-c
4   0.462712    b   4   c   b-c


texts: Generic Comparator Using Class Fields & Lambda Java

texts:
I have a grid in which i have to display some/all fields of a Java Class,
this grid displays the List of elements of that class type.

I have to sort this list provided:

Class type of the List item
Field name of the class to be sorted

to get field from a class by field name

private static <T> Field getField(Class<T> clazz,String fieldName){
    Field field = null;
    try {
        field = clazz.getDeclaredField(fieldName);
    }catch(java.lang.NoSuchFieldException e){
        e.printStackTrace();
    }
    return field;
}

and the comparator method using lambda, providing class type, field name to sort, and sort order

public static <T> Comparator<T> getGenericComparatorLambda(Class<T> clazz,
        String fieldName,boolean orderByAsc){

    //get field from class
    final Field field = getField(clazz, fieldName);
    field.setAccessible(true);

    //Lambda comparator
    Comparator<T> orderByComparator = (f1, f2) -> {

        Comparable compA = null;
        Comparable compB = null;

        // getting fields from object f1,f2
        try {
            compA =(Comparable) field.get(f1);
            compB =(Comparable) field.get(f2);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }

        // handling null comparators
        if(compA == null)
            return -1;
        else if(compB == null)
            return 1;

        return compA.compareTo(compB);
    };

    //reverse comparator if order is descending
    if (orderByComparator != null && !orderByAsc)
        orderByComparator = orderByComparator.reversed();

    return orderByComparator;
}

As the code consists of Lambda as well as generics of java,
I want an overall analysis of the code, improvements where needed, how much is the performance penalty when using generics with long lists.


texts: Find the third largest element in the array in linear time

texts:
Find Third largest element in an array

  Input  : arr[] = {1, 14, 2, 16, 10, 20}

  Output : 14

Its a simple program, but would be great to know how it can be improved for better readability or any feedback regarding styling, etc.

public static int findThirdLargest(int[] numbers) {
    if (numbers.length < 3) {
        throw new IllegalArgumentException("there should be at least three numbers");
    }

    int largest, secondLargest, thirdLargest;
    largest = secondLargest = thirdLargest = Integer.MIN_VALUE;

    for (int number : numbers) {

        if (number > largest) {
            thirdLargest = secondLargest;
            secondLargest = largest;
            largest = number;
        } else if (number > secondLargest) {
            thirdLargest = secondLargest;
            secondLargest = number;
        } else if (number > thirdLargest) {
            thirdLargest = number;
        }
    }

    return thirdLargest;
}

@Test
public void findThirdLargest() throws Exception {

    // with positive numbers
    Assert.assertEquals(1, ThirdLargestNumber.findThirdLargest(new int[]{1, 2, 3}));
    Assert.assertEquals(2, ThirdLargestNumber.findThirdLargest(new int[]{1, 2, 3, 4}));
    Assert.assertEquals(2, ThirdLargestNumber.findThirdLargest(new int[]{1, 4, 3, 2}));
    Assert.assertEquals(14, ThirdLargestNumber.findThirdLargest(new int[]{1, 14, 2, 16, 10, 20}));
    Assert.assertEquals(16, ThirdLargestNumber.findThirdLargest(new int[]{19, -10, 20, 14, 2, 16, 10}));

    // with negative numbers
    Assert.assertEquals(-100, ThirdLargestNumber.findThirdLargest(new int[]{-100, -2, -3}));
    Assert.assertEquals(-3, ThirdLargestNumber.findThirdLargest(new int[]{1, 2, -3, -1000}));
    Assert.assertEquals(-3000, ThirdLargestNumber.findThirdLargest(new int[]{-1000, -2000, -3000, -4000, -5000}));

    // what happens when all the numbers are same
    Assert.assertEquals(1, ThirdLargestNumber.findThirdLargest(new int[]{1, 1, 1, 1}));
}

Code: https://github.com/Ramblers-Code/CodeKata/blob/master/src/main/java/kata/array/ThirdLargestNumber.java#5


texts:
I have written a program to evaluate a postfix expression using a stack. I had my stack implementation using a linked list reviewed here, so I am only including the header file here.

I have taken the postfix expression in form of a string where the operators and operands are delimited by spaces and have used a sentinel at the end to mark the end of the expression.

stack.h

#ifndef STACK_H
#define STACK_H

#include <stdbool.h>

typedef int StackElement;

typedef struct stack_CDT *Stack;

Stack stack_init();

void stack_destroy(Stack s);

bool stack_is_empty(Stack s);

void stack_push(Stack s, StackElement elem);

StackElement stack_pop(Stack s);

#endif

eval_postfix.h

#ifndef EVAL_POSTFIX_H
#define EVAL_POSTFIX_H

// space is the delimiter between the different tokens

extern const char *sentinel;

int eval_postfix(char *exp);

#endif

eval_postfix.c

#include "eval_postfix.h"
#include "stack.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>

#define MAX_TOKEN_LEN 25

const char *sentinel = "$";

static char *get_token(char *token, char *exp, int idx)
{
    sscanf(exp + idx, "%s", token);
    return token;
}

static bool is_operator(char *token)
{
    return (strcmp(token, "/") == 0 || strcmp(token, "*") == 0 ||
            strcmp(token, "%") == 0 || strcmp(token, "+") == 0 ||
            strcmp(token, "-") == 0);
}

static int eval(int a, int b, char *op)
{
    if (strcmp(op, "/") == 0)
        return a / b;
    if (strcmp(op, "*") == 0)
        return a * b;
    if (strcmp(op, "%") == 0)
        return a % b;
    if (strcmp(op, "+") == 0)
        return a + b;
    if (strcmp(op, "-") == 0)
        return a - b;

    return 0;
}

int eval_postfix(char *exp)
{
    Stack s = stack_init();
    char token[MAX_TOKEN_LEN + 1];
    int i = 0;
    while (strcmp(get_token(token, exp, i), sentinel) != 0) {
        if (is_operator(token)) {
            int operand1 = stack_pop(s);
            int operand2 = stack_pop(s);
            stack_push(s, eval(operand2, operand1, token));
        } else {
            stack_push(s, (int)strtol(token, NULL, 0));
        }

        i += strlen(token) + 1; // one extra for the space
    }

    int res = stack_pop(s);
    stack_destroy(s);
    return res;
}

test.c

#include "eval_postfix.h"
#include <stdio.h>
#include <string.h>

#define MAX_EXPRESSION_LEN 100

int main()
{
    printf("Enter postfix expression(no more than %d characters): ",
            MAX_EXPRESSION_LEN);
    char exp[MAX_EXPRESSION_LEN + 3];
    fgets(exp, sizeof exp, stdin);
    char *pos;
    if ((pos = strchr(exp, '\n')) != NULL)
        *pos = '\0';
    strcat(strcat(exp, " "), sentinel);

    printf("Result = %d\n", eval_postfix(exp));
    return 0;
}


texts:
Simply put, is this function a correct and safe way to add and/or subtract time to a tm struct (from <time.h>)?

void AddTime(int seconds, tm *date)
{
    date->tm_sec += seconds;
    mktime(date);
}

seconds could be any value, supposedly larger than 60 (or smaller than -60). I'm using mktime to readjust the other values in tm, but I don't know if that's right.

I'm also not taking into account going below 1970 or above 3001 for the year, which I think are the default bounds for mktime to operate. I can check for that elsewhere.


texts:
I have tried like this to check a substring in a mainstring in 8086.  Is there any shorter way of doing this?  My implementation seems lengthy.

DATA SEGMENT
STR1 DB 'MADAM'
LEN1 DW ($-STR1);       storing the length of STR1
STR2 DB 'MADAA'
LEN2 DW ($-STR2);       stroing the length of STR2
DATA ENDS

CODE SEGMENT

LEA SI, STR1
LEA DI, STR2
MOV DX, LEN1
MOV CX, LEN2
CMP CX, DX;             comparing main & substring length
JA EXIT;                if substring size is bigger than there is no chance to be found it in main string
JE SAMELENGTH;          if main & sub string both have same length the we can compare them directly
JB FIND;                general case (substring length < mainstring length): we can apply our main process

SAMELENGTH:
        CLD
        REPE CMPSB
        JNE RED
        JMP GREEN

FIND:
        MOV AL, [SI];   storing the ascii value of current character of mainstring
        MOV AH, [DI];   storing the ascii value of current character of substring
        CMP AL,AH;      comparing both character
        JE CHECK;
        JNE NOTEQL

NOTEQL:
        INC SI;         if both character don't match then we would point to the next char of main string
        DEC DX;         DX keeps track of how many character of mainstring is left to process
        CMP DX, 0000H;  checking if there are any character left in the main string for further comparison
        JE RED;         if no character is left in main string then obviously the substring doesn't exists in main string
        JMP FIND

CHECK:
        MOV CX, LEN2;   CX is used internally for REPE CMPSB. So storing length of the substring in CX would limit the number of characters for comparison to exact length of substring.
        ;               For example to compare between "madam" & "ada" we need to compare *ada* portion of main string with substring ada, no more, no less
        MOV SP, SI;     storing the index of current character of main string so if the following REPE CMPSB find mismatch then the process can be started over from the next character of main string (SEE line 1 of TEMPRED) by going to TEMPRED > FIND
        ADD SP, 0001H
        CLD
        REPE CMPSB
        JNE TEMPRED
        JMP GREEN

TEMPRED:;               substring not found starting from the current character of main string, but it is possible to find match if we start from next character in main string
        MOV SI,SP;      going to the next character of main string (after REPE CMPSB of CHECK segment)
        DEC DX
        LEA DI, STR2;   reloading substring index in DI (after REPE CMPSB of CHECK segment)
        JMP FIND;       if a character matches but the following substring mismatches in main string then we start over the same process from the next character of main string by going to FIND segment

GREEN:
        MOV BX, 0001H;  substring found
        JMP EXIT

RED:
        MOV BX, 0000H;  substring not found
        JMP EXIT

EXIT:
    CODE ENDS
    END
    RET


texts: Lowering the cyclomatic complexity of this method, suggestions?

texts:
The PHP Mess Detector of my IDE warns about a Cyclomatic Complexity of 14 (threshold is 10). To me this code doesn't seem to hard to follow. Would you refactor it in some way to lower the metric?

Exit if $payload isn't an array or has a number of elements not equal to 1
If $payload is array or ArrayAccess build a proper checker/setter
If $payload is stdClass do the same as 2
Use control options and checker/setter to actually set the value inside $payload

The method:

public function onBeforeEncrypt(CryptDecryptEvent $event)
{
    // Get the actual parameters of the call
    $payload = $event->getPayload();

    // Avoid errors when __soapCall is invoked directly with custom arguments
    if (!is_array($payload) || 1 !== count($payload)) {
        return;
    }

    // Reference to the payload (by reference just in case it's an array)
    $payload = &$payload[0];

    // Shortcuts to control options
    $paramName      = $this->options['name'];
    $paramValue     = $this->options['value'];
    $allowOverride  = $this->options['allowOverride'];
    $nullLikeNotSet = $this->options['threatNullLikeNotSet'];

    // Dynamically build checker and setter based on the type
    $checker = $setter = null;

    // Payload is array or ArrayAccess implementation inside main array
    if (is_array($payload) || $payload instanceof \ArrayAccess) {
        $checker = function ($k) use ($payload, $nullLikeNotSet) {
            return isset($payload[$k]) || (null === $payload[$k] && $nullLikeNotSet);
        };

        $setter = function ($k, $v) use (&$payload) { $payload[$k] = $v; };
    }

    // Payload is stdClass inside the main array
    if ($payload instanceof \stdClass) {
        $checker = function ($p) use ($payload, $nullLikeNotSet) {
            return isset($payload->$p) || (null === $payload->$p && $nullLikeNotSet);
        };

        $setter = function ($p, $v) use ($payload) { $payload->$p = $v; };
    }

    // Set the value if we can override or parameter is abset
    if ($checker && $setter && ($allowOverride || !$checker($paramName)) {
        $setter($paramName, $paramValue);
    }
}


texts: Is this the only or best method for classes serializing in Java?

texts:
I usually use the static methods from this designed class in order to perform objects serializing of custom classes.

Even though I'm getting good results, I wonder if this is the most appropriate way for it and if there are any improvements for it?

public class InputOuput {
    private static FileOutputStream         flujoSalida;
    private static ObjectOutputStream       flujoSalidaObjetos;
    private static File                     archivo;
    private static final FileChooser        seleccionador = new FileChooser();

    private static FileInputStream          flujoEntrada;
    private static ObjectInputStream        flujoEntradaObjetos;

    public static boolean serialize(Object anObject) {
        seleccionador.setTitle("Dónde guardar el estado del programa");

        try {
            archivo = seleccionador.showSaveDialog(null);
            if (archivo == null) return false;

            flujoSalida = new FileOutputStream(archivo);
            flujoSalidaObjetos = new ObjectOutputStream(flujoSalida);
            flujoSalidaObjetos.writeObject(anObject);
            flujoSalidaObjetos.close();
            flujoSalida.close();
        } catch (IOException error) {
            System.out.println(error.toString());
            System.out.println(error.getStackTrace());
        }
        return true;
    }

    public static Object deserialize() {
        Object m=null;

        try {
            archivo = seleccionador.showOpenDialog(null);
            if (archivo == null) return null;
            flujoEntrada = new FileInputStream(archivo);
            flujoEntradaObjetos = new ObjectInputStream(flujoEntrada);
            m= (Object) flujoEntradaObjetos.readObject();
            flujoEntradaObjetos.close();
            flujoEntrada.close();
        } catch (IOException | ClassNotFoundException error) {
            System.out.println(error.toString());
            System.out.println(error.getStackTrace());
        }
        return m;
    }
}

*I change Object for the custom intended class

One good point to ask: how could I be not making the InputOutput class to implement Serializable, yet it works properly anyway?


texts:
I have a macroscript which reads a query string for search term parameters, and then does a multiple word GroupedOr search through UmbracoExamine / Lucene.NET.  Because this is a full site search, I have hard-coded an array of about 100 fields across the site to allow the user to search against pretty much anything on the site.

Is there any way to make this search more efficient?  Currently I'm averaging about 5 seconds (per 10,000 iterations on stopwatch) to search 100 fields on about ~2.2k nodes and returning ~600 results.

NOTE: I have removed the HTML / Inner loop code as I've already determined that this area isn't where the search is hanging.

string SearchTerm = string.Empty;
if (!string.IsNullOrEmpty(Request.Form["SearchTerm"]))
{
    SearchTerm = Request.Form["SearchTerm"];
    string[] SearchTermList = SearchTerm.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
    string[] aliasList = new string[]{"umbracoUrlName", "menuText", "pageHeading", "pageSubheading",
        "bodyText", "alerts", "headerQuote", "headerQuoteAttribution", "officePhone", "officeFax",
        "officeEmail", "officeAddress", "officeCityofficeState", "officeZip", "officeAddress2",
        "officeName", "navSummary", "latestJournals", "frequentNumbers", "searchIntro", "introduction",
        "heading", "introText", "smName", "divisionTitle ", "districtTitle ", "districtNotes ",
        "authorFirst ", "authorLast ", "articleTitle ", "articleKeywords ", "associatedJournal ",
        "headline ", "content", "ruleSection", "articleCategories", "staffListing", "categoryTitle",
        "articleAuthor", "articleCategory", "articleEndnotes", "journalVolume", "journalIssue",
        "journalDate", "ruleCategory", "caseNotes", "proposedOpinion", "opinionAdopted", "opinionSummary",
        "opinionEndnotes", "secondarySegment", "primaryTitle", "primarySubtitle", "primaryIntro",
        "primaryNote", "secondaryTitle", "secondarySubtitle", "secondaryIntro", "secondaryNote",
        "contactName", "contactTitle", "contactPhone", "contactEmail", "contactLabel", "contactIntro",
        "orgMembers", "faqQuestion", "faqAnswer", "eventSummary", "eventVenue", "eventAddress1",
        "eventAddress2", "eventCity", "eventState", "eventZip", "eventStartDateTime", "eventEndDateTime",
        "eventContactName", "eventContactTitle", "eventContactEmail", "eventContactPhone", "groupMembers",
        "pluralName", "makePlural", "subMembers", "newsDate", "newsLocation", "newsSummary", "newsCategory"};

    BaseSearchProvider collection = ExamineManager.Instance.SearchProviderCollection["SiteSearchSearcher"];
    ISearchCriteria searchCriteria = collection.CreateSearchCriteria(IndexTypes.Content, BooleanOperation.Or);
    ISearchCriteria filter = searchCriteria.GroupedOr(aliasList, SearchTermList).Compile();
    var SearchResults = collection.Search(filter).OrderByDescending(n => n.Score);
    string resultText = SearchResults.Count() == 1 ? "result" : "results";

    if (SearchResults.Count() > 0)
    {
      //Removed HTML / Printing Nodes & URL's
    }
}


texts:
I needed to parse some command line switches from a string and I tried to do it the easy way so I just wrote this:

static class CommandLineParser
{
    public static IEnumerable<string> ParseCommandLine(this string text)
    {
        if (Regex.Matches(text, "\"").Count % 2 != 0)
        {
            throw new ArgumentException("Invalid number of qotes.");
        }
        return text.Aggregate(new
        {
            lastChar = '\0',
            isEscaped = false,
            result = new List<StringBuilder> { new StringBuilder() }
        }, (state, next) =>
        {
            var isQuote = next == '"';
            var isEscapedQuote = state.lastChar == '\\' && isQuote;

            if (next == ' ' && !state.isEscaped)
            {
                // Ignore multiple spaces between switches.
                if (state.lastChar != ' ')
                {
                    state.result.Add(new StringBuilder());
                }
            }
            else
            {
                state.result.Last().Append(next);
            }

            return new
            {
                lastChar = next,
                isEscaped = isQuote && !isEscapedQuote ? !state.isEscaped : state.isEscaped,
                result = state.result
            };
        }).result.Select(x => x.ToString());
    }
}

Example:

var text = "foo -bar -baz=\"abc \\\"def\\\"   ghi\"    -qux";
text.ParseCommandLine().Dump();

and the result:

foo
-bar
-baz="abc \"def\" ghi"
-qux

What do you think? Is this enough? Can this be even shorter?


texts: Storing singleton instances in a generic utils class

texts:
In one of my java projects I use singletons a lot and I was looking for a way to reduce repeating code. I made a SingletonUtils class that accepts a class and supplier parameter. Then stores the instance in a hash map. This way the static instance isn't stored as a static variable in the class I want to make a singleton.

My question is, is there any problems/cons with implementing the singleton pattern like this and is there an easier way to do this or is this the best way?

public class SingletonUtils {
    public static HashMap<Class, Object> instances = new HashMap<>();
    public static <T> T getInstance(final Class<T> singletonObj, final Supplier<T> creator) {
        if(!instances.containsKey(singletonObj)) {
            if(creator == null) return null;
            else instances.put(singletonObj, creator.get());
        }
        return (T) instances.get(singletonObj);
    }

    public static boolean instanceExists(final Class singletonObj) {
        return instances.containsKey(singletonObj);
    }

    public static void removeInstance(final Class singletonObj) {
        instances.remove(singletonObj);
    }
}

public final class AuthManager {
    private AuthManager() { }

    public static AuthManager getNewInstance() {
        return SingletonUtils.getInstance(AuthManager.class, AuthManager::new);
    }
}


texts: Java interface to C library - Refactoring to singleton usage

texts:
I am currently writing a Java interface to a C library. It mostly just delegates calls and adds a object oriented layer on top of it to make integration into a regular Java program more natural.

The C library talks to a (local) server which in turn communicates with a real device.

My current design uses dependency injection and a central Connection class which provides access to the lower level C API binding (I use JNA). It looks like this:

public class Connection {
    public void connect(int port);
    public APIBinding getBinding();
}

public interface DataReceiver {
    public Data getData();
}

public class DeviceDataReceiver implements DataReceiver {
    public DeviceDataReceiver(Connection conn);
    public Data getData(); // Use conn.getBinding() to retrieve Data package
}

public class FileDataReceiver implements DataReceiver {
    public FileDataReceiver(File file);
    public Data getData(); // Load data from file, for device simulation
}

I think this is quite solid, as it provides the user with the opportunity to run a program with the FileDataReceiver instead of the DeviceDataReceiver, so that they can use pre-recorded data.

But there is one thing bugging me - There can actually only be one instance of every Device dependant class. Creating multiple instances would only result in confusing behavior, since there is only one state, which is held inside the C library. The imperative nature of the C library doesn't translate to the object oriented nature of my Java API.

I want to solve this by making my device dependant classes singletons. Personally I dislike singletons, but the usage of the API would get a lot more intuitive.

My main problem is how to name my singleton classes and how to access them in a way that doesn't feel awkward for the user. My first approach was this:

public class Device {
    // Handles the single instance problem
    // The old classes stay the same
    public static ConnectionManager getConnectionManager();
    public static DataReceiver getDataReceiver();
    ...
}

// Using it like this:
Device.getConnectionManager().connect(1234);
DataReceiver dr = Device.getDataReceiver();
for (int i = 0; i < 10; i++) {
    System.out.println(dr.getData());
}

There are two things that I am not sure about with this solution:

Is Manager a good name? It feels very generic.
The single instance management is done by my Device class. Normally you have something like Connection.INSTANCE and a private constructor. While being more restrictive, this approach also would make my classes pretty much untestable, as I have to inject a mock of the JNA binding. Is using Device as a instance-manager a good approach to circumvent that problem?


texts: A program to represent a coin amount using the smallest number of coins

texts:
Recently, I was learning about greedy algorithms. One example that was given was an algorithm for exchanging a given money amount using the smallest number of coins. After the lecture, I wrote a C program implementing this:

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

static int compareDenominations(const void *a, const void *b) {
    return (*((int*) b) - *((int*) a));
}

int main(int argc, char *argv[]) {
    long amount;
    int count;
    long *denominations;
    if (argc > 2) {
        errno = 0;
        amount = strtol(argv[1], NULL, 10);
        if (errno || amount <= 0) {
            puts("The coin amount is either negative, zero, or too big.");
            return EXIT_FAILURE;
        }
        count = argc - 2;
        if (count == 0) {
            puts("Please input at least one coin denomination.");
            return EXIT_FAILURE;
        }
        denominations = malloc(sizeof(*denominations) * count);
        if (denominations == NULL) {
            puts("Insufficient memory.");
            return EXIT_FAILURE;
        }
        int i;
        for (i = 0; i < count; i++) {
            errno = 0;
            denominations[i] = strtol(argv[i + 2], NULL, 10);
            if (errno || denominations[i] <= 0) {
                puts("A denomination amount is either negative, zero, or too big.");
                return EXIT_FAILURE;
            } else {
                int j;
                for (j = 0; j < i; j++) {
                    if (denominations[j] == denominations[i]) {
                        fprintf(stderr, "%ld is a duplicate coin denomination.\n", denominations[j]);
                        return EXIT_FAILURE;
                    }
                }
            }
        }
    } else {
        puts("Please enter a coin amount followed by a non-zero number of unique denominations, all separated by spaces.");
        return EXIT_FAILURE;
    }
    heapsort(denominations, count, sizeof(*denominations), compareDenominations);
    printf("Amount: %ld | Denominations: [ ", amount);
    int i;
    for (i = 0; i < count; i++) {
        printf("%ld ", denominations[i]);
    }
    puts("]");
    int denominationCount = 0;
    for (i = 0; i < count; i++) {
        denominationCount = 0;
        while (amount >= denominations[i]) {
            amount -= denominations[i];
            denominationCount++;
        }
        denominations[i] = denominationCount;
    }
    if (amount) {
        puts("The coin amount could not be represented using the given denominations.");
        return EXIT_FAILURE;
    }
    printf("Counts: [ ");
    for (i = 0; i < count; i++) {
        printf("%ld ", denominations[i]);
    }
    puts("]");
    return EXIT_SUCCESS;
}

Because my program can accept arbitrary inputs, this greedy algorithm may not always output the most optimal solution, but I am still interested in the quality of my implementation.


texts: Toggling a taxi between busy and available states

texts:
Is there a better way to do this? That switch_status method seems like it could be made a lot more compact.

class Taxi
  def initialize
    @status = :available
  end

  def switch_status
    if @status == :available
      @status = :busy
    else
      @status = :available
    end
  end
end

t = Taxi.new
t.switch_status


texts:
Some friends and I were playing the game Spot It, which has x cards each with y symbols on them, from a potential of z potential symbols.  The trick is every card has exactly 1 of the same symbol as any other card in the deck.  We were talking about the numbers y and z effect the total number of possible cards x, and we could not figure out a formula for figuring it out.  I decided I would just write a program to brute force it below:
class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine("Number of cards: {0}", getCount(55, 8));
    }

    static int getCount(int numberOfSymbols, int symbolsPerCard)
    {
        int[] nextCardArr = new int[symbolsPerCard];
        for (int i = 0; i < symbolsPerCard; i++)
        {
            nextCardArr[i] = i;
        }
        HashSet<int> potentialCard;
        List<HashSet<int>> deck = new List<HashSet<int>>();
        while (getNextValidCard(nextCardArr, numberOfSymbols, out potentialCard))
        {
            if (isValidInDeck(potentialCard, deck))
            {
                deck.Add(potentialCard);
            }
        }

        return deck.Count;
    }

    private static bool isValidInDeck(HashSet<int> potentialCard, List<HashSet<int>> deck)
    {
        bool retVal = true;
        foreach (HashSet<int> card in deck)
        {
            int commonalities = 0;
            foreach (int symbol in potentialCard)
            {
                if (card.Contains(symbol))
                {
                    commonalities++;
                }
            }
            retVal = retVal && commonalities == 1;
            commonalities = 0;
        }

        return retVal;
    }

    private static bool isValidCard(int[] potentialCard)
    {
        HashSet<int> tester = new HashSet<int>(potentialCard);
        return tester.Count == potentialCard.Length;
    }

    private static bool getNextValidCard(int[] nextCardArr, int numberOfSymbols, out HashSet<int> potentialCard)
    {
        potentialCard = new HashSet<int>(nextCardArr);
        bool isThereAValidCard = false;
        int i = 0;
        while(true)
        {
            if (nextCardArr[i] < numberOfSymbols)
            {
                nextCardArr[i]++;
                if (isValidCard(nextCardArr))
                {
                    isThereAValidCard = true;
                    break;
                }
            }
            else if (nextCardArr[i] == numberOfSymbols)
            {
                nextCardArr[i] = 0;
                while (!isValidCard(nextCardArr))
                {
                    nextCardArr[i]++;
                }
                i++;
                if (i == nextCardArr.Length)
                {
                    break;
                }
            }
        }

        return isThereAValidCard;
    }
}

I'm quite certain the program is working, but it is ridiculously slow because of how it brute forces every potential card and then tests if it can be added to the deck.  I'm really at a loss of how to better approach this problem to create a more efficient program, so I thought I'd ask here.  I am also not 100% sure it's totally correct as all the decks it creates all match on the same symbol, but I'm thinking that may be ok for calculating 1 possible deck, and the max cards doesn't change if that weren't the case.


texts: Car store implementation using abstract factory

texts:
I'm studying design patterns and I made this car store implementation. Although I'm confident that the idea is right, I'm not confident that the implementation is good. I would like you to check it out and give me some advice.

It doesn't have tests, and I'm using an abstract class with a private method.

Car:

<?php namespace Pattern\AbstractFactory;

interface Car {

}

CarFactory:

<?php namespace Pattern\AbstractFactory;

use InvalidArgumentException;

abstract class CarFactory {

  private $sports = [];
  private $family = [];

  function __construct(array $sports, array $family)
  {
    $this->sports = $sports;
    $this->family = $family;
  }

  public function makeSportsCar($name)
  {
    return $this->makeCar($this->sports, $name);
  }

  public function makeFamilyCar($name)
  {
    return $this->makeCar($this->family, $name);
  }

  private function makeCar(array $cars, $name)
  {
    if (! isset($cars[$name]))
    {
      throw new InvalidArgumentException('You tried to make a nonexistent car');
    }

    return new $cars[$name];
  }
}

CarStore:

<?php namespace Pattern\AbstractFactory;

class CarStore {

  private $factory;

  function __construct(CarFactory $factory)
  {
    $this->factory = $factory;
  }

  public function orderSportsCar($name)
  {
    return $this->factory->makeSportsCar($name);
  }

  public function orderFamilyCar($name)
  {
    return $this->factory->makeFamilyCar($name);
  }

}

Chevrolet:

<?php namespace Pattern\AbstractFactory\Factory;

use Pattern\AbstractFactory\CarFactory;

/**
 * @codeCoverageIgnore
 */
class Chevrolet extends CarFactory {

  private $sports = [
    'miray' => 'Pattern\AbstractFactory\Car\Sport\Miray'
  ];

  private $family = [
    'equinox' => 'Pattern\AbstractFactory\Car\Family\Equinox'
  ];

  function __construct()
  {
    parent::__construct($this->sports, $this->family);
  }

}

Equinox:

<?php namespace Pattern\AbstractFactory\Car\Family;

use Pattern\AbstractFactory\Car\Family;

class Equinox implements Family {

}

Evos:

<?php namespace Pattern\AbstractFactory\Car\Sport;

use Pattern\AbstractFactory\Car\Sport;

class Evos implements Sport {

}

Family:

<?php namespace Pattern\AbstractFactory\Car;

use Pattern\AbstractFactory\Car;

interface Family extends Car {

}

Ford:

<?php namespace Pattern\AbstractFactory\Factory;

use Pattern\AbstractFactory\CarFactory;

/**
 * @codeCoverageIgnore
 */
class Ford extends CarFactory {

  private $sports = [
    'evos' => 'Pattern\AbstractFactory\Car\Sport\Evos'
  ];

  private $family = [
    'galaxy' => 'Pattern\AbstractFactory\Car\Family\Galaxy'
  ];

  function __construct()
  {
    parent::__construct($this->sports, $this->family);
  }

}

Galaxy:

<?php namespace Pattern\AbstractFactory\Car\Family;

use Pattern\AbstractFactory\Car\Family;

class Galaxy implements Family {

}

Miray:

<?php namespace Pattern\AbstractFactory\Car\Sport;

use Pattern\AbstractFactory\Car\Sport;

class Miray implements Sport {

}

Sport:

<?php namespace Pattern\AbstractFactory\Car;

use Pattern\AbstractFactory\Car;

interface Sport extends Car {

}