texts: Enum with associated value as stored property in Swift extension

texts:
I have a service which connects to server using socket and stays connected,
I used this enum to manage connection state:

enum ConnectionState {
  case none, connecting, failed(Error), connected, disconnected(Error), blocked
}

I wanted to have connectionState as property to know current connection state of service but in extension of service provider class.

Why in extension and not in class itself?
Because ServiceProvider class is not Swift class, its ObjC class and there is no way we I can declare ConnectionState swift enum with associated values in ObjC class.

So I used associative stored property in swift extension, but as ConnectionState has associated values I need to do little more.

First I created extension to enum to make dictionary convertible as:

extension ConnectionState {
  var dictPresentation: [String: Error?] {
    switch self {
    case .none: return ["none": nil]
    case .connecting: return ["connecting": nil]
    case .failed(let error): return ["failed": error]
    case .connected: return ["connected": nil]
    case .disconnected(let error): return ["disconnected": error]
    case .blocked: return ["blocked": nil]
    }
  }

  init(dict: [String: Error?]) {
    assert(!dict.isEmpty, "dict must contain one key")
    let key = dict.keys.first!
    let error: Error? = dict[key] ?? nil
    switch key {
    case "none": self = .none
    case "connecting": self = .connecting
    case "failed": self = .failed(error!)
    case "connected": self = .connected
    case "disconnected": self = .disconnected(error!)
    case "blocked": self = .blocked
    default:
        assert(false, "wrong key in dict")
        self = .none
    }
  }
}

Then used it in service provider class extension as:

private var ConnectionStateHolderKey: UInt8 = 7
extension ServiceProvider {
  private var _connectionStateHolder: NSDictionary {
    get {
        if let connectionStateDict = objc_getAssociatedObject(self, &ConnectionStateHolderKey) as? NSDictionary {
            return connectionStateDict
        }
        //return ["none": nil] gives error "nil is not compatible with expected dictionary value type 'Any'"
        //return ["none": nil as Any] gifs error "Nil is not compatible with 'Any' in coercion"

        let dict = NSDictionary()
        dict.setValue(nil, forKey: "none")
        return dict//default state = none
    }
    set {
        objc_setAssociatedObject(self, &ConnectionStateHolderKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
    }
  }

  var connectionState: ConnectionState {
    get {
        return ConnectionState(dict: _connectionStateHolder as! [String : Error?])
    }
    set {
      _connectionStateHolder = newValue.dictPresentation as NSDictionary
    }
  }
}

Is there anything that can be used to simplify this code and avoid dictionary conversion?
Any suggestions that can improve this code are welcomed!


texts:
I'm playing around with switching some code to using Parallel.ForEach and I have a question about whether I need to be concerned about the effects of concurrency here. Here's a simplified version of what I'm doing:

public IList<Item> RetrieveAllItems(int paramValue)
{
    var itemFuncs = new List<Func<int, IEnumerable<Item>>>
                {
                    RetrieveItems1,//one method to retrieve items, taking an int param
                    RetrieveItems2//another one that takes an int param
                };

    List<Item> allItems = new List<Item>();

    Parallel.ForEach(itemFuncs, (f) =>
                {
                    //is this a problem?
                    allItems.AddRange(f(paramValue));
                });

    return allItems;
}

For this application, I do not care about the order that my Item objects are added to allItems (in fact, I do explicit ordering later on). My question is whether I could get into trouble here with both functions attempting to add Item objects at the same time.

My motivation for playing around with this is simply to try to speed up this sequence of events, and when I tried using a BlockingCollection instead, my timings, obviously slowed down to the point that there was hardly any difference between doing these two operations in parallel versus the old, serial way. When I use a simple List<Item> then I do see impressive speed-ups.

So, considering I am just adding objects to a collection in a parallel fashion, is using a non-thread safe collection asking for trouble here? My real-world experience with multi-threaded/parallel programming is very sparse, hence the uncertainty here.


texts: Using RestTemplate with HttpComponentsClientHttpRequestFactory in a multithreaded environment

texts:
I am working on a project in which I need to make an HTTP URL call to my server, running RESTful service, which returns the response as a JSON String. I am using RestTemplate here along with HttpComponentsClientHttpRequestFactory to execute a URL.

I have set up an HTTP request timeout (READ and CONNECTION time out) on my RestTemplate by using HttpComponentsClientHttpRequestFactory.

Here is my main code which is using the future and callables:

public class TimeoutThreadExample {

    private ExecutorService executor = Executors.newFixedThreadPool(10);
    // does it have to be static final?
    private static final RestTemplate restTemplate = createRestTemplate();

    // does this look right with the way I am creating `RestTemplate`?
    private static RestTemplate createRestTemplate(){
        // is it ok to create a new instance of HttpComponentsClientHttpRequestFactory everytime?
       HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory();
       requestFactory.setReadTimeout(READ_TIME_OUT);
       requestFactory.setConnectTimeout(CONNECTION_TIME_OUT);
       return new RestTemplate(requestFactory);
     }

    public String getData() {
        Future<String> future = executor.submit(new Task(restTemplate));
        String response = null;

        try {
            response = future.get(500, TimeUnit.MILLISECONDS);
        } catch (TimeoutException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }

        return response;
    }
}

Here is my Task class which implements the Callable interface and uses the RestTemplate:

class Task implements Callable<String> {

    private RestTemplate restTemplate;

    public Task(RestTemplate restTemplate) {
        this.restTemplate = restTemplate;
    }

    public String call() throws Exception {

        String url = "some_url";
        String response = restTemplate.getForObject(url, String.class);

        return response;
    }
}

Now I have everything working in my above code. Is the way I am creating RestTemplate along with HttpComponentsClientHttpRequestFactory thread-safe and efficient? Since RestTemplate is very heavy to be created so not sure whether I have it right or not. I'd like to improve anything in creation of RestTemplate with HttpComponentsClientHttpRequestFactory.


texts: Determine concurrent access to a function

texts:
Someone asked here how to determine a function is being called from multiple threads. My take on this is that they are asking about concurrent access not sequential access. The accepted answer therefore seems inadequate. Detecting concurrent access is also a problem I need to solve for debugging purposes so I thought I'd take a stab at a solution.

This takes an RAII-style approach to the solution, requiring only an instantiation of the class at the top of the function in question.

template <std::ostream& stream> class ConcurrentPrint: public std::ostringstream
{
public:
    ~ConcurrentPrint()
    {
        std::scoped_lock lock(printMutex);
        stream << this->str();
    }

private:
    static std::mutex printMutex;
};

template <std::ostream& stream> std::mutex ConcurrentPrint<stream>::printMutex;

class ConcurrencyChecker
{
public:

    ConcurrencyChecker(const std::string& id_) :
    id(id_)
    {
        std::scoped_lock lock(mapMutex);
        if (++numInstances[id] > 1)
        {
            ConcurrentPrint<std::cerr>() << "Warning: concurrent access to " << id << " from " << std::this_thread::get_id() << std::endl;
            abort();
        }
    }

    ~ConcurrencyChecker()
    {
        std::scoped_lock lock(mapMutex);
        --numInstances[id];
    }

private:
    static std::map<std::string, int> numInstances;
    static std::mutex cerrMutex;

    const std::string id;
    std::mutex mapMutex;
};

std::map<std::string, int> ConcurrencyChecker::numInstances = {};

Intended usage:

void functionToCheck()
{
    ConcurrencyChecker check(__func__);

    /* Function body */
}

Working example here

Things I'm interested in:

Are there any flaws in this general approach and is there a better one?
Any general improvements to the code


texts: Given a Haskell list, return all sub-lists obtained by removing one element

texts:
I am trying to write a Haskell function which takes a list ls and returns all sub-lists obtained by removing one element from ls. An additional constraint is that the returned list of lists must be in the order of the missing element.

Here is what I have. I know there must be a simpler solution.

subOneLists :: [a] -> [[a]]
subOneLists ls = let  helper :: [a] -> [a] -> [[a]] -> [[a]]
                      helper _ [] ss = ss
                      helper ps (x:xs) ss = helper ps' xs ss'
                        where ps' = ps ++ [x]
                              ss' = ss ++ [ps ++ xs]
                 in helper [] ls []

λ> subOneLists [1, 2, 3, 4]
[[2,3,4],[1,3,4],[1,2,4],[1,2,3]]


texts:
I'm learning C++ and here I've written a little toy program that is supposed to list all the arguments passed to it through the command line.

#include <iostream>;
using namespace std;

int main (int argc, char *argv[]) {
  for (int number = 1; number < argc; ++number) {
    cout << argv[number] << endl;
  }
  return 0;
}

It is possible to use indexing instead and rewrite it in the following way:

#include <iostream>
using namespace std;

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

  for (int j = 1; j < argc; ++j) {
    i = 0;
    while (argv[j][i]) {
      cout << argv[j][i];
      ++i;
    }
    cout << endl;
  }
   return 0;
}

I personally like the first version more. It doesn't need one more variable and it doesn't need one more cycle, so making use of pointers here seems like a good idea: it helps improve readability and as far as I know performance.

Is this actually a good alternative to the second version that uses indexing? And if so, how could it be improved?


texts: Match values between 2 sheets on excel, if match found, update cell

texts:
I'm using openpyxl to manipulate some spreadsheets.  I have this code to match values between two sheets on Excel, if the values match it updates a cell in that row:

for cell in ws1['a']:
    for num in ws4['a']:
        if cell.value == num.value:
            ws1.cell(row=cell.row, column=23).value = ws4.cell(row=num.row, column=9).value

There are 10000 rows of data on each sheet.  This task takes a couple minutes to complete.  Is there a faster way to do this?


texts: Search script for autocomplete suggestions

texts:
The following search script creates a JSON response for an autocomplete field. The tables and fields search from are flexible to allow using the same script for different type of searches - the idea is to search from each database field separately and see how often a term appears and sort them in descending order.
The part about ordering the found hits for a word by number of occurrences seems like it could be improved, but I don't know how to better approach the problem.
if (isset($_REQUEST['term']) && !empty($_REQUEST['term'])) {

    // define what table -> array(fields) to search from based on a possibly sent
    // parameter 'type', which is 'customer' or 'admin' or empty or some specific
    if (!isset($_REQUEST['type']) || $_REQUEST['type'] === 'customer') {
        $searchFrom = array(
            'tuotesarjat' => array('sarjanimi', 'laattatyyppi'),
            'tuotteet'    => array('varikategoria1', 'varikategoria2', 'pinta', 'hakupinta')
        );
    } else if ($_REQUEST['type'] === 'admin') {
        $searchFrom = array(
            'tuotesarjat' => array('sarjanimi', 'laattatyyppi'),
            'tuotteet'    => array('tuotenumero', 'kuvaus1', 'varikategoria1', 'varikategoria2', 'pinta', 'hakupinta')
        );
    } else if ($_REQUEST['type'] === 'tuotesarja') {
        $searchFrom = array(
            'tuotesarjat' => array('sarjanimi')
        );
    } else if ($_REQUEST['type'] === 'tuotenumero') {
        $searchFrom = array(
            'tuotteet'    => array('tuotenumero')
        );
    }

    $found = array();
    $terms = explode(' ', $_REQUEST['term']);

    // loop through all split up terms
    foreach ($terms as $key => $term) {
        if (!empty($term)) {
            $term = mysql_real_escape_string($term);

            // loop through tables
            foreach ($searchFrom as $table => $cols) {
                // for searches from table 'tuotesarjat' limit hits to published items
                $andWhere = $table == 'tuotesarjat' ? ' AND arkistoitu != 1 ' : '';

                // loop through fields
                foreach ($cols as $column) {
                    $sql = "SELECT $column FROM $table WHERE $column ";

                    // to limit searches, for 1-2 letter terms search string start,
                    // else from whole term
                    if (strlen($term) < 2) {
                        $sql .= "LIKE '$term%' $andWhere GROUP BY $column";
                    } else {
                        $sql .= "LIKE '%$term%' $andWhere GROUP BY $column";
                    }
                    // in case a field does not exist, fail silently
                    // (a json query will still be generated returning the
                    // _other_ fields' searches' results)
                    $res = @mysql_query($sql);
                    if (mysql_num_rows($res) > 0) {
                        while($row = mysql_fetch_assoc($res)) {
                            // insert new found word to array with count 1
                            // or increment already found words' counts
                            if (!key_exists($row[$column], $found)) {
                                $found[$row[$column]] = 1;
                            } else {
                                $found[$row[$column]] += 1;
                            }
                        }
                    }
                }
            }
        }
    }

    // sort by number of hits for each word desc
    arsort($found);

    // filter empty strings
    $found = array_filter(array_keys($found));

    // reduce array to global max hits
    while (count($found) > MAX_LIVESEARCH_SUGGESTIONS) {
        array_pop($found);
    }

    // generate and echo json
    $json = '[';
    foreach ($found as $sana) {
        $json .= '"' . $sana . '", ';
    }
    $json = substr($json, 0, -2) . ']';
    echo $json;
}


