texts: Given entrance and exit logs, find the population maximum

texts:
I was given this problem during an interview. And I solved it using Python. Would like to get feedback to see how I can improve my interview response.

  Busiest Time in The Mall

  The Westfield Mall management is trying to figure out what the busiest
  moment at the mall was last year. You’re given data extracted from the
  mall’s door detectors. Each data point is represented as an integer
  array whose size is 3. The values at indices 0, 1 and 2 are the
  timestamp, the count of visitors, and whether the visitors entered or
  exited the mall (0 for exit and 1 for entrance), respectively. Here’s
  an example of a data point: [ 1440084737, 4, 0 ].

  Note that time is given in a Unix format called Epoch, which is a
  nonnegative integer holding the number of seconds that have elapsed
  since 00:00:00 UTC, Thursday, 1 January 1970.

  Given an array, data, of data points, write a function
  findBusiestPeriod that returns the time at which the mall reached its
  busiest moment last year. The return value is the timestamp, e.g.
  1480640292. Note that if there is more than one period with the same visitor peak, return the earliest one.

  Assume that the array data is sorted in an ascending order by the
  timestamp.

"""
input:  data = [ [1487799425, 14, 1],
                 [1487799425, 4,  0],
                 [1487799425, 2,  0],
                 [1487800378, 10, 1],
                 [1487801478, 18, 0],
                 [1487801478, 18, 1],
                 [1487901013, 1,  0],
                 [1487901211, 7,  1],
                 [1487901211, 7,  0] ]

output: 1487800378 # since the increase in the number of people
                   # in the mall is the

"""

def find_busiest_period(data):

  people = 0
  max_time = 0
  max_people = 0
  for i in range(len(data)):

    if data[i][2] == 1:
      people += data[i][1]
    else:
      people -= data[i][1]

    if (i < len(data)-1 and data[i][0] == data[i+1][0]):
      continue

    if people > max_people:
      max_people = people
      max_time = data[i][0]
  return max_time

data = [ [1487799425, 14, 1],
                 [1487799425, 4,  0],
                 [1487799425, 2,  0],
                 [1487800378, 10, 1],
                 [1487801478, 18, 0],
                 [1487801478, 18, 1],
                 [1487901013, 1,  0],
                 [1487901211, 7,  1],
                 [1487901211, 7,  0] ]

test = find_busiest_period(data)
print(test)


texts:
I write abstract repository

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Linq.Expressions;

namespace Framework.DataLayer
{
    public class Context<T> : IContext<T> where T : class
    {
        private readonly DbContext _dbContext;

        public Context(DbContext dbContext)
        {
            _dbContext = dbContext;
        }

        public bool TryGet(Expression<Func<T, bool>> predicate, out T entity)
        {
            entity = List(predicate).SingleOrDefault();
            return entity != null;
        }

        public T Get(Expression<Func<T, bool>> predicate)
        {
            return List(predicate).Single();
        }

        public List<T> List(Expression<Func<T, bool>> predicate = null)
        {
            IQueryable<T> result = _dbContext.Set<T>().AsQueryable();
            if (predicate != null)
                result = result.Where(predicate);
            return result.ToList();

        }

        public T Add(T t)
        {
            _dbContext.Entry(t).State = EntityState.Added;
            return t;

        }

        public void Delete(Expression<Func<T, bool>> predicate)
        {
            List(predicate).ToList().ForEach(p => { _dbContext.Entry(p).State = EntityState.Deleted; });
        }

        public void Delete(T entity)
        {
            _dbContext.Entry(entity).State = EntityState.Deleted;
        }

        public T Update(T t)
        {
            _dbContext.Entry(t).State = EntityState.Modified;
            return t;

        }

    }
}

Is this correct?


texts:
I'm working on getting switch and if statements down and I came up with this.  It works well and I don't have any problems with it running properly.  I was wondering if I could get some feedback on how I put it together.  If there are things I am doing wrong or could do better, I'm very open to suggestions!

public static void main(String[] args) {

    double edge = 0;

    Scanner sc = new Scanner(System.in);

    System.out.println("Enter the name of your Casino.");
    String casino = sc.nextLine();

    System.out.println("How many decks? (1, 2, 4, 6, 8)");
    int decks = sc.nextInt();
    System.out.println("Dealer hits Soft 17 (1 for Yes; 2 or No)");
    int soft17 = sc.nextInt();
    System.out.println("Double after Splits Allowed (1 for Yes; 2 or No)");
    int doubleAfterSplit = sc.nextInt();
    System.out.println("Double 10/11 Only (1 for Yes; 2 or No)");
    int double1011 = sc.nextInt();
    System.out.println("Double 9/10/11 Only (1 for Yes; 2 or No)");
    int double91011 = sc.nextInt();
    System.out.println("Resplit Aces (1 for Yes; 2 or No)");
    int rSA = sc.nextInt();
    System.out.println("Late Surrender (1 for Yes; 2 or No)");
    int lateSurrender = sc.nextInt();
    System.out.println("Early Surrender (1 for Yes; 2 or No)");
    int earlySurrender = sc.nextInt();
    System.out.println("Lose All Doubles/Splits vs. Natural (1 for Yes; 2 or No)");
    int loseAllDS = sc.nextInt();
    sc.close();

    //Number of Decks Option
    if (decks == 1) {
        edge += 0.01;
    } else if (decks == 2) {
        edge -= 0.32;
    } else if (decks == 4) {
        edge -= 0.49;
    } else if (decks == 6) {
        edge -= 0.54;
    } else if (decks == 8) {
        edge -= 0.57;
    } else {
        System.out.println("You made a mistake.  Start over.");
    }

    //Soft 17 Options
    if (soft17 == 1) {
        edge -= 0.20;
    } else {
        edge += 0;
    }

    //Double After Splits Option
    if (doubleAfterSplit == 1) {
        edge += 0.14;
    } else {
        edge += 0;
    }

    //Double 10 and 11 Only Option
    if (double1011 == 1) {
        edge -= 0.17;
    } else {
        edge += 0;
    }

    //Double 9, 10, and 11 Only Option
    if (double91011 == 1) {
        edge -= 0.08;
    } else {
        edge += 0;
    }

    //Resplit Aces Option
    if (rSA == 1) {
        edge += 0.08;
    } else {
        edge += 0;
    }

    //Late Surrender Option
    if (lateSurrender == 1) {
        edge += 0.08;
    } else {
        edge += 0;
    }

    //Early Surrender Option
    if (earlySurrender == 1) {
        edge += 0.65;
    } else {
        edge += 0;
    }

    //Lose on All Doubles and Splits vs Natural Option
    if (loseAllDS == 1) {
        edge -= 0.11;
    } else {
        edge += 0;
    }

    DecimalFormat newFormat = new DecimalFormat("#.##");
    edge =  Double.valueOf(newFormat.format(edge));

    System.out.print("At, " + casino + " ");
    if (edge >= 0) {
        System.out.print("your advantage is: " + edge + "%");
    } else {
        System.out.print("your disadgantage is: " + edge + "%");
    }

}

}


texts: Binary search that returns bitwise complement of missing index

texts:
While re-writing some old JavaScript code to better handle large arrays, I ended up writing my own binary search method.

I found many examples of binary search methods written in JavaScript, but all the examples I found returned -1 whenever the target was not found in the array. What I really wanted was the bitwise complement of the index where the target belonged if it did not exist in the array, like the BinarySearch method on generic lists in .NET.

This is the code I ended up writing, but I'm curious if I've overlooked any potential performance problems or logic errors. To the best of my knowledge, the code works sufficiently as designed (see my fiddle). Please help me review this code and verify that it follows common best practices.

binarySearch Method

Inputs: target: the object being sought in the array;
comparator: (optional) comparison method

Returns: If positive or zero, the index of the item in the array. If negative, the bitwise complement of the item's proper location in the array.

Array.prototype.binarySearch = function (target, comparator) {
    var l = 0,
        h = this.length - 1,
        m, comparison;
    while (l <= h) {
        m = (l + h) >> 1;
        comparison = typeof (comparator) == "undefined" ? (this[m] < target ? -1 : (this[m] > target ? 1 : 0)) : comparator(this[m], target);
        if (comparison < 0) {
            l = m + 1;
            continue;
        } else if (comparison > 0) {
            h = m - 1;
            continue;
        } else {
            return m;
        }
    }
    return~l;
};

Using the above, I also wrote a binary insert method, which adds an item to the correct location in an array. I'm curious about this also, and whether there's anything I can do to improve its performance or handle any edge case bugs.

binaryInsert Method

Inputs: target: object being inserted; duplicate: (optional) whether to add if it already exists in the array (false by default); comparator: (optional) comparison method

Returns: Index of new item added to array

Array.prototype.binaryInsert = function (target, duplicate, comparator) {
    if (typeof (duplicate) == "undefined") duplicate = false;
    var i = this.binarySearch(target, comparator);
    if (i >= 0) {
        if (duplicate) {
            this.splice(i, 0, target);
        }
    } else {
        i = ~i;
        this.splice(i, 0, target);
    }
    return i;
};


texts:
For many days, I've been re-designing my application, applying some custom pattern and making our code looks like a framework. I have something like this for separate the business logic, from views:

    if(file_exists($route . $urlpara[0] . ".template.php")){
        require_once($route . $urlpara[0] . ".functions.php");
        require_once($route . $urlpara[0] . ".template.php");
    }else{
        // 404 error
    }

$route means the route.

$urlpara[0] means a parsed URL, where $urlpara[0] should be in this case the URL.  In this case, we could say $urlpara[0] = index. So this would like like this without variables:

    if(file_exists("app/index.template.php")){
        require_once("app/index.functions.php");
        require_once("app/index.template.php");
    }else{
        // 404 error
    }

Inside index.template goes the view, and inside index.functions goes the model.

Here's the .htaccess

RewriteEngine On
Options -MultiViews
Options +FollowSymlinks

RewriteBase /script/
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d

#Basic params MVC
RewriteRule ^(.*)$ index.php?page=$1 [L]

Here the index.php (the part where it reads and splits up the model/view):

    $exploded = explode('/', $_GET['page']); // pagename/param1/param2/etc..

    $route = 'script/path/';
    $first_param = $exploded[0];
    $second_param = $exploded[1];
    // Controller
            if(file_exists($route . $first_param . ".template.php")){
                require_once($route . $first_param . ".functions.php");
                require_once($route . $urlpara[0] . ".template.php");
            }else{
                // 404 error
            }

    // now it checks if param1 = pagename exists. For example dashboard.template.php. Same with dashboard.functions.php

function generateTitle(){
echo 'this title generated dynamically';
}

Within dashboard.template.php we find this:

<!-- View -->
<html>
<head>
<title><?php echo generateTitle(); ?></title>
</head>
<?php
foreach($whatever as $some){
echo $some;
}
?>
</html>

And within the dashboard.functions.php we find this:

<?php
// Model
$whatever = array('test', 'test2', 'test3');
?>

I don't really know if I'm doing it well.  Could be this represented as a MVC pattern?


texts:
While going through SICP and trying to implement the code in clojure, I've found that while I can get the code in chapter 3 to work, it seems to go against Clojure idioms, but I can't quite imagine the "Clojure way" to do it either.

Take for example, the digital circuit simulator. This is my implementation:

(declare call-each)
(defn make-wire []
  (let [signal-value (atom 0)
        action-procedures (atom '())
        set-my-signal (fn [new-value]
                        (if-not (= @signal-value new-value)
                          (do (reset! signal-value new-value)
                              (call-each @action-procedures))
                          'done))
        accept-action-procedure! (fn [proc]
                                   (swap! action-procedures
                                          conj proc)
                                   (proc))
        dispatch (fn [m]
                   (cond (= m 'get-signal) @signal-value
                         (= m 'set-signal) set-my-signal
                         (= m 'add-action) accept-action-procedure!
                         :else (error "Unknown operation -- WIRE" m)))]
    dispatch))

(defn call-each [[proc & rest :as procedures]]
  (if (empty? procedures)
    'done
    (do (proc)
        (call-each rest))))

(defn get-signal [wire]
  (wire 'get-signal))
(defn set-signal! [wire new-value]
  ((wire 'set-signal) new-value))
(defn add-action! [wire action-procedure]
  ((wire 'add-action) action-procedure))

As you can see, it has an internal signal-value and action-procedures as state. Is this the natural way to do this in Clojure, and if not, how would you do it?


texts:
I would like the program to ask the user if they want to add a color.  If they say yes, then ask what color to add. Then after that happens, once the program would ask if you want to, run it again. If they say no to add a color, the program ask if you want to remove a color from the list. If they say yes, it would then ask what color to remove, with error handling built in if the color wasn't in that list. Then after that happens once the program would ask if you want to run it again.

Just wanted to point out I do not know a lot about Python, so please don't be harsh, but I can take constructive criticism.

import socket # imports the socket module
import sys # imports the sys module
import console # imports the console module

usr = raw_input('What is your name? \n').title() # asks for users name for the hostname information
sname = socket.gethostname() # sets sname to gethostname
print '\nThis program is being run by', usr, 'on machine name', sname # displays host information

mylist = ['Red', 'White', 'Blue', 'Yellow', 'Green', 'Orange'] # sets mylist to colors
templist = list(mylist) # sets templist as mylist
runagain = 'y' # sets runagain to a y values

while runagain == 'y': # for looping
print '\nThe current colors are:', templist # print out list so user knows what colors are already there

clradd = raw_input('\nWould you like to add any colors to the list? y or n\n')

while clradd == 'y':
    colors = raw_input('\nWhat colors would you like to add to the list? Please type one color. \n').title()
    templist.append(colors) # appends color to the list

    print templist # prints out new list
    print '\nAscending and Descending'  # print out ascending and descending lists
    print '-' * 30
    print '\nAscending (high to low): ', sorted(templist, reverse=True)
    print '\nDescending (low to high): ', sorted(templist, reverse=False)

    clrdel = raw_input('\nWould you like to remove any colors from the list? y or n\n')

while clradd == 'n':
    clrdel = raw_input('\nWould you like to remove any colors from the list? y or n\n')

    while clrdel == 'y':
            try:
                removecolor = raw_input('\nWhat colors would you like to remove? ').title() # asks user color to remove
                templist.remove(removecolor) # removes color from the list
            except ValueError:
                print 'Looks like that color was not in the list, try again.'
                continue

            print 'Updated list\n', templist # prints out updated list

            runagain = raw_input('\nWould you like to run this program again again? y or n')

            if runagain == 'n': # if runagain is n
                console.hide_output() # hide the output

    while clrdel == 'n':
        runagain = raw_input('\nWould you like to run this program again again? y or n') # asks user to run again

        if runagain == 'n': # if runagain is n
            console.hide_output() # hide the output
            sys.exit() # stops the program


texts:
I have a dataframe pairs where each row is a transaction with corresponding price and date. Now, I need to assign each transaction to a quintile (add a new column), but the quintile bins have been defined for each period frequency (year, quarter or month) and borough separately, so generally what I need is groupby -> qcut.

Here is an existing function:

def tier_data(pairs, tiers_typed):
    '''for each record returns tier

    cuts pairs according to their tier (quintile)

    Arguments:
        pairs -- transaction pairs to operate on
        tiers_type -- tiers dataframe
    Returns:
        pd.Series -- tier for each pair
    '''

    freqstr = tiers_typed.index.get_level_values(0).freqstr
    pairs['tiers'] = pd.Series(pd.np.empty(len(pairs)) * pd.np.nan, index=pairs.index)
    global LABELS

    freq_date = pairs['date0'].dt.to_period(freqstr)
    for (y, b), bins in tiers_typed.iterrows():
        mask = (freq_date == y) & (pairs['Borough'] == b)
        trs[mask] = pd.cut(pairs.loc[mask, 'price0'], bins, labels=LABELS)

    return trs

However it turns out to be pretty slow... any ideas on how to boost it up?

here, price is an integer, date is a date, Borough is a string, bins is a pd.Series, obviously.


texts:
Is this a reasonable C++ wrapper function for Python's "list.count([character])" method?

int count( char CHAR, string STR ) {
    int counter = 0;
    for ( int i = 0 ; i < STR.size() - 1 ; i++  ) {
        if ( STR[i] == CHAR ) {
            counter++;
        }
    }
    return counter;
}
//Edited "for( int i = 0 ; i++ < STR.size-1 ;  )" to "for(int i = 0 ; i < STR.size ; i++)" now it counts the first char of the string =D

Tested it...works exactly like the python <3


texts:
I am working on an HTML / JavaScript listings template for online auctions.  There are two sets of tabbed navigation features in the listing that are driven by JavaScript as well as a dynamic image gallery. Everything appears to be functioning very nicely. The template is fiddled here. (complete project repository here). However, I have one BIG issue I need help resolving and a couple of smaller items I'd like feedback on.

BIG Issue:

This is the showstopper.  I am NOT a JavaScript programmer yet, so I don't know how involved of a question this is. Because the template will be used on Ebay, I am restricted to what can be done with JavaScript.  The tabs module that I am using (which I forked from here) uses the replace() function in two places:

removeClass: function (element, className) {
    element.className = element.className.replace(new RegExp("(^|\\s)" + className + "(\\s|$)"), "$1");
    if (element.className === " ") {
        element.className = "";
    }
},

and here:

getStyle: function (element, property) {
    if (element.style[property]) {
        return element.style[property];
    }
    if (element.currentStyle) {    // IE.
        return element.currentStyle[property];
    }
    property = property.replace(/([A-Z])/g, "-$1").toLowerCase();    // Turns propertyName into property-name.
    var style = document.defaultView.getComputedStyle(element, "");
    if (style) {
        return style.getPropertyValue(property);
    }
},

Unfortunately, the replace() function is one of the Ebay BANNED JavaScript functions.  Is there a replacement or work-around for the replace()?  I did find a couple of ideas over on SO here, but I am not sure how to implement them.

Questions:

I feel like the CSS is a mess.  Is there a tool available that could help streamline CSS and help identify redundant, useless or otherwise inefficient CSS (besides good old fashioned experience, which I am working on)? For instance, I find myself putting a margin:0; or padding:0 quite often.
Cross browser compatibility.  I am making use of the border-radius style in a couple of places.  In the CSS, I have added the prefixes -moz and -webkit for these features.  However, looking over at caniuse.com, it looks like support for this feature is pretty high (over 90%).  Is it necessary to include these prefixes in the CSS?
The image gallery is using the onclick() function to pass name attributess to the preview area whenever a thumbnail is clicked.  Because the name attribute is obsolete, this method is preventing the file from validating to HTML 5.  Is there a different way this could be done using id attributes instead? I tried simply replacing name with id but that didn't work. Alternatively, I do have a script I can use, but it also requires solving the BIG issue above.


texts: java.util.Observable but with generics to avoid casts

texts:
This is an Observable class similar to java.util.Observable. The difference is that it uses generics to avoid casts. The question is: Is it really worth the effort? What are the problems with this code?

import java.util.ArrayList;
import java.util.Collection;

/**
 * like java.util.Observable, But uses generics to avoid need for a cast.
 *
 * For any un-documented variable, parameter or method, see java.util.Observable
 */
public class Observable<T>  {
   private boolean changed = false;

   // Holds registered observers.
   // @TODO if class is not final can we make this protected? (should we?).
   private final Collection<Observer<? super T>> observers;

   /**
    * observersSet gives the opportunity of changing the implementing set. The
    * benefit is, final user can specify the 'order' of observers notified.
    * Generally, not a good idea at all.
    *
    * @TODO should this be private and the class final?.
    */
   protected Observable(Collection<Observer<? super T>> observersSet) {
      this.observers = observersSet; }

   public static <F> Observable<F>getInstance() {
      // return getInstance(container);
      ArrayList<Observer<? super F>> container = new ArrayList<>();
      return new Observable<>(container);
   }

   /**
    * Before this method can be actually used, this.update(T arg) must be fixed.
    * It has a hard-coded ArrayList. Generally, not a good idea, not at all.
    *
    * User would expect the call getInstance(ArrayList<SomeObserver> ar) to
    * work however it wont. It must be:
    * getInstance(ArrayList<? extends SomeObserver> ar);
    *
    * It's bad, ugly, and more importantly, violating.
    *
    * Unless of course the first example could be made to work. Maybe a cast
    * will do.
    */
   @SuppressWarnings("UnusedParameters")
   public static <F> Observable<F>
      getInstance(Collection<Observer<? super F>> observersSet) {
      throw new UnsupportedOperationException("Not yet implemented.");
      // return new Observable<>(observersSet);
   }

   // @TODO null check maybe for add?
   public synchronized boolean add(final Observer<? super T> o) {
      return !this.observers.contains(o) && observers.add(o);

   }
   public void addObserver(final Observer<? super T> o)         { this.add(o); }

   public synchronized boolean rm(final Observer<? super T> o)  { return observers.remove(o); }
   public void deleteObserver(final Observer<? super T> o)      { this.rm(o); }

   public synchronized void clear() { this.observers.clear(); }
   public void deleteObservers()    { this.clear(); }
   // @TODO all of them need synchronized?
   public synchronized void setFlag() { this.changed = true; }
   public synchronized void clrFlag() { this.changed = false; }

   // Hei! did you know if you used projectLombok.org you could remove this
   // method? didn't you?!!! :O 0_o
   public synchronized boolean getFlag() { return this.changed; }
   public boolean hasChanged() { return this.getFlag(); }
   public int countObservers() { return this.observers.size(); }

   public void update(final T args) {
      ArrayList<Observer<? super T>> copy;

      synchronized (this) {
     if(!changed) return;
     copy = new ArrayList<>(this.observers);
     this.clrFlag();
      }
      // Look at OpenJDK to see why a new Collection is used.
      for(Observer<? super T> o : copy) o.update(args);
   }
   public void notifyObservers(final T args) { this.update(args); }

   public void update() { this.update(null); }
   public void notifyObservers() { this.update(); }
}

Observable now carries type of args sent to each Observer, and Observer is also aware of it, thus no cast needed.

The follow up question is located here.


texts:
I have written a function that launches the default editor set in git config, right now I have managed to get it working for Sublime, nano and Vim.

def launchEditor(editor):
    """ this function launches the default editor
        for user to compose message to be sent
        along with git diff.

        Args:
            editor(str): name or path of editor
        Returns:
            msg(str): html formatted message
    """

    filePath = os.path.join(os.getcwd(), "compose.txt")
    wfh = open(filePath, 'w')
    wfh.close()

    if os.path.exists(filePath):
        # using sublime
        if re.search(r'ubl', editor):
            diff = subprocess.Popen(['cat',filePath], stdout=subprocess.PIPE)
            pr = subprocess.Popen(
                editor,
                stdout=subprocess.PIPE,
                stderr=subprocess.PIPE,
                shell=True,
                stdin=diff.stdout
                )
            pr.wait()
            if pr.returncode == 0:
                msg = pr.stdout.read()
        else:
            # using vim or nano
            pr = subprocess.Popen([editor, filePath], stdin=open('/dev/tty', 'r'))
            pr.wait()
            if pr.returncode == 0:
                with open(filePath, 'r') as fh:
                    msg = fh.readlines()
    os.remove(filePath)
    return "".join(msg).replace("\n","<br>")

Any suggestion on improvement and adding support to other text editors is welcome!!

Revision update:

 Traceback (most recent call last):
  File "/Users/san/Development/executables//git-ipush", line 268, in <module>
    sys.exit(main())
  File "/Users/san/Development/executables//git-ipush", line 46, in main
    preCheck(args)
  File "/Users/sanjeevkumar/Development/executables//git-ipush", line 156, in preCheck
    message = launchEditor(editor)
  File "/Users/san/Development/executables//git-ipush", line 77, in launchEditor
    if subprocess.call([editor, f.name]) != 0:
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/subprocess.py", line 524, in call
    return Popen(*popenargs, **kwargs).wait()
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/subprocess.py", line 711, in __init__
    errread, errwrite)
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/subprocess.py", line 1308, in _execute_child
    raise child_exception
OSError: [Errno 2] No such file or directory


texts:
I am not used to generators and wonder how to make code cleaner/Pythonic in the generator part.

The function is about validating a binary search tree. The inorder_gen function yield one element a time. The main function compares the value yielded and previous yielded value to determine whether BST's invariant is violated.

# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution(object):

    def isValidBST(self, root):
        """
        :type root: TreeNode
        :rtype: bool
        """
        last_val = None
        for idx, v in enumerate(self.inorder_gen(root)):
            if idx != 0 and v <= last_val:
                return False
            last_val = v
        return True

    def inorder_gen(self, node):
        if node is None:
            return
        if node.left != None:
            for v in self.inorder_gen(node.left):
                yield v
        yield node.val
        if node.right != None:
            for v in self.inorder_gen(node.right):
                yield v


texts:
I am new to jQuery and currently practicing. I wrote a little piece of code to show and hide a navigation on click and change the text of the button when the navigation is opened and closed.

I am fresh in this area, therefore I would very much value getting some feedback about the code.  For example, are there any ways to do it better, with less code or any other area of the matter? I would like a code review to learn and practice (the second if is especially bothering me).

// Function Hide nav
function hideNav() {
$('nav').hide();
}

// Hide Nav
hideNav();

// Function Show Nav

function showNav() {
$('nav').show();
}

// Clickevent on Button
$('button').click(function() {
if($('nav').is(':hidden')){
// Show Nav on Clickevent
showNav();
// Change Text when Nav is showing
$(this).text('Close me');

}
else
hideNav();
// Change Text back when Nav is hiding
if($('nav').is(':hidden')){
$('button').text('Open me');
}
});


texts:
There are 2 arrays. One that consists of Categories and one of Products. Each product pertains to its specific category. I want to join each product to its right category (a category can have multiple products). Each product that 'finds' its category will go in this category's products array.

for ($i = 0; $i < count($prods); $i++)
{
    for ($u = 0; $u < count($cats); $u++)
    {
        if ($prods[$i]['category_code'] === $cats[$u]['category_style_code'])
        {
            if ( !isset($cats[$u]['products']) )
            {
                $cats[$u]['products'] = array();
            }
            array_push($cats[$u]['products'], $prods[$i]);
        }
    }
}

It results in something like:

Array
(
    [0] => Array
        (
            [id] => 1
            [category_style_code] => GA
            [products] => Array
                (
                    [0] => Array
                        (
                            [id] => 1
                            [default_price] => 37.50
                            [category_code] => GA
                        )

                    [1] => Array
                        (
                            [id] => 2
                            [default_price] => 15.00
                            [category_code] => GA
                        )
                )
        )
)

Let's say there are many categories and many products. How would you optimize this code (or do it differently)?


texts: Nesting 3 divs within another div using JavaScript

texts:
For a class that I'm in, we're creating digital Pokemon cards. I'm trying to create elements that are nested within another element and repeated multiple times. For example, I have currently:

But, I only want 3 of the box divs to be inside the column div and then for this model to repeat for every 3 box divs so that it looks like this:

And I want that to repeat until all of the box divs are filled into a column div.

The javascript that I used to make these divs is the following:

function createPokeCard(pokeData) {
  let scene = document.createElement('div')
  let card = document.createElement('div')

  scene.className = 'scene'
  card.className = 'box'

card.addEventListener( 'click', function() {
  card.classList.toggle('is-flipped')
})

  card.appendChild(cardFront(pokeData))
  card.appendChild(cardBack(pokeData))
  mainContainer.appendChild(card)
  mainContainer.appendChild(section)
  mainContainer.appendChild(columns)
  mainContainer.appendChild(column)
  section.appendChild(columns)
  columns.appendChild(column)
  columns.appendChild(card)
  column.appendChild(card)
}

Can you review this code for best coding practices?


texts: Loop Vue2 tag with keyup + modifier and click

texts:
I have following code but wonder if I can loop it instead of copy-pasting.

calculator.ts

data: function() {
  return {
    calcInput: 'user types some value in input with v-model'
  }
},
template: `
  calc

  del

  clr
`

Pass modifier to v-on:keyup is the hardest part here.
@[loopedItem.key]={loopedItem.method} - doesn't work.
In this case I can see in event listeners for example keyup.enter but it doesn't work.


texts:
I previously posted a question on finding the maximum value of an InputIterator range. For completeness, I thought it would be useful to post an implementation that finds the minimum & maximum values, in a similar way to std::minmax_element.

#include <iterator>
#include <algorithm>
#include <functional>
#include <utility>

namespace detail
{
    template <typename InputIt, typename Compare>
    auto minmax_input(InputIt first, InputIt last, Compare comp, std::input_iterator_tag)
    {
        using ValueType = typename std::iterator_traits<InputIt>::value_type;

        std::pair<ValueType, ValueType> result {*first, *first};

        if (++first == last) return result;

        if (comp(*first, result.first)) {
            result.first = *first;
        } else {
            result.second = *first;
        }

        while (++first != last) {
            auto prev = *first;
            if (++first == last) {
                if (comp(prev, result.first))
                    result.first = std::move(prev);
                else if (!comp(prev, result.second))
                    result.second = std::move(prev);
                break;
            } else {
                if (comp(*first, prev)) {
                    if (comp(*first, result.first))
                        result.first = *first;
                    if (!comp(prev, result.second))
                        result.second = std::move(prev);
                } else {
                    if (comp(prev, result.first))
                        result.first = std::move(prev);
                    if (!comp(*first, result.second))
                        result.second = *first;
                }
            }
        }

        return result;
    }

    template <typename ForwardIt, typename Compare>
    auto minmax_input(ForwardIt first, ForwardIt last, Compare comp, std::forward_iterator_tag)
    {
        const auto itr_result = std::minmax_element(first, last, comp);
        return std::make_pair(*itr_result.first, *itr_result.second);
    }
} // namespace detail

template <typename InputIt, typename Compare = std::less<void>>
auto minmax_input(InputIt first, InputIt last, Compare comp = Compare {})
{
    return detail::minmax_input(first, last, comp, typename std::iterator_traits<InputIt>::iterator_category {});
}

As this will presumably be used mostly on input streams, I also thought to provide this helper method:

#include <istream>

template <typename T>
auto minmax_stream(std::istream& in)
{
    return minmax_input(std::istream_iterator<T> {in}, std::istream_iterator<T> {});
}

Used like:

#include <iostream>
#include <sstream>

int main()
{
    std::istringstream ss {"0.1 0.2 0.3 0.4 0.2 0.05 0.1"};

    const auto minmax = minmax_stream<double>(ss);

    std::cout << "minmax is (" << minmax.first << ", " << minmax.second << ")" << std::endl;
}


texts: Generic error handler function for POSIX shell scripts

texts:
Intention

I came with the idea of generic, portable, highly reliable, and further customizable function for Shell scripts, written in POSIX, for error handling.

Purpose

The function shall find out, if the terminal has color support, and act accordingly. If it has, then I highlight the error origin and the exit code with different colors. The main message shall be tabbed from the left, all for the best readability.

Example function call and error handler output (textual) + Explanation

print_usage_and_exit is a self-explanatory function, which watches over the number of given arguments, it accepts exactly one, let's give it some more:

Example function:

print_usage_and_exit()
{
    # check if exactly one argument has been passed
    [ "${#}" -eq 1 ] || print_error_and_exit 1 "print_usage_and_exit" "Exactly one argument has not been passed!\\n\\tPassed: ${*}"

    # check if the argument is a number
    is_number "${1}" || print_error_and_exit 1 "print_usage_and_exit" "The argument is not a number! Exit code expected."

    echo "Usage:   ${0} [-1]"
    echo "         -1: One-time coin collect."
    echo "Default: Repeat coin collecting until interrupted."
    exit "${1}"
}

Example function call - erroneous:

print_usage_and_exit a b c 1 2 3

Example output:

print_usage_and_exit()

        Exactly one argument has not been passed!
        Passed: a b c 1 2 3

exit code = 1

Example error handler output (visual)

The actual error handler function code

print_error_and_exit()
# expected arguments:
# $1 = exit code
# $2 = error origin (usually function name)
# $3 = error message
{
    # check if exactly 3 arguments have been passed
    # if not, print out an internal error without colors
    if [ "${#}" -ne 3 ]
    then
        printf "print_error_and_exit() internal error\\n\\n\\tWrong number of arguments has been passed: %b!\\n\\tExpected the following 3:\\n\\t\\t\$1 - exit code\\n\\t\\t\$2 - error origin\\n\\t\\t\$3 - error message\\n\\nexit code = 1\\n" "${#}" 1>&2
        exit 1
    fi

    # check if the first argument is a number
    # if not, print out an internal error without colors
    if ! [ "${1}" -eq "${1}" ] 2> /dev/null
    then
        printf "print_error_and_exit() internal error\\n\\n\\tThe first argument is not a number: %b!\\n\\tExpected an exit code from the script.\\n\\nexit code = 1\\n" "${1}" 1>&2
        exit 1
    fi

    # check if we have color support
    if [ -x /usr/bin/tput ] && tput setaf 1 > /dev/null 2>&1
    then
        # colors definitions
        readonly bold=$(tput bold)
        readonly red=$(tput setaf 1)
        readonly yellow=$(tput setaf 3)
        readonly nocolor=$(tput sgr0)
        # combinations to reduce the number of printf references
        readonly bold_red="${bold}${red}"
        readonly bold_yellow="${bold}${yellow}"
        # here we do have color support, so we highlight the error origin and the exit code
        printf "%b%b()\\n\\n\\t%b%b%b\\n\\nexit code = %b%b\\n" "${bold_yellow}" "${2}" "${nocolor}" "$3" "${bold_red}" "${1}" "${nocolor}" 1>&2
        exit "$1"
    else
        # here we do not have color support
        printf "%b()\\n\\n\\t%b\\n\\nexit code = %b\\n" "${2}" "${3}" "${1}" 1>&2
        exit "$1"
    fi
}

EDIT

I realized the tput could very well be anywhere else than in /usr/bin/.

So, while keeping the original code untouched, I have changed the line:

if [ -x /usr/bin/tput ] && tput setaf 1 > /dev/null 2>&1

to a more plausible check:

if command -v tput > /dev/null 2>&1 && tput setaf 1 > /dev/null 2>&1


texts: Interpreting database values as times and integers

texts:
I am working through Chapter 10 of Haskell Programming from First Principles.

I've gotten the code to work, but I am uneasy about the fact that a few of my functions - namely, extractUTCTime and extractInteger - are not total functions. There is valid input for which those functions are bottom. I've added the code below, but I was wondering what strategies are available for making extractUTCTime and extractInteger safe. (One strategy that I do know of is changing the type signature of these functions so that they return a value of type Maybe: extractUTCTime :: DatabaseItem -> Maybe UTCTime. I was wondering if there was anything else that can be done).

import Data.Time

data DatabaseItem = DbString String | DbNumber Integer | DbDate UTCTime deriving (Eq, Ord, Show)

theDatabase :: [DatabaseItem]
theDatabase = [DbDate (UTCTime (fromGregorian 1911 5 1) (secondsToDiffTime 34123)), DbNumber 9001, DbString "Hello, world!", DbDate (UTCTime (fromGregorian 1921 5 1) (secondsToDiffTime 34123))]

filterDbDate :: [DatabaseItem] -> [UTCTime]
filterDbDate [] = []
filterDbDate dataBase = [extractUTCTime item | item <- dataBase, isDbDate item]

isDbDate :: DatabaseItem -> Bool
isDbDate (DbDate _) = True
isDbDate _          = False

extractUTCTime :: DatabaseItem -> UTCTime
extractUTCTime (DbDate utcData) = utcData

filterDbNumber :: [DatabaseItem] -> [Integer]
filterDbNumber [] = []
filterDbNumber dataBase = [extractInteger item | item <- dataBase, isDbNumber item]

extractInteger :: DatabaseItem -> Integer
extractInteger (DbNumber int) = int

isDbNumber :: DatabaseItem -> Bool
isDbNumber (DbNumber _) = True
isDbNumber _ = False

mostRecent :: [DatabaseItem] -> UTCTime
mostRecent dataBase = foldr max y ys
                where dates = filterDbDate dataBase
                      y     = head dates
                      ys    = tail dates

sumDb :: [DatabaseItem] -> Integer
sumDb dataBase = foldr (+) 0 dbNumbers
                 where dbNumbers = filterDbNumber dataBase

avgDb :: [DatabaseItem] -> Double
avgDb dataBase = dividend / divisor
                 where dividend = fromIntegral $ sumDb dataBase
                       divisor = fromIntegral $ length $ filterDbNumber dataBase


texts:
The main idea behind this code is to distribute multiple random numbers, but guarantee that the probability of each coming is equal.

The code is really basic:

( function( window ){

    window.RNG = function(min, max){

        if( min / 1 != min )
        {
            throw new TypeError('Expecting Number or NumericString, got ' + ( min != min ? 'NaN' : typeof min ) );
        }
        if(arguments.length > 1)
        {
            if( max / 1 != max )
            {
                throw new TypeError('Expecting Number or NumericString as the second parameter, got ' + typeof max);
            }
            else if( ( min = min >> 0 ) >= ( max = max >> 0 ) )
            {
                throw new RangeError('The 2nd parameter should be higher than the first');
            }
        }
        else
        {
            max = min << 0;
            min = 0;
        }

        var dif = max - min, refill=function(){
            for(var i = min, result={length:0}; i <= max; i++)
            {
                result[i]=true;
                result.length++;
            }
            return result;
        }, avail = refill();

        return {
            valueOf:function(){
                if( !avail.length )
                {
                    avail = refill();
                }

                if( avail.length > 1 )
                {
                    var result;
                    do
                    {
                        result = ( window.Math.random() * ( dif + 1 ) + min ) << 0;
                    }
                    while( !avail[result] );

                    delete avail[result];
                    avail.length--;

                    return result;
                }
                else
                {
                    for(var k in avail)
                    {
                        if(k != 'length')
                        {
                            break;
                        }
                    }

                    avail = refill();

                    return k / 1;

                }
            },
            toString:function(){
                return this.valueOf() + '';
            }
        };

    };

} )( Function('return this')() );

The reason why I use that Function('return this')() is just to ensure I have the actual window object.

In terms of readability, what can I improve?

Is there what bad practices that I'm using?


texts:
My Implementation of a FIFO queue. I am mainly curious about my initialization of empty generic arrays.

public class Queue<T> {

    T queue[];
    public Queue()
    {
        queue = (T[])new Object[0];
    }

    public T pop()
    {
        T queue2[] = (T[])new Object[queue.length-1];
        T obj = queue[0];
        for(int i = 0; i < queue.length-1; i++)
            queue2[i] = queue[i+1];
        queue = queue2;
        return obj;
    }

    public void push(T node)
    {
        T queue2[] = (T[])new Object[queue.length+1];
        for(int i = 0; i < queue.length; i++)
        {
            queue2[i] = queue[i];
        }
        queue2[queue.length] = node;
        queue = queue2;
    }

    public T peek()
    {
        return queue[0];
    }

    public int size()
    {
        return queue.length;
    }

}


texts:
I decided that it would be nice to write some code to draw a cloud of points.

Of course my first thought was to draw some random points but the result is not cloud-ish, it is well... random.

In the end I decided to use the Mitchell random points algoritmh generating pretty good results:

Blue = Random
Red = Cloud (Michelin)

from __future__ import division
import matplotlib.pyplot as plt
import random

# The more the nearest the points
RANDOM_POINTS_PER_GENERATION = 6

def random_point():
    return [random.random(), random.random()]

def average(lst):
    return sum(lst) / len(lst)

def distance(a,b):
    return ((a[0]-b[0])**2 + (a[1]-b[1])**2)

def nearest(random_points, seen_points):
    def distance_to_points(point):
        return average([distance(point, seen_point)
                             for seen_point in seen_points])
    return min(random_points, key=distance_to_points)

def next_point(points):
    random_points = [random_point() for _ in range(RANDOM_POINTS_PER_GENERATION)]
    return nearest(random_points, points)

def mitchell(number_of_points):
    """
    Generates almost random points, but at each iteration
    `k` points are generated and the nearest is taken, in
    order to have a better looking points-cloud.
    """
    points = [random_point()]
    while len(points) < number_of_points:
        points.append(next_point(points))
    return points

def plot_points(points, color):
    plt.plot(*zip(*points), color=color, linestyle='none', marker='.',
             markerfacecolor='blue', markersize=4)

if __name__ == "__main__":
    plot_points(mitchell(250), "red")
    plot_points([random_point() for _ in range(250)], "blue")
    plt.show()


texts: Printing the sums of numbers from 1 to 10 with only 1 loop

texts:
The code below prints sum from 1 to 10:

  \$1\$
  \$1+2 =\$
  \$1+2+3 =\$
  \$1+2+3+4 =\$
  \$......\$
  \$1 + ... 10 = 55\$

public class Solution{

    public static void print_sums(){

        int sum = 0 ;
         for(int i = 1 ; i <= 10 ; i++){
             for(int j = 1 ; j <= i; j++ ){
                sum = sum + j ;
             }
             System.out.println( sum) ;
             sum = 0 ;
         }

    }

    public static void main(String[] args)
    {
        print_sums() ;

    }
}

I wonder out of "efficiency curiosity" - is it possible to do it in 1 loop?  Without 2 nested loops?

i.e. put both i and j in one loop and increment them from there.

I think it is impossible, because **the whole loop will run only 10 times - i = [1,10]

 for(int i = 1 , j = 1 ; j <= i && i <= 10 ; i++, j++)
             //for(int j = 1 ; j <= i; j++ ){
                sum = sum + j ;
             //}
             System.out.println( sum) ;
             sum = 0 ;


texts: Producer - multiple consumer implementation using futures

texts:
I've tried to implement a producer-multiple consumer pattern using futures and I was wondering should it ever deadlock, and if it should, why?

I have this method RunNTimes which I implemented in order to run the implementation, e.g. 1000 times with 500 consumers.

The implementation shouldn't deadlock as far as I know and it often doesn't (running it multiple times and telling RunNTimes to repeat for 1000 times). However, every once in a while it blocks at the first or second run (I'm running it from sbt). For the sake of simplicity, ignore the RunNTimes method, I've included it only to explain why the occasional deadlock seems strange to me.

package comparison_examples.futuresimplementation

import common.MeasurementHelpers._
import common._

import scala.collection.mutable
import scala.concurrent.blocking
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.duration.Duration
import scala.concurrent.{Await, Future, Promise}

case class Item(value: Int)

object ProducerConsumer {

    private val sharedQueue = mutable.Queue[Item]()

    def main(args: Array[String]): Unit = {

        val n: Double = if (args.nonEmpty) args(0).toDouble else Configuration.runTimes.toDouble
        val numConsumers = if (args.length == 2) args(1).toInt else Configuration.numberOfConsumers

        val funRunNTimes = MeasurementHelpers.runNTimes(n.toInt) _

        val results = funRunNTimes {

            val p = Promise[Boolean]()

            val producer = new Producer(p, sharedQueue)
            val cs = startConsumers(numConsumers, List[Consumer](), sharedQueue, p)

            val fp = producer.start()
            val fs = cs.map(x => x.start())

            val f = Future.sequence(fs)

            Await.result(fp, Duration.Inf)
            Await.result(f, Duration.Inf)

            val allElementsObtained = cs.flatMap(_.getObtainedItems)

            println(allElementsObtained.length)
        }

        println(s"Run times: $n")
        println(s"Average number of distinct threads: ${results.map(x => x._3.length).sum / n }")
        println(s"Average duration: ${results.map(x => x._2).sum / n} milliseconds")

        println()
    }

    def startConsumers(max: Int, result: List[Consumer], sharedQueue: mutable.Queue[Item], p: Promise[Boolean]): List[Consumer] =
         if (max == 0) result
         else {
             val consumer = new Consumer(p, sharedQueue)

             startConsumers(max - 1, consumer :: result, sharedQueue, p)
        }
 }

class Producer(p: Promise[Boolean], sharedQueue: mutable.Queue[Item]) {

def start(): Future[Unit] = Future {

    val n = Configuration.workToProduce

        for (i <- 1 to n) {

            val item = Item(i)

                sharedQueue.synchronized {

                    sharedQueue.enqueue(item)
                    sharedQueue.notifyAll()
                }
        }

    p success true
}
}

class Consumer(p: Promise[Boolean], sharedQueue: mutable.Queue[Item]) {

private var obtainedItems = List[Item]()

def getObtainedItems: List[Item] = obtainedItems

def start(): Future[Unit] = Future {

    addCurrentThread()

        while (sharedQueue.nonEmpty || !p.isCompleted) {

            obtainedItems = getItem match {

                case None => obtainedItems
                case Some(item) => item :: obtainedItems
            }
        }
}

def getItem: Option[Item] = blocking {

    sharedQueue.synchronized {

        while (sharedQueue.isEmpty && !p.isCompleted) {

            sharedQueue.wait()
        }

        val result = if (sharedQueue.nonEmpty)
            Some(sharedQueue.dequeue())
        else
            None

        sharedQueue.notifyAll()

        result
    }
}

def printObtainedItems(): Unit =
    obtainedItems.foreach(x => print(s"\t ${x.value}"))
}


texts:
I have a project (ldaplib) I am working on that needs to do ASN1-BER decoding and encoding.  The function I have for the decoding portion is slightly more complex but neither are all that complicated.  I would like to get some feedback on the overall approach as well as the code/exceptions/inline comments.

The decoding specifically uses a named tuple defined much higher in the code as a return type which is then used in many places throughout the code:

BER = namedtuple('BER', 'cls pc tag value')

The encoding portion:

def ber_encode(ber_cls, ber_pc, ber_tag, message):
    """ Encode a message into ASN1-BER (TLV) bytes.
    The ber_cls, ber_pc, and ber_tag should be numbers, the message can be
    bytes, str, or int. """
    if type(message) not in (str, int, bytes):
        raise TypeError("Requires str, int, or bytes object.")

    encoded = (ber_cls + ber_pc + ber_tag).to_bytes(1, byteorder='big')

    if type(message) is int:
        bytelength = (message.bit_length() // 8) + 1
        message = message.to_bytes(bytelength, byteorder='big')
    elif type(message) is str:
        message = message.encode(encoding='ascii')

    if len(message) == 0:
        return encoded + int(0).to_bytes(1, byteorder='big')

    # Short form or Long form?
    length = len(message)
    if length < 0x80:
        encoded += length.to_bytes(1, byteorder='big')
    else:
        bytelength = (length.bit_length() // 8) + 1
        encoded += (0x80 + bytelength).to_bytes(1, byteorder='big')
        encoded += length.to_bytes(bytelength, byteorder='big')

    # Add the message
    encoded += message

    return encoded

The decoding portion:

def ber_decode(message, result=None):
    """ Decode a message from ASN1-BER (TLV) bytes into a list of byte values.
    Values that contain embedded types will need to call this function to
    break the objects into their individual type/value components. """
    if type(message) is not bytes:
        raise TypeError("Requires bytes object.")

    if not result:
        result = []

    if len(message) == 0:
        raise Exception("No message")

    # Use masks to isolate the binary parts
    ber_type = message[0]  # NOQA
    ber_cls = ber_type & 0b11000000
    ber_pc  = ber_type & 0b00100000
    ber_tag = ber_type & 0b00011111

    ber_len = message[1]

    # Assume that the ber_value is offset 2 or is blank
    offset = 2

    # Only the definite form of length encoding is used.
    if ber_len > 0x80:
        nbytes = ber_len & 0x7f
        ber_len = int.from_bytes(
                message[offset:offset + nbytes], byteorder='big')
        offset = offset + nbytes
        ber_value = message[offset: offset + ber_len]
    else:
        ber_value = message[offset: offset + ber_len]

    # Append the decoded message part.
    result.append(BER(ber_cls, ber_pc, ber_tag, ber_value))
    message = message[ber_len + offset:]

    # If the message had only one type then we are done, if not recurse.
    if len(message) == 0:
        return result
    else:
        return ber_decode(message, result)


texts:
I started Python 2-3 months ago, but I really haven't done much since then, just little things. Yesterday, I wrote this simple quadratic equation solver. You can give \$a, b\$ and \$c\$ any value, but they must all be integers.

I really want to know what you think about it.

from math import sqrt

while True:
        try:
                a = int(input("\nEnter a : "))
                b = int(input("Enter b : "))
                c = int(input("Enter c : "))
        except:
                print("You can only enter integers")
                continue
        if a > 0:
            sgn_a = ""
            if b > 0:
                sgn_b = "+"
            else:
                sgn_b = "-"
            if c > 0:
                sgn_c = "+"
            else:
                sgn_c = "-"
        else:
            sgn_a = "-"
            if b > 0:
                sgn_b = "+"
            else:
                sgn_b = "-"
            if c > 0:
                sgn_c = "+"
            else:
                sgn_c = "-"

        if a == 0:
            part_a = ""
        elif a == 1:
            part_a = sgn_a+"x"+str(chr(0x00B2))
        else:
            part_a = sgn_a+str(abs(a))+"x"+str(chr(0x00B2))

        if b == 0:
            part_b = ""
        elif b == 1:
            if a != 0:
                part_b = sgn_b+"x"
            else:
                part_b = "x"
        else:
            if a != 0:
                part_b = sgn_b+str(abs(b))+"x"
            else:
                part_b = str(abs(b))+"x"

        if c == 0:
            if a == 0 and b == 0:
                part_c = "0"
            else:
                part_c = ""
        elif a == 0 and b == 0:
            part_c = str(abs(c))
        else:
            part_c = sgn_c+str(abs(c))

        print("\nYour equation is %s%s%s = 0\n" %(part_a,part_b,part_c))
        if a != 0 and b != 0 and c != 0:
                D = b**2-(4*a*c)
                if D > 0:
                        x_1 = ((-b+sqrt(D))/2*a)
                        x_2 = ((-b-sqrt(D))/2*a)
                        print("X1 = %f\nX2 = %f" %(x_1,x_2))
                elif D == 0:
                        x = -b/(2*a)
                        print("X1 = X2 = %d" %x)
                elif D < 0:
                        x_1 = ((-b+sqrt(-D))/2*a)
                        x_2 = ((-b-sqrt(-D))/2*a)
                        print("X1 = %f%s\nX2 = %f%s" %(x_1,"i",x_2,"i"))
        elif a == 0 and b != 0 and c != 0:
                x = -c/b
                if c % b != 0:
                        print("X = %d/%d or %f" %(-c,b,x))
                else:
                        print("X = %d" %x)
        elif a != 0 and b == 0 and c != 0:
                if -c > 0:
                        x_1 = sqrt(-c/a)
                        x_2 = -x_1
                        print("X1 = %f\nX2 = %f" %(x_1,x_2))
                else:
                        x_1 = sqrt(c/a)
                        x_2 = -x_1
                        print("X1 = %f%s\nX2 = %f%s" %(x_1,"i",x_2,"i"))
        elif a != 0 and b != 0 and c == 0:
                x_2 = -b/a
                if b % a != 0:
                        print("X1 = 0\nX2 = %d/%d or %f" %(-b,a,x_2))
                else:
                        print("X1 = 0\nX2 = %d" %x_2)
        elif a == 0 and b != 0 and c == 0:
                        print("X = 0")
        elif a == 0 and b == 0:
                if c != 0:
                        print(c,"!= 0")
                else:
                        print("0 = 0. DUH!")


texts: 2 Weeks into Go: Golang Tour WebCrawler Exercise

texts:
I'm on week 2 of learning go. I just completed the golang.org exercise on creating web crawler (https://tour.golang.org/concurrency/10) and I would please like feedback on my code.  It feels overly complicated but I'm a noob so I don't know.
I came across this post on the same exercies a few minutes ago while writing up this question. The only posted feedback there is one that I already implemented, so I'm hoping to get something different.
I also am not a fan of that implementation because it relies on knowing exactly how many urls will need to be fetched, which works with the fake data but wouldn't work with real data.
type Fetcher interface {
    // Fetch returns the body of URL and
    // a slice of URLs found on that page.
    Fetch(url string) (body string, urls []string, err error)
}

type FetchState struct {
    sync.Mutex
    fetchedUrls map[string]bool
}

// Crawl uses fetcher to recursively crawl
// pages starting with url, to a maximum of depth.
func Crawl(url string, depth int, fetcher Fetcher, state *FetchState) {
    if depth <= 0 {
        return
    }

    state.Lock()

    if _, ok := state.fetchedUrls[url]; ok {
        state.Unlock()
        return
    }

    state.Unlock()
    body, urls, err := fetcher.Fetch(url)

    if err != nil {
        fmt.Println(err)
        return
    }

    fmt.Printf("found: %s %q\n", url, body)
    state.Lock()
    state.fetchedUrls[url] = true
    state.Unlock()

    var wg sync.WaitGroup

    for _, u := range urls {
        wg.Add(1)
        go func(urlToCrawl string, group *sync.WaitGroup) {
            Crawl(urlToCrawl, depth-1, fetcher, state)
            group.Done()
        }(u, &wg)
    }

    wg.Wait()

    return
}

func main() {
    state := &FetchState{
        fetchedUrls: make(map[string]bool),
    }

    Crawl("https://golang.org/", 4, fetcher, state)
}

// fakeFetcher is Fetcher that returns canned results.
type fakeFetcher map[string]*fakeResult

type fakeResult struct {
    body string
    urls []string
}

func (f fakeFetcher) Fetch(url string) (string, []string, error) {
    time.Sleep(1000 * time.Millisecond)

    if res, ok := f[url]; ok {
        return res.body, res.urls, nil
    }
    return "", nil, fmt.Errorf("not found: %s", url)
}

// fetcher is a populated fakeFetcher.
var fetcher = fakeFetcher{
    "https://golang.org/": &fakeResult{
        "The Go Programming Language",
        []string{
            "https://golang.org/pkg/",
            "https://golang.org/cmd/",
        },
    },
    "https://golang.org/pkg/": &fakeResult{
        "Packages",
        []string{
            "https://golang.org/",
            "https://golang.org/cmd/",
            "https://golang.org/pkg/fmt/",
            "https://golang.org/pkg/os/",
        },
    },
    "https://golang.org/pkg/fmt/": &fakeResult{
        "Package fmt",
        []string{
            "https://golang.org/",
            "https://golang.org/pkg/",
        },
    },
    "https://golang.org/cmd/": &fakeResult{
        "Package cmd",
        []string{
        },
    },
    "https://golang.org/pkg/os/": &fakeResult{
        "Package os",
        []string{
            "https://golang.org/",
            "https://golang.org/pkg/",
        },
    },
}

Original Exercise: https://tour.golang.org/concurrency/10
This solution: https://play.golang.org/p/PKnquXa0D82


texts:
This method changes all URLs in the string into an HTML link. The goal is to not mutate the string passed in, which I believe is a good practice.

The new_string code in this method does not seem idiomatic.

def autolink_string string
  return    if string.nil?
  return '' if string.empty?

  regex = /(\S+\.(com|net|org|edu|gov)(\/\S+)?)/
  groups = string.scan regex
  matches = groups.map &:first
  new_string = string.clone

  matches.each do |match|
    new_string.gsub! match, "#{ match }"
  end

  new_string
end

How can I refactor to remove the new_string? Any other suggestions?


texts:
This code is meant to create a list of subsets of a given set which is represented as a list.

I'm doing this to improve my style and to improve my knowledge of fundamental algorithms/data structures for an upcoming coding interview.

def subsets(s):
    if s == []:
        return [s]
    sets = [s]
    for i in range(0, len(s)):
        tmp_subsets = subsets(s[:i] + s[i+1:])
        for subset in tmp_subsets:
            if subset not in sets:
                sets.append(subset)
    return sets

I'm also not sure if using the set() data structure would be considered cheating in an interview context.

If there are any ideas about how to improve its performance without significantly compromising on readability I would also be open to that.


texts: Convert query string into object in JavaScript

texts:
Suppose I have this query and want to convert into an object

  a1.b2.article1=0&a2.article2=1&c3!article3=0&article16-abc=2

output for this should be

article1: 'DRAFT',
article2: 'REVISION',
article3: 'DRAFT',
article16: 'READY'

Please review my code. Is this the right way to do perform this task?

let a = "a1.b2.article1=0&a2.article2=1&c3!article3=0&article16-abc=2";
let con = {'0':'DRAFT', '1':'REVISION', '2':'READY'}
let obj = {};
a = a.replace(/-abc/g, "");
a = a.replace(/[.!]/g, "&");
a = a.split("&").forEach((v, i) => {
    let b = v.split("=");
    if (b.length > 1) {
       Object.assign(obj,{[b[0]]:con[b[1]]})
    }
});

I'm wondering if there any optimized way to do this.


texts: How to Improve This Program, Add Comments, etc.?

texts:
Do you have any suggestions to improve or extend this script? Any ideas for removing or adding comments/docstrings?

import dbm
import subprocess
import time
subprocess.call("clear")
try:
    # Tries to import cPickle, a faster implementation of pickle.
    import cPickle as pickle
except ImportError:
    import pickle

class PickleDB:
    def open_db(self):
        """Gets and opens the database"""
        self.db_name = input("Enter a database name\n")
        # Makes sure the database name is compatible
        db_parts = self.db_name.split(".")
        self.db_name = db_parts[0]
        self.db = dbm.open(self.db_name, "n")

    def get_data(self):
        """Gets data to write into the database"""
        subprocess.call("clear")
        self.raw_data = input("Enter your raw data\n")
        # Pickles data
        self.pickled_data = pickle.dumps(self.raw_data)

    def write_to_db(self):
        """Writes data into database"""
        # Logs time
        self.start = time.time()
        # Creates keys
        self.db["raw"] = self.raw_data
        self.db["pickled"] = self.pickled_data

    def close_db(self):
        """Closes database"""
        self.db.close()
        # Logs end time
        self.end = time.time()

    def info(self):
        """Prints out info about the database"""
        subprocess.call("clear")
        print("Load data from database using dbm")
        print("Keys: raw\tpickled")
        # Prints total time
        print("Speed:", self.end - self.start, "seconds")

# Function calls
pickled_db = PickleDB()
pickled_db.open_db()
pickled_db.get_data()
pickled_db.write_to_db()
pickled_db.close_db()
pickled_db.info()


texts: Find all the countries I can visit by just crossing direct borders

texts:
I was helping on this question. There you have a table border to indicate countryA and countryB have a common border. And want to know what country you can reach starting from country S Sweden.

I did my recursion and works ok. But I feel I cheat a little bit. Taking advantage the number of countries are limited put a break on 300. But in a different problem where I don't know the upper limit won't be able to do the same.

How I optimize my query so recursion doesn't travel the same path again?

SQL Fiddle Demo

WITH RECURSIVE travel(r_level, country) AS (
    select distinct 1 as r_level,
                    CASE WHEN country1 = 'S' THEN country2
                         ELSE country1
                    END as country
    from borders
    where country1 = 'S'
       or country2 = 'S'
    UNION
    select distinct t.r_level + 1 as r_level,
                    CASE WHEN b.country1 = t.country THEN b.country2
                         ELSE b.country1
                    END as country
    from borders b
    join travel  t
      ON (b.country1 = t.country OR b.country2 = t.country)
     AND (b.country1 <> 'S' AND b.country2 <> 'S')
    WHERE t.r_level < 300
)
SELECT DISTINCT country
FROM travel

I can't use subquery based on the same recursive table:

AND (    b.country1 NOT IN (SELECT country FROM Travel)
     AND b.country2 NOT IN (SELECT country FROM Travel)
    )


texts: Static variable representing program state accessed with multiple functions

texts:
I have this method that performs certain functions based on the state that the algorithm is currently at:

static infoStruct_t info;

void first_part_of_algorithm(void){
    info.state = FIRST_STATE;
    //set other information here as well
    while(info.state < FINAL_STATE){
        switch(info.state){

            case FIRST_STATE:
                perform_first_state_function();
                break;

            case SECOND_STATE:
                perform_second_state_function();
                break;

            case THIRD_STATE:
                perform_check_needed_for_algorithm();
                break;

            default:
                //should never be reached
                break;

        }
    }

}

Now in each of these "perform" functions, the state can change. The first function always causes the state to go to the second state, the second function always makes the state go to the third state, and the third function will either reset the state to the first state, or go to the final state and leave the first part of the algorithm. Also, different parts of the info struct are set at various points in any of the functions.

I have not yet written the second part of the algorithm, but it will need to have access to the info struct

Here are the following state / check functions:

void perform_first_state_function(void){
    while(wait_for_condition()!=SUCCESS){
        sleep();
    }
    info.state = SECOND_STATE;
    sleep();
}

void perform_second_state_function(void){
    int attempts = 0;
    while(attempts < ALLOWED_ATTEMPTS){
        if(event_is_ready()){
            if(info.detection_number==0){
                //set various info properties
                ...
                info.first_detection_time = get_time();
                info.detection_number = 1;
                break;
            }
            else{
                //set other info properties
                ...
                info.second_detection_time = get_time();
                info.state = THIRD_STATE;
                break;
            }
        }
        attempts++;
        sleep();
    }
}

My questions are:

Is this a code smell that the functions are implicitly accessing the static info variable?
Should I explicitly pass in the info struct as a pointer? (for readability)
Does the info struct need to be a singleton?
Any general suggestions?


texts:
I have one function in my code to detect edges in a canvas but it's the slowest part of my code and is used everywhere. If I could just optimise this, my whole program would speed up considerably.

Maybe something better can be done with Em6?

Basically the function goes from the left until it finds a pixel colour greater (or less than) the colour value passed to the function. Then it gets the maximum or minimum of all the values which is the edge of whatever is inside the image.

Then it does the same for the top, the right the bottom to find all edges. Useful for cropping something within a canvas.

function getEdges(tempcanv, colour, which, condition) {
    let ledge = [], redge = [], tedge = [], bedge = [];
    const canvwidth = tempcanv.width, canvheight = tempcanv.height;
    const contextd = tempcanv.getContext('2d');
    for (let y = 0; y < canvheight; y++) {//left edge
        for (let x = 0; x < canvwidth; x++) {
            const data = contextd.getImageData(x, y, 1, 1).data;
            if (condition(data[which], colour)) {
                ledge.push(x);
                break;
            }
        }
    }
    ledge = Math.min(...ledge);
    const llim = ledge === 0 ? ledge : ledge - 1;
    for (let x = llim; x < canvwidth; x++) {//top edge
        for (let y = 0; y < canvheight; y++) {
            const data = contextd.getImageData(x, y, 1, 1).data;
            if (condition(data[which], colour)) {
                tedge.push(y);
                break;
            }
        }
    }
    tedge = Math.min(...tedge);
    const tlim = tedge === 0 ? tedge : tedge - 1;
    for (let y = tlim; y < canvheight; y++) {//right edge
        for (let x = canvwidth - 1; x >= ledge; x--) {
            const data = contextd.getImageData(x, y, 1, 1).data;
            if (condition(data[which], colour)) {
                redge.push(x);
                break;
            }
        }
    }
    redge = Math.max(...redge);
    for (let x = llim; x <= redge; x++) {//bottom edge
        for (let y = canvheight - 1; y >= tedge; y--) {
            const data = contextd.getImageData(x, y, 1, 1).data;
            if (condition(data[which], colour)) {
                bedge.push(y);
                break;
            }
        }
    }
    return [ledge, tedge, redge + 1, Math.max(...bedge) + 1]
}

//(canvas passed, colour threshold, R,G or B, greater or less than)
getEdges(canvas, 180, 0, (a, b) => a > b))

My code does have some optimisation since as it finds an edge, the next edge check does not check the dead space already checked.

Here is a test shape.


texts:
I've written an algorithm for integer multiplication using the Karatsuba method in C++. This implementation is far from ideal, so any comments are welcome.

#define _CRT_SECURE_NO_WARNINGS

#include <iostream>

#include <cstdio>
#include <algorithm>
#include <cstring>
#include <cstdlib>
#include <cassert>
#include <cstring>

const int MAX_LENGTH = 50000 * 2 + 1;

void add_leading_zeros(char* a, int n) {
  int lena = strlen(a);
  for (int i = lena - 1 + n; i >= n; --i) {
    a[i] = a[i - n];
  }
  a[lena + n] = 0;
  for (int i = 0; i < n; ++i) {
    a[i] = '0';
  }
}

void remove_leading_zeros(char* a) {
  int lena = strlen(a);
  int ind = 0;
  while (ind < lena && a[ind] == '0') {
    ++ind;
  }

  for (int i = ind; i < lena; ++i) {
    a[i - ind] = a[i];
  }
  a[lena - ind] = 0;
}

void sum(char* a, char* b, char* res) {
  int lena = strlen(a);
  int lenb = strlen(b);

  if (lena < lenb) {
    std::swap(a, b);
    std::swap(lena, lenb);
  }

  int toAdd = 0;
  for (int inda = lena - 1, indb = lenb - 1; inda >= 0; --inda, --indb) {
    int x = a[inda] - '0';
    int y = indb >= 0 ? b[indb] - '0' : 0;

    int cur = x + y + toAdd;

    if (cur >= 10) {
      toAdd = 1;
      cur -= 10;
    } else {
      toAdd = 0;
    }

    res[inda] = cur + '0';
  }

  if (toAdd == 1) {
    add_leading_zeros(res, 1);
    res[0] = '1';
  }
}

// assume that a > b
void sub(char* a, char* b, char* res) {
  int lena = strlen(a);
  int lenb = strlen(b);

  //assert(lena >= lenb);

  int toSub = 0;
  for (int inda = lena - 1, indb = lenb - 1; inda >= 0; --inda, --indb) {
    int x = a[inda] - '0';
    int y = indb >= 0 ? b[indb] - '0' : 0;

    if (toSub == 1) {
      x--;
    }
    int cur;
    if (x < y) {
      cur = x + 10 - y;
      toSub = 1;
    } else {
      cur = x - y;
      toSub = 0;
    }

    res[inda] = cur + '0';
  }
}

// returns a * 10^n
void mult10(char* a, int n) {
  int lena = strlen(a);

  if (lena == 1 && a[0] == '0') {
    return;
  }

  for (int i = lena; i < lena + n; ++i) {
    a[i] = '0';
  }
  a[lena + n] = 0;
}

char* CreateArray(int len) {
  char* res = new char[len];
  memset(res, 0, len);
  return res;
}

// add leading zeros if needed
void make_equal_length(char* a, char* b) {
  int lena = strlen(a);
  int lenb = strlen(b);

  int n = std::max(lena, lenb);

  add_leading_zeros(a, n - lena);
  add_leading_zeros(b, n - lenb);
}

void karatsuba(char* x, char* y, char* res) {
  make_equal_length(x, y);

  int len = strlen(x);
  if (len == 1) {
    int val = (x[0] - '0') * (y[0] - '0');
    if (val < 10) {
      res[0] = val + '0';
    } else {
      res[0] = (val / 10) + '0';
      res[1] = (val % 10) + '0';
    }
  } else {
    char* xl = CreateArray(len);
    char* xr = CreateArray(len);
    char* yl = CreateArray(len);
    char* yr = CreateArray(len);

    int rightSize = len / 2;
    int leftSize = len - rightSize;

    strncpy(xl, x, leftSize);
    strcpy(xr, x + leftSize);
    strncpy(yl, y, leftSize);
    strcpy(yr, y + leftSize);

    int maxl = 3 * len;
    char* P1 = CreateArray(maxl);
    char* P2 = CreateArray(maxl);
    char* P3 = CreateArray(maxl);

    karatsuba(xl, yl, P1);
    karatsuba(xr, yr, P2);

    char* tmp1 = CreateArray(maxl);
    char* tmp2 = CreateArray(maxl);

    sum(xl, xr, tmp1);
    sum(yl, yr, tmp2);
    karatsuba(tmp1, tmp2, P3);

    sub(P3, P1, P3);
    sub(P3, P2, P3);
    mult10(P3, rightSize);

    mult10(P1, 2 * rightSize);

    sum(P1, P2, res);
    sum(res, P3, res);

    remove_leading_zeros(res);

    delete[] xl;
    delete[] xr;
    delete[] yl;
    delete[] yr;
    delete[] tmp1;
    delete[] tmp2;
    delete[] P1;
    delete[] P2;
    delete[] P3;
  }
}

int main() {
  char a[MAX_LENGTH], b[MAX_LENGTH];
  scanf("%s\n%s", a, b);

  char* res = CreateArray(MAX_LENGTH);
  karatsuba(a, b, res);

  printf("%s\n", res);

  scanf("%d", 1);

  return 0;
}


texts: Excel .find Macro to write data to archive

texts:
I would like to speed up this piece of code. The macro gets a search variable from the worksheet "RAW_DATA_ARCHIVE" and then it should find it in the worksheet "RAW DATA". When it finds accordance then the value of column A from worksheet "RAW DATA" will be written in the last column of "RAW_DATA_ARCHIVE".

 For i = 2 To ws1LRow
    SearchString = ws1.Range("A" & i).Value
    Set aCell = ws2.Columns(5).Find(What:=SearchString, LookIn:=xlValues, _
                LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
                MatchCase:=False, SearchFormat:=False)
    'If match found
    If Not aCell Is Nothing Then
        ws1.Cells(i, 80).Value = ws2.Cells(aCell.Row, 1).Value

    End If
Next


texts: CSS Coding Style - Floating and text alignment

texts:
I'm not sure what is the best way to handle css when I have two uses of a class where the difference is one floats left and the other right.
An example:

img.screenshot{
width:100px;
height:110px;
padding:5px;
}

Do I do this:

img.screenshot.floatLeft{
float:left
}
img.screenshot.floatRight{
float:right;
}

Or this:

.floatLeft{float:left;}
.floatRight{float:right;}

Or:

...
...

Or something else?

The one that makes the most sense to me is the .float... class because it can be used my many elements, but it seems a bit pointless having a class that just wraps a single tag like that.
I have the same question regarding text alignment as well.

I don't have much experience with CSS & HTML.


texts:
i have some issues dealing with a simple case in my redux-react app: i want to reset an input text after an asynchronous operation ignited by a button.

Let’s say we have an input text in which you put a text and this is passed through a onClick event to a dispatch action.
This action contacts a server and after the server response i want to reset the input field.

I’ve implemented a number of solutions (i’m using redux thunk) to this problem but i’m not sure if they are hacky ways to solve it, let me show you:

1) Presentational component (the input field) implements a reset method that is passed as a value to the onClick method.

export default React.createClass({

  reset: function () {
    this.setState({searchText: ''})
  },

  getInitialState: function () {
    return {
      searchText: ''
    }
  },

  render: function () {
    return (

          <TextField
            value={this.state.searchText}
            onChange={e => this.setState({ searchText: e.target.value })}
          />
          <RaisedButton
            onClick={this.props.startSearch.bind(null,
              this.state.searchText,
              this.reset)} // ===> HERE THE RESET FUNCTION IS PASSED
          />

    )
  }
})

The container dispatches the action and then calls the reset method.

const mapDispatchToProps = (dispatch) => {
  return {
    startSearch: (searchText, reset) => {
      dispatch(actions.startSearch(searchText))
      .then(() => reset())
    }
  }
}

2) Using ref (https://facebook.github.io/react/docs/refs-and-the-dom.html)

The container gets a reference to its child and calls reset through it

const SearchUserContainer = React.createClass({

  startSearch: (searchText) => {
    dispatch(actions.startSearch(searchText))
    .then(() => this.child.reset())
  },

  render: function () {
    return (
      <SearchUser {...this.props} ref={(child) => { this.child = child; }}/>
    )
  }
})

3) The Redux Way.

searchText is managed by the store thus the action dispatched triggers a resolver that reset the searchText value, the container updates its child and we are done, well… almost:
the presentational component is a controlled component that means it manages the input text as an internal state, i think we have to find a way to make the two ‘state managers’ coexist.

I wrote this code to manage the internal state and the state coming from redux, in few words the presentational gets the initial value from redux, then updates it in the onChange event and it’s ready to receive updates from redux thanks to componentWillReceiveProps.

export default React.createClass({

  getInitialState: function () {
    return {
      searchText: this.props.searchText ==> REDUX
    }
  },

  componentWillReceiveProps: function (nextProps) {
    this.setState({
      searchText: nextProps.searchText ==> REDUX
    })
  },

  render: function () {
    return (

          <TextField
            value={this.state.searchText}
            onChange={e => this.setState({ searchText: e.target.value })}
          />
          <RaisedButton
            onClick={this.props.startSearch.bind(null, this.state.searchText)}
          />

    )
  }
})

4) Redux-Form
To complete the picture i link the redux-form options to do that
http://redux-form.com/6.5.0/docs/faq/HowToClear.md/

What do you think about those ideas?
Thanks.


texts:
I have some elixir code I am using to score a ping pong game. Since I am new to functional programming I was hoping there might be a more elegant solution to this.

This part of the code is used in a GenServer to check if the next point could result in a win. So that means will the leading players next point meet the minimum score requirement (11 or 21 in ping pong) and also be 2 points in front of the other play.

Anyone got a better idea here?

def handle_call(:next_point_wins, _from, game) do
#game.score = [10,5]
nextPlayer1 = List.first(game.score) + 1
nextPlayer2 = List.last(game.score) + 1

scoreDifference =
  case nextPlayer1 > nextPlayer2 do
    true
      ->
      leader = nextPlayer1
      nextPlayer1 - nextPlayer2
    false
      ->
      leader = nextPlayer2
      nextPlayer2 - nextPlayer1
  end

cond do
  scoreDifference + 1 >= 2 and leader >= game.winningScore
    ->
      IO.puts "SOMEONE IS ABOUT TO WIN"
      {:reply, :ok, game}
  true
    ->
      IO.puts "NO-ONE IS ABOUT TO WIN"
      {:reply, :ok, game}
end

end


texts:
Given a set of overlapping boxes, and a set of points, I'd like to be able to determine which of the boxes contain each point. The number of points is much larger than the number of boxes, and I'd like to do it faster that brute force, so I'm trying to do it with a map-like structure.

My current attempt is below, it seems to pass my initial tests but I think there are some problems.

There's a few places where I decrement std::map iterators - is it well defined in this case? Should I not be using lower_bound?
I keep an empty map on the BoxTree purely so I can make GetBoxesContaining() return by const reference - is there a better solution?

#include <list>
#include <map>
#include <limits>

struct BoxSample {
  double m_lowerX, m_upperX, m_lowerY, m_upperY;
};

//Templated so can handle either the outer or inner map of BoxTree
//Checks that the map contains an element with the same key
template<typename T, typename Bound>
typename std::map<Bound, T>::iterator VerifyBound(typename std::map<Bound, T>& mapRef, Bound key)
{
  auto lb = mapRef.lower_bound(key);
  if(lb == mapRef.end() || (lb != mapRef.begin() && lb->first != key))
  {
    --lb;
    //Populates the new key with the contents from the immediately lowest keypair
    auto parib = mapRef.insert(std::make_pair(key, lb->second));
    return parib.first;
  } else {
    //Either entry already exists or new key <= minimum
    return lb;
  }
}

template<typename Box, typename Bound>
class BoxTree {
  std::map<Bound, std::map<Bound, std::list<Box>>> m_tree;
  std::list<Box> m_empty;
public:
  BoxTree(Bound min)
    :m_tree() {
      m_tree[min][min] = std::list<Box>();
  }
  void Insert(const Box& t)
  {
    auto xLB = VerifyBound(m_tree, t.m_lowerX);
    auto xUB = VerifyBound(m_tree, t.m_upperX);
    while(xLB != xUB) {
      auto yLB = VerifyBound(xLB->second, t.m_lowerY);
      auto yUB = VerifyBound(xLB->second, t.m_upperY);
      while(yLB != yUB)
      {
        yLB->second.push_front(t);
        ++yLB;
      }
      ++xLB;
    }
  }
  //Should return all boxes A such that A.lowerX <= x < A.lowerX && A.lowerY <= y < A.lowerY
  const std::list<Box>& GetBoxesContaining(const Bound& x, const Bound& y) {
    auto xSet = m_tree.lower_bound(x);
    if(xSet != m_tree.begin())
    {
      --xSet;
      auto ySet = xSet->second.lower_bound(y);
      if(ySet != xSet->second.begin())
      {
        --ySet;
        return ySet->second;
      }
    }
    return m_empty;
  }

};

//Sample usage
class BoxTreeSample {
  BoxTree<BoxSample, double> m_impl;
public:
  BoxTreeSample(): m_impl(-1.0 * std::numeric_limits<double>::infinity()) {
    BoxSample box1 = { 0.0, 10.0, 0.0, 10.0 };
    BoxSample box2 = { 0.0, 10.0, 0.0, 20.0 };
    BoxSample box3 = { 5.0, 10.0, 5.0, 15.0 };
    m_impl.Insert(box1);
    m_impl.Insert(box2);
    m_impl.Insert(box3);
    auto t1 = m_impl.GetBoxesContaining(2.5, 12.5);
    auto t2 = m_impl.GetBoxesContaining(7.5, 12.5);
  }
};
int main() {
  auto zz = BoxTreeSample();
  return 0;
}


texts:
I've implemented the search/insert part of a hashtable in JavaScript.
This is in linear probing style. It resizes when the array is out of space.

var share = { bucketSize: 10 };

function hash(key){
  return key % share.bucketSize;
}

function expandArr(arr){
  share.bucketSize = share.bucketSize * 2;
  let newArr = [];
  for(let i=0; i<arr.length; i++){
    let item = arr[i];
    let key = item.key;
    hashInsert(key, item, newArr);
  }
  arr = newArr;
}

function hashInsert(key, data, arr){
  let bucketKey = hash(key);
  let hasReset = false;
  let pointer = bucketKey;
  while(true){
    if(pointer >= share.bucketSize){ // bound check
      pointer = 0;
      hasReset = true;
    }
    if(pointer === bucketKey && hasReset){ // all full
      expandArr(arr);
      bucketKey = hash(key);
      pointer = bucketKey;
      hasReset = false;
    }
    if(arr[pointer] === undefined){ // found space
      arr[pointer] = { key: key, data: data };
      break;
    }
    pointer++;
  }
}
function hashSearch(key, arr){
  let bucketKey = hash(key);
  let hasReset = false;
  let pointer = bucketKey;
  while(true){
    if(pointer === bucketKey && hasReset){ // complete cycle
      return undefined;
    }
    if(pointer >= share.bucketSize){ // bound check
      pointer = 0;
      hasReset = true;
    }
    let curr = arr[pointer];
    if(curr === undefined){ // not found
      return undefined;
    }
    if(curr.key === key){ // found it
      return curr;
    }
    pointer++;
  }
}

var arr = [];

for(var i=0; i<100; i++){
  hashInsert(i, 'data ' + i, arr);
  console.log( hashSearch(i, arr) );
}


texts:
I wrote a solution for SPOJ "It's a murder!". I'm exceeding the time limit even after n log(n) solution and fast I/O.

Given a list of numbers, I need to calculate the sum of the sum of the previously encountered numbers that are smaller than the current number.  For example, given 1 5 3 6 4, the answer is

(0) + (1) + (1) + (1 + 5 + 3) + (1 + 3) = 15

My code has complexity n log(n) and is pretty much similar to how we calculate the number of inversions. The function merge in the code below merges two sorted arrays and the function merge_sort is the basic call to merge sort procedure. The array sum1 stores the cumulative sum in array1 of elements whose index is strictly less less that current index . The variable ans stores the final answer. How can I make my code more efficient ?

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

//Declaration of global variables
int array[100000] , array1[100000] , array2[100000]   ;
long long int sum1[100000] ;
long long int ans ;

void merge_sort(int left , int right) ;
void merge(int left , int mid , int right) ;

int main()
{
    int t,counter,n,i ;

    // t is the number of testcases
    scanf("%d",&t) ;

    for(counter=0;counter<t;counter++)
    {
        // n is the number of elements in the array
        scanf("%d",&n) ;

        for(i=0;i<n;i++)
        {
            scanf("%d",&array[i]) ;

        }

        // ans hold the final answer and so it is initialized to 0 for every test case
        ans =0 ;
        merge_sort(0 , n-1) ;

        printf("%lld\n",ans );

    }

}

void merge(int left , int mid , int right)
{
    int  index , index1 , index2 ;

     // array1 is used to store the elements from left to mid
     // array2 is used to store the elemetns from mid+1 to right
     // sum1 holds the sum of elements whose index is less than current index in array1 so that sum1[0] is always 0 .

     // sum1 is initialised to 0
     memset(sum1,0,sizeof(sum1)) ;

    // copying into array1 from left to mid
    index1 = 0 ;
    for(index=left;index<mid+1;index++)
    {
        if(index1!=0)
        {
            sum1[index1] = sum1[index1-1] + array1[index1-1] ;
        }

        array1[index1] = array[index] ;
        index1++ ;
    }

    // copying into array2 from mid+1 to right
    index2 = 0;
    for(index=mid+1;index<right+1;index++)
    {

        array2[index2] = array[index] ;
        index2++ ;
    }

    //merging the two arrays array1 and array2 and adding to the variable  ans array[index1] if array1[index1] < array2[index2]
    index1 = 0 ;
    index2 = 0 ;
    index = left ;
    while((index1<mid-left+1)&&(index2<right-mid))
    {
        if(array1[index1]<array2[index2])
        {

            array[index] = array1[index1] ;
            index++ ;
            index1++ ;
        }
        else if(array1[index1]>=array2[index2])
        {
            ans = ans + sum1[index1];
            array[index] = array2[index2] ;
            index++ ;
            index2++ ;
        }

    }

    if(index1<mid-left+1)
    {
        while(index1<mid-left+1)
        {
            array[index] = array1[index1] ;
            index++ ;
            index1++ ;
        }
    }
    else if(index2<right-mid)
    {
        while(index2<right-mid)
        {
            ans = ans + sum1[index1-1] + array1[index1-1];
            array[index] = array2[index2] ;
            index++ ;
            index2++ ;
        }
    }
}

void merge_sort(int left , int right)
{
    // Typical merge sort procedure
    if(left==right)
    {

    }
    else
    {
        int mid = (left+right)/2 ;
        merge_sort(left , mid) ;
        merge_sort(mid+1 , right) ;
        merge(left , mid , right) ;
    }
}


texts: Run control tasks asynchronously using TPL

texts:
One of my classes regularly triggers one of two asynchronous operations: a "turn on" and a "turn off" that each take about a second. I'm using this method below to make sure that they don't run simultaneously. It doesn't seem very elegant to me. Is there some better way to do this? I'm using .NET 4.0, but I would like to know if there are any .NET 4.5 methods that make this easier.

private Task _changingControl;
private void RunControlTask(Task newTask)
{
    var cc = _changingControl;
    if (cc == null || cc.IsCompleted)
    {
        _changingControl = newTask;
        newTask.Start();
    }
    else
    {
        _changingControl = cc.ContinueWith(old =>
        {
            newTask.RunSynchronously();
            newTask.Dispose(); // only needed if we manually wait for it to finish
        });
    }
}


texts: Reading integers from a file and counting the length of a descending subsequence

texts:
I had a school project to solve, which I did. The basic focus of the project was to create the simplest code possible to solve it. This topic was created just to ensure if I wrote the code correctly.

The problem is the following:

  We have declared a dynamic array which will take numeric values from a txt file. We
  want to read the array backwards and to make a simple check.
  Read every 'i' element in the array and check if the value of the array is greater than > the last one.If it is the value saved in the int called temp_max which will be the > value of the array in the i position. The program will continue to check every number
  and if a value in the array is greater than temp_max we will overwrite the value of the temp_max to the value of the array in that position.

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

int main() {

    FILE *input, *output;
    int *children;
    int size, i;

    input = fopen("xxx.in", "r");

    if(input == NULL)
    return 1;

    fscanf(input,"%d",&size);

    if(size < 1 || size > 1000000)
    return 1;

    children = malloc(size * sizeof(int));

    if (children==NULL)
    return 1;

    for ( i = 0; i < size; i++ )
    {
        fscanf(input, "%d",&children[i]);
    }
    fclose(input);

    int total = 0;
    int temp_max = 0;
    for(i = size - 1; i >= 0; i--)
    {
        if(children[i] > temp_max) {
            temp_max = children[i];
            total++;
        }
    }

    free(children);

    output = fopen("xxx.out", "w+");
        fprintf(output, "%d\n", total );
        fclose(output);

    //This is the end, my dear friend!
    exit(0);
}

The int size was declared in one step above and is the size of the dynamic array.
The int total calculate how many times a number is greater than another. Default value is zero cause, I believe that should be what is your opinion.
The array hasn't any zero values or negative values at all.

The text file has the following format:

Example (xxx.in) 1:

5
9 6 5 4 2

Example (xxx.in) 2:

6
8959 5594 595 2 949 9


texts: Return screenshot data from subprocess without residual files

texts:
I have a use case, where I want to take screenshots via scrot without leaving behind residual files:
"""Takes screenshots."""

from pathlib import Path
from subprocess import check_call
from tempfile import TemporaryDirectory

from digsigclt.os.posix.common import SCROT
from digsigclt.types import Screenshot

__all__ = ['screenshot']

JPEG = 'image/jpeg'
FORMATS = {
    'jpe': JPEG,
    'jpeg': JPEG,
    'jpg': JPEG,
    'png': 'image/png',
    'gif': 'image/gif'
}

def screenshot(filetype: str = 'jpg', display: str = ':0',
               quality: int = None, multidisp: bool = False,
               pointer: bool = False) -> Screenshot:
    """Takes a screenshot."""

    try:
        content_type = FORMATS[filetype]
    except KeyError:
        raise ValueError('Invalid image file type.') from None

    command = [SCROT, '--silent', '--display', display]

    if quality is not None:
        command += ['--quality', str(quality)]

    if multidisp:
        command.append('--multidisp')

    if pointer:
        command.append('--pointer')

    with TemporaryDirectory() as tmpd:
        tmpfile = Path(tmpd).joinpath(f'digsigclt-screenshot.{filetype}')
        command.append(str(tmpfile))
        check_call(command)

        with tmpfile.open('rb') as file:
            return Screenshot(file.read(), content_type)

The code works as intended. What bothers me, however, is the workaround that I had to take using TemporaryDirectory. All tests using a ǸamedTemporaryFile directly failed due to the fact, that python opens the target file before the subprocess writes to it, so that a subsequent read() would return an empty bytes object.
Is there a way to improve the intermediate file handling without the TemporaryDirectory workaround and without opening and closing the intermediate file more than once?


texts:
Given n and k, I need to find Euler's totient exactly k times where n and k are very large numbers. Can anyone help with an optimized solution for a large number?

#include <iostream>
using namespace std;

 int gcd(int a, int b)
{
    if (a == 0)
        return b;
    return gcd(b%a, a);
}

int phi(unsigned int n)
{
    unsigned int result = 1;
    for (int i=2; i < n; i++)
        if (gcd(i, n) == 1)
            result++;
    return result;
}

int main()
{
    long n,i,k;

    cin >>n>>k;
    long a[n];

    for (i=1; i<=k; i++)
        n = phi(n);

    cout << n<<endl;

    return 0;
    }


texts: CasperJS continue equivalent inside for loop with casper.then

texts:
CasperJS doesn't allow continue statement inside a casper.then functions. This was my solution but I'm not happy about it. Is there a better way to achieve this effect?

casper.start();
        casper.then(function() {
            var current = 1;
            var end = 4;
            var skip;

for (;current < end;) {
  (function(cntr) {
    casper.thenOpen('about:blank', function() {
          this.echo('loop number: '+ cntr);
          skip = false;
    });
    casper.then(function(){
        if (skip) {
            this.echo('skipping');
        }
        else {
            // put all code here that was in casper.then
            this.echo('proceed as normal');
            // some condition requires skipping...
            skip = true;

        }
    });

    casper.then(function(){
        if (skip) {
            this.echo('skipping');
        }
        else {
            // put all code here that was in casper.then
            this.echo('this no longer gets printed');
        }
    });
  })(current);
  current++;
}
});


texts: Recursive method turning flat structure to recursive

texts:
I often end up working with systems where the data is delivered with some Id property and possibly a parentId prop, but never do anyone tempt to actually give me a nice recursive object to play with.

Now, the code below is merely a suggestion in how to solve these kind of "problems", I've created the FlatObject to simulate an incoming  with data.

class Program
{
    static void Main(string[] args)
    {
        // Fill list with sample data
        List<FlatObject> flatObjects = new List<FlatObject>
        {
            new FlatObject(1,0),
            new FlatObject(2,0),
            new FlatObject(3,0),
            new FlatObject(4,0),
            new FlatObject(5,1),
            new FlatObject(6,2),
            new FlatObject(7,6),
            new FlatObject(8,6)
        };

        // call the recursive method
        var recursiveObjects = FillRecursive(flatObjects, 0);

    }

    private static List<RecursiveObject> FillRecursive(List<FlatObject> flatObjects, int parentId)
    {
        List<RecursiveObject> recursiveObjects = new List<RecursiveObject>();

        foreach (var item in flatObjects.Where(x => x.ParentId.Equals(parentId)))
        {
            recursiveObjects.Add(new RecursiveObject
            {
                Id = item.Id,
                ParentId = item.ParentId,
                Children = FillRecursive(flatObjects, item.Id)
            });
        }

        return recursiveObjects;
    }
}

public class FlatObject
{
    public int Id { get; set; }
    public int ParentId { get; set; }

    public FlatObject(int id, int parentId)
    {
        Id = id;
        ParentId = parentId;
    }
}

public class RecursiveObject
{
    public int Id { get; set; }
    public int ParentId { get; set; }
    public List<RecursiveObject> Children { get; set; }
}

I am aware of some Linq alternatives to solve the foreach loop but that does hardly not change the approach of this.

private static List<RecursiveObject> FillRecursive(List<FlatObject> flatObjects, int parentId)
{
    return flatObjects.Where(x => x.ParentId.Equals(parentId)).Select(item => new RecursiveObject
    {
        Id = item.Id, ParentId = item.ParentId, Children = FillRecursive(flatObjects, item.Id)
    }).ToList();
}