SPOJ "TESSER" - Getting TLE using KMP algorithm The TESSER - Finding the Tesserect problem is tagged as a problem to be solved by Knuth-Morris-Pratt (KMP) algorithm. I'm using KMP, but am still getting time-limit-exceeded.

Task

Each of T test cases (1 ≤ T ≤ 105) consists of three lines:

A single integer N (2 ≤ N ≤ 105) denoting the number of data points.
N integers (ai, where 1 ≤ ai ≤ 109)
A message pattern (a string consisting only of letters G, L, and E).

In the sequence of ai, each element may be greater than (G), less than (L), or equal to (E) the preceding element.  Find out whether there is some substring of consecutive elements within the sequence that matches the given message pattern, and print "YES" if it is found or "NO" if it is not found.

Example

Input:

1
5
1 2 3 4 1
GGL

Output:

YES

The answer is "YES", because 2 3 4 1 satisfies the pattern GGL, i.e. 3 is greater than 2, 4 is greater than 3, 1 is less than 4.

Here is the code that I submitted:

#include <bits/stdc++.h>

using namespace std;

int main()
{
    string text, pattern;
    vector<int> computePrefixFunction(string p);
    vector<long long int> v;
    int no, test_case;
    long long value;
    cin >> test_case;
    while(test_case)
    {
        cin >> no;
        bool flag = false;
        for(int i = 0; i < no; ++i)
        {
            cin >> value;
            v.push_back(value);
        }

        for(int i = 0; i < (no - 1); ++i)
        {
            if(v[i+1] > v[i])
                text = text + 'G';
            else if(v[i] == v[i+1])
                text = text + 'E';
            else
                text = text + 'L';
        }
        v.clear();
        cin >> pattern;
        int n = no - 1;
        int m = pattern.length();
        vector<int> pi = computePrefixFunction(pattern);
        int q = -1;
        for(int i = 0; i < n; ++i)
        {
            while(q > -1 && pattern[q+1] != text[i])
                q = pi[q];
            if(pattern[q+1] == text[i])
                q = q + 1;
            if(q == (m-1))
            {
                flag = true;
                break;
            }
        }

        if(flag == true)
            cout << "YES\n";
        else
            cout << "NO\n";
        pi.clear();
        test_case = test_case - 1;
    }
    return 0;
}

vector<int> computePrefixFunction(string p)
{
    int m = p.length();
    vector<int> pi;
    pi.push_back(-1);
    int k = -1;
    for(int q = 1; q < m; ++q)
    {
        while(k > -1 && p[k+1] != p[q])
            k = pi[k];
        if(p[k+1] == p[q])
            k = k + 1;
        pi.push_back(k);
    }
    return pi;
}

Before addressing your performance problem, I'd like to discuss the readability of your code:

It's not immediately obvious that there are T test cases, all independent of each other.  while (test_case) { …; test_case = test_case - 1; } would be clearer if written as

while (test_case--) {
    …
}

All of the variables used in each test case (text, pattern, v, etc.) should be declared inside the loop, to make it clear that no state persists between cases, other than the test_case counter.  That would be less error-prone than calling .clear() to reuse the vectors.

Better yet, define a helper function for handling one test case.  Then it will be obvious that there should be no side-effects.
What is flag?  Flag variables, especially poorly named ones, are a code smell.  At the very least, rename it to pattern_found.

For a program whose main functionality is performing a substring search, it is baffling that nothing like a find(needle, haystack) function appears in your code.  That would be a more appropriate fix for your flag variable.
no is a weird name for an integer variable, yes?
Why bother building v and throwing it away?  You could just construct text directly.

In addition, there are some abuses of C++.

#include <bits/stdc++.h> is not standard C++.
using namespace std defeats the benefits of the namespace, and is not recommended.
Declaring vector<int> computePrefixFunction(string p) inside your main() function is highly unconventional.  Declarations usually go before the function or in a header file.  Better yet, put if you put main() at the end, you won't even need any declaration.
computePrefixFunction(string p) should accept a const std::string & — otherwise you end up copying the string.

I would drop "compute" and "function" from the function name, since those words don't contribute to the meaning.

I recommend the following outline for the code.  Note that you can replace the call to kmpFind() with std::string::find() and still get the same answer (though not necessarily with the right performance characteristics).

#include <iostream>
#include <string>
#include <utility>
#include <vector>

static std::vector<std::string::size_type> kmpPrefixTable(const std::string &w) {
    std::string::size_type candidate = 0;
    std::vector<std::string::size_type> t;
    t.reserve(w.length());
    for (std::string::size_type pos = 2; pos < w.length(); ) {
        …
    }
    return t;
}

/**
 * https://en.wikipedia.org/wiki/Knuth–Morris–Pratt_algorithm
 */
std::string::size_type kmpFind(const std::string &s, const std::string &w) {
    std::vector<std::string::size_type> t = kmpPrefixTable(w);
    for (std::string::size_type m = 0, i = 0; m + i < s.length(); ) {
        …
    }
    return std::string::npos;
}

/**
 * Reads a test case, expecting:
 * 1) the number of data points (2 <= n <= 1e5),
 * 2) the sequence of data points (space-separated integers, each up to 1e9),
 * 3) the pattern to look for (a string consisting of letters 'G', 'L', and 'E').
 *
 * Returns the sequence (represented as a string, using 'G', 'L', 'E' to
 * represent an increase, decrease, or equality relative to the preceding
 * number), and the pattern to look for.
 */
std::pair<std::string, std::string> tesserect(std::istream &in) {
    size_t n;
    uint32_t prev, curr;
    std::string s, pattern;

    std::cin >> n;
    s.reserve(n);
    for (in >> prev; --n; prev = curr) {
        in >> curr;
        s += (curr < prev) ? 'L' :
             (curr > prev) ? 'G' : 'E';
    }

    in >> pattern;
    return std::make_pair(s, pattern);
}

int main() {
    int testCases;
    for (std::cin >> testCases; testCases; --testCases) {
        std::pair<std::string, std::string> strings = tesserect(std::cin);

        // Equivalent to: pos = strings.first.find(strings.second);
        std::string::size_type pos = kmpFind(strings.first, strings.second);

        std::cout << (pos != std::string::npos ? "YES\n" : "NO\n");
    }
}

Now, with the Knuth-Morris-Pratt algorithm moved into its own function, you can test and analyze it properly.  You seem to be using a variant that is different from the algorithm given in Wikipedia.  The version in Wikipedia doesn't use nested while loops — you may find it easier to analyze its performance.


Run different methods in background threads without duplication In my Android app I have number of methods that should be executed in a background thread.

One of the methods looks like this

public static void processItem(final Context context, final String itemId)
{
    if (Looper.myLooper() == Looper.getMainLooper())
    {
        Thread task = new Thread()
        {
            @Override
            public void run()
            {
                processItem(context, playlistId);
            }
        };

        task.start();
        return;
    }

    // actual processing
}

As you can see, there are some code that only ensures an eligible thread is used.

How can I avoid copying this "threading" code over and over for each method that should be run in a background thread?

Extending Thread is an 'anti-pattern' in Java. The right way to do this work is to create an instance of a Runnable, and use the runnable as a constructor to a Thread instance.

Thread t = new Thread(new Runnable() {
    public void run() {
        /*
         * Do something
         */
    }
});

t.start();

But, and this is a big "but", in Java, in general, the practice of creating and using threads like this is being replaced by frameworks that manage the threads in a better way. In regular Java, you should be using the Executor, ExecutorService, and Executors class in the concurrent package.

As for android-specific use cases, you should read up on the threading models in Android paying special attention to the AsyncTask in Android dev kit

Update: more about the Thread anti-pattern

Jon Skeet says so ... ;-)  and most people agree. What you have is something that needs to be done. That is what you need to implement, the way to do it. The place to run that something is on a thread. You do not implement the thread, you implement the task. There are two different concepts here: what needs to be done, and where it needs to be done. You are only implementing one of those.

Update: alternative solution

To reduce the logic required for managing the thread the code runs on, I would do one of two things:

simply always use a different thread. Simply remove the if-condition and do all the processing in a Runnable's run method.
Have a common utility method that looks something like:

private static final ExecutorService THREADPOOL = Executors.cachedThreadPool();

public static void runButNotOn(Runnable toRun, Thread notOn) {
    if (Thread.currentThread() == notOn) {
        THREADPOOL.submit(toRun);
    } else {
        toRun.run();
    }
}

and then you can call it in your method with:

private static void processImplementation(final Context context, final String itemId) {
     // ... the actual work.
}

public static void processItem(final Context context, final String itemId) {
    Runnable task = new Runnable(){
        public void run() {
            processImplementation(context, itemId);
        }
    };
    runButNotOn(task, Looper.getMainLooper().getThread());
}


Send parameter to server and reload page My first ASP.NET MVC 6 / jQuery web site - the site header has a "Change Language" selector (named LanguagePicker) - this is actually placed in a _Layout view, a container shared by all views.

When users change the language, I need to save that in the db, and reload current page, with language changed.

I have this on client-side:

$('#LanguagePicker').selectpicker('val', '@CultureHelper.GetCurrentLanguage()');
$('#LanguagePicker').on('change', function () {
            var currentPageUrl = 'TODO'; // Get current Url here
            window.location = "/Base/ChangeLanguage/" +
                $('.selectpicker option:selected').val() +
                "?returnUrl=" + currentPageUrl ;
        });
    });

Is there a better way to do this, both in client side code and in server side? Ideally, the purpose is to send a newLanguage param to the server, save to db, and then refresh the current page so that the resources associated with the new language are displayed. it should obviously work from whatever page it is triggered.

To get the current page you could use this (as long as the javascript is in your layout file or other view, this will not work if in an external js file):

<%= Request.Url.PathAndQuery %>

I would suggest using ajax to call an api that returns json with a success status since you sound like you are using jquery quite a bit. If the call is successful, then set the window.location to the current page, if it fails, then you can gracefully handle the error.  Here is an example of the controller:

public JsonResult UpdateLanguage(string language)
{
   var languageUpdated = LanguageEngine.UpdateLanguage(language);  // Your code to update db

   var json = new
   {
       success = languageUpdated,
       newLanguage = language
   };
   return Json(json);
}

Then you can use a regular ajax call or something like jQuery getJSON function:

$.getJSON("../UpdateLanguage", { language: "Chinese" },
    function (data) {
        if (data.success === true) {
            window.location = currentPageUrl;
        }
        else {
            alert("Sorry, we failed to update the language to '" + data.newLanguage + "'.  Please try again.");
        }
    }
};

Is this way much better?  That I am not so sure.