texts:
I have a function that loops through large objects of raw data, translating coded strings into readable words. The function is very basic, and I keep wondering if I should use an object instead containing the words to be detected and translated. This would be cleaner-looking and more flexible, but it would not like it to harm the performance of the script, since it needs to run through potentially thousands of items.

function formatTitle(input) {
    var input_lowercase = input.toLowerCase()
    if (input == "total") {
        return "Title"
    } else if ( input_lowercase == "type" || input_lowercase == "dokumenttype" ||  input_lowercase == "km_type"  ) {
        return label_documenttype
    } else if ( input_lowercase.indexOf("tema_") >= 0 || input_lowercase == "spesfikasjon" ) {
        return label_theme
    } else if ( input_lowercase.indexOf("prosess_") >= 0) {
        return label_process
    } else if (input.indexOf("SM_") >= 0) {
        return input.substr(3);
    }
    else {
        return input.charAt(0).toUpperCase() + input.slice(1)
    }
}

There are more exceptions in the list, I've shortened it a bit down for practical reasons. I use the function in the following context (when t_formatheader is switched on):

    if ( skipping_mechanism == "lookup" ) { //42% faster than switch block in IE
        for (var key in arr_firstnode) {
            if (key in keysToIgnore) continue;
            if ( t_formatheader == "1" ) {
                arrayPushUnknown( columns, formatTitle( key ), "", true, key )
            }
            else {
                arrayPushUnknown( columns, key, "", true, key )
            }
        }
    }


texts: C function to check the validity of a date in DD.MM.YYYY format

texts:
I was tasked with writing a function, that checks whether a date is valid in the following format: DD.MM.YYYY. Here's what I wrote:

bool isValidDate(const char* date)
{
    int a, b, c;
    size_t len = strnlen(date, 255);
    for (size_t i = 0; i < len; i++)
    {
        if (!isdigit(date[i]) && date[i] != '.') return false;
    }
    int validConversions = sscanf_s(date, "%2d.%2d.%4d", &a, &b, &c);
    return validConversions == 3 ? true : false;
}

From my testing I can conclude that this function does reasonably well: it doesn't accept anything except dots and digits, it expects to read exactly 3 numbers and it knows how many digits to read for the days and months.

Something it doesn't check however, is whether the days are less than 31 or the months are less than 12. Another thing it doesn't do is that it doesn't check correct looking, but invalid dates such as 30.02.2013 or 31.06.2012.

Solving that problem is trivial, but I don't wanna write 12 ifs for each month to check the dates. I'm starting to think I should just generate a data structure of valid dates and use that to check, i.e. if the passed date is there, then it's valid.

Is that the best way to do it or are there other ways?


texts: Python loop to write all possible strings that can be formed from some letters

texts:
The code below generates a query with the product of possibilities that may vary from 'abc' to 'abc ... z'

import itertools
import time

res = itertools.product('abcdefgh', repeat=8)
fileObj = open("txt_abcdefgh.txt","w")
timestamp1 = time.time()

for i in res:
    print (i) #this only to check the progress of the process
    fileObj.write(i[0] + i[1] + i[2] + i[3] + i[4] + i[5] + i[6] + i[7] + '\n')

timestamp2 = time.time()
fileObj.write('This took %.2f seconds' % (timestamp2 - timestamp1))
fileObj.close()

However, I have an entry of only 8 items and the runtime is unsatisfactory.

Input      Time             Possibilities
abc        0.01 seconds     27
abcd       0.29 seconds     256
abcde      4.28 seconds     3,125
abcdef     31.59 seconds    46.656
abcdefg    542.44 seconds   823,543
abcdefgh   4806.84 seconds  16,777,216

Is there any other way to better this code, maybe with some other language, or with another programming technique?


texts:
I have started to interest myself in artificial intelligence a while ago, especially within the game industry. I have started with state machines moved on to fuzzy logic and now I want to learn and implement a neural network which will also work for games.

However to not overwhelm my tiny little head I wanted to start small. I have found on Wikipedia this article: Künstliches Neuron(Artificial Neuron) and if you hit strg+f you can search for "Darstellung boolescher Funktionen" which is basically what I have implemented.

So my questions regarding the implementation are:
 Is this class usefull for a later neural network (keeping in mind that this class only represents a neuron) so that I than can use this class inside a neuronal network?

 Are there any bad issues which I haven't seen?

One thing I have to mention is that in this situation I didn't want to implement a really good unit testing class or doctests (I hate doctests) thats why my test looks weird.

import numpy as np
import math

# From Stackoverflow
def find_nearest(array,value):
    idx = (np.abs(array-value)).argmin()
    return array[idx]

def hlim(x):
    return 0.5 if x == 0 else 0 if x < 0 else 1

class Synapse(object):
    def __init__(self, origin, destination, weight = 0):
        self.weight = weight
        self.origin = origin
        self.destination = destination

        self.origin.synapse = self
        self.destination.synapse = self

class Neuron(object):
    def __init__(self, bias, synapse = None):
        self.bias = bias # Schwellwert
        self.weight = 0
        self.synapse = synapse

    def addValue(self, value):
        self.weight += value
        self._output()

    def _output(self):
        print(1 if hlim(self.weight-self.bias) else "not fired")

class Input(object):
    def __init__(self, synapse = None):
         self.synapse = synapse

    def setInput(self, value):
         val = self.synapse.weight * value
         self.synapse.destination.addValue(val)

if __name__ == "__main__":
    # AND
    print("-AND-------")
    print("1&1")
    n = Neuron(1.5)
    x1 = Input()
    x2 = Input()
    s1 = Synapse(x1, n, 1)
    s2 = Synapse(x2, n, 1)
    x1.setInput(1)
    x2.setInput(1)

    # OR
    print("-OR--------")
    print("0|0")
    n = Neuron(0.5)
    s1 = Synapse(x1, n, 1)
    s2 = Synapse(x2, n, 1)
    x1.setInput(0)
    x2.setInput(0)

    # NOT
    print("-NOT----------")
    print("~0")
    n = Neuron(-0.5)
    x = Input()
    s = Synapse(x, n, -1.0)
    x.setInput(0)


texts:
I've decided to learn Haskell by following the current Coursera algorithms course using Haskell to implement the algorithms discussed.

First up is merge sort, which I've implemented as shown here. I'm brand new to Haskell so looking for any suggestions for improvements to the code - it seems quite verbose - and pointers on anything I may be doing wrong or in a weird way because I don't know what I'm doing.

module Main where

import System.Environment

main :: IO ()
main = do
  args <- getArgs
  mapM_ putStrLn $ sort args

sort :: (Ord a) => [a] -> [a]
sort xs = reduce True $ map (arr) xs

arr :: a -> [a]
arr x = [x]

reduce :: (Ord a) => Bool -> [[a]] -> [a]
reduce _ []            = []
reduce forwards (x:[]) = if forwards then x else reverse x
reduce forwards xs     = reduce (not forwards) (combine forwards [] xs)

combine :: (Ord a)   => Bool -> [[a]] -> [[a]] -> [[a]]
combine forwards acc []       = acc
combine forwards acc (x:[])   = (reverse x):acc
combine forwards acc (x:y:zs) = let merged = merge forwards x y
                                    acc'   = merged:acc
                                in  combine forwards acc' zs

merge :: (Ord a) => Bool -> [a] -> [a] -> [a]
merge forwards xs ys = mergeIter forwards [] xs ys

mergeIter :: (Ord a) => Bool -> [a] -> [a] -> [a] -> [a]
mergeIter _        acc [] []     = acc
mergeIter forwards acc (x:xs) [] = mergeIter forwards (x:acc) xs []
mergeIter forwards acc [] (y:ys) = mergeIter forwards (y:acc) [] ys
mergeIter forwards acc (x:xs) (y:ys)
    | x <=  y && forwards     = mergeIter forwards (x:acc) xs (y:ys)
    | x > y && not forwards   = mergeIter forwards (x:acc) xs (y:ys)
    | otherwise               = mergeIter forwards (y:acc) (x:xs) ys

One specific question I have is around recursive function with accumulator arguments - you'll see in the listing that I've had to create a mergeIter function just to allow a default for the initial argument for the accumulator.

As far as I can see Haskell doesn't support default values for arguments - should I be doing something else instead? A fold maybe?


texts: Get string distance for a pseudo fuzzy search

texts:
We are using the following for evaluating strings for a pseudo fuzzy search. Curious if anything sticks out as needing optimization

    function getEditDistance(a, b) {
    if (a.length == 0) return b.length;
    if (b.length == 0) return a.length;

    var matrix = [];
    var i;
    for (i = 0; i <= b.length; i++) {
        matrix[i] = [i];
    }

    var j;
    for (j = 0; j <= a.length; j++) {
        matrix[0][j] = j;
    }

    for (i = 1; i <= b.length; i++) {
        for (j = 1; j <= a.length; j++) {
            if (b.charAt(i - 1) == a.charAt(j - 1)) {
                matrix[i][j] = matrix[i - 1][j - 1];
            } else {
                matrix[i][j] = Math.min(matrix[i - 1][j - 1] + 1,
                    Math.min(matrix[i][j - 1] + 1,
                        matrix[i - 1][j] + 1));
            }
        }
    }

    return matrix[b.length][a.length];
};


texts: A genric extension method to filter Linq-EF queries

texts:
I have various types of EF entities, all of them have a navigation property called "Employee". When generating reports the user will have the option to filter the report according to the different employee properties (Cost Center, gender, etc.).

Something like this:

var courses = context.Courses
              .Where(c => c.Employee.CostCenterID == ccID
                     && c.Employee.Rank == rankID
                     ....
                    )
                    .ToList();

The real filter code is much more longer but this was just a hint. Anyway, I figured out an easier way of doing this filtering with an extension method using an interface:

public interface IFilterable
{
    Employee Employee
    {
        get;
        set;
    }
}

Then, I added partial classes to inherit the previous interface for different entities that has the Employee navigation property, for example:

public partial class Course: IFilterable
{
}

Then created the following generic method:

public static IQueryable<T> Filter<T>(this IQueryable<T> source, SearchCriteria sc)
    where T : class, IFilterable
{
    var filtered = source.Where(e => e.Employee.CostCenterID == sc.CostCenterID
        && e.Employee.Gender == sc.Gender
        .....
        );

     return filtered;
}

then simply I can use it like this on any class that inherits IFilterable:

var list = context.Courses.Filter(sc).ToList();

Note: the SearchCriteria is just a simple class that holds different employee properties.

Q: Is this the way to do it? or is there a more elegant way?


texts: My Python 3.6 script to detect stamp card redeem fraud and prepare a csv report

texts:
I have a requirement to write a Python 3.6 script which should be able to detect following case within a time period and be able to create a text file report that lists the condition violated and transaction that caused the violation:

Redeeming over 3 time on same stamp card within 10 mins

The required table in database for storing user and stamp card details has following structure-

Here the 'to_sate' column with values 2,3 and 4 means a card is redeemed.

Now, I have written following script to fulfill above requirement and it is working as expected. In my local environment it is taking 2.7 minutes to complete the process for 36000 records-

def insert_data(csv_import_path, csv_export_path):
    import time
    from multiprocessing import Pool
    import multiprocessing
    import pandas as pd
    import pymysql
    # Connect to the database
    engine = pymysql.connect(host='localhost',
                             user='admin',
                             password='MY_PASSWORD',
                             db='MY_DB',
                             charset='utf8mb4',
                             cursorclass=pymysql.cursors.DictCursor)
    df = pd.read_sql(
        "SELECT stamps_record_id, user_id,  stamp_card_id, stamp_time, merchant_id, merchant_store_id FROM rmsdb.user_stamping_records where to_state in (2,3,4) order by stamp_card_id",
        engine)
    df.to_csv(csv_import_path)
    df = pd.read_csv(csv_import_path, index_col=["stamps_record_id"])
    unique_users = df.user_id.unique()
    df["stamp_time"] = pd.to_datetime(df["stamp_time"])
    num_processes = multiprocessing.cpu_count()
    s_time = time.time()
    with Pool(num_processes) as p:
        final_df = pd.DataFrame()
        for i in range(0, len(unique_users)):
            user = unique_users[i]
            new_df = df[df.user_id == user]
            sid = new_df.stamp_card_id.unique()
            for i in sid:
                fdf = new_df[new_df.stamp_card_id == i]
                # len(fdf) can be user given value
                if len(fdf) > 3:
                    for i in range(0, len(fdf)):
                        g = (fdf.iloc[i:i + 3])
                        if len(g) >= 3:
                            x = (g.tail(1).stamp_time.values - g.head(1).stamp_time.values).astype("timedelta64[s]")
                            if x[0].astype(int) < 600:
                                final_df = final_df.append(g)

    e_time = time.time() - s_time
    #     final_df.drop_duplicates(keep="first").to_csv("C:\\Users\\rahul.khanna\\Desktop\\user_stamping_records_frauds.csv", index=False)
    final_df.drop_duplicates(keep="first").to_csv(csv_export_path, index=False)

    print("Total Time taken is: " + str(e_time / 60) + " minutes.")

if __name__ == '__main__':
    insert_data("C:\\Users\\hitman\\Desktop\\user_stamping_records_import.csv", "C:\\Users\\hitman\\Desktop\\user_stamping_records_frauds.csv")

I have converted the df to dictionary for a sample-

34198: '2018-10-13 16:48:03', 34199: '2018-10-13 16:48:03', 34200: '2018-10-13 16:48:03', 34201: '2018-10-13 16:48:03', 34202: '2018-10-13 16:48:03', 34203: '2018-10-13 16:48:03', 34204: '2018-10-13 16:48:03', 34205: '2018-10-13 16:48:03', 34206: '2018-10-13 16:48:03', 34207: '2018-10-13 16:48:03', 34208: '2018-10-13 16:48:03'

Before moving my script to production, I need your suggestion for any improvement in my code.

Can anyone please have a look on my code and let me know any improvement in it?

Let me know also if I forgot to include any required information here.


texts: Simple finite difference employing Maccormack technique

texts:
I am relatively new to programming and while I am fairly comfortable with the math, I cannot say with confidence that I feel the same way with programming. Anyway here is a simple finite difference employing Maccormack technique. There are some lines with similar commands and I am sure there is a way to make this more compact. Especially with for loops and making some lines disappear due to redundancy which I cannot figure out.

import numpy as np

dx=0.1
t_max=3.1
dt=.1
gamma=1.4
C=0.5

k=np.arange(0,t_max,dt)
x=np.arange(0,3.1,dx)

s=len(x)
r=len(k)

T=1-0.2314*x  #initial condition
rho=1-0.3146*x #initial condition
V=(0.1+1.09*x)*np.sqrt(T)   #initial condition

rho_t=np.zeros([s])
V_t=np.zeros([s])
T_t=np.zeros([s])
t=np.ones([s])
rho_bar=np.ones([s])
V_bar=np.ones([s])
T_bar=np.ones([s])
rho_tbar=np.ones([s])
V_tbar=np.ones([s])
T_tbar=np.ones([s])
rho_avg=np.ones([s])
T_avg=np.ones([s])
V_avg=np.ones([s])
rho_r=np.zeros([s,r])
V_r=np.zeros([s,r])
T_r=np.zeros([s,r])

for n in range(0,r): #time step
    V[0]=2*V[1]-V[2]  # Subsonic Inflow Boundary
    V[30]=2*V[29]-V[28] # Supersonic Outflow Boundary
    rho[30]=2*rho[29]-rho[28] # Supersonic Outflow Boundary
    T[30]=2*T[29]-T[28] # Supersonic Outflow Boundary
    V_r[:,n]=V # compliation of flowfield variable at each timestep
    T_r[:,n]=T # compliation of flowfield variable at each timestep
    rho_r[:,n]=rho # compliation of flowfield variable at each timestep
    for i in range(1,s-1):
# Predictor Step
        rho_t[i]=-rho[i]/dx*(V[i+1]-V[i])-rho[i]*V[i]/dx*(np.log1p(A[i+1])-np.log1p(A[i]))-V[i]/dx*(rho[i+1]-rho[i])
        V_t[i]=-V[i]/dx*(V[i+1]-V[i])-1/gamma*((T[i+1]-T[i])/dx+T[i]/rho[i]/dx*(rho[i+1]-rho[i]))
        T_t[i]=-V[i]/dx*(T[i+1]-T[i])-(gamma-1)*T[i]*((V[i+1]-V[i])/dx+V[i]/dx*(np.log1p(A[i+1])-np.log1p(A[i])))

        t[i]=C*dx/(np.sqrt(T[i])+V[i]) # time step

        rho_bar[i]=rho[i]+rho_t[i]*min(t)
        V_bar[i]=V[i]+V_t[i]*min(t)
        T_bar[i]=T[i]+T_t[i]*min(t)

        rho_tbar[i]=-rho_bar[i]/dx*(V_bar[i]-V_bar[i-1])-rho_bar[i]*V_bar[i]/dx*(np.log1p(A[i])-np.log1p(A[i-1]))-V_bar[i]/dx*(rho_bar[i]-rho_bar[i-1]) #t=t+dt
        V_tbar[i]=-V_bar[i]/dx*(V_bar[i]-V_bar[i-1])-1/gamma*((T_bar[i]-T[i-1])/dx+T_bar[i]/rho_bar[i]/dx*(rho_bar[i]-rho[i-1]))    #t=t+dt
        T_tbar[i]=-V_bar[i]/dx*(T_bar[i]-T_bar[i-1])-(gamma-1)*T_bar[i]*((V[i]-V[i-1])/dx+V_bar[i]/dx*(np.log1p(A[i])-np.log1p(A[i-1])))   #t=t+dt

        rho_avg[i]=0.5*(rho_t[i]+rho_tbar[i])
        T_avg[i]=0.5*(T_t[i]+T_tbar[i])
        V_avg[i]=0.5*(V_t[i]+V_tbar[i])

        t[i]=C*dx/(np.sqrt(T[i])+V[i]) # time step

        rho[i]=rho[i]+rho_avg[i]*min(t)
        V[i]=V[i]+V_avg[i]*min(t)
        T[i]=T[i]+T_avg[i]*min(t)


texts:
Basically, all I have to do is read some xml from a file. And I have a working solution, although I am not sure that it is the best way of going about doing things, as I have only recently started working with xml. Any advice on how I could improve the following?

[XmlRoot("iosLayout")]
public class iosLayoutXml
{
    [XmlElement("transactionLayout")]
    public List<TransactionLayoutXml> transactionLayouts { get; set; } = new List<TransactionLayoutXml>();
}

[XmlRoot("transactionLayout")]
public class TransactionLayoutXml
{
    [XmlElement("field")]
    public List<FieldXml> fields { get; set; } = new List<FieldXml>();

    [XmlAttribute("type")]
    public string type { get; set; }
}

[XmlRoot("field")]
public class FieldXml
{
    [XmlAttribute("element")]
    public string element { get; set; }

    [XmlAttribute("text")]
    public string text { get; set; }

    [XmlAttribute("value")]
    public string value { get; set; }
}


texts: Memory optimization when finding the Cartesian product in Python

texts:
My function gets the Cartesian product of a list of lists of tuples.  The function is correctly producing the list of lists, but it's a memory hog (and leads to a MemoryError for large data sets, with the mapping/casting line probably the biggest culprit) and I have very little experience optimizing code with memory in mind.  The function is given here:

def make_ratio_groups(self):

    list_of_lists_of_tuples = []
    for part in whole:
        list_of_lists_of_tuples.append(part.list_of_tuples)

    all_groups = itertools.product(*list_of_lists_of_tuples)

    # Mapping and casting to list is necessary to put in the correct format for a subsequent function
    all_groups_list = list(map(list, all_groups))

    return all_groups_list

Is there a more memory-efficient way of doing this?  Thanks in advance for your time and patience.

Edit:  It's definitely the mapping and casting that's causing the problem.  I created a generator that handled the Cartesian product calculations and didn't see a big improvement in performance, so I tried profiling and found that the mapping/casting is definitely the issue.


texts:
I recently bought a 4x4 keypad.
It is one like this:
http://www.learningaboutelectronics.com/images/4x4-matrix-keypad-pinout.png

Now every code I found on the net was either using a highly overloaded library or was poorly hacked by a guy in the arduino forums.
I realized that almost all blogs about electronics just seem to copypaste the same code and changing the pictures so I felt like I had to work out something by myself.

Now, the common explained "tactic" was to iterate through every column and give it a LOW signal [for button pressed DOWN] and then check if anything came in at the row sides.Then use a technique from video game programming to make sure the button would not stay in a pin-down state [so one press would count at a time and not a press occurred every whatsomany nanoseconds].

I was highly uncomfortable with this solution, so I came up with this code:

/* Reverse Keypad Handler
 * 2nd version
 * by clockw0rk @ 26.02.2017
 */

//define rows and columns
byte row [4] = {9,8,7,6};
byte col [4] = {5,4,3,2};

byte counter = 0;
byte colCount;

//16 fields keymapping 4x4 matrix
byte keys [ 0x4 ] [ 0x4 ] =
{
   {0x1,0x2,0x3,0xA},
   {0x4,0x5,0x6,0xB},
   {0x7,0x8,0x9,0xC},
   {0xE,0x0,0xF,0xD}
};

void setup() {
  for(int c = 0; c != 4; c++)
  {
    pinMode (row[c], INPUT_PULLUP);
    pinMode (col[c], OUTPUT);
    digitalWrite(col[c], LOW);
  }

   Serial.begin (9600);  //9600 BAUD for Uno Board Serial Communication
   Serial.println("INITIALISATION FINISHED\nEntering work loop...\n");

}

void loop() {

  // cycle through input pins and check for a signal
  if(digitalRead(row[counter]) == 0)
  {
    checkRoutine();
  }

  //reset counter for each iteration cycle
  counter <3 ? counter++ : counter = 0;

}

void checkRoutine(){

  colCount = 0;

  //debugging: give me the linecount
  Serial.print("[ LOW ] on line ");
  Serial.print(counter);
  Serial.print("\n");

  //now find which number is pressed
  while(colCount < 4 && digitalRead(row[counter]) == 0)
  {
     digitalWrite(col[colCount], HIGH);
     colCount++;
  }

  //remember we incremented in while loop
  Serial.print("Button pressed is [ ");
  Serial.print(keys[counter][colCount -1]);
  Serial.print(" ]\n");

  //reinitialise output
  for(int c = 0; c != 4; c++)
  {
        digitalWrite(col[c], LOW);
  }

  //wait until user releases button
  while(digitalRead(row[counter])==0)
  {;}
}

As you can see, I reversed the idea (kind of) by giving every output a permanent LOW and made sure the program flow is stopped until the user releases the button.

I would like to hear your thougths on this solution.
Is it wasting memory or CPU time?
Arduino programming is absolutely fun but I just recently started with it and want to get better so I ask all of you "old veterans" to look over the lines and give me a feedback.


texts: Constructing a query string using StringBuilder

texts:
I speedily wrote a bunch of crappy checks, to check whether strings are empty, in order to build a query string.

StringBuilder SB = new StringBuilder();

SB.AppendFormat("{0}guide/search.aspx?", root);

root is a const, containing the website address.
It's like this because we have test servers.

if (!String.IsNullOrEmpty(item)) {
    SB.AppendFormat("&i={0}", Server.UrlEncode(item));
}
if (!String.IsNullOrEmpty(found)) {
      SB.AppendFormat("&f={0}", Server.UrlEncode(found));
}
if (!String.IsNullOrEmpty(what)) {
      SB.AppendFormat("&wt={0}", Server.UrlEncode(what));
}
if (!String.IsNullOrEmpty(where)) {
      SB.AppendFormat("&wr={0}", Server.UrlEncode(where));
}

I tried replacing these with ternaries, but I couldn't get my head around how to do that with the sb.AppendFormat in place.

Is there a better way to check empty strings than -String.IsNullOrEmpty?
Is my method of naming variables correct with C# standards?
Is Server.UrlEncode the best way to format strings into query strings?


texts: Still learning, looking for general advice about a 4-function calculator I programmed using java

texts:
here's some code I wrote in java SE to get use to if statements and scanning. just looking for suggestions that will improve this program or/and teach me techniques that I should get use to using.
import java.util.Scanner;

public class Calculator {
   public static void main(String[] args) {
      System.out.print("Enter the first value ");
      Scanner scan = new Scanner(System.in);
      int x = scan.nextInt();
      System.out.print("Enter the next value ");
      int y = scan.nextInt();
      System.out.println("Choose an operation: 1-multiply 2-divide 3-add 4-subtract");
      int z = scan.nextInt();
      if (z == 1) {
         int a = x * y;
         System.out.println("Result: " + a);
      }//end of if multiply
      else if (z == 2) {
         int a = x / y;
         System.out.println("Result: " + a);
      }//end of if divide
      else if (z == 3) {
         int a = x + y;
         System.out.println("Result: " + a);
      }// end of if add
      else {
         int a = x-y;
         System.out.println("Result: " + a);
      } //end of is subtract
   }// End of main
}// End of public class

here's my new program, still not perfect but the class i'm taken hasn't even gone over data types and classes yet so i'm already ahead lol
Thank you every one for your help!
import java.util.Scanner;

 public class Calculatortwo {
   public static void main(String[] args) {
   //get imput values from user
      System.out.print("Enter the first value ");
      Scanner scan = new Scanner(System.in);
      double x = scan.nextDouble();
      System.out.print("Enter the next value ");
      double y = scan.nextDouble();
      System.out.println("Choose an operation: 1-multiply 2-divide 3-add 4-subtract");
      int operation = scan.nextInt();
    //calculator logic
      double result = 0;
      switch (operation) {
       case 1:
         result = x * y;
         break;
       case 2:
         if(y != 0) {
         result = x / y;
        }
        else {
        System.out.println("Error: Divide by 0");
        }
         break;
       case 3:
         result = x + y;
         break;
       case 4:
         result = x - y;
         break;
         default:
            System.out.println("Error: operation not found");
      }
            System.out.println("Result: " + result);
   }
}


texts: Automatic variable generation from data table

texts:
I am adjusting Fast Report to create some reports, and I have created a loop that runs through query results stored inside a datatable and assigns each TenantName to a variable. However, the code I wrote seems bulky and would get out of hand if I needed more variables.

Would there be a more sensible way to do this?

If cmbReports.Text = "Conditions Of Tenancy" Then
        Dim ListReport = New FastReport.Report
        ListReport.Load("C:\Users\richard\Documents\BMSSouthSide\BMSPanda\Reports\CONDITIONSOFTENANCY.frx")
        ListReport.SetParameterValue("CRMConnectionString", "Data ..... ")
        Dim strSql As String = "Select  TenantForename + ' ' + TenantSurname as FullName From Tenants Where '" & lblLeaseIDValue.Text & "' = LeaseID and PropertyID =" & lblPropertyIDValue.Text
        Dim dtb As New DataTable
        Dim ten1 As String
        Dim ten2 As String
        Dim ten3 As String
        Dim ten4 As String
        Dim ten5 As String
        Dim ten6 As String
        Dim ten7 As String
        Dim ten8 As String
        Dim ten9 As String
        Dim ten10 As String
        Dim ten11 As String
        Dim IntTenantID As Integer
        Using cnn As New SqlConnection(My.Settings.BMSSouthSideConnectionString)
            cnn.Open()
            Using dad As New SqlDataAdapter(strSql, cnn)
                dad.Fill(dtb)
            End Using
            Dim Ten As Integer = dtb.Rows.Count
            Do Until Ten = 0
                For Each row As DataRow In dtb.Rows
                    If Ten = 11 Then Ten1 = row("FullName")
                    If Ten = 10 Then Ten2 = row("FullName")
                    If Ten = 9 Then Ten3 = row("FullName")
                    If Ten = 8 Then Ten4 = row("FullName")
                    If Ten = 7 Then Ten5 = row("FullName")
                    If Ten = 6 Then Ten6 = row("FullName")
                    If Ten = 5 Then Ten7 = row("FullName")
                    If Ten = 4 Then Ten8 = row("FullName")
                    If Ten = 3 Then Ten9 = row("FullName")
                    If Ten = 2 Then Ten10 = row("FullName")
                    If Ten = 1 Then Ten11 = row("FullName")
                    Ten = Ten - 1T
                Next row
            Loop
            Dim strSql2 As String = "Select Top 1 TenantID From Tenants Where '" & lblLeaseIDValue.Text & "' = LeaseID and PropertyID =" & lblPropertyIDValue.Text
            Dim datatableTenantID As New DataTable
            Using Tenant As New SqlDataAdapter(strSql2, cnn)
                Tenant.Fill(datatableTenantID)
            End Using
            For Each IntTenant As DataRow In datatableTenantID.Rows
                IntTenantID = IntTenant("TenantID")
            Next
            cnn.Close()
        End Using
        Dim TenantList As String = Ten11 & " " & Ten10 & " " & Ten9 & " " & Ten8 & " " & Ten7 & " " & Ten6 & " " & Ten5 & " " & Ten4 & " " & Ten3 & " " & Ten2 & " " & Ten1
        ListReport.SetParameterValue("PropertyID", Val(lblPropertyIDValue.Text))
        ListReport.SetParameterValue("LeaseID", Val(lblLeaseIDValue.Text))
        ListReport.SetParameterValue("TenantID", IntTenantID)
        ListReport.SetParameterValue("TenantList", TenantList)
        ListReport.Show()
    End If


texts:
I have two database table name called "tablestr table" and "restbookingtable":

tablestr:

restbooking:

I want to retrieve bookingsection_id from the booking table with a few conditiona and need to remove from tablestr. I have a query for this, but I could achieve it by using subquery, which executes very slowly.

SELECT `str_id` FROM (`rest_tablestr`) WHERE str_id NOT IN (
SELECT SUBSTRING_INDEX(SUBSTRING_INDEX(t.bookingsection_id, ",", n.n), ",", -1) value FROM rest_restaurantbooking t
CROSS JOIN (
SELECT a.N + b.N * 10 + 1 n FROM (
SELECT 0 AS N
UNION ALL
SELECT 1
UNION ALL
SELECT 2
UNION ALL
SELECT 3
UNION ALL
SELECT 4
UNION ALL
SELECT 5
UNION ALL
SELECT 6
UNION ALL
SELECT 7
UNION ALL
SELECT 8
UNION ALL
SELECT 9) a , (
SELECT 0 AS N
UNION ALL
SELECT 1
UNION ALL
SELECT 2
UNION ALL
SELECT 3
UNION ALL
SELECT 4
UNION ALL
SELECT 5
UNION ALL
SELECT 6
UNION ALL
SELECT 7
UNION ALL
SELECT 8
UNION ALL SELECT 9)
b ORDER BY n ) n
WHERE n.n <= 1 + (LENGTH(t.bookingsection_id) -
LENGTH(REPLACE(t.bookingsection_id, ",", ""))) AND
t.res_id = 21 AND
t.booking_status not in ("cancelled","departed","noshow") AND
((t.bookingstart_time <= "2015-06-12 19:45:00" AND t.bookingend_time >= "2015-06-12 22:15:00") OR
(t.bookingend_time >= "2015-06-12 19:45:00" AND t.bookingend_time <= "2015-06-12 22:15:00") OR
(t.bookingstart_time >= "2015-06-12 19:45:00" AND t.bookingstart_time <= "2015-06-12 22:15:00") OR
(t.bookingstart_time >= "2015-06-12 19:45:00" AND t.bookingend_time <= "2015-06-12 22:15:00")) ) AND
`res_id` = '21' AND
`area_id` = '28' AND
`wait_table` = 'no' AND
`availability` = 'yes';

Result Set:

When I execute the subquery and main query, the separate execution time is just 0.1 sec. But while executing both, execution time is takes more than 5 to 7 seconds. How can I optimize this query?


texts:
Problem: What is the largest prime factor of the number 600851475143?

Hi, I'm really new with Python. Can anyone give me some feedback for this code? it seem to produce the correct answer

a=600851475143
x=2
while x<(a/x):
    if a%x==0: a=a/x
    else: x+=1

print a


texts: Is there any way to shorten up this Facebook API call?

texts:
Right now I am working on an AJAX call that grabs a random photo that a Facebook user is tagged in and then grabs the large source for it. Is there any way to speed this up or at least distill the call into one query?

var query1 = encodeURI("SELECT pid,xcoord,ycoord FROM photo_tag WHERE subject={{mystery.uid}} order by rand() LIMIT 1");
var query2 = encodeURI("SELECT src_big FROM photo WHERE pid=");