Another strategy would be to include a base model that all your view models inherit from that contains a property for language and current page (with query results if you use them), then set this when then they change the drop down and call a controller to update the language which should take the base model object as a param, after the controller finishes the update, it can then redirect you back to that page.  The nice thing about this strategy is you can include other information that is typically useful on every page, such as the logged in user object.  This is also more "MVC-y" in my opinion, but probably a lot more work depending how far your project is.


Magento MySQL search based on phone number I'm building a search for Magento. Magento API doesn't provide an easy way to look up a customer using a phone number so I created a custom solution. My MySQL/PHP OOP skills are limited. Did I miss anything or is there a better way to do this?

<?php

    DEFINE ('DB_HOST',      'localhost');
    DEFINE ('DB_USER',      'theuser');
    DEFINE ('DB_PASSWORD',  'thepassword');
    DEFINE ('DB_NAME',      'magento');

    $dbc = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);

    $search_query = "5555555555";

    // find customers with matching phone numbers
    $query = "SELECT value, entity_id FROM customer_address_entity_varchar WHERE value=$search_query LIMIT 100";

    $response = mysqli_query($dbc, $query);

    // save found phone numbers to $found_customers array
    $found_customers = array();
    $position = 0;

    while($row = mysqli_fetch_array($response)) {

        $found_customers[$position]['entity_id']    = $row['entity_id'];
        $found_customers[$position]['value']        = $row['value'];

        $position++;
    }

    // reset everything just in case
    unset($query, $response, $row);
    $position = 0;

    // find matching parent_ids and save to $found_customers array
    foreach($found_customers as $found_customer) {
        $friendly_entity_id = $found_customer['entity_id'];

        $query = "SELECT parent_id FROM customer_address_entity WHERE entity_id=$friendly_entity_id LIMIT 1";
        $response = mysqli_query($dbc, $query);
        $row = mysqli_fetch_array($response);
        $found_customers[$position]['parent_id'] = $row['parent_id'];

        $position++;
    }

    var_dump($found_customers);

?>

you haven't missed anything (the code works as intended), but you can improve the performance a bit and make it more readable (for someone who is used to PHP and MySQL).

I've modified your code and added comments where necessary.
As on of the comments requested, I'll add a bit more detail.

The most important thing is the select query. As it was originally you had to performed another query for every row from the original query in order to get the corresponding parent_id from the customer_address_entity table. You should avoid doing this because it is not very efficient.

The modified query selects everything you need in one go using a JOIN statement. The JOIN statement allows you to perform a SELECT on both tables that were joined, but you have to specify which column you want from each table, that's why the original SELECT value becomes SELECT customer_address_entity_varchar.value.

When looping the return results in order to assign them to a new array, like you're doing below, it's useful to now that:
a. Using $found_customers[]['entity_id'] instead of $found_customers[$position]['entity_id'] has the same results, because the $array[] notation in PHP makes it so that every assignment appends that assignment to the end of the array, auto-incrementing the index.
b. Since you want to transfer all the data from $row into $found_customers, you can simply do $found_customers[] = $row and it will have the same effect in this case.
c. (Optional) A simple quality of life trick, use mysqli_fetch_assoc' instead of 'mysqli_fetch_array'. Whenvar_dump`ing you won't see the same values twice for each row (one with and index and one with the key, as seen in the comments), only once, with the key.

$position = 0;

while($row = mysqli_fetch_array($response)) {

    $found_customers[$position]['entity_id']    = $row['entity_id'];
    $found_customers[$position]['value']        = $row['value'];

    $position++;
}

If you want to have unique values for a column (as requested in the comments), one way to do it is to GROUP BY that column. The downside is that you will lose the data contained in the duplicate results.

<?php

DEFINE ('DB_HOST',      'localhost');
DEFINE ('DB_USER',      'theuser');
DEFINE ('DB_PASSWORD',  'thepassword');
DEFINE ('DB_NAME',      'magento');

$dbc = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);

$search_query = "5555555555";

// find customers with matching phone numbers
/* This is probably the most important part: using a JOIN.
   It will save you having to do a separate query for each customer */

$query = "SELECT customer_address_entity_varchar.value, customer_address_entity_varchar.entity_id, customer_address_entity.parent_id
          FROM customer_address_entity_varchar
          JOIN customer_address_entity
              ON customer_address_entity_varchar.entity_id = customer_address_entity.entity_id
          WHERE customer_address_entity_varchar.value = $search_query
          GROUP BY customer_address_entity.parent_id
          LIMIT 100";

$response = mysqli_query($dbc, $query);

// save found phone numbers to $found_customers array
$found_customers = array();

/* in PHP you can just use $found_customers[] and it will auto-increment
 no need to use $position */

/* also, since your select query on selects 3 columns, you can assign the results directly */

while($row = mysqli_fetch_assoc($response)) {
    $found_customers[] = $row;
}

/* The foreach loop is no longer necessary because the initial query  (now with a JOIN) returns all the required data */

var_dump($found_customers);

?>


Reusable configuration reader for Java This is related to a question I posted on Stack Overflow.  The consensus was to use JAXB, which is what I did.

One of the requirements was that it needed to work with legacy XML configuration files. The code needed to be able to start reading new configuration settings from XML files already used to configure pre-existing applications.

In trying to make the code reusable, I added the generic type parameter. However, this causes some yuckiness for the user, as it requires user to pass in the class type.   (It shouldn't be necessary - but due to Java implementation of generics, there's no easy way around that).

I had to throw this together very quickly, so I would welcome any suggestions on improvement (or finding errors). I wasn't very skilled with JAXB, so perhaps there is a better solution I overlooked.

package com.eztech.config;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;

import org.w3c.dom.Document;
import org.w3c.dom.Node;

import com.eztech.xml.XmlUtils;

public class JAXBConfigurator<T> {

    private String filePath;
    private Class<T> clazz;
    public JAXBConfigurator(Class<T> toConfigure, String xmlFilePath) {
        this.clazz = toConfigure;
        this.filePath = xmlFilePath;
    }

    /**
     * Parses Xml and reads configuration from Document element. Using this method
     * assumes that the configuration xml starts at the top of the xml document.
     * @return
     * @throws Exception
     */
    public T createAndConfigure() throws Exception {
        return createAndConfigure(null);
    }

    /**
     * Selects specified element from the parsed Xml document to use as the base
     * for reading the configuration.
     *
     * @param tagName
     * @return
     */
    public T createAndConfigure(String tagName) throws Exception {
        Document doc = XmlUtils.parse(filePath);
        Node startNode;
        if (tagName == null) {
            startNode = doc;
        } else {
            startNode = XmlUtils.findFirstElement(doc, tagName);
        }

        return readConfigFromNode(startNode);
    }

    private T readConfigFromNode(Node startNode) throws JAXBException {
        JAXBContext context = JAXBContext.newInstance(clazz);
        Unmarshaller unmarshaller = context.createUnmarshaller();
        JAXBElement<T> configElement = unmarshaller.unmarshal(startNode, clazz);
        return configElement.getValue();
    }

}

How to use it:

JAXBConfigurator<MyConfig> configurator =
    new JAXBConfigurator<Config>(MyConfig.class, xmlfilePath);
instance = configurator.createAndConfigure("MyXmlStartTag");

Two things which are good to know about JAXB:

You can annotate private methods and fields, JAXB can call/modify them. It could help hiding internal data structure from clients.
Marshaller as well as Unmarshaller has event callbacks. They can help handing deprecated or compound fields.

Just two small notes about the code:

I would call the class JaxbConfigurator. Lowercase letters are easier to read. (Effective Java, Second Edition, Item 56: Adhere to generally accepted naming conventions)
It would be worth checking input parameters in the constructor to avoid latter mysterious NullPonterExceptions:

import static com.google.common.base.Preconditions.*;

...

public JaxbConfigurator(final Class<T> toConfigure, final String xmlFilePath) {
    this.clazz = checkNotNull(toConfigure, "toConfigure cannot be null");
    this.filePath = checkNotNull(xmlFilePath, "xmlFilePath cannot be null");
}


Passing uint64_t from C++ to R: Hilbert Mapping - xy2d function I have been working with Rcpp to perform a forward and backward Hilbert Mapping.  Below is an implementation based on this code.

My application is in genomics and I may be dealing with enormous datasets, which necessitates the use of very large integers for indices, so I found this code for passing large integers to R using Rcpp and the bit64 R package and incorporated it after the for loop.

The xy2d() function works properly.  My interest is on your thought regarding the code AFTER the for loop, which prepared the result for passage back to R. Please let me know what you think  :)

#include <Rcpp.h>
using namespace Rcpp;
# include <bitset>
# include <cstdint>
# include <ctime>
# include <iomanip>
# include <iostream>
using namespace std;
//****************************************************************************80
// [[Rcpp::export]]
Rcpp::NumericVector xy2d ( int m, uint64_t x, uint64_t y )
//
//****************************************************************************80
{
  uint64_t d = 0;
  uint64_t n;
  int rx;
  int ry;
  uint64_t s;

  n = i4_power ( 2, m );

  if ( x > n - 1 || y > n - 1) {
    throw std::range_error("Neither x nor y may be larger than (2^m - 1)\n");
  }

  for ( s = n / 2; s > 0; s = s / 2 )
  {
    rx = ( x & s ) > 0;
    ry = ( y & s ) > 0;
    d = d + s * s * ( ( 3 * rx ) ^ ry );
    rot ( s, x, y, rx, ry );
  }

  std::vector<uint64_t> v;
  v.push_back(d);
  //v[0] = d

  size_t len = v.size();
  Rcpp::NumericVector nn(len);         // storage vehicle we return them in

  // transfers values 'keeping bits' but changing type
  // using reinterpret_cast would get us a warning
  std::memcpy(&(nn[0]), &(v[0]), len * sizeof(uint64_t));

  nn.attr("class") = "integer64";
  return nn;
}

This post will be followed up shortly with another post regarding the rot() function, and well as the reverse d2xy() function

Because we write C++, there's no reason to declare (most) variables at the beginning of the scope of your function. For example, all of d, rx, ry and s have been declared for no reason if you happen to throw and exit the function.
You don't need s after the for-loop, so it should be local to the loop only. Similar for rx and ry.
Make use of shorthand operators like /= and +=.
You can make v const and initialize it with a suitable constructor, in this case std::vector<uint64_t> v(1, d); initializes v to hold one element equal to d. But really, as it stands, I see no point in using an array here if you just have a single value (I suspect your example is incomplete and not representative of your real use case, which is a shame).
Because len can be const, make it const. This protects from unintended errors and possibly allows the compiler to perform more optimizations.
As a general comment, avoid saying using namespace std;, it's not good for you.
I don't know the interface of Rcpp::NumericVector, but might you initialize it directly in the spirit of const Rcpp::NumericVector nn(v.cbegin(), v.cend()), for instance?