function get_pic() {
        var l = $.get("https://graph.facebook.com/fql?q="+query1,
                {access_token: "{{token}}"},
                function(data1) {
                        $.get("https://graph.facebook.com/fql?q="+query2+data1.data[0].pid,
                        {access_token: "{{token}}"},
                        function(data2) {
                                $("#mystery_img").html('');
                                var top = $("#mystery_img img").offset().top + Math.floor(data1.data[0].ycoord);
                                var left = $("#mystery_img img").offset().left + Math.floor(data1.data[0].xcoord);
                                var img = $(document.createElement('img')).attr({src: "/static/images/curved_arrow.gif"})
                                    .css('position', 'absolute')
                                    .css('top', top)
                                    .css('left', left);
                                    $("#mystery_img").append(img);
                        },
                        "json");
                },
                "json");
    }


texts: Symlinking git-managed dotfiles into a home directory

texts:
As a learning exercise, I decided to write a script for helping me maintain my Unix configuration/dot-files under a git repository. I check out a copy of the repository in my home directory called .dotfiles, and, inside that, I have the Python script called linkify, which deals with creating links from my home directory to the real files inside the .dotfiles directory.

For your reference, the respective code is in my GitHub repository.

#!/usr/bin/env python

import errno
import os

to_keep_private = [
    'cifs-credentials',
    'config',
    'fetchmailrc',
    'gitconfig',
    'gnupg',
    'mpoprc',
    'msmtprc',
    'mutt',
    'netrc',
    'offlineimaprc',
    'pim',
    'purple',
    'quodlibet',
    'ssh',
    ]

to_ignore = [
    '.',
    '.git',
    '.gitignore',
    'linkify',
]

def make_private(files=[]):
    if len(files) == 0:
        files = os.listdir('.')
    else:
        # Use the list of files passed by the user, if it is not empty
        pass
    for filename in files:
        if os.path.isdir(filename):
            os.chmod(filename, 0700)
        else:
            os.chmod(filename, 0600)

def linkify(files=[]):
    if len(files) == 0:
        files = os.listdir('.')
    else:
        # Use the list of files passed by the user, if it is not empty
        pass

    os.chdir(os.path.join(os.environ['HOME'], '.dotfiles'))
    for source in files:
        if source not in to_ignore:
            target = os.path.join('..', '.' + source)
            source = os.path.join('.dotfiles', source)
            try:
                os.unlink(target)
            except OSError, e:
                if e.errno == errno.ENOENT:
                    pass
                elif e.errno == errno.EISDIR:
                    print("%s is a directory. Ignoring." % target)
                else:
                    print errno.errorcode[e.errno]
            finally:
                os.symlink(source, target)

def add_hook():
    f = open('.git/hooks/post-commit', 'w')
    f.write('#!/bin/sh\ngit push\n')
    f.close()
    os.chmod('.git/hooks/post-commit', 0755)

def parse_cli():
    import optparse
    parser = optparse.OptionParser()

    parser.add_option('-H',
                      '--install-hook',
                      help='Install git hook for automatic push.',
                      action='store_true',
                      default=False)
    parser.add_option('-n',
                      '--no-linkify',
                      help='Disable creation of symlinks',
                      action='store_true',
                      default=False)
    parser.add_option('-P',
                      '--no-fix-perms',
                      help='Disable fix of permission for private files.',
                      action='store_true',
                      default=False)

    return parser.parse_args()

if __name__ == '__main__':
    opts, args = parse_cli()

    if not opts.no_linkify:
        linkify(args)
    if not opts.no_fix_perms:
        make_private(args)
    if opts.install_hook:
        add_hook()


texts:
An office has a bathroom that can be used by both men and women, but not both at the same time. If a man is in the bathroom, other men may enter, but any women wishing to use the bathroom should wait for it to be empty. If a woman is in the bathroom, other women may enter, but any men wishing to use the bathroom should wait it to be empty. Each person (man or woman) will spend some time using the bathroom.