compile time template bernstein polynomial I wrote a compile time bernstein polynomial instead to define several functions for different coefficients. I wonder whether there is a way to make the function faster. std::powf is known to be relatively slow and the binominal coefficient is for some cases 1. Also style fixes are appreciated.

// Template functions to estimate the binominal coefficient
template<uint8_t n, uint8_t k>
struct binomial {
  static constexpr int value = (binomial<n - 1, k - 1>::value + binomial<n - 1, k>::value);
};

template<>
struct binomial<0, 0> {
  static constexpr int value = 1;
};

template<uint8_t n>
struct binomial<n, 0> {
  static constexpr int value = 1;
};

template<uint8_t n>
struct binomial<n, n> {
  static constexpr int value = 1;
};

// Template bernstein polynomial
template <uint8_t n, uint8_t k>
float bernstein(const float val) {
  constexpr float binom_coeff = binomial<n, k>::value;
  const float a = std::powf(val, k);
  const float b = std::powf(1 - val, n - k);
  return binom_coeff * a * b;
}

You could check against the most common cases you expect to occur:

float a;
switch (k)
{
case 0:
    a = 1.0f;
    break;
case 1:
    a = val;
    break;
case 2:
    a = val*val;
    break;
// maybe some more common cases...
default:
    a = std::powf(val, k);
}

But I personally wouldn't do such optimizations unless you really see that there is some significant slowdown in your particular case and benchmarks show that such an optimization really does make a difference.


My unique_ptr implementation This is my simple unique_ptr implementation. Anything that could be improved upon or should be added?

#include <algorithm>

template<typename T>
class unique_ptr
{
private:
    T * ptr_resource = nullptr;
public:
    // Safely constructs resource. Operator new is called by the user. Once constructed the unique_ptr will own the resource.
    // std::move is used because it is used to indicate that an object may be moved from other resource.
    explicit unique_ptr(T* raw_resource) noexcept : ptr_resource(std::move(raw_resource)) {}
    unique_ptr(std::nullptr_t) : ptr_resource(nullptr) {}

    // destroys the resource when object goes out of scope
    ~unique_ptr() noexcept
    {
        delete ptr_resource;
    }
    // Disables the copy/ctor and copy assignment operator. We cannot have two copies exist or it'll bypass the RAII concept.
    unique_ptr(const unique_ptr<T>&) noexcept = delete;
    unique_ptr& operator = (const unique_ptr&) noexcept = delete;
public:
    // releases the ownership of the resource. The user is now responsible for memory clean-up.
    T* release() noexcept
    {
        T* resource_ptr = this->ptr_resource;
        this->ptr_resource = nullptr;

        return resource_ptr;
    }
    // returns a pointer to the resource
    T* get() const noexcept
    {
        return ptr_resource;
    }
    // swaps the resources
    void swap(unique_ptr<T>& resource_ptr) noexcept
    {
        std::swap(ptr_resource, resource_ptr.ptr_resource);
    }
    // replaces the resource. the old one is destroyed and a new one will take it's place.
    void reset(T* resource_ptr) noexcept(false)
    {
        // ensure a invalid resource is not passed or program will be terminated
        if (resource_ptr == nullptr)
            throw std::invalid_argument("An invalid pointer was passed, resources will not be swapped");

        delete ptr_resource;

        ptr_resource = nullptr;

        std::swap(ptr_resource, resource_ptr);
    }
public:
    // operators
    T* operator->() const noexcept
    {
        return this->ptr_resource;
    }
    T& operator*() const noexcept
    {
        return *this->ptr_resource;
    }
    // May be used to check for nullptr
};

Let me first assume that your unique_ptr is supposed to be movable. Then, any basic test case whould have unrevealed this:

unique_ptr<int> ptr1(new int());
unique_ptr<int> ptr2 = std::move(ptr1); // Fails to compile

Recall that = delete-ing special member functions means user-declaring them. And user-declared copy and copy assignment constructors prevent compiler-generated move (assignment) constructors! You have to manually define them. This case is by the way covered by the rule of five/C.21 Core Guidelines, and also have a look at the table posted in this SO answer for an overview of compiler-generated/-deleted/not-declared special member functions.
Is the non-availability of an implicit conversion to bool intended? Checking if a (smart) pointer is in an empty/null state is so common in ordinary control flow statements that clients will expect this to compile:

unique_ptr<SomeType> ptr = ...;

if (ptr) ... // currently fails to compile

But not that this might be debatable. Implicit conversions can cause a lot of pain, so if you intend to not allow them for the sake of a more explicit

if (ptr == nullptr) ...

that's a design decision. But one that should be documented in a comment at the top of the class.
Except the non-explicit-ness of the second constructor (thanks to @Deduplicator for pointing that out) taking a std::nullptr_t, it is superfluous. You can construct an empty unique_ptr by

unique_ptr<SomeType> empty{nullptr};

which simply invokes the first constructor taking a T* argument. I would remove the second constructor.
... and add a default constructor that initializes ptr_resource to nullptr, as

unique_tr<SomeType> empty;

might be a way of constructing an empty smart pointer that users would expect to compile.
Move-constructing the ptr_resource in the constructor initializer by ptr_resource(std::move(raw_resource)) doesn't make much sense. Just copy the pointer instead. The comment // std::move is used because it is used to indicate that an object may be moved from other resource. is rather confusing, because T* raw_resource is already a pointer, and hence a handle to a resource, not the resource itself.
The release member function can be implemented more conveniently as

T* release() noexcept
{
    return std::exchange(ptr_resource, nullptr);
}

I wouln't let the reset member function throw when the input is a nullptr. Why shouldn't it be allowed to reset a unique_ptr with a nullptr, turning it back into an empty state?
The only facilities you use from the standard library are std::move and std::swap. Those are in <utility>, so you don't need to include <algorithm>, which is probably much heavier in terms of compile times.
I would omit the this-> prefix, it's unnecessarily verbose. But that might be a matter of taste.
Have you considered custom deleters? This makes the class template more reusable in scenarios other than pointers to heap resources, e.g. closing a file upon destruction etc.


Pythonic way to manipulate arrays: a case study I just spent almost one day to figure out the following code, which analyzes the output data from material science programs called VASP and Bader. As a Python beginner, I earnestly ask some aces to help me make this code more pythonic, or efficient. Because I know that although the code can run smoothly, it definitely needs more modification from professionals. The code is listed below, with the data file ACF.dat after it.

#!/usr/bin/python
import numpy as np

def charge(x): # function to calculate charge difference
    if x<4:
        return 4-x # atom1
    else:
        return 6-x # atom2

# read from file ACF.dat
f = open('ACF.dat', 'r')
lines = []
for row in f.readlines():
    tmp = row.split()
    lines.append(tmp)

lines = lines[2:-4] # remove unecessary rows
lines = np.array(lines, dtype=float)
lines = lines[:,0:5] # remove unecessary columns

# calculate residual charge
chg = np.vectorize(charge)
lines[:,4] = chg(lines[:,4])

# calculate interatomic distances
dist = []
for i in range(0,len(lines)):
    d = np.sqrt(np.sum((lines[i,1:4]-lines[0,1:4])**2))
    dist.append(d)

lines = np.column_stack((lines, dist)) # attach dist to lines
lines = lines[lines[:,5].argsort()]

for row in lines:
     print '{0:<3.0f} {1:12.6f} {2:12.6f}'.format( row[0], row[5], row[4])

f.close()

ACF.dat

The structure of the file is seen as the heading. What I need are the first five columns: the atomic index, the x, y, z coordinates of each atom, the atomic charge.

#         X           Y           Z        CHARGE     MIN DIST    ATOMIC VOL
--------------------------------------------------------------------------------
1      7.5119      7.5119      7.5119      2.9875      1.1144     20.7692
2     18.0286     18.0286     18.0286      2.8514      1.3688     23.0095
3      6.0058     18.0205     18.0205      2.8500      1.3599     22.9265
4     12.0323     18.0342     18.0342      2.8480      1.3638     22.9816
5     18.0205      6.0058     18.0205      2.8500      1.3599     22.9265
6      5.9968      5.9968     17.9789      2.7979      1.2317     22.3582
--------------------------------------------------------------------------------
VACUUM CHARGE:               0.0000
VACUUM VOLUME:               0.0000
NUMBER OF ELECTRONS:      1085.9999

What the code does is:

Read in the content of ACF.dat, and removes the first two rows and last four rows. Then saves only the first five columns into array lines.
Calculates the residual charge using function charge(x).
Calculates the interatomic distances using the x, y, z coordinates of the atoms, and attach the array of distances to lines as its last column.
Sorts lines according to the interatomic distances (column #6 of lines).
Prints out the atomic index, interatomic distances, and atomic charges.

I understand that this is a lengthy question, but I still would like to ask someone helping me, and other newbies, learn Python faster by optimizing our own code. Any suggestion is welcomed.

Coding style

For starters, read PEP 8, which is the Python style guide. This gives suggestions on whitespace around operators and commas, variable names, and the like. Your code isn’t bad if it doesn’t follow these conventions, but it will slow down more experienced Python programmers reading your code, and might make it harder for you later when you read other people’s Python.

You should also read PEP 257, which explain the Python conventions for docstrings. Rather than including a description for the function on the same line as the def, we put it on a special line inside the function definition.

With those two in mind, I might rewrite your charge function as:

def residual_charge(x):
    """Returns the residual charge of an atom."""
    if x < 4:
        return 4 - x # atom 1
    else:
        return 6 - x # atom 2

The rest of the style changes are only minor, and you can find them yourself.

Opening/closing the file

As far as I can tell, the six lines after you’ve defined charge are the only lines where you’re directly interacting with the file ACF.dat, but you don’t issue a close() command until the end of the script. That can cause problems if the input file is large, or if you want to load multiple files.

I’d make three changes:

Use Python’s with open() ... construction – this keeps all the file handling code in one place, and automatically closes it for you as well.
Wrap this in a function: it keeps the code for processing the file input in one place, and means you can use it again if you want to feed it a different file.
Go through the file a line at a time (you might not need this, but it saves loading the whole file into memory if ACF.dat is large).

So I’d write something like:

def parse_dat_file(filename):
    """Returns a numpy array based on the contents of the input file."""
    # read the file contents
    with open(filename, 'r') as f:
        for line in f:
            parsed_lines.append(line.split())

    # remove unnecessary rows and columns
    parsed_lines = parsed_lines[2:-4]
    parsed_lines = np.array(parsed_lines, dtype=float)
    parsed_lines = parsed_lines[:,0:5]

    return parsed_lines

Doing the necessary calculations

Again, I’d break this into a single function. It separates that block of work from the rest of the file, and makes it easier to organise. This means that if you get the data from another source, you can use the same code untouched.

Some notes:

In Python, a range() starts at 0 by default, so you don’t need to add it. If no start is supplied, it just counts from 0 upwards. You can find out more by typing help(range) at a Python shell.
If the data set is large, you should use xrange() instead. This is faster when you’re using a large range of objects. See What is the difference between range and xrange? for more details.

This is what I get at the end:

def process_lines(lines):
    """Returns the lines with the residual charge and
    interatomic distances computed and added.
    """
    # Calculate residual charge
    v_charge = np.vectorize(residual_charge)
    lines[:, 4] = v_charge(lines[:, 4])

    # Calculate atomic distances
    distances = []
    for i in xrange(len(lines)):
        line_sum = np.sum((lines[i, 1:4] - lines[0, 1:4]) ** 2)
        min_dist = np.sqrt(line_sum)
        distances.append(min_dist)

    lines = np.column_stack((lines, dist))
    lines = lines[lines[:, 5].argsort()]

    return

Printing the file

Without wishing to sound like a broken record, put this in a function as well. This one is easy:

def print_data(lines):
    """Prints the parsed and formatted data."""
    for row in lines:
         print '{0:<3.0f} {1:12.6f} {2:12.6f}'.format( row[0], row[5], row[4])

Script vs. module

At the end of the script, we can add the lines

acf_lines = parse_dat_file('ACF.dat')
print_data(process_lines(acf_lines))

and it will do the printing we originally set out to do.

But now the code has been broken into separate functions, we can use it in other scripts. Say this was atomic.py; then we could write from atomic import residual_charge in another file, and we’d have access to the residual_charge function.

However, when we import this file in another script, we don’t want it to start reading and printing ACF.dat; we just want the definitions. If we put the particular code for ACF.dat in a special if statement, then it only gets run if the file is called directly:

if __name__ == '__main__':
    acf_lines = parse_dat_file('ACF.dat')
    print_data(process_lines(acf_lines))

Now, if we type python atomic.py at a command line, this code gets run and the data is printed. If we use import atomic elsewhere, then we just get the function definitions. You can find out more in What does if __name__ == "__main__": do?

Summary

If I combine everything I’ve done above and put it into a single file, then this is what I’m left with:

#!/usr/bin/python
import numpy as np

def residual_charge(x):
    """Returns the residual charge of an atom."""
    if x < 4:
        return 4 - x # atom 1
    else:
        return 6 - x # atom 2

def parse_dat_file(filename):
    """Returns a numpy array based on the contents of the input file."""
    # read the file contents
    parsed_lines = []
    with open(filename, 'r') as f:
        for line in f:
            parsed_lines.append(line.split())

    # Remove unnecessary rows and columns
    parsed_lines = parsed_lines[2:-4]
    parsed_lines = np.array(parsed_lines, dtype=float)
    parsed_lines = parsed_lines[:,0:5]

    return parsed_lines

def process_lines(lines):
    """Returns the lines with the residual charge and
    interatomic distances computed and added.
    """
    # Calculate residual charge
    v_charge = np.vectorize(residual_charge)
    lines[:, 4] = v_charge(lines[:, 4])

    # Calculate atomic distances
    distances = []
    for i in xrange(len(lines)):
        line_sum = np.sum((lines[i, 1:4] - lines[0, 1:4]) ** 2)
        min_dist = np.sqrt(line_sum)
        distances.append(min_dist)

    lines = np.column_stack((lines, distances))
    lines = lines[lines[:, 5].argsort()]

    return lines

def print_data(lines):
    """Prints the parsed and formatted data."""
    for row in lines:
         print '{0:<3.0f} {1:12.6f} {2:12.6f}'.format( row[0], row[5], row[4])

if __name__ == '__main__':
    acf_lines = parse_dat_file('ACF.dat')
    print_data(process_lines(acf_lines))


Hackerrank Funny String python solution "Funny String" problem from Hackerrank

  Suppose you have a String, \$S\$ of length \$N\$ indexed from \$0\$ to \$N-1\$. You also have some String, \$R\$, that is the reverse of \$S\$, where \$S\$ is funny if the condition is \$\left|S[i] - S[i-1]\right| = \left|R[i] - R[i-1]\right|\$ is true for all \$i \in [1, N-1]\$.

I code mainly in Java. I'm very new to Python, so I would appreciate feedback on how I can make this code more Pythonic, cleaner and more efficient in general.

import math

def isFunny(word):
    i = 0
    length = len(word)
    arr = []
    revarr = []
    for i in range(0,math.ceil(length/2)):
        sdiff = abs(ord(word[i])-ord(word[i+1]))
        rdiff = abs(ord(word[length-i-1])-ord(word[length-i-2]))
        if sdiff == rdiff:
               continue
        else:
               return False
    return True

if __name__ == "__main__":
    n = int(input())
    for _ in range(n):
        word = input();
        if isFunny(word):
            print("Funny")
        else:
            print("Not Funny")

Code organisation and other things well done

You've extracted the algorithm in a function on its own. Also, you've written you code behind the "if name == main" guard. Congratulations on this, these are two good things beginners usually don't do properly.
This makes your code clearer, easier to maintain and easier to test.

Also, I'd like to take this chance to congratulate you for using _ as a name for a throw-away value which is quite a nice habit.

Finally, you did notice that there was not point in looping over the whole string once you've reached the middle.

Getting rid of useless things

  It seems that perfection is attained not when there is nothing more to add, but when there is nothing more to remove. - Antoine de Saint Exupéry

I can see in your code artifacts of old versions of your code : arr and revarr are not used at all. Also you don't need to define i before the loop.

continue is nice keyword, available in most programming languages. However, from my experience, you don't need it that often. In your case, you might as will just write :

    if sdiff != rdiff:
           return False

Finally, 0 is not required as a first argument to range.

Style

Python has a style guide called PEP 8. It is definitly worth a read. You'll find various tools online to check your code's compliancy to PEP 8. From what I can see, the main "issue" is that the function name is CamelCased and not snake_cased.

Documentation

If you wanted to do things properly, it might be interesting to add some documentation to your function.

More details (and personal preferences)

We have a nice ternary operator in Python. Using it, you could write :

    print("Funny" if is_funny(word) else "Not Funny")

Also, your is_funny function looks like the typical situation where you could use the all/any Python builtin. However, because of the length of the expressions involved, it becomes a bit of a matter of personal preference. I'd write this (but you don't have to like it) :

def is_funny(word):
    """Check if a word is funny."""
    length = len(word)
    return all(
        abs(ord(word[i])-ord(word[i+1])) == abs(ord(word[length-i-1])-ord(word[length-i-2]))
        for i in range(math.ceil(length/2))
    )

Another thing that could be changed but might not make the code clearer to every one is the way you get the n-th element of the reversed string. You can use word[length-i-1] like you did but you can also take the most out of Python's index handling : negative indices are taken from the end of the container. So that you can write word[-i-1] instead (and the same principle applies to word[length-i-2]).


Static wcf client to make multiple request with one object I want to make a static client to call a wcf because the first time I call the wcf it takes too long, even sometimes it throws time out.

I have the following class:

public class Repository : IRepository
{
    protected static ServiceClient Client { get; set; }

    public Repository()
    {
        if (Client == null)
        {
            Client = new ServiceClient();
        }

        if (Client.ChannelFactory.State != CommunicationState.Opened
            || Client.ChannelFactory.State != CommunicationState.Created)
        {
            Client = new ServiceClient();
        }
    }

    public virtual async Task<Response> GetPersonsFromAddress(string address)
    {
        try
        {
            Request request = new Request();
            request.Address = address;
            Response response = await Client.GetPersonsAsync(request);

            return response;
        }
        catch (Exception ex)
        {
            // ...
            // Handle exception
            // ...
        }
    }
}

And this class calls the method:

public class Conector : IConector
{
    private IRepository Repository { get; }

    public Conector()
    {
        Repository = new Repository();
    }

    public virtual async Task<Response> GetPersonsFromAddress(string address)
    {
        Response response = await Repository.GetPersonsFromAddress(address);
        return response;
    }
}

The object that calls the wcf service is static so I want to know if this is a good practice.

Also if there are a lot of people at the same time using this method, it will return the correct response for each request.

I think you should consider inverting control and moving ServiceClient instantiation outside the repository class. Whether or not ServiceClient is a singleton (in single-instance sense) or not is not something that repository should manage or care about:

public class Conector : IConector
{
    private IRepository Repository { get; }

    public Conector(IRepository repository)
    {
         Repository = repository;
    }
    ...
}

public class Repository : IRepository
{
    protected ServiceClient Client { get; }

    public Repository(ServiceClient client)
    {
        Client = client;
    }

    ...
}


Simple event management system In an effort to rid my code of jQuery, I wrote a custom global event management/handling system. I was expecting this to be hard as, from what I've read, most people don't create their own. It's far simpler than most libraries I've seen. Is there a flaw in this method? What are the benefits of using something like EventEmitter.js?

var EvtMgr = function() {
  var events = {};
  this.on = function(evtName, callback) {
    if (!events[evtName]) events[evtName] = [];
    events[evtName].push(callback);
  }
  this.trigger = function(evtName, evtObj) {
    events[evtName].forEach(function(callback) {
      callback(evtObj);
    });
  }
  this.remove = function(evtName) {
    delete events[evtName];
  }
}

exports.evtMgr = new EvtMgr();

Then I can register listeners with evtMgr.on('foo', function(evtObj) {…});

I was expecting this to be hard as, from what I've read, most people don't create their own

Actually, there are more people who create event emitters than you think. I'm one of them, and here's my implementation. Aside from Event Emitter, it's also called "pub-sub", and here's one of the same nature under that label.

It's a basic practice of the concept of managing async and decoupled code. It also makes for a good practice in code performance, coding style and sample code when learning GIT.

  It's far simpler than most libraries I've seen.

Because it is very simple. Collect callbacks, and when triggered, you look for the right collection and fire. That's about it.

  Is there a flaw in this method?

Yes, and that's what I haven't fixed in mine. The following code in trigger is the problem:

events[evtName].forEach(function(callback) {
  callback(evtObj);
});