package basics.problems;

    //BATHROOM_SIZE - 5
    //2 types of threads - MEN and WOMEN
    import java.util.concurrent.Semaphore;
    import java.util.concurrent.atomic.AtomicInteger;

    public class UniSexBathroom {
        AtomicInteger currentSize;
        int capacity;
        Semaphore noOfEntriesSemaphore;
        Semaphore currentGenderSemaphore = new Semaphore(1);
        volatile Person currentGender;

        public UniSexBathroom(int capacity) {
            this.capacity = capacity;
            this.noOfEntriesSemaphore = new Semaphore(capacity);
            this.currentSize =  new AtomicInteger(0);
        }

        public void occupy(Person personSex) throws InterruptedException {
            acquireGenderSemaphore(personSex);
            useBathroomAndExit(personSex);
            releaseGenderSemaphore(personSex);
        }

        private void releaseGenderSemaphore(Person personSex) {
            if(currentSize.get()==0){
                currentGenderSemaphore.release();
                currentGender = null;
                System.out.println(personSex.type+ Thread.currentThread().getName()+" releasing gender semaphore");
            }
        }

        private void useBathroomAndExit(Person personSex) throws InterruptedException {
            noOfEntriesSemaphore.acquire();
            currentSize.incrementAndGet();
            System.out.println(personSex.type +  Thread.currentThread().getName()+" is stepping in, current capacity is : "+currentSize.get());
            Thread.sleep(100);
            noOfEntriesSemaphore.release();
            currentSize.decrementAndGet();
            System.out.println(personSex.type +  Thread.currentThread().getName()+" is stepping out, current capacity is : "+ currentSize.get() +"-----------------");
        }

        private void acquireGenderSemaphore(Person personSex) throws InterruptedException {
            if(currentSize.get() == 0){
                currentGenderSemaphore.acquire();
                currentGender = personSex;
            }
            if(!personSex.type.equals(currentGender.type)){
                currentGenderSemaphore.acquire();
                currentGender = personSex;
            }
        }

        public static void main(String[] args){
            UniSexBathroom uniSexBathroom = new UniSexBathroom(2);
            new Thread(new PersonThread(uniSexBathroom, Person.MALE)).start();
            new Thread(new PersonThread(uniSexBathroom, Person.MALE)).start();
            new Thread(new PersonThread(uniSexBathroom, Person.MALE)).start();
            new Thread(new PersonThread(uniSexBathroom, Person.MALE)).start();

            new Thread(new PersonThread(uniSexBathroom, Person.FEMALE)).start();
            new Thread(new PersonThread(uniSexBathroom, Person.MALE)).start();
            new Thread(new PersonThread(uniSexBathroom, Person.FEMALE)).start();
        }
    }

    enum Person {
        MALE("Male"), FEMALE("Female");
        String type;

        Person(String type) {
            this.type = type;
        }
    }

    class PersonThread implements Runnable {
        public UniSexBathroom uniSexBathroom;
        public Person person;
        public PersonThread(UniSexBathroom uniSexBathroom, Person person){
            this.uniSexBathroom = uniSexBathroom;
            this.person = person;
        }

        @Override
        public void run() {
            try {
                uniSexBathroom.occupy(person);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }


texts:
This is a follow-up to this question my code has evolved since so I'm reposting my question.

What is the best way to tidy this up? How can this be refined? I am finding it's thrashing the layout quite a lot and the scroll function seems to lag.

;(function ($, window) {
var main = $("#swab"),
    sbContainer = $("#sb-container"),
    sbContainerDiv = sbContainer.find("div"),
    tblcontents = $('#tblcontents'),
    tblcontentstwo = $('#tblcontents_2'),
    button = $('#wrap_return, .thumb, #tblcontents'),
    slideele = $('.site, .menu-panel'),
    slideele2 = $('.site, .menu-panel_2');

function animate() {
    sbContainerDiv.css({
        "transform": "rotate(0deg)",
            "-webkit-transform": "rotate(0deg)",
            "-ms-transform": "rotate(0deg)",
            "-moz-transform": "rotate(0deg)",
            "-o-transform": "rotate(0deg)"
    });

    main.animate({
        "right": "1%",
            "left": "auto",
            "top": "4px"
    }, "slow");
}

function toggletwo() {

    var toggleStatetwo = true;
    $(tblcontents).on("click", function () {
        if (toggleStatetwo) {
            animate({
                "top": "15%"
            });
            main.fadeOut(1000);
        } else {
            animate();
            main.fadeIn(1000);
        }
        toggleStatetwo = !toggleStatetwo;
    });

}

function toggleone() {
    $(tblcontents).on("click", function () {
        main.stop(true, true).animate();
    });

}

var $window = $(window);
$window.resize(function () {
    if (this.resizeTO) clearTimeout(this.resizeTO);

    this.resizeTO = setTimeout(function () {
        $(this).trigger('resizeEnd');
    }, 500);
});

$window.on('resizeEnd', function () {
    var winWidth = $window.width();

    if (winWidth < 960) {
        toggletwo();
        animate();
    } else {
        toggleone();
    }
});

$(document).scroll(function () {
    animate();
});
var toggleState = true;
$('#toggle_div').on("click", function () {
    if (toggleState) {
        main.animate({
            "right": "50%"
        }, "slow");
    } else {
        main.animate({
            "right": "1%",
                "top": "4px"
        }, "slow");
        main.css("left", "auto");
    }
    toggleState = !toggleState;
});

$(tblcontents).effect("pulsate", {
    times: 100
}, 2000).on('click', function () {
    $(this).effect().stop(true, true);
    $(this).animate({
        "opacity": "1"
    }, "fast");
});
$(button).on("click", function () {
    animate({
        "top": "4px"
    }, "slow");
});
main.draggable()

$(function () {

    sbContainer.swatchbook({
        center: 6,
        angleInc: 20,
        speed: 700,
        easing: 'ease',
        proximity: 120,
        neighbor: 20,
        onLoadAnim: true,
        initclosed: true,
        closeIdx: 11,
        openAt: -1

    });
});

var toggleStatemenu2 = true;
$(tblcontentstwo).on("click", function () {
    if (toggleStatemenu2) {
        $(slideele2).animate({
            top: '+=171'
        }, 458, 'swing', function () {});
    } else {
        $(slideele2).animate({
            top: '-=171'
        }, 458, 'swing', function () {});
    }
    toggleStatemenu2 = !toggleStatemenu2;
});
var toggleStatemenu = true;
$(tblcontents).on("click", function () {
    if (toggleStatemenu) {
        $(slideele).animate({
            left: '+=240'
        }, 458, 'swing', function () {});
    } else {
        $(slideele).animate({
            left: '-=240'
        }, 458, 'swing', function () {});
    }
    toggleStatemenu = !toggleStatemenu;
});

})(jQuery, window, document);


texts:
The exercise is from Alex Allain's book "Jumping into C++".
From Chapter 10 Practical Problem 4:

  Write a small tic-tac-toe program that allows two players to play
  tic-tac-toe competitively. Your program should check to see if either
  player has won, or if the board is filled completely (with the game
  ending in a tie). Bonus: can you make your program detect if the game
  cannot be won by either side before the entire grid is filled?

Here's my code. My main goal was a functioning tick-tack-toe game with little concern on the user experience (e.g.: the coordinates a player enters start from 0, or (0,0) coordinate is in the upper left corner no lower left as one would intuitively think). As for coding style I wanted the code to be as DRY as possible, with small, atomic, easy to understand functions doing most of the work.

#include <iostream>

using namespace std;

bool checkWin(int board[][3], int player) {
    // horizontal
    for (int i = 0; i < 3; i++) {
        if (board[i][0] == player && board[i][1] == player && board[i][2] == player) return true;
    }

    // vertical
    for (int i = 0; i < 3; i++) {
        if (board[0][i] == player && board[1][i] == player && board[2][i] == player) return true;
    }

    // diagonal
    if ((board[0][0] == player && board[1][1] == player && board[2][2] == player) ||
        (board[0][2] == player && board[1][1] == player && board[2][0] == player))
        return true;

    return false;
}

// TODO implement function if the game is a tie before the last move

bool fillPlace(int board[][3], int x, int y, int value) {
    if (x > 2 || x < 0) {
        cout << "Invalid x coordinate. Try again.\n";
        return false;
    } else if (y > 2 || y < 0) {
        cout << "Invalid y coordinate. Try again.\n";
        return false;
    } else if (board[x][y] != 0) {
        cout << "Place is already filled. Try again.\n";
        return false;
    } else {
        board[x][y] = value;
        return true;
    }
}

void initBoard(int board[][3], int size) {
    for (int i = 0; i < size; i++) {
        for (int j = 0; j < 3; j++) {
            board[i][j] = 0;
        }
    }
}

void printBoard(int board[][3], int size) {
    cout << "-----" << endl;
    for (int i = 0; i < size; i++) {
        for (int j = 0; j < 3; j++) {
            cout << board[i][j] << " ";
        }
        cout << endl;
    }
    cout << "-----" << endl;
}

bool isBoardFilled(int board[][3]) {
    bool isFilled = true;
    for (int i = 0; i < 3; i++) {
        for (int j = 0; j < 3; j++) {
            if (board[i][j] == 0) isFilled = false;
        }
    }
    return isFilled;
}

int main() {

    int board[3][3];
    initBoard(board, 3);
    printBoard(board, 3);

    int playerOnesTurn = true;
    while (true) {
        int x, y;

        if (playerOnesTurn) {
            cout << "Player 1's turn" << endl;
            do {
                cout << "Enter x coordinate: "; cin >> x;
                cout << "Enter y coordinate: "; cin >> y;
            } while (!fillPlace(board, x, y, 1));
        } else {
            cout << "Player 2's turn" << endl;
            do {
                cout << "Enter x coordinate: "; cin >> x;
                cout << "Enter y coordinate: "; cin >> y;
            } while (!fillPlace(board, x, y, 2));
        }
        playerOnesTurn = !playerOnesTurn;

        if (isBoardFilled(board)) {
            cout << "The game is a tie.\n";
            break;
        }

        printBoard(board, 3);
        if (checkWin(board, 1)) {
            cout << "Player 1 has won\n";
            break;
        } else if (checkWin(board, 2)) {
            cout << "Player 2 has won\n";
            break;
        }
    }

    return 0;
}


texts:
I want to group the two very similar jQuery functions into just one. Any idea?

HTML:

<input id="progress" type="text" class="spinner-input form-control" maxlength="3" readonly value="<?php echo $progreso['progress'] ?>">

    <button id="plus" type="button" class="btn spinner-up btn-xs btn-info">

    </button>
    <button id="minus" type="button" class="btn spinner-down btn-xs btn-info">

    </button>

jQuery:

$(document).on('click', '#plus', function(e){
    var progress = parseInt( $('#progress').val() ) + 5;
    if ( progress <= 100 ) {
        $('#progress').val( progress );
    }
    else{
        $('#progress').val( 100 );
    };
});

$(document).on('click', '#minus', function(e){
    var progress = parseInt( $('#progress').val() ) - 5;
    if ( progress >= 0 ) {
        $('#progress').val( progress );
    }
    else{
        $('#progress').val( 0 );
    };
});


texts:
I am getting familiar with decorators, and after a couple of tutorials i came up with a decorator that might is useful for me. Is this the proper way to use decorators? Any suggestion about the code?

def timeit_decorator(original_function):
    import time
    import colorama

    def wrapper(*args, **kwargs):
        tm = time.time()
        res = original_function(*args, **kwargs)
        print("Function " + colorama.Fore.GREEN + original_function.__name__ + colorama.Style.RESET_ALL + " executed in " + colorama.Fore.GREEN + "~{:.2f}".format(
            (time.time() - tm) / 60) + colorama.Style.RESET_ALL + " minutes!")
        return res

    return wrapper

Example of usage:

@timeit_decorator
def display(msg):
    time.sleep(10)
    return msg

print(display(1))


texts: Print last Sunday of each month in a given year

texts:
I'm an experienced programmer trying to learn OCaml. I figured a good way to do that would be to pick a simple task on Rosetta code that didn't yet have an OCaml example and do it myself. With that in mind, I wrote this program to find the last sunday of each month in a given year. It works by using Gauss's algorithm to determine what day of the week the last day in each month of the year is and if it's not a Sunday it moves backwards until it is. I run it with "./ocaml sundays.ml N" where N is the year in question. Are there any spots where my code is written in a way unusual for OCaml developers or where there is a more OCamlish way of doing things?

let is_leap_year y =
  (* See OCaml solution on Rosetta Code for
     determing if it's a leap year *)
   if (y mod 100) = 0
     then (y mod 400) = 0
     else (y mod 4) = 0;;

let get_days aYear =
  if is_leap_year aYear
    then
      [31;29;31;30;31;30;31;31;30;31;30;31]
    else
      [31;28;31;30;31;30;31;31;30;31;30;31];;

let print_date y m d =
  print_int y;
  print_char '/';
  print_int m;
  print_char '/';
  print_int d;
  print_endline "";;

let get_day_of_week y m d =
  let y = if m > 2 then y else y - 1 in
  let c = y / 100 in
  let y = y mod 100 in
  let m_shifted = float_of_int ( ((m + 9) mod 12) + 1) in
  let m_factor = int_of_float (2.6 *. m_shifted -. 0.2) in
  let leap_factor = 5 * (y mod 4) + 3 * (y mod 7) + 5 * (c mod 4) in
  (d + m_factor + leap_factor) mod 7;;

let get_shift y m last_day =
  get_day_of_week y m last_day;;

let print_last_sunday y m =
  let days = get_days y in
  let last_day = List.nth days (m - 1) in
  let last_sunday = last_day - (get_shift  y m last_day) in
  print_date y m last_sunday;;

let print_last_sundays y =
  let months = [1;2;3;4;5;6;7;8;9;10;11;12] in
  List.iter (print_last_sunday y) months;;

match (Array.length Sys.argv ) with
  2 -> print_last_sundays( int_of_string (Sys.argv.(1)));
 |_ -> invalid_arg "Please enter a year";


texts: String compression using repeated character counts

texts:
Implement a method to perform basic string compression using the counts of
  repeated characters. For example, the string aabcccccaaa would become
  a2blc5a3. If the "compressed" string would not become smaller than the original string, your method should return the original string.

Can this be implemented in a better way performance-wise?

package string;

public class CompressChar {

    int[] seq = new int [256];

    public String compressString(String str){

        StringBuffer strComp = new StringBuffer();
        for( char c : str.toCharArray()){
            seq[c]++;
        }
        for (char c : str.toCharArray()){
            if(seq[c]>0){
                strComp.append(c).append(seq[c]);
                seq[c]=0;//so that it does not enter , when char occurs again
            }
        }

        if(str.length()<strComp.length()){
            return str;
        }
        return strComp.toString();

    }
    public static void main(String[] args) {
        CompressChar ch = new CompressChar();
        System.out.println(ch.compressString("abbcdrfac"));
    }
}


texts:
This little app converts 1-800 numbers (with letters) to actual numbers. I'm very frustrated by the insertDashes function as it's very brute force. I'm sure there's a far more elegant solution. I'd appreciate any feedback on anything else though.

module Dial
    ( enter,
    stripDashes
    ) where

import Data.Char (ord, toLower, isNumber, intToDigit, isPunctuation)
import System.IO
import Data.List

enter = do
    putStrLn "Enter a phone number"
    num <- getLine
    let converted = insertDashes $ convertLetters $ stripDashes num
    putStrLn $ "You may dial " ++ converted

stripDashes :: String -> String
stripDashes xs = [ x | x <- xs, not (elem x  "-") ]

insertDashes :: String -> String
insertDashes xs = take 1 xs ++ ['-'] ++ take 3 (drop 1 xs) ++ ['-'] ++ take 3 (drop 4 xs) ++ ['-'] ++ take 4 (drop 7 xs)

getDigit :: Char -> Int
getDigit letter
    | (ord letter >= 97) && (ord letter <= 99) = 2
    | ord letter <= 102 = 3
    | ord letter <= 105 = 4
    | ord letter <= 108 = 5
    | ord letter <= 111 = 6
    | ord letter <= 115 = 7
    | ord letter <= 118 = 8
    | ord letter <= 122 = 9
    | otherwise = 0

convertLetters :: String -> String
convertLetters xs = map (\x -> if (isNumber x) then x else (intToDigit $ getDigit $ toLower x)) xs


texts:
On our main symfony2 application at work I have had to manipulate some outputted grid fields by wrapping them in a hyperlink tag.  This happens in quite a few different controllers, so I made a method to do this to prevent code repetition.

I decided to do this using DOMDocument and construct the new hyperlink with that.

public function linkWrap($string, $route, array $route_params = [], $prefilter = null)
  {
    if(strlen($string) > 0)
    {
      $dom = new \DOMDocument();
      $new_hyper = $dom->createElement('a');
      $new_hyper->setAttribute('href', $this->generateUrl($route, $route_params).(isset($prefilter) ? '?'.htmlspecialchars($prefilter) : ''));
      $new_hyper->nodeValue = $string;

      return $dom->saveHTML($new_hyper);
    }

    return $string;
  }

The method takes a number of options the last of which is used only to append a prefilter query string for use with APYGridBundle.

My question is, does this cause a significantly larger overhead than just constructing the link in a more 'conventional' way?

As follows:

$link = "generateUrl('a_route', array('id' => 23)) . '?'.$prefilter">some text";

In addition, any tips on how any of could be improved would be appreciated.


texts:
I wanted to get some criticism for the below ADT. This is just a basic ADT that will be fed into a TVM calculator. Main purpose is to have it initialized and correct for input errors.

Full disclosure: I am modeling it after Code Complete 2 guidelines. You should notice if statements stating nominal cases first followed by error-checking in else statements. I am trying to come as close as possible to the guidelines in the book. However, it is difficult to grasp 900+ pages of material. Aside from the incompleteness of the class, what am I missing, or what would Code Complete 2 catch?

public class TVMData
{
public decimal DiscountRate;
public decimal PeriodLength;
public decimal CashFlowFromAsset;
public decimal CashOutFlow;
public decimal PaymentFrequency;

   decimal DiscountedCashFlow;

    public TVMData(){}

    public TVMData(double discountRate, double periodLength, double cashFlowFromAsset, double cashOutFlow, PaymentPerPeriod paymentFrequency= PaymentPerPeriod.Annual)
      : this(Convert.ToDecimal(discountRate), Convert.ToDecimal(periodLength), Convert.ToDecimal(cashFlowFromAsset), Convert.ToDecimal(cashOutFlow), paymentFrequency){}

    public TVMData (decimal discountRate, decimal periodLength, decimal cashFlowFromAsset, decimal cashOutFlow, PaymentPerPeriod paymentFrequency= PaymentPerPeriod.Annual)
    {
        this.PaymentFrequency = Convert.ToDecimal(paymentFrequency);

        if (discountRate>=0m)
        {
           this.DiscountRate= discountRate;

            if (periodLength >= 1m)
            {
                this.PeriodLength = periodLength;

                if(cashFlowFromAsset >= 0m)
                {

                 this.CashFlowFromAsset=cashFlowFromAsset;

                   if(cashOutFlow <= 0m)
                   {

                    this.CashOutFlow = cashOutFlow;

                   }

                   else
                   {
                    throw new ArgumentOutOfRangeException("Cash Out Flow must be less than or equal to Zero", "cashOutFlow");
                   }

                }

                else
                {
                throw new ArgumentOutOfRangeException("Cash Flow From Asset must be greater than Zero","cashFlowFromAsset");
                }

            }

            else
            {
            throw new ArgumentOutOfRangeException("Period Length must be equal or greater than One", "periodLength");
            }

        }

        else
        {
         throw new ArgumentOutOfRangeException("Discount Rate must be greater than Zero", "discountRate");
        }

     }

}


texts:
In the Object-Oriented Design Pattern Implementation chapter of the second edition of The Rust Programming Language, the basic code structure is given and it suggests trying to add features:

  This implementation is easy to extend to add more functionality. Here
  are some changes you can try making to the code in this section to see
  for yourself what it's like to maintain code using this pattern over
  time:

  Only allow adding text content when a post is in the Draft state
  Add a reject method that changes the post's state from PendingReview back to Draft
  Require two calls to approve before changing the state to Published

Please critique my approach:

struct Post {
    content: String
}

struct DraftPost {
    content: String
}

struct PendingPost {
    content: String,
    approvals: u32

}

impl Post {
    fn new() -> DraftPost {
        DraftPost { content: String::new() }
    }

    fn content(&self) -> &str {
        &self.content
    }
}

impl DraftPost {
    fn req_review(self) -> PendingPost {
        PendingPost {
            content: self.content,
            approvals: 0
        }
    }

    fn add_text(&mut self, content: &str) {
        self.content.push_str(content);
    }
}

enum PublishResult {
    PendingPost(PendingPost),
    Post(Post)
}

impl PendingPost {
    fn approve(&mut self) {
        self.approvals += 1;
    }
    fn reject(self) -> DraftPost {
        DraftPost { content: self.content }
    }
    fn publish(self) -> PublishResult {
        if self.approvals > 1 {
            PublishResult::Post(Post{content: self.content})
        } else {
            PublishResult::PendingPost(self)
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn publish_workflow() {
        let mut draft = Post::new();
        draft.add_text("ashish first post");
        let mut pending = draft.req_review();
        pending.approve();
        pending.approve();
        let publish = pending.publish();
        match publish {
            PublishResult::Post(p) => assert_eq!(p.content(),
                                                 "ashish first post"),
            _ => assert!(false)
        }
    }

    #[test]
    fn reject_workflow() {
        let mut draft = Post::new();
        draft.add_text("ashish first post");
        let pending = draft.req_review();
        let mut again_draft = pending.reject();
        again_draft.add_text(".. after first one..");
    }

    #[test]
    fn two_approvals_workflow() {
        let mut draft = Post::new();
        draft.add_text("ashish first post");
        let mut pending = draft.req_review();
        pending.approve();
        match pending.publish() {
            PublishResult::PendingPost(_) => assert!(true),
            _ => assert!(false)
        }
    }
}


texts: Writing a better alternative to jQuery Autocomplete

texts:
Over the last months I have been writing a jQuery plugin called Better Autocomplete (Code on Github). It originated from another project, a Drupal module called Linkit, but I decided it should be a standalone plugin. I have spent a lot of time refactoring the code, mainly to make it more generic and flexible for multiple purposes. I have now reached a point where it makes sense to actually ask for advice on the code, hopefully by professional, more experienced JavaScript developers.

EDIT: I read in the FAQ that I'm supposed to include some of the code. This is a shorter version of the code, describing the structure of the code. There is also documentation available.

(function ($) {

$.fn.betterAutocomplete = function(method) {

  var methods = {
    init: function(resource, options, callbacks) {
      var $input = $(this),
        bac = new BetterAutocomplete($input, resource, options, callbacks);
      $input.data('better-autocomplete', bac);
      bac.enable();
    },
    enable: function(bac) {
      bac.enable();
    },
    disable: function(bac) {
      bac.disable();
    },
    destroy: function(bac) {
      bac.destroy();
    }
  };

  var args = Array.prototype.slice.call(arguments, 1);

  // Method calling logic
  this.filter(':input[type=text]').each(function() {
    switch (method) {
        // ... Code here
    }
  });

  // Maintain chainability
  return this;
};

// This is the constructor function. Instantiated by using the new keyword
var BetterAutocomplete = function($input, resource, options, callbacks) {

  options = $.extend({
    charLimit: 3,
    // More options
  }, options);

  /**
   * These callbacks are supposed to be overridden by you when you need
   * customization of the default behavior. When you are overriding a callback
   * function, it is a good idea to copy the source code from the default
   * callback function, as a skeleton.
   */
  callbacks = $.extend({

    /**
     * Gets fired when the user selects a result by clicking or using the
     * keyboard to select an element.
     *
     *

Default behavior: Simply blurs the input field.
     *
     * @param {Object} result
     *   The result object that was selected.
     */
    select: function(result) {
      $input.blur();
    },
    // ... More callbacks for fetching data, parsing results etc.
  }

  var self = this,
    lastRenderedQuery = '',
    results = {}, // Caching database of search results.
    // ... More private instance variables

  // Create the DOM elements necessary and attach eventhandlers
  var $wrapper = $('
')
      .addClass('better-autocomplete')
      .insertAfter($input);

  // Public methods
  this.enable = function() { ... };

  // Then private methods
  var fetchResults = function() { ... };

  var getHighlighted = function() { ... };
};

}(jQuery);

Some hands on questions:

Does my design patterns look good? I am talking about modularity, namespacing, closures etc.
How can I stand out more from jQuery UI autocomplete and other existing plugins? What can I provide that they can't? Also, where can I reach the people who need this plugin?
Documentation. I have been using JSDoc toolkit but it is sometimes hard to understand. I have a few warnings when I generate the docs. Also I'm unsure about if I have correctly labeled functions, constructors etc. Can I improve it?

I can take criticism, so don't be shy, rather be honest.


texts:
I work on ubuntu machine and my backup requirements are straightforward. My only requirement is the usual copy paste, but only changed files (ie. the files whose modification-time OR size has changed) should get replaced.

Since I could not find such option in the default nautilus copy-paste (it only allows a merge with a blanket replace), I decided to write a backup script in python myself that I would like to get reviewed. Here is the script for backup.py:

 #!/usr/bin/env python
#@module: backup.py
#@description: Script to take backup to a fixed location
#@author: Prahlad Yeri
#@copyright: MIT Licensed

#from __future__ import print_function
import os
import os.path
import sys
import time
from datetime import datetime
import shutil

backup_loc = '/media/username/1tera/backup'
#backup_loc = '/tmp/backup'

locations = ['/home/username/docs',
    '/home/username/source',
    '/home/username/scripts',
    '/home/username/library',
    '/home/username/programs',
    '/home/username/staging',
    '/home/username/soft',
    '/home/username/Desktop',
    '/home/username/Downloads',
    '/home/username/movies',
    '/home/username/songs',
    ]

if __name__ == "__main__":
    #loop thru the folders
    start = time.clock()
    num=0
    for s in locations: #[0:1]:
        #print s + "\n"
        #files = os.listdir(s)
        print 'listing for '  + s
        for (root, dirs, files) in os.walk(s):
            subpath = root.replace('/home/prahlad','')
            for f in files:
                filename = os.path.join(root, f)
                dfilename = backup_loc + subpath + os.sep + f
                link = ''
                if os.path.islink(filename):
                    link = os.readlink(filename)

                if not os.path.exists(dfilename):
                    #check dirs
                    if not os.path.exists(backup_loc + subpath):
                        os.makedirs(backup_loc + subpath)
                        print 'creating directory: ' + backup_loc + subpath

                    #just copy the files
                    print 'copying from: ' + filename
                    print 'to: ' + dfilename
                    if link == '':
                        shutil.copy2(filename, dfilename)
                    else:
                        os.symlink(link, dfilename)
                    num+=1
                else:
                    sz = os.path.getsize(filename); lm = datetime.fromtimestamp(os.path.getmtime(filename)).timetuple()
                    dsz = os.path.getsize(dfilename); dlm = datetime.fromtimestamp(os.path.getmtime(dfilename)).timetuple()

                    if (sz == dsz and lm == dlm):
                        print 'skipped: ' + dfilename
                        #time.sleep(3)
                    else:
                        #copy the files
                        print 'copying from: ' + filename
                        print 'to: ' + dfilename
                        if link == '':
                            shutil.copy2(filename, dfilename)
                        else:
                            os.symlink(link, dfilename)
                        num+=1

    mins = (time.clock() - start)
    #print "All files copied in %d minutes" % mins
    print "{0} files copied in {1} minutes".format(int(num), round(mins))


texts: Counting rows in a CSV file that correspond to a database row, each with a million records

texts:
I have two DataTables:

dt: is populated from a CSV file with over 1.7 million rows
dataStructure.Tables["AccountData"]: is populated from a database query also roughly a million rows

I use the following code to iterate through and compare the data from each set of rows. The code takes over 48 hours to complete. I have changed the properties of the application to x64 to allow it to use more Process Memory. It now uses roughly 2.5GB.

My question is, is there a more efficient way of doing this that would decrease run time?

//set is_legal column value for each row
foreach (DataRow row in dt.Rows)
{
    var acctNum = row[0].ToString().Replace("\"", "");
    foreach (DataRow queryRow in dataStructure.Tables["AccountData"].Rows)
    {
        var queryAcctNum = queryRow[0].ToString();
        if (acctNum.Equals(queryAcctNum))
        {
            row[12] = "Y";
            Console.WriteLine("Yes count: " + cnt);
        }
        else
        {
            row[12] = "N";
        }
    }
    cnt++;
};

How dataStructure.Tables["AccountData"] is being populated:

//Read each row from the table and output the results into the data set
while (readFile.Read())
{
    //Create a row to hold data
    DataRow datarow = dataStructure.Tables["AccountData"].NewRow();

    datarow["AccountNumber"] = readFile.GetString(0).Trim();
    datarow["LegalStatus"] = readFile.GetString(1);

    //add the row to the data table AccountData
    dataStructure.Tables["AccountData"].Rows.Add(datarow);
}


texts: The best way to unwrap the optional in java

texts:
Instead of using the null checks I tried using Optional and safely unwrapping the optional.

Approach 1

My first approach of unwrapping the Optional is using map() followed by orElseThrow().

Approach 2

My second approach if unwrapping the Optional is using orElseThrow() and setting the value to a variable and using it.

Service

@Inject
private UserConfigurationRepository userConfigurationRepository;

public UserConfiguration updateConfigUsingOrElseThrow(User user, String value) {
    UUID configurationId = user.getConfigurationId().orElseThrow();
    UserConfiguration userConfiguration = userConfigurationRepository
            .findById(configurationId).orElseThrow();
    return updateUserConfiguration(userConfiguration, value); // Performs update operation
}

public UserConfiguration updateConfigUsingMapOrElseThrow(User user, String value) {
    return user.getConfigurationId().map(configurationId ->{
        return userConfigurationRepository.findById(configurationId).map(userConfiguration -> {
            return updateUserConfiguration(userConfiguration, value); // Performs update operation
        }).orElseThrow();
    }).orElseThrow();
}

private UserConfiguration updateUserConfiguration(UserConfiguration userConfiguration, String value)
{
    userConfiguration.setValue(value);
    // Business Logics
    return userConfigurationRepository.save(userConfiguration);
}

Repository

public interface UserConfigurationRepository extends JpaRepository<UserConfiguration, UUID>{}

Model

public class User {
   private int id;
   private String name;
   private String email;
   private UUID configurationId;

   public Optional<UUID> getConfigurationId() {
       return Optional.ofNullable(configurationId);
   }

   public void setConfigurationId(UUID configurationId) {
       this.configurationId = configurationId;
   }

   //Ignored getters and setters of other properties those are not used in this part of code
}

public class UserConfiguration {
   private UUID id;
   private String value;

   public UUID getId() {
       return id;
   }

   public void setId(UUID id) {
       this.id = id;
   }

   public String getValue() {
       return value;
   }

   public void setValue(String value) {
       this.value = value;
   }
}

I am used to using null check using if statement and since I am new to this style of programming I am not sure which one is the best approach and gives more readability, Or is there any other recommended way to do this?

The task of this service is to get the configuration id and a configuration message from front end and update the data in the configuration table. And returns the updated configuration information. Not all the users will have an entry in the configuration so there is a possibility of getting null value for configurationId in the User model thats is why the getter returns the optional of configurationId.

Since this is my client code I am unable to expose the complete code, So I provided the structure of the model, services and repository. Hope I have provided necessary information.


texts:
This is code for a caesar cipher that I wrote, I would love for anyone who can to offer any improvements/corrections/more efficient methods they can think of. Thanks.
alphabet=["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"," ","1","2","3","4","5","6","7","8","9","0",",","."]
enc_text=[]
dec_text=[]

def number_check(a):
  valid=False
  while valid==False:
    try:
      number=int(a)
      valid=True
    except ValueError:
      print("Invalid entry, You must enter a number.")
      a=input("please enter a number.\n")
  return number

def encrypt():
  for x in org_text:
    index=alphabet.index(x)
    enc_letter=(index+int(enc_key))%39
    new_let=alphabet[enc_letter]
    enc_text.append(new_let)
  return enc_text

def decipher():
  for x in message:
    index=alphabet.index(x)
    dec_letter=(index-int(enc_key))%39
    new_let=alphabet[dec_letter]
    dec_text.append(new_let)
  return dec_text

enc_key=number_check(input("Please enter your encryption key:\n"))
org_text=input("please enter the message you would like encrypted:\n").upper()
message=encrypt()
message1="".join(message)
print(message1)
decode=decipher()
decode1="".join(decode)
print(decode1)


texts:
I'd like to improve my code, but I'm not sure where to start. Everything works as I want it to; I just think it's ugly.

I'll split this into two parts:

I have two drop-downs that I'll explain later. In these drop-downs, I have options to set currency and language. I use a hidden form to set the current values with PHP, and extract the current value from these field. I then compare if the selected value matches the initial one.
Within my two drop-downs, clicking on one or the other closes the other one, and open itself if it's not open. Upon closing the drop-down, I check if I should submit the form (reloadPage()).

I think this should be split into separate functions, but I don't really know how to merge all of this together. I'm not asking for a full recode of my stuff, but I'd appreciate how to make this less ugly.

Part 1

$(function() {
    hasChanged = false;
    var $options = $('#options');
    var $currencycode = $options.find('#currency_code');
    var $languagecode = $options.find('#language_code');
    var $initCurrencycode = $currencycode.val();
    console.log($initCurrencycode);
    $('.monnaie').find('a').click(function() {
        $this = $(this);
        if(!$this.hasClass('selected')) {
            $this.parent().siblings().find('a').removeClass('selected');
            $myCurrencycode = $this.attr('class');
            $currencycode.val($myCurrencycode);
            $this.addClass('selected');
            if($myCurrencycode == $initCurrencycode) {
                hasChanged = false;
                console.log(hasChanged);
            } else {
                hasChanged = true;
                console.log(hasChanged);
            }
        }
    });
});

Part 2

$optionsdropdown = $('#mobile-options');
$menudropdown = $('#mobile-menu');
function reloadPage() {
    if(hasChanged) {
        alert('reload now');
    } else {
        console.log('nope');
    }
}
$('.options-toggler').click( function() {
    if(!$optionsdropdown.hasClass('hide')) {
        $optionsdropdown.addClass('hide');
    } else {
        $optionsdropdown.removeClass('hide');
    }
    if(!$menudropdown.hasClass('hide')) {
        $menudropdown.addClass('hide');
    }
});
$('.menu-toggler').click( function() {
    if(!$menudropdown.hasClass('hide')) {
        $menudropdown.addClass('hide');
    } else {
        $menudropdown.removeClass('hide');
    }
    if(!$optionsdropdown.hasClass('hide')) {
        $optionsdropdown.addClass('hide');
    }
});
$('html').click(function() {
    if(!$optionsdropdown.hasClass('hide')) {
        $optionsdropdown.addClass('hide');
    }
    if(!$menudropdown.hasClass('hide')) {
        $menudropdown.addClass('hide');
        reloadPage();
    }
});
$('#mobile-menu, .menu-toggler').click(function(event){
    event.stopPropagation();
});
$('#mobile-options, .options-toggler').click(function(event){
    event.stopPropagation();
});


texts: Concatenate disjoint Excel ranges to use as a single range in a formula

texts:
I need to vertically concatenate two disjoint ranges in VBA to be passed to an Excel function (in this case the LINEST function). I hate working with arrays in VBA but I managed to get it working using the following code:

Option Base 1

Function VERTCAT(R1 As Range, R2 As Range) As Variant

    Dim ncols As Integer
    ncols = R1.Columns.Count
    Dim nrows1 As Integer
    nrows1 = R1.Rows.Count
    Dim nrows2 As Integer
    nrows2 = R2.Rows.Count

    Dim arr1 As Variant
    arr1 = R1
    Dim arr2 As Variant
    arr2 = R2

    Dim arr3 As Variant
    ReDim arr3(nrows1 + nrows2, ncols)

    For Col = 1 To ncols
        For Row = 1 To nrows1
            arr3(Row, Col) = arr1(Row, Col)
        Next Row
        For Row = 1 To nrows2
            arr3(Row + nrows1, Col) = arr2(Row, Col)
        Next Row
    Next Col

    VERTCAT = arr3

End Function

I'm not worried about adding basic error checking, like making certain that the two arrays have the same number of columns or adding features. I am hoping that someone can show me what the idiomatic VBA way is to have written this function? Could I have avoided some of the helper variables (like arr3 for example?)? Could I have avoided the loops?


texts: Find sequence to a target number using restricted set of primitive operations

texts:
Given an integer , compute the minimum number of operations(+1, x2, x3) needed
to obtain the number  starting from the number 1.

I did this using this code:
#include<iostream>
#include<algorithm>
#include<vector>
using namespace std;
int main()
{
    int n;
    cin >> n;
    vector<int> v(n+1, 0);
    v[1] = 1;
    for(int i = 1; i < v.size(); i++)
    {
        if((v[i + 1] == 0) || (v[i + 1] > v[i] + 1))
        {
            v[i + 1] = v[i] + 1;
        }
        if((2*i <= n) && (v[2*i] == 0 || v[2*i] > v[i] + 1))
        {
            v[2*i] = v[i] + 1;
        }
        if((3*i <= n) && (v[3*i] == 0 || v[3*i] > v[i] + 1))
        {
            v[3*i] = v[i] + 1;
        }
    }
    cout << v[n] - 1 << endl;
    vector<int> solution;
    while(n > 1)
    {
        solution.push_back(n);
        if(v[n - 1] == v[n] - 1)
        {
            n = n-1;
        }
        else if(n%2 == 0 && v[n/2] == v[n] - 1)
        {
            n = n/2;
        }
        else if(n%3 == 0 && v[n/3] == v[n] - 1)
        {
            n = n/3;
        }
    }
    solution.push_back(1);
    reverse(solution.begin(), solution.end());
    for(size_t k = 0; k < solution.size(); k++)
    {
        cout << solution[k] << ' ';
    }
}

Input:
5

Output:
3
1 2 4 5

Do you have any optimized way to do this?


texts:
I am practicing Rust by creating data structures, such as this N-dimensional array.
The purpose of this structure is to easily define and address into arbitrarily-deeply nested arrays without having to write out Vec<Vec<Vec<T>>> and incur the performance penalty coming from this (although performance is not a priority).
I am looking for feedback on how idiomatic the interface and implementation are,
as well as how to improve my tests since I don't think they're very robust.
use std::ops::{Index, IndexMut};

#[derive(Debug, Clone)]
pub struct NdArray<T, const N: usize> {
    dim: [usize; N],
    data: Vec<T>,
}

impl<T, const N: usize> NdArray<T, N> {
    fn calculate_capacity(dim: &[usize; N]) -> usize {
        let mut cap = 1;
        for &x in dim {
            cap = usize::checked_mul(cap, x).expect("vector capacity overflowed usize");
        }
        cap
    }

    pub fn new(dim: [usize; N], default: T) -> Self
    where
        T: Clone,
    {
        let cap = Self::calculate_capacity(&dim);
        NdArray {
            dim,
            data: vec![default; cap],
        }
    }

    pub fn new_with(dim: [usize; N], generator: impl FnMut() -> T) -> Self {
        let cap = Self::calculate_capacity(&dim);
        NdArray {
            dim,
            data: {
                let mut v = Vec::new();
                v.resize_with(cap, generator);
                v
            },
        }
    }

    fn get_flat_idx(&self, idx: &[usize; N]) -> usize {
        let mut i = 0;
        for d in 0..self.dim.len() {
            assert!(
                idx[d] < self.dim[d],
                "index {} is out of bounds for dimension {} with size {}",
                idx[d],
                d,
                self.dim[d],
            );
            // This cannot overflow since we already checked product of all dimensions fits usize
            // and idx < self.dim.
            i = i * self.dim[d] + idx[d];
        }
        i
    }
}

impl<T, const N: usize> Index<&[usize; N]> for NdArray<T, N> {
    type Output = T;

    fn index(&self, idx: &[usize; N]) -> &T {
        &self.data[self.get_flat_idx(idx)]
    }
}

impl<T, const N: usize> IndexMut<&[usize; N]> for NdArray<T, N> {
    fn index_mut(&mut self, idx: &[usize; N]) -> &mut T {
        let i = self.get_flat_idx(idx);
        &mut self.data[i]
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::panic::catch_unwind;

    #[test]
    fn nd_array_1d() {
        let mut array = NdArray::new_with([10], || 1);
        assert_eq!(array[&[0]], 1);
        assert_eq!(array[&[9]], 1);
        assert!(catch_unwind(|| array[&[10]]).is_err());

        array[&[5]] = 99;
        assert_eq!(array[&[4]], 1);
        assert_eq!(array[&[5]], 99);
        assert_eq!(array[&[6]], 1);
    }

    #[test]
    fn nd_array() {
        let mut array = NdArray::new([2, 3, 4], 0);
        array[&[1, 2, 3]] = 10;
        assert_eq!(array[&[1, 2, 3]], 10);
        assert_eq!(array[&[1, 0, 0]], 0);
        assert!(catch_unwind(|| array[&[2, 0, 0]]).is_err());
        assert_eq!(array[&[0, 2, 0]], 0);
        assert!(catch_unwind(|| array[&[0, 3, 0]]).is_err());
        assert_eq!(array[&[0, 0, 3]], 0);
        assert!(catch_unwind(|| array[&[0, 0, 4]]).is_err());
    }

    #[test]
    fn nd_array_overflow() {
        // Panics at the allocator code since sizeof(usize) > 2
        // NdArray::new([usize::MAX / 2], 0);
        assert!(catch_unwind(|| NdArray::new([usize::MAX / 2 + 1, 2], 0)).is_err());
        assert!(catch_unwind(|| NdArray::new(
            [usize::MAX / 3, usize::MAX / 3, usize::MAX / 3 + 1],
            0
        ))
        .is_err());
    }
}