In your trigger, you fire the callbacks one after the other. That's fine for sequential code. But what if each of the callbacks contained operations that are synonymous to looping 100k times? And imagine if every callback listening to that fired event did that? That would freeze up the browser.

A solution to that is using timers. Timers can be "set aside" when JS is busy. They don't "block the thread", as they usually call it. That way, you have these "gaps" when executing the callbacks, allowing the browser to breathe and do something else, like render the page perhaps.

var length = events[evtName].length;
var i = 0;
var timer = setInterval(function(){       // Execute whenever possible
  events[evtName][i].call();              // Nothing special about the call()
  if(++i == length) clearInterval(timer); // Clear when done
},0);

  What are the benefits of using something like EventEmitter.js?

If you mean the concept of pub-sub, then you have decoupled of code which means it's easier to put in and pull out code without breaking the rest of the app. You also have a basic facility for managing asynchronous events.

If you meant the library itself, then you just saved your time writing, testing and maintaining a pub-sub library. Not to mention, it's all free. All you need to do is grab and go (and maybe give credits where it's due).


Multiword Expression Tagging in Python I am trying to write a small python code,where
I am reading a text file-which contains both Multiwords (MWEs)
and singular words (NMWEs).

I am trying to tag each one, as follows.

I have a dictionary of entries, containing the MWE and tagged MWE.
I am tagging them as replace, and whichever I could not tag as MWE
-the NMWE I am marking them so.

I wrote the following code

def rule_disc():
    corp=open("/python27/MWETagtext1.txt","r").read().lower()
    print "The Text file given Is:",corp
    mwedict={'prime minister':'prime/MWE minister/MWE','new delhi':'new/MWE    delhi/MWE','reserve bank':'reserve/MWE bank/MWE'}
    dict=mwedict
    mwetag=reduce(lambda x, y: x.replace(y, dict[y]), dict, corp)
    print "MWE Tagged String Is:",mwetag
    mwetagw=mwetag.split()
    list1=[]
    for word in mwetagw:
        if "/" in word:
            list1.append(word)
        else:
            word1=word+"[NMWE]"
            list1.append(word1)
    nlist=list1
    nstring=" ".join(nlist)
    print "The Tagged Text File Is:",nstring

on the given sample data, which is producing me the result.

My question is, is there a smarter way to do it?
Actual data size may run on millions of files.

I am using Python2.7.12 on MS-Windows 7

Several things we can improve:

don't repeat the multi words and the same multi words with tags - just have a list of multi-words and, if it is in the corp, replace each word with a tagged word
use with context manager to read the file contents
use a list comprehension for tagging all other words
generalize the function a bit and provide it with data as an argument

Improved version:

MWE = ['prime minister', 'new delhi', 'reserve bank']

def tag_words(text):
    # tag all MWEs
    for multi_word in MWE:
        if multi_word in text:
            for word in multi_word.split():
                text = text.replace(word, word + "/MWE")

    # tag all NMWEs and return
    return " ".join([word if "/" in word else word + "[NMWE]"
                     for word in text.split()])

with open("/python27/MWETagtext1.txt") as f:
    corp = f.read().lower()

print(tag_words(corp))

Since you are doing natural language processing, I think you should also be using word_tokenize() instead of the naive str.split().


Class-based Message System Pattern I'm trying to create an extensible system for building messages.

I want each style of message to be a unique class. I don't want the client to have to worry about the class type when creating the message (or reading it – but that is not included here).

In the code below, I only use ints and Strings. The final version would wrap ints and Strings in another class with data validation if necessary.

// Run from main
import xx.xxx.StandardFactory.*;
private void standardFactoryTest() {
    StandardFactory standardFactory = new StandardFactory();

    BasePackage testPackage1 = standardFactory.makePackage("Text for One");
    BasePackage testPackage2 = standardFactory.makePackage(999);
    BasePackage testPackage3 = standardFactory.makePackage("Text for Three", 129);

    testPackage1.printData(); // prints “StringPackage value: Text for One”
    testPackage2.printData(); // prints “IntPackage value: 999”
    testPackage3.printData(); // prints “StringIntPackage value: Text for Three, 129”
}

package xx.xxx.StandardFactory;

public class StandardFactory {
    public abstract class BasePackage{
        public abstract void printData();
    }

    public class StringPackage extends BasePackage {
        private final String value;

        StringPackage(String value) {
            this.value = value;
        }

        public void printData() {
            System.out.println("StringPackage value: " + value);
        };
    }

    public class IntPackage extends BasePackage  {
        private final int value;

        IntPackage(int value) {
            this.value = value;
        }

        public void printData() {
            System.out.println("IntPackage value: " + value);
        };
    }

    public class StringIntPackage extends BasePackage  {
        private final String stringValue;
        private final int intValue;

        StringIntPackage(String stringValue, int intValue) {
            this.stringValue = stringValue;
            this.intValue = intValue;
        }

        public void printData() {
            System.out.println("StringIntPackage value: " + stringValue + ", " + intValue);
        };
    }

    public StringPackage makePackage(String value) {
        return new StringPackage(value);
    }

    public IntPackage makePackage(int value) {
        return new IntPackage(value);
    }

    public StringIntPackage makePackage(String stringValue, int intValue) {
        return new StringIntPackage(stringValue, intValue);
    }
}

Potential problems:
    If I add new classes I need to add them to the factory. I don't see this as too much work.
    Messages could take arguments in a different order. I will not need to make every different     combination of input for my purposes so this should not be a problem.
    Large packages may need five or six different arguments. This goes against the principle of     using few arguments in a function, but it would be the exception not the rule.

I am interested specifically in the following:

Is this a common design
pattern (is it a version of the factory pattern)?
Are there more
suitable design pattern options available?
Are there any obvious
improvements?
Is it possible to have the factory static so I don't
need a factory object?

I am not interested in the following (with reasons):

Naming – This has been done as example code
Comments – I have not attempted to comment this code
Data validation – Not required at this point

Everything else is fair game.

Seems you are on the right way. But mostly depends how will the client use your factory and BasePackage.
Here are some my minor remarks for improvements:

Only BasePackage is to be public, all the implementation classes are to be hidden.
makePackage() should return BasePackage type.
To reduce possible 5..6 arguments think about varargs solution.
Yes, you may have factory as a static, because you don't have an internal state (at least for now).
Naming: if possible rename BasePackage to reflect your domain area. BasePackage for client perspective may be not clear. But it is ok if you have good package hierarchy.


Simple registration form I'm very new to backbone.js and JavaScript.  I would like to hear some reasonable critiques / advice against my JavaScript code based on backbone.js framework with backbone-forms.

The aim of this simple app is to present a user with a simple registration form (twitter bootstrap modal dialog) and upon clicking on registration button post the model to a RESTful web service.

Model:

var MemberModel = Backbone.Model.extend({
    schema: {
        name: {
            type:  'Text',
            title: 'Full Name',
            validators: [
                'required'
            ],
            editorAttrs: {
                'placeholder': 'Type in your full name...',
                'class':'input-xlarge'
            }
        },
        email: {
            dataType: 'email',
            title: 'E-mail address',
            validators: [
                'required',
                'email'
            ],
            editorAttrs: {
                'placeholder': 'Type in your email address...',
                'class':'input-xlarge'
            }
        },
        country: {
            type: 'Select',
            options: [
                {
                    val: 0,
                    label: 'Choose a country...'
                },
                {
                    val: 1,
                    label: 'Country #1'
                },
                {
                    val: 2,
                    label: 'Country #2'
                },
                {
                    val: 3,
                    label: 'Country #3'
                }
            ],
            editorAttrs: {
                'data-placeholder': 'Choose a country',
                'class': 'input-xlarge'
            }
        }
    },
    urlRoot: '/api/members',
    validate: function(attrs) {
        var errors = {};
    if ( attrs.country == 0 ) {
        errors.country = 'Choose a country from list';
    }
        if ( !_.isEmpty(errors) ) return errors;
    }
});

Create an instance of the model:

var member = new MemberModel();

The View:

var MemberSignUpView = Backbone.View.extend({
    name: "MemberSignUpView",
    model: MemberModel,
    el: $('#frontend'),
        initialize:
            function()
            {
                if ( ! ich['signup'] ) {
                    ich.addTemplate('signup', 'ajax:/media/js/tpl/frontend/' + this.name + '.html?' + (Math.random() * 1000000).toString());
                }
            },
        events:
            {
                "click #wndSignupClose": "onCloseClick",
                "click #wndSignupSubmit": "onSubmitClick"
            },
        onSubmitClick:
            function()
            {
                var errors = frmSignUp.commit();
                if ( _.isEmpty(errors) ) {
                    member.save();
                }
            },
        onCloseClick:
            function()
            {
                this.el.modal('hide');
                this.el.remove();
                this.undelegateEvents();
            },
        render:
            function()
            {
                this.el = ich.signup();
                if ( typeof window.frmSignUp == "undefined" ) {
                    window.frmSignUp = new Backbone.Form({
                        model: member
                    }).render();
                }
                $(this.el).find('.modal-body').append(window.frmSignUp.el);
                $(this.el).modal({
                backdrop: 'static',
                keyboard: false
            });
            return this;
        }
});

Create modal window uppon clicking on a button:

$(function() {
        $('#btnSignup').bind('click', function(){
            var wndSignUp;
            if ( typeof wndSignUp == "undefined" ) {
                wndSignUp = new MemberSignUpView().render().el;
            }
            $('#frontend').append(wndSignUp);
    wndSignUp.modal('show');
    });
});

It's pretty good code. Well done! There are no major mistakes or pain points that  would annoy other developers. All I can do is to nitpick a little bit.

First of all take a look at some JavaScript style guide. jQuery has a good one and Google has a great one, too. You may find many others and although they all diverge a little bit there are a lot of common practices that they all agree on. One of those is braces' positioning. Instead of

render:
    function()
    {

you'd better use

render: function () { // note the spaces, too :)

Another point is the use of === instead of ==. I've noticed that you've never used a triple-equals operator in your code and I'm a little bit nervous. Maybe you know about the one vs. the other and you know what are you doing in this particular code (and btw your code works totally fine with double-equals). But what if you don't know? And what if some other developer who doesn't know JavaScript well take a look at your code and try to do something similar? Suppose he doesn't know the rules and you code is the largest and most complicated piece of JavaScript he's ever seen. Which way of thinking do you think is more bullet-proof for a JS-newbie:

  JavaScript is somewhat weird: I have to use === to compare things.

or

  JavaScript is so easy! I'll use == to compare stuff everywhere in my code!

I guess the former is better.
I noticed you use .bind() method for event binding. Consider switching to new .on() method introduced in jQuery 1.7. One of the current goals for jQuery team is to make their library smaller and more lightweight so they work hard to cut off all the fat that's accumulated over the years. At some point in future they may remove the old API so it's better start using new API today to make your code future-proof. It''l be a lot less hassle to switch to new version of jQuery in future.

Other than that your code is fine. I really like the fact that you use Underscore JS. That saves you and other developers a lot of time and headaches.


Thread-safe bounded buffer FIFO queue using C++11 I have started learning multi-threading using C++ 11 and here I have posted the code for thread-safe FIFO queue for multiple producers and consumers.
Though it works fine but I want to know any suggestions,best practices or even any loop hole if you guys can find it.

#ifndef BOUNDEDBUFFER_H
#define BOUNDEDBUFFER_H

#include <thread>
#include <mutex>
#include <condition_variable>
#include <iostream>

// T must implement operator <<

template< typename T>
class BoundedBuffer
{
public:
    BoundedBuffer(size_t size) :m_size(size), m_front(0), m_rear(-1), m_count(0)
    {
        m_queue = new T[m_size];
    }

    void enqueue( const T& obj )
    {
        std::unique_lock<std::mutex> writerLock(m_mutex);

        while ( m_size == m_count )
        {
            writers.wait(writerLock);
        }
        m_rear = (m_rear + 1) % m_size;
        m_queue[m_rear] = obj;
        ++m_count;
        std::cout << std::this_thread::get_id() << " has Enqueued Object =" << obj << std::endl;
        readers.notify_all();
    }

    void dequeue( T& obj )
    {
        std::unique_lock<std::mutex> readerLock(m_mutex);
        while (0 == m_count)
        {
            readers.wait(readerLock);
        }
        obj = m_queue[m_front];
        m_front = (m_front + 1) % m_size;
        --m_count;
        std::cout << std::this_thread::get_id() << " has Dequeued Object =" << obj << std::endl;
        writers.notify_all();
    }

    ~BoundedBuffer()
    {
        if (m_queue)
        {
            delete[] m_queue;
        }
    }

private:
    size_t m_size;
    T * m_queue;
    int m_front, m_rear, m_count;
    std::mutex m_mutex;
    std::condition_variable readers;
    std::condition_variable writers;
};

#endif

If the allocation in the ctor throws, the dtor will have to contend with an uninitialized owning raw pointer. In other words, you have Undefined Behavior.

The minimal fix would be value-initializing m_queue before trying to allocate the memory. Moving the allocation into the ctor-init-list would not work, as constructing a std::condition_variable can throw.

The better fix would be using a std::unique_ptr<T[]>, and maybe allocating the memory with a back-port of C++14 std::make_unique, though assigning in the ctor-body would then also work.
delete [] pointer; and if(pointer) delete [] pointer differ in exactly one point:
The second is longer.

Not that you should have any raw owning pointers.
You know remainder (%) is a fairly expensive operation? And the dividend is in the range [0, divisor] inclusive.
You can suppress the notification of writers if the buffer wasn't full before the call to dequeue().
Likewise, you can suppress the notification of readers if the buffer wasn't empty before dequeue().
You should direct debug-output to std::cerr instead. Which would obviate the need for manually flushing with std::endl.

Of course, the debug-output should be removed from the release version.
Strictly speaking, one of m_front, m_rear is superfluous because you also have m_count.
It's a curious decision to make m_rear always point to the last object you enqueue()d, instead of past it, and thus adjusting it before you actually copy the object. It means that enqueue() depends on copy-assignment of T not throwing for correctness.
Your decision to use different names for the std::unique_lock in enqueue() and dequeue() threw me for a loop. For a moment I thought there was a reason for them, namely two different mutexes. Better change that...


Find the number of elements larger than a given element in BST I'm trying to solve the Hackerrank's Insertion Sort Advanced Analysis problem using BST (similar to this question on SO). As I put items in the tree, I need to find out the number of items greater than it (the get_rank() method in the code):

class Node:
    def __init__(self, data):
        self.left = None
        self.right = None
        self.data = data
        self.num_left_children = 0
        self.num_right_children = 0

    def insert(self, data):
        if data <= self.data:
            if self.left is None:
                self.left = Node(data)
            else:
                self.left.insert(data)
            self.num_left_children += 1
        else:
            if self.right is None:
                self.right = Node(data)
            else:
                self.right.insert(data)
            self.num_right_children += 1

    def get_rank(self, data):
        if data < self.data:
            return self.num_right_children + self.left.get_rank(data) + 1
        elif data > self.data:
            return self.right.get_rank(data)
        else:
            return self.num_right_children

How can I improve the performance of this code (e.g. in case multiple identical items are put into the tree) ?

Answering my own question, I made these improvements to the code which allowed me to solve the HR problem:

Instead of representing duplicate values as separate nodes use a counter of occurrences of the value.
Since we need to get the rank of a value immediately after inserting it, we can combine the insert() and get_rank() methods.
Turn recursion into iteration.

The final code:

class Node:
    def __init__(self, data):
        self.data = data
        self.left = None
        self.right = None
        self.num_right_children = 0
        self.occurrences = 1

    def insert(self, data):
        current_node = self
        rank = 0

        while True:
            if data < current_node.data:
                rank += current_node.num_right_children + current_node.occurrences
                if current_node.left is None:
                    current_node.left = Node(data)
                    break
                current_node = current_node.left
            elif data > current_node.data:
                current_node.num_right_children += 1
                if current_node.right is None:
                    current_node.right = Node(data)
                    break
                current_node = current_node.right
            else:
                current_node.occurrences += 1
                rank += current_node.num_right_children
                break
        return rank


Storing .h files in SQLite using SQLJet I’m trying to learn as much as I can on my own by reading lots of examples, documentations, and asking here. I would like to improve my style to write efficient code and adhere to Java standards.

In this small sample of code I would like to get feedback on a few things:

Exception throwing
Opening/closing database connection
Any other comments in general style

There are two classes, Database and Main.

My Database class:

public class Database {

    private String dbName = "";
    private SqlJetDb db = null;

    public Database(String dbName) {
        this.dbName = dbName;
    }

    public void CreateDatabase() throws SqlJetException {...}

    public void OpenDatabaseConnection() throws SqlJetException {...}

    public void CloseDatabaseConnection() throws SqlJetException {...}

    private void InsertRecord(String file) throws SqlJetException {...}

    public void GetDirectoryContent(String dir) {
        File directory = new File(dir);
        if (directory.isDirectory()) {
            String[] content = directory.list();
            for (String s : content) {
                GetDirectoryContent(dir + "\\" + s);
            }
        } else {
            String file = directory.toString();
            String extension = file.substring(file.lastIndexOf("."));
            if (extension.equals(".h")) {
                try {
                    InsertRecord(file);
                } catch (SqlJetException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

Call in main:

Database db = new Database("test.db");
    try {
        db.CreateDatabase();
        db.OpenDatabaseConnection();
        db.GetDirectoryContent("C:\\test");
    } catch (SqlJetException e) {
        e.printStackTrace();
    } finally {
        try {
            db.CloseDatabaseConnection();
        } catch (SqlJetException e) {
            e.printStackTrace();
        }
    }
}

Consider in the following:

public Database(String dbName) {
    this.dbName = dbName;
}

I would check for a null dbName being passed in. Note that you pass this reference and then simply store it. Consequently, if it's null, you won't find out until later (perhaps, much later). You then have to work out at what point that was set to null.
Will you change dbName ? If not, make it final. It'll stop you changing it inadvertently later on. Immutability is often a good idea. It makes the class more robust and thread-safety easier to achieve. Perhaps not a requirement here, but who knows ? It's easier to relax a restriction rather than apply it after-the-fact.


Functions to escape CSS rules in PHP Some context

I've been tasked with supplying an escaping function to arbitrary CSS values that are entered through a form. The goals and caveats are:

I know it's bad practice to let users input CSS. Deal with it.
Data will be injected either to a style attribute, or to an external stylesheet.
This is run on PHP 5.1 (Again, I know, deal with it).
I'm trying to follow this cheat sheet as closely as possible.

The Code

/**
 * ord() alternative that works with UTF8 characters
 * @param string $c
 *
 * @return int      UTF-8 character code value
 */
function getUTF8CharCode($c) {
    $h = ord($c{0});
    if ($h <= 0x7F) {
        return $h;
    } else if ($h < 0xC2) {
        return false;
    } else if ($h <= 0xDF) {
        return ($h & 0x1F) << 6 | (ord($c{1}) & 0x3F);
    } else if ($h <= 0xEF) {
        return ($h & 0x0F) << 12 | (ord($c{1}) & 0x3F) << 6
        | (ord($c{2}) & 0x3F);
    } else if ($h <= 0xF4) {
        return ($h & 0x0F) << 18 | (ord($c{1}) & 0x3F) << 12
        | (ord($c{2}) & 0x3F) << 6
        | (ord($c{3}) & 0x3F);
    } else {
        return -1;
    }
}

/**
 * Escape a single character for CSS context.
 * @param $c
 * @return string
 */
function escapeCSSCharacter($c) {
    return "\\" . base_convert(getUTF8CharCode($c), 10, 16) . " ";
}

/**
 * Escape CSS rule
 *
 * @param string $data          The CSS rule
 * @param array $immuneChars    Array of immune character. These characters will not be escaped.
 *
 * @return string               Escaped string
 */
function escapeCSSValue($data, array $immuneChars = array()) {
    $result = "";
    for ($i = 0; $i < mb_strlen($data); $i++) {
        $currChar = mb_substr($data, $i, 1);
        if (getUTF8CharCode($currChar) < 256 && //Character value is less than 256
            !preg_match("/^\w$/", $currChar) && //Character is not alphanumeric (underscore is considered safe too)
            !in_array($currChar, $immuneChars)  //Character is not immune
        ) {
            $result .= escapeCSSCharacter($currChar);
        }
        else {
            $result .= $currChar;
        }
    }
    return $result;
}

Usage

$colorRule = "color: " . escapeCSSValue("#BADA55;}*{display:none;}/*", array("#")) . ";"; //Will be obviously broken, but will not break the rest of the document.
echo $colorRule;

My worries

Is this a good way to escape CSS? Is this safe? Will this method be impossible to break out of?
Am I doing this relatively efficiently? Given that the strings I'm going to be encoding are arbitrary, I'm worried about attacks that involve thousands of characters.

Any review will be welcomed.

There's not much to say. Overall, the code is small and quite readable.

Just a small nitpick:

if (getUTF8CharCode($currChar) < 256 && //Character value is less than 256
    !preg_match("/^\w$/", $currChar) && //Character is not alphanumeric (underscore is considered safe too)
    !in_array($currChar, $immuneChars)  //Character is not immune

These comments say the what, not the why. They're akin to:

$i++; // increments i by one

Your if condition should be commented, but not like this.

I can't comment on the security-side of things.


Copying orders and prices into another Excel sheet I would like to know if the below VBA can be streamlined to process faster, since it takes on average 9hrs to complete a sheet (800 000 lines), and I have quite a few to get through. Running on 3 computers already to get ahead of the work.

Sub Calculate_Sheet()

Dim orderSh As Worksheet
Dim wiroSh As Worksheet
Dim lastRow As Long, r As Long
Dim pctComp As Double
Dim Arr1 As Variant
Dim StartTime As Double
Dim MinutesElapsed As String

StartTime = Timer

With ThisWorkbook
'calculator
  Set orderSh = .Sheets("ORDER")
'price list
  Set wiroSh = .Sheets("WiroA3C100gsmI100gsm116-118pp ")
End With

Arr1 = wiroSh.Range("C1:M800001")
lastRow = wiroSh.Cells(Rows.Count, 3).End(xlUp).Row

For r = 2 To 2

'copy from price list to calculator
  orderSh.Range("F4") = Arr1(r, 1)
  orderSh.Range("F5") = Arr1(r, 2)
  orderSh.Range("F6") = Arr1(r, 3)
  orderSh.Range("F7") = Arr1(r, 4)
  orderSh.Range("F8") = Arr1(r, 5)
  orderSh.Range("F9") = Arr1(r, 6)
  orderSh.Range("F10") = Arr1(r, 7)
  orderSh.Range("F11") = Arr1(r, 8)
  orderSh.Range("F12") = Arr1(r, 9)
  orderSh.Range("F13") = Arr1(r, 10)

'copy result
  wiroSh.Range("m" & r).Value = orderSh.Range("F14")

 Next r

    For r = 3 To 400001

    'copy from price list to calculator
        orderSh.Range("F4") = Arr1(r, 1)

    'copy result
        wiroSh.Range("m" & r).Value = orderSh.Range("F14")

         'display the row and percentage each 1000 rows
        If r Mod 1 = 0 Then
        Application.StatusBar = "Row = " & r & Format(r / lastRow, " #0.00%")
        End If

     Next r

          For r = 400002 To 400002
          'copy from price list to calculator
              orderSh.Range("F4") = Arr1(r, 1)
              orderSh.Range("F5") = Arr1(r, 2)
              orderSh.Range("F6") = Arr1(r, 3)
              orderSh.Range("F7") = Arr1(r, 4)
              orderSh.Range("F8") = Arr1(r, 5)
              orderSh.Range("F9") = Arr1(r, 6)
              orderSh.Range("F10") = Arr1(r, 7)
              orderSh.Range("F11") = Arr1(r, 8)
              orderSh.Range("F12") = Arr1(r, 9)
              orderSh.Range("F13") = Arr1(r, 10)

        'copy result
              wiroSh.Range("m" & r).Value = orderSh.Range("F14")

     Next r

                For r = 400003 To 800001
                  'copy from price list to calculator
                      orderSh.Range("F4") = Arr1(r, 1)

                  'copy result
                         wiroSh.Range("m" & r).Value = orderSh.Range("F14")

           'display the row and percentage each 1000 rows
  If r Mod 1 = 0 Then
     Application.StatusBar = "Row = " & r & Format(r / lastRow, " #0.00%")

  End If
Next r

MinutesElapsed = Format((Timer - StartTime) / 86400, "hh:mm:ss")
MsgBox "This code ran successfully in " & MinutesElapsed & " minutes", vbInformation

End Sub

There's likely many factors at play here, but here's my two cents:

It looks like you're copying whole cell's onto another sheet for calculation, and again to a results sheet.

What will be happening here is that when copying the values, it will be copying all the information about cells and not just the values. By adding a cell to the watch list you can see just how much information is there that in most cases you don't need (this is just a small section of the entire list):

I would suggest reviewing your copy method to copy only the information you actually need (quite possibly just .Value), this will save both memory and processing.


Reverse vowels in a string What do you think about this solution? I guess there are too many lists...

vowels = "aeiou"

def reverseVowels(string):
    vowels_list = []
    string_list = list(string)

    for index,letter in enumerate(string_list):
        if letter in vowels:
            vowels_list.append(letter)

    reversed_vowels_list = list(reversed(vowels_list))

    new_string_list = list(string_list)
    for index,vowel in enumerate(vowels_list):
        idx_vowel_in_string =  string_list.index(vowel)
        new_string_list[idx_vowel_in_string] = reversed_vowels_list[index]

    print new_string_list

reverseVowels("aupiple")

You use for index, letter in enumerate(string_list): but don't use the index.
Instead of using string_list.index(vowel) in the second loop you can instead build an index list in the first loop.
And reverse either the index list or the vowels list.
This should have a better time complexity as string_list.index(vowel) seems to be making your code time complexity \$O(n^2)\$.

I'd also change your code to follow PEP8, and remove all the redundant _list parts in your variable names.
As this makes your code easier to read.

Finally I'd return, rather than print, the final list as it makes the code  more reusable. And, as Mathias commented, you could also change your return type to a string, as giving a string as input and getting a list of strings as output is a little odd.

VOWELS = set('aeiou')

def reverse_vowels(string):
    string = list(string)
    vowels = []
    indexes = []

    for index, letter in enumerate(string):
        if letter in VOWELS:
            vowels.append(letter)
            indexes.append(index)

    for i, char in zip(indexes, reversed(vowels)):
        string[i] = char

    return ''.join(string)


Variadic templated method to extract values from a table Is this the correct, most sane way to do variadic templates in C++?

All that this function does is to see if gate has a key, if it has, it adds it to a vector of values, if not, it default constructs an object in place.

This function belongs to a templated class called core_table where K is the key type and V the value type.

template <typename ...Args>
std::vector<V> values_at(Args const & ...args) const {
    std::initializer_list<K> input {args...};
    std::vector<V> output;
    output.reserve(input.size());
    for (auto const & e : input) {
        auto const it = gate.find(e);
        if (it != gate.end()) {
            output.emplace_back((*it)->second);
            continue;
        }
        output.emplace_back();
    }
    return output;
}

I'm asking it because all the examples of variadic templates that I saw until now made use of recursion. I'm still in a state of desbelief that I can just write std::initializer_list<K> input {k, args...}; and iterate over it, I literally didn't knew until now that this was possible - this does make variadic templates much more approachable in C++, at least for me.

So, is this a good example? How can I make it better, more optimized?

Working Example

#include <iostream>
#include <list>
#include <set>
#include <string>
#include <vector>

using std::cout;
using std::endl;

template <typename K, typename V>
class core_table {
    using value = std::pair<K, V>;
    using chain = std::list<value>;

    using iterator = typename chain::iterator;
    using const_iterator = typename chain::const_iterator;

    struct compare {
        using is_transparent = void;

        bool operator ()(const_iterator x, const_iterator y) const {
            return x->first < y->first;
        }

        bool operator ()(const_iterator x, K const & k) const {
            return x->first < k;
        }

        bool operator ()(K const & k, const_iterator y) const {
            return k < y->first;
        }
    };

    chain data;
    std::set<iterator, compare> gate;

public:
    core_table() = default;

    core_table(core_table && ct) = default;

    core_table(core_table const & ct) {
        for (auto const & e : ct) {
            push(e.first, e.second);
        }
    }

    core_table(std::initializer_list<value> il) {
        for (auto const & e : il) {
            push(e.first, e.second);
        }
    }

    template <typename Key, typename Value>
    core_table & insert(const_iterator cit, Key && k, Value && v) {
        auto const it = gate.find(k);
        if (it != gate.end()) {
            (*it)->second = std::forward<Value>(v);
            return *this;
        }
        gate.emplace(data.emplace(cit, std::forward<Key>(k), std::forward<Value>(v)));
        return *this;
    }

    template <typename Key, typename Value>
    core_table & push(Key && k, Value && v) {
        return insert(data.end(), std::forward<Key>(k), std::forward<Value>(v));
    }

    template <typename ...Args>
    std::vector<V> values_at(Args const & ...args) const {
        std::initializer_list<K> input {args...};
        std::vector<V> output;
        output.reserve(input.size());
        for (auto const & e : input) {
            auto const it = gate.find(e);
            if (it != gate.end()) {
                output.emplace_back((*it)->second);
                continue;
            }
            output.emplace_back();
        }
        return output;
    }
};

int main() {

    core_table<std::string, std::string> ct {{"a", "hello"}, {"b", "world"}};

    for (auto const & e : ct.values_at("b", "a")) {
        cout << e << endl;
    }

    return 0;
}

Yes, it is a good example

Variadic templates are associated with recursion by similarity to functional programming, where an recursion is a simple method of operating on sequences. Direct expansion is akin to a map or fold, or some other higher-order function.

It can be simplified even more

If you have a similar function

/* find value or return default */
template <typename Arg>
V value_at(Arg const & key) const
{
    auto const it = gate.find(key);
    if (it != gate.end()) {
        return it->second;
    }
    return {};
}

Then you can condense this down into a single expression

return vector<V>({value_at(args)...});

as that expands the parameter pack into multiple calls to value_at, which goes into vector's std::initializer_list<V> constructor.


Calling method with complex arguments Whats the best practice for calling a function with a complex set of arguments?

I've seen a 1 and 2 in most codebases, but I haven't seen 3.
Since it's almost impossible to search for **{ in codebases, does anyone know why this pattern isn't used more often?

I'm using Google's Sheet's API v4 as a demonstration, which has a complex API.

1. Calling with arguments (Most commonly observed)

Requires building the inner structure first

body = {
    "body": {
        "requests": [
            {
                "addSheet": {
                    "properties": {
                        "title": "some title"
                    }
                }
            }
        ]
    }
}
request = service.spreadsheets().batchUpdate(
    spreadsheetId=spreadsheetId, body=body)

2. Define a dict first (Similar vertical parsing to 1)

Cleaner to see on invocation
May allow for manipulation of values

params = {
    "spreadsheetId": spreadsheetId
    "body": {
        "requests": [
            {
                "addSheet": {
                    "properties": {
                        "title": "some title"
                    }
                }
            }
        ]
    }
}
request = service.spreadsheets().batchUpdate(**params)

3. Inline a dict (Not seen in practice, why?)

Clear intent (single-source, fixed properties)
Single pass vertical parsing

request = service.spreadsheets().batchUpdate(**{
    "spreadsheetId": spreadsheetId
    "body": {
        "requests": [
            {
                "addSheet": {
                    "properties": {
                        "title": "some title"
                    }
                }
            }
        ]
    }
})

As general practice, I prefer using positional arguments simply because they're easier to typecheck with mypy.  In the case of using some external API that doesn't have python3 type annotations (booo) I'd create a stub file that includes all of the types that I'm using and then code against that.

For your example, a quick search didn't turn up any existing mypy stubs, so I assume I'm stuck writing my own.  Here's how I'm gonna do it for the code sample you've provided:

from typing import List, TypedDict

class _Properties(TypedDict, total=False):
    title: str

class _AddSheet(TypedDict, total=False):
    properties: _Properties

class _Request(TypedDict, total=False):
    addSheet: _AddSheet

class _Body(TypedDict, total=False):
    requests: List[_Request]

def batchUpdate(spreadsheetId: str, body: _Body) -> None: ...

This is a very incomplete type declaration for that potentially massive _Body object (also, note that I'm assuming that none of these fields are required; omit the total=False if you want to enforce totality), but since I'm probably not going to use all of those fields, my strategy is going to be to add them to my declaration as I use them, and have that be the source of truth (i.e. as long as I declare it correctly once in that file, mypy will make sure I use it correctly everywhere else).

Now I can call that function in my code like this:

batchUpdate(
    spreadsheetId, {
        'requests': [{
            'addSheet': {
                'properties': {
                    'title': "some title"
                }
            }
        }]
    }
)

(BTW, if you want to completely ignore my advice about typing, this is the calling syntax I'd use regardless.)

The benefit of having added typing is that if I typo something, e.g. I misspell "properties", I'll get an error from mypy like this:

spreadsheet.py:22: error: Extra key 'prperties' for TypedDict "_AddSheet"

If I forget that requests is a list and I omit the brackets, I get:

spreadsheet.py:21: error: Incompatible types (expression has type "Dict[str, Dict[str, Dict[str, str]]]", TypedDict item "requests" has type "List[_Request]")

Getting a static error like this is a lot easier than having a typo in my server API call that results in a (possibly cryptic) runtime error.

My experience is that using the **kwargs syntax generally makes it harder to enforce good typing, so I tend to avoid it.


Sorting products by name or price Lets preface this by saying that when it comes to javascript, I am a hack. I make what I need happen by cobbling together crappy, inefficient, redundant code. I want to get better.
Recently I was asked if I could make a set of elements on a page sort-able by price, A-Z and Z-A. The code on the page looks something like the below:

<select id="sorting" onchange="selectionChange()">
      <option value="Sort By">Sort Products</option>
      <option value="Sort By Price" id="price">Sort By Price</option>
      <option value="Sort By A-Z" id="az">Sort By A-Z</option>
      <option value="Sort By Z-A" id="az">Sort By Z-A</option>
</select>

                 text link

$item price

                 text link

$item price

I was able to make things work by assigning a sort class to the text link and the price "p" tag, listen for onchange from the dropdown and when it fired either the price or the name of the item was assigned as an attribute to the containing product wrapper, then the wrappers are sorted using a simple sort function. My working but embarrassing attempt is below.

jQuery(document).ready(function( $ ) {
sortPrice = function(){
$('.product-wrapper').each(function(){
    var data1 = $(this).find(".sortprice").text();
    $(this).attr('data-name', data1);

});

var $products = $('.products'),
    $singleProduct = $('.product-wrapper');

$singleProduct.sort(function(a,b){
        var an = a.getAttribute('data-name');
        var bn = b.getAttribute('data-name');
        var numberA = Number(an.replace(/[^0-9\.]+/g,""));
        var numberB = Number(bn.replace(/[^0-9\.]+/g,""));
        an = numberA;
        bn = numberB;

        if(an > bn) {
        return 1;
    }
    if(an < bn) {
        return -1;
    }
    return 0;
});

$singleProduct.detach().appendTo($products);

};

sortA = function(){
$('.product-wrapper').each(function(){
    var data1 = $(this).find(".sort1").text();
    $(this).attr('data-name', data1);

});

var $products = $('.products'),
    $singleProduct = $('.product-wrapper');

$singleProduct.sort(function(a,b){
        var an = a.getAttribute('data-name');
        var bn = b.getAttribute('data-name');

        if(an > bn) {
        return 1;
    }
    if(an < bn) {
        return -1;
    }
    return 0;
});

$singleProduct.detach().appendTo($products);

};

sortZ = function(){
$('.product-wrapper').each(function(){
    var data1 = $(this).find(".sort1").text();
    $(this).attr('data-name', data1);

});

var $products = $('.products'),
    $singleProduct = $('.product-wrapper');

$singleProduct.sort(function(a,b){
        var an = a.getAttribute('data-name');
        var bn = b.getAttribute('data-name');

        if(an > bn) {
        return -1;
    }
    if(an < bn) {
        return 1;
    }
    return 0;
});

$singleProduct.detach().appendTo($products);

};
selectionChange = function(){
var selectResult = $("#sorting").val();

if(selectResult == "Sort By Price"){
    sortPrice();

} else if(selectResult == "Sort By A-Z"){
    sortA();

} else if(selectResult == "Sort By Z-A"){
    sortZ();

}
};
});

I would be eternally indebted to whoever will show me what an elegant version would look like and maybe how and where I would add error handling.

All the sort functions follow the same pattern, with a few key differences:

A field to extract for comparison (.sortprice, .sort1)
A comparison function (numeric, alphabetic, ascending and descending)

These can be parameters for a general-purpose implementation:

sortHelper = function(search, comparator) {
    $('.product-wrapper').each(function() {
        var data = $(this).find(search).text();
        $(this).attr('data-name', data);
    });

    var $products = $('.products'),
        $singleProduct = $('.product-wrapper');

    $singleProduct.sort(comparator);

    $singleProduct.detach().appendTo($products);
};

The price comparator function can be implemented simpler than you did,
considering that it doesn't need to return precisely -1, 1 values,
any other negative and positive values would be fine:

var cmpPrice = function(a, b) {
    var an = a.getAttribute('data-name');
    var bn = b.getAttribute('data-name');
    var numberA = Number(an.replace(/[^0-9\.]+/g, ""));
    var numberB = Number(bn.replace(/[^0-9\.]+/g, ""));
    return numberA - numberB;
};

The string comparator function can be much like it was:

var cmpName = function(a, b) {
    var an = a.getAttribute('data-name');
    var bn = b.getAttribute('data-name');
    if (an > bn) {
        return 1;
    }
    if (an < bn) {
        return -1;
    }
    return 0;
});

The string comparator in descending order can be implemented in terms of the other one in ascending order:

var cmpNameDesc = function(a, b) {
    return cmpName(b, a);
});

And then the main function can be implemented in terms of these helpers:

selectionChange = function() {
    var selectResult = $("#sorting").val();

    if (selectResult == "Sort By Price") {
        sortHelper('.sortprice', cmpPrice);
    } else if (selectResult == "Sort By A-Z") {
        sortHelper('.sort1', cmpName);
    } else if (selectResult == "Sort By Z-A") {
        sortHelper('.sort1', cmpNameDesc);
    }
};


Strip a newline and add more text to a Go bytes.Buffer I wrote a little timer middleware to append the request duration to the end of the log message returned by the excellent Gorilla Toolkit's CombinedLoggingHandler from the handlers package.

That handler accepts an io.Writer and an http.Handler, and fills the Writer with a newline-terminate string containing the Apache Combined Format log entry for the current server request. I would like to remove the trailing newline and add " completed in xxx", where xxx is the amount of time the request took.

The following code works, but I am not sure that I made the best use of the Go bytes.Buffer in the way I stripped the newline:

func timerHandler(h http.Handler) http.Handler {
    return http.HandlerFunc(func(res http.ResponseWriter, req *http.Request) {
        var b bytes.Buffer
        hand := handlers.CombinedLoggingHandler(&b, h)

        defer func(start time.Time) {
            prefix := bytes.TrimRight(b.Bytes(), "\n")
            os.Stdout.Write(prefix)
            fmt.Printf(" completed in %v\n", time.Since(start))
        }(time.Now())

        hand.ServeHTTP(res, req)
    })
}

Is there a better way to write this in Go?

I believe you are over-complicating the handler function by introducing the deferred function with the start time closure. Additionally, you are performing 2 writes to accomplish the logging, when one would be better.

So, Why have the "defer"? This code:

    var b bytes.Buffer
    hand := handlers.CombinedLoggingHandler(&b, h)

    defer func(start time.Time) {
        prefix := bytes.TrimRight(b.Bytes(), "\n")
        os.Stdout.Write(prefix)
        fmt.Printf(" completed in %v\n", time.Since(start))
    }(time.Now())

    hand.ServeHTTP(res, req)

would be simpler to understand as:

    start := time.Now()
    var b bytes.Buffer
    hand := handlers.CombinedLoggingHandler(&b, h)

    hand.ServeHTTP(res, req)

    prefix := bytes.TrimRight(b.Bytes(), "\n")
    os.Stdout.Write(prefix)
    fmt.Printf(" completed in %v\n", time.Since(start))

Then, in addition, I would manipulate the bytes to trim and add the completion message, and then output them...., so I would change the last part of the code to be something like:

    msg := bytes.TrimRight(b.Bytes(), "\n")
    msg := append(msg, []byte(fmt.Sprintf(" completed in %v\n", time.Since(start)...)
    os.Stdout.Write(msg)

That still irks me a bit, because i don't like the os.Stdout.Write being a constant value in there.... I would make that a parameter somehow, or a constant of some sort....

var logDest io.Writer = os.Stdout


JavaScript syntax: bucketing based on days (today, yesterday and past) I am trying to create three buckets of objects. Today, yesterday and past. I am wondering can the following be done in a more concise way in pure JavaScript without any libraries?
const [todayBucket, yesterdayBucket] = [0, 1].map(offset =>
  recordings.filter(({ createdOn }) =>
    moment(createdOn).isSame(moment().add(-offset), 'day'),
  ),
);
const pastBucket = recordings.filter(
  recording => ![...todayBucket, ...yesterdayBucket].includes(recording),
);

Doing it without an additional library you could try a custom function that does the same thing
function isSame(a,offset) {
    const b = new Date();
    b.setDate(b.getDate() - offset);
    return a === b
}

const [todayBucket, yesterdayBucket] = [0, 1].map(offset =>
  recordings.filter(({ createdOn }) =>
    isSame(createdOn,offset),
  ),
);
const pastBucket = recordings.filter(
  recording => ![...todayBucket, ...yesterdayBucket].includes(recording),
);