Q:

Why my image update is not "binded"?

I have a gird view of my objects "Sessions". On user selection, every Session's Image gets display in an Image on my GUI. I have this routine where, on user SelectedSession, it Deletes any existing image, Takes a new Image frameSource, Saves it locally and then sets the private member variable ImagePath as its path:
    public Session SelectedSession { get { return selectedSession; } set { SetValue(ref selectedSession, value); } }
    public BitmapSource SessionImage { get { return sessionImage; } private set { SetValue(ref sessionImage, value); } }

//..
    public void TakeSessionImage(BitmapSource frameSource)
    {
        if (SelectedSession != null)
        {
            if (File.Exists(SelectedSession.ImagePath))
                File.Delete(SelectedSession.ImagePath); // delete old - works

            SelectedSession.ImagePath = FileStructure.CurrentSessionPath + "\\" + SelectedSession.Name + ".png"; // set ImagePath - works - Technically it does not change. I kept it if I needed later to add anything to the file name like GUID or whatever
            ImageIO.RotateAndSaveImage(SelectedSession.ImagePath, (WriteableBitmap)frameSource, -270); // save new image - works
            SessionImage = SelectedSession.LoadImageFromFile(); // binded the image to display
        }
    }

Binding in Xaml:
<Image x:Name="currentSessionImage" Source="{Binding SessionImage}"/>

In "Session.cs" class:
public BitmapImage LoadImageFromFile()
{
    if (File.Exists(ImagePath)) // image path is correct
    {
        try
        {
            BitmapImage image = new BitmapImage();
            image.BeginInit();
            image.CacheOption = BitmapCacheOption.OnLoad;
            image.UriSource = new Uri(ImagePath);
            image.EndInit();
            return image;
        }
        catch
        {
            return null;
        }
    }
    return null;
}

This has been debugged and all statements are valid. SessionImageis my property that is "binded" to an Image on my GUI. However, a very weird behavior is happening:

It is deleting the old image file and I can see that in windows explorer that the file is gone.
It is saving the new one correctly
It is loading the new image from the correct path
But then, it only displays the very First Image I ever took.

Whatever new image I send. It always displays the same image I took the first time. Could anyone please check it for me? I validated the whole code and all values are logical. No syntax errors anywhere.
Edit:
protected virtual bool SetValue<T>(ref T storage, T value, [CallerMemberName] string propertyName = null)
{
    if (!EqualityComparer<T>.Default.Equals(storage, value))
    {
        storage = value;
        OnPropertyChanged(propertyName);
        return true;
    }

    return false;
}

//..

protected void OnPropertyChanged(string propertyName)
{
    try
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
    catch (Exception ex)
    {

    }
}

A:

WPF caches bitmaps that are loaded from URIs. To avoid that, load the BitmapImage directly from file instead:
using (var fileStream = new FileStream(ImagePath, FileMode.Open, FileAccess.Read))
{
    BitmapImage image = new BitmapImage();
    image.BeginInit();
    image.CacheOption = BitmapCacheOption.OnLoad;
    image.StreamSource = fileStream;
    image.EndInit();
    return image;
}


Q:

How can I Streamline Images and Screenshots I Embed into my Post?

Uploading 1MB images or even 300KB images in a question or answer is often unnecessary/overkill and slows down page loads significantly especially when viewing on a mobile connection.
Similarly, really large dimensions are often pointless due to real-estate restrictions.
How can I keep file sizes down or adjust the dimensions of the images to reasonable and sensible numbers?
This post is shamelessly stolen from one by coleopterist over on Anime and Manga Stack Exchange. Go and visit for all your Anime question needs!

A:

If you don't have the wherewithal to optimise an image prior to upload, here are a few tips on doing so directly on UX Stack Exchange:
After embedding an image to your post, you should see an imgur URL similar to http://i.stack.imgur.com/Bg1Lm.png (just using this image of a handsome chappie as an example). This should result in a large image (280KB, it could be a worse size, but even this can be optimised further):

But this image can now be optimised even further simply by tweaking the URL being used. For example tweaking the URL to http://i.stack.imgur.com/Bg1Lmt.png (note that the filename now has an t (for small thumbnail) at the end) will result in an image of smaller size and dimension:

This file is only 6.9KB in size and also smaller in terms of dimensions.
If the dimensions are unsuitable add an m (for medium thumbnail) or an l (for large thumbnail) instead. This will result in the following images respectively:

Other options that appear to work are:
b (Big square crop):

s (Small square crop):

h (Huge thumbnail crop):

If you'd nevertheless prefer viewers to be able to view your uploaded image in all its raw glory, simply link an optimised image to it by wrapping the code like this:
[![...my optimised image!][2]][1]
This will link the thumbnail to the original source file, like so:

In other words, those wanting to view a higher resolution [1] can do so by simply clicking on the thumbnail [2].
Imgur also have more detailed documentation on this


Q:

Does WebView need a WebViewClient to work?

I was going through android tutorials and tried out the WebView example. This is what I ended up with:
WebAppActivity
public class WebAppActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        WebView wv = (WebView) findViewById(R.id.webView1);
        wv.loadUrl("http://www.google.com");

    }
}

main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <WebView
        android:id="@+id/webView1"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent" >
    </WebView>

</LinearLayout>

But instead of loading the page in the application itself, as soon as the application starts the default android browser opens and the page loads in the browser instead of the application. When I press back I return to the application activity which displays a blank screen.
Does anyone know why this is happening?
Edit:
manifest

<uses-sdk android:minSdkVersion="7" />
<uses-permission android:name="android.permission.INTERNET"/>

<application
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name" >
    <activity
        android:label="@string/app_name"
        android:name=".WebAppActivity" >
        <intent-filter >
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>

This was just to show that I have added the INTERNET permission
Edit :
As soon as I add a WebViewClient,
wv.setWebViewClient(new WebViewClient() {});

the page loads in the application. Is this expected behaviour? Does an Android WebView require a WebViewClient?
(couldn't find any documentation on it)
Edit :
I noticed that this problem occurs when I install the apk in an emulator which has the Google APIs. On a normal emulator (without the Google APIs) it behaves as expected.

A:

Yes, you have to set a WebViewClient that returns true on the overridden method 'shouldOverrideUrlLoading' so that your webview loads the URL in your app.
Let me know if you want an example.

Edit
@Aki WebViewClient.shouldOverrideUrlLoading Documentation

Give the host application a chance to take over the control when a new url is about to be loaded in the current WebView. If WebViewClient is not provided, by default WebView will ask Activity Manager to choose the proper handler for the url. If WebViewClient is provided, return true means the host application handles the url, while return false means the current WebView handles the url.


Q:

Git oddity with folders between branches

I am working with git, still fairly new to working with branches, and I am coming across a real odd problem. I am not sure what is going on to be honest.
I am creating a git repo then adding a readme to it, and committing the changes.
git init
git touch README
git add README
git commit -m 'add readme'

From there I now have a master branch. I do:
git branch development
git checkout development

From there I have added 3 folders of files, since I am adding an old project to source control for the first time. The folders are:
Theme-arm
FrontEnd
ControlPanel

My goal is to add these files to the development branch and no other branches. I then do
git add *
git commit -m 'initial commmit'

That all works good. However When I switch back to master with
git checkout master

The problem, and what is leading to my confusion, is that ControlPanel and FrontEnd, but not theme-arm are now in master as well. I don't want them there, yet.
Am I doing something wrong or misunderstanding how git is working?

A:

Check ControlPanel and FrontEnd for files that weren't put under version control when you did git add * in the development branch (you could just check what the contents of those directories are in your master branch).


Q:

Excel-DNA: grouping rows via C API feature of Excel-DNA

I'm familiar with how to group a range in Excel VSTO/COM interop:
ws.EnableOutlining = true;
ws.Outline.SummaryRow = XlSummaryRow.xlSummaryAbove;
var rng = GetRangeSomeHow();
rng.EntireRow.Group();
rng.EntireRow.OutlineLevel = someLevel;

What is the most efficient way to do this in Excel-DNA?  I would imagine there must be a C-API way to do it, encapsulated cleverly in Excel-DNA somehow, but for the life of me, I can't figure it out via online documentation (incl. Google).
There's a lot of posts using code similar to my sample above, but these are pretty expensive calls, especially since I need to do this ~5000 times overall (I have a really big data set).
EDIT:
So there seems to be this method call:
XlCall.Excel(XlCall.xlfGroup...)

The only problem is, I have no idea what the parameters are. It seems an ExcelReference should be passed in, but how is the .EntireRow resolved? Will the C API just handle it for me - in which case I just need to pass a new ExcelReference(1,100,1,1) and be done with it... or is there more to this?
Thanks in advance to anyone who can answer my question!

A:

I don't think the C API GROUP function is te one you're looking for. The documentation says:

GROUP
Creates a single object from several selected objects and returns the
  object identifier of the group (for example, "Group 5"). Use GROUP to
  combine a number of objects so that you can move or resize them
  together.
If no object is selected, only one object is selected, or a group is
  already selected, GROUP returns the #VALUE! error value and interrupts
  the macro.

I'd suggest you use the COM object model for this kind of thing, even in an Excel-DNA add-in. The C API has not really been updated over the years for the general sheet manipulation like this case, so you're likely to run into some features that don't work right or are incomplete relative to the COM object model.
From your Excel-DNA add-in, just make sure your get hold of the right Application root object with a call to ExcelDnaUtil.Application.
For improved performance of this kind of sheet editing, you pretty much have to use the same tricks as from VBA or VSTO - disable screen updating and calculations etc.


Q:

Cassandra - Row cache tuning

I'm new to Cassandra and trying to get a better understanding on how the row cache can be tuned to optimize the performance.
I came across think this article: https://docs.datastax.com/en/cassandra/3.0/cassandra/operations/opsConfiguringCaches.html
And it suggests not to even touch row cache unless read workload is > 95% and mostly rely on machine's default cache mechanism which comes with OS.
The default row cache size is 0 in cassandra.yaml file so the row cache won't be utilized at all.
Therefore, I'm wondering how exactly I can decide to chose to tweak row cache if needed. Are there any good pointers one can provide on this?

A:

What they are saying in this article, is that OS cache is better than row cache.
Cassandra's rows cache known as not efficient for most cases. The only case i see you can even start trying, is that 95% of your workload are reads + you have a relatively small set of hot rows that are not updated frequently.


Q:

Automatically product assign particular category?

I have a new attribute called feature (Yes or No), If i set yes it automatically assign one new category called feature.

A:

I currently don't have time to write the full code for you, but I can point you in the right direction.
What i would do is create a custom module for this. I will create an observer that listens for a event like catalog_product_save_after. See this blog post for example
The observer could look like something like this:
public function catalog_product_save_after($observer)
{
    $product = $observer->getProduct();

    if($product->getData('feature') == 1){ //1 for yes, 0 for no
        Mage::getSingleton('catalog/category_api')->assignProduct(111,$product->getId()); //replace 111 with the category id
    }
}

I have not tested if it works, but it should be something in the right direction. The code can probably be improved, for example by checking if the product already are in the category.
My workflow for this solution was to google for:

Event fired when product is saved magento
Get product attribute data magento
Magento programmatically add product to category


Q:

jQuery. Check each item by class name

For example, there are some tags
<input value="1000" class="chrome-input" />
<input value="2000" class="chrome-input" />

How can I make manipulation with each value?
Here I can set value to each input. $(".chrome-input").val("10");
But what if I want multiply each value by 10.
Something like that  $(".chrome-input").val($(".chrome-input").val()*10);
And I want to get that
<input value="10000" class="chrome-input" />
<input value="20000" class="chrome-input" />

A:

The clean way of doing this is with the callback signature of val:
$('.chrome-input').val(function(i, oldVal) {
    return parseInt(oldVal, 10) * 10;
});

If you pass a function as the first argument of val, that function will be called on each element.  The second argument passed will be the current value of the element.  The return value of the function will be set as the new value.


Q:

If domain A has an iframe of domain B, which has an iframe of domain A, can domain A access the cookies of domain B?

I remember reading about domain A being able to control domain B if domain B has a helper frame inside it. I have pages like StumbleUpon, where I place other websites in iframes. What if one of those websites place my page in an iframe? Also, stuff like Facebook's Like button and Twitter's Tweet button are all iframes. What data would/woudn't that have access to?
Would they be able to inject scripts into my page?

A:

No, they can not access other domains cookie.
No matter where you hide an iframe with different domain, browser will always send cookies that were set for that specific domain.
Like button can be created utilizing Referer header.
Say, http://domainA.com/index.html contains

Here when http://domainB.com/like.html is called inside the iframe an HTTP header Referer: http://domainA.com/index.html is sent along with the request. This way domainB.com/like.html always knows who is requesting. When domainB.com got this little piece for information it can just check the number of likes of the page and show the result.
A live example
Put the bellow code in any of your websites. After that every time you refresh the the website it'll show how many times its loaded. It'll count the number of hits.

This page is viewd
 1 times


Q:

Positive, comparative, superlative and... is there a fourth?

I'm wondering whether English has something beyond its superlative degree. In my language we call that "túlzófok", it literally translates to "exaggerative degree."
I'm wondering because I often hear and read phrases where the much more is used before the comparative, e.g.

much more stronger

but this is grammatically incorrect. Still, whenever I hear or read something like this, I can't help but think of our "túlzófók" and how people who use a phrase like this may have a similar intention, they may want to exaggerate. I don't know however if that's the case or if it's just something some people do as a habit and without any particular reason.
So, does English have an actual, non-arbitrary way of exaggerating adjectives in a way which is comparable to the superlative, or if it doesn't, has it ever had anything similar?

A:

I found this pretty self-explanatory example of a "whimsical" usage that would be comprehensible to most native speakers even if they'd never come across it before...

“Wanna go get some ice cream? I'm buying!” asks Jazmun.
  “Sure.”
   “You know what?” asks Jazmun.
  “What?”
  “You are my best...no, my bestest friend.”
  “You are mine, too, little sis.”

...where even though everyone knows bestest isn't really a "valid" English word, it's perfectly acceptable in an informal context to use it to mean better than best.

I'll also just flag up these several hundred written instances of more betterer - though as pointed out here, that's more "dialectal" than "whimsically emphatic".
But neither of my examples (or any others, so far as I know) are valid in "standard, formal" English. To be strictly correct, Jazum would have needed to use a separate intensifier, such as very best friend.

A:

What I've found, not in English but in Hungarian, is that English normally expresses this idea by using a combination of an adverb or phrase with the superlative, e.g.:

the very best
  by far the best
  the best of all
the best (strong emphasis on the "the")

English doesn't have an "exaggerative degree" per se but it can express the idea.


Q:

C++11 Command Line Address Book

A friend is doing a CS course that has a command line address book as
a term assignment. Although I am a programmer in industry, I don't do
a lot of C++, so I ended up doing this as a learning exercise for C++.
     The address book is supposed to read a CSV file named addressBook.csv and parse contacts in the specified order
(first,middle,last,phone,address) and enable sorting, searching, and
writing to disk.
     There are "known unknowns" and "unknown unknowns". First of all, I want to hear about style issues that I don't even know enough to ask
about. But I did have some specific questions that came up.

line 100: I have to friend ContactListManager so it can dig at the underlying vector in order to find max column widths. It seems dirty.
I should be able to expose a contacts iterator without letting
ContactListManager know that it's really just a std::vector. How would
you expose that? Would you bother to hide the fact that ContactList is a glorified
std::vector<Contact> in real code, or are these classes so close
together that you wouldn't bother?
158-162: Any better way to express going through all of these named members? It's an awful lot of code duplication.
size_t. My understanding is that size_t is just a typedef that can hold any index to an array without overflow. Does this apply to
std::vector as well?
Specifically I am getting compiler warnings
losing integer precision when I pass size_t to setw. What would you do
about that? Is there a way to get rid of them by maxing them. What I
really want to is to setw(min(my_size_t, 80)). Maybe I can do
(unsigned int)min(my_size_t, (size_t)80). Is there a better way to
cast to express the concept?
446: Everything is done in memory with an explicit commit step. The dirty flag prompts the user if they try to quit with unsaved changes.
But if they drop an EOF onto stdin, I don't know how to recover the
stream. in.ignore() + in.clear() don't recover the stream. I can't
find anything on the internet that works in my terminal to this. Is
this just really really hard to get around?
127: contacts.push_back(c). I fear that I'm making a copy of c and pushing that onto the vector, when in fact this local
variable is about to go out of scope. Because I need to check
parsefail before I push, I can't emplace_back. Can I std::move?

Code:
//
//  main.cpp
//  AddressBook
//
//  Created by Mason Kramer on 11/15/16.
//  Copyright © 2016 Mason. All rights reserved.
//

#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
#include <vector>
#include <iomanip> /* setw */
#include <algorithm>    /* random_shuffle */

const bool QUIET = false;
const bool VERBOSE = false;

/* always separate side effects like error logging so that you can handle them differently later */
void error(std::string msg) {
    if (!QUIET) {
        std::cerr << msg << std::endl;
    }
}
void vocalize(std::string msg) {
    if (VERBOSE) {
        std::cerr << msg << std::endl;
    }
}

/* trim classes cribbed from SO */
static inline std::string &ltrim(std::string &s) {
    s.erase(s.begin(), std::find_if(s.begin(), s.end(),
                                    std::not1(std::ptr_fun<int, int>(std::isspace))));
    return s;
}

// trim from end
static inline std::string &rtrim(std::string &s) {
    s.erase(std::find_if(s.rbegin(), s.rend(),
                         std::not1(std::ptr_fun<int, int>(std::isspace))).base(), s.end());
    return s;
}

// trim from both ends
static inline std::string &trim(std::string &s) {
    return ltrim(rtrim(s));
}

class Contact {
    char field_separator = ',';
    void get_optional_field(std::istream& in, std::string& field, const std::string& fieldid) {
        std::getline(in, field, field_separator);
        if (in.fail()) {
            parse_fail = true;
        }
        field = trim(field);
    }
    void get_field(std::istream& in, std::string& field, const std::string& fieldid) {
        get_optional_field(in, field, fieldid);
        if (field == "") {
            parse_fail = true;
            vocalize("Field " + fieldid + " was empty");
        }
    }

    public:
    bool parse_fail = false;
    Contact(std::string first, std::string middle, std::string last, std::string phone, std::string address):
        first_name{first},
        middle_name{middle},
        last_name{last},
        phone_number{phone},
        address{address} {}

    Contact(std::string line) { /* parse a single line for a contact, set failure if parse failed */
        std::stringstream ss {line};
        get_field(ss, first_name, "first name (1)");
        get_optional_field(ss, middle_name, "middle name (2)");
        get_field(ss, last_name, "last name (3)");
        get_field(ss, phone_number, "phone number (4)");
        get_field(ss, address, "address (5)");
    };
    std::string  first_name;
    std::string  middle_name;
    std::string  last_name;
    std::string  phone_number;
    std::string  address;

    std::string serialize() const {
        std::stringstream ss;
        ss << first_name << field_separator << middle_name << field_separator << last_name << field_separator << phone_number << field_separator << address;
        return ss.str();
    }
};

/* all the things you can do to a list of contacts */
class ContactList {
    friend class ContactListManager;
    std::vector<Contact> contacts;

    std::string normalize(std::string str)
    {
        // convert the string to upper case
        for (std::string::size_type i = 0; i < str.length(); ++i)
        {
            str[i] =  std::tolower(str[i]);
        }

        return trim(str);
    }
public:
    ContactList(): contacts{std::vector<Contact> {}} {}
    ContactList(std::ifstream& in) {
        std::string line;
        int line_number = 1;

        if (in.good()) {
            while (getline(in, line)) {
                Contact c {line};
                /* We don't have to completely fail if one line is weird */
                if (c.parse_fail) {
                    error("Failed to parse a contact on line number " + std::to_string(line_number));
                }
                else {
                    contacts.push_back(c);
                }
                ++line_number;
            }
        }
    }
    size_t count() {
        return contacts.size();
    }
    void shuffle() {
        std::random_shuffle(contacts.begin(), contacts.end());
    }

    void remove_record(unsigned long idx) {
        contacts.erase(contacts.begin() + idx);
    }

    void add_record(Contact c) {
        contacts.push_back(c);
    }

    void sort_last_name() {
        std::sort(contacts.begin(), contacts.end(), [](Contact &a, Contact &b) {
            return a.last_name < b.last_name;
        });
    }
    std::vector<size_t> search(std::string t) {
        std::vector<size_t> matches;
        std::string term { normalize(t) };
        for (size_t i = 0; i < contacts.size(); i++) {
            Contact &c = contacts[i];
            if (normalize(c.last_name).find(term) != std::string::npos) { matches.push_back(i); continue; }
            if (normalize(c.first_name).find(term) != std::string::npos) { matches.push_back(i); continue; }
            if (normalize(c.middle_name).find(term) != std::string::npos) { matches.push_back(i); continue; }
            if (normalize(c.phone_number).find(term) != std::string::npos) { matches.push_back(i); continue; }
            if (normalize(c.address).find(term) != std::string::npos) { matches.push_back(i); continue; }
        }
        return matches;
    }

};

/*
Something that pairs a ContactList with a file that acts as a persistent database of that contact list,
 and manages reads and writes to the backing file.
 */

class ContactListManager {
    bool dirty = false;
    ContactList list {};
    const char* databaseFile;
public:
    bool parsefailure = false;
    size_t count() {
        return list.count();
    }
    ContactListManager(const char* databaseFile): databaseFile{databaseFile} {
        std::ifstream in;
        in.open(databaseFile);

        if (in.good()) {
            list = ContactList{in};
        }
        else {
            parsefailure = true;
            if (in.eof()) {
                error("Database file was empty");
            }
            else {
                error("Unable to open database file for parsing");
            }
        }

    }

    bool safe_commit() {
        if (dirty) {
            std::string tmpnam { "buffer.db" };
            std::ofstream in;
            in.open(tmpnam.c_str());
            in << *this;
            in.close();

            /* Write the new database to a temp file. Then try to parse that file back into a ContactList.
             If that succeeds then we have a valid database file, so replace the current database file with the new one */
            ContactListManager test {tmpnam.c_str()};
            if (!test.parsefailure && test.count() == count()) {
                std::remove(databaseFile);
                std::rename(tmpnam.c_str(), databaseFile);
                dirty = false;
                return true;
            }
            else {
                error("Commit would create an unparseable database, aborting.");
                return false;
            }
        }
        return true;
    }

    void sort_last_name() {
        dirty = true;
        list.sort_last_name();
    }
    void shuffle() {
        list.shuffle();
    }

    void remove_record(unsigned long idx) {
        list.remove_record(idx);
    }

    void add_record(Contact c) {
        list.add_record(c);
    }

    friend std::ostream& operator<< (std::ostream& stream, const ContactListManager& csm) {
        for (auto &c : csm.list.contacts) {
            stream << c.serialize() << std::endl;
        }
        return stream;
    }

    size_t max_width( std::string(*field)(const Contact&) ) const {
        size_t max = 0;
        for (auto& c : list.contacts) {
            auto str = field(c);
            max = std::max(str.length(), max);
        }
        return max;
    }

    size_t max_width_idx(std::vector<size_t> idxes, std::string(*field)(const Contact&) ) const {
        size_t max = 0;
        for (auto& idx : idxes) {
            auto str = field(list.contacts[idx]);
            max = std::max(str.length(), max);
        }
        return max;
    }

    /* Print these specific indexes */
    void pretty_print(std::ostream &stream, std::vector<size_t> idxs) const {
        if (idxs.size() == 0) {
            return;
        }

        /* find the max length of each field so I can pretty each column with a fixed width */
        size_t last_w = max_width_idx(idxs, [](const Contact &c) { return c.last_name; });
        size_t first_w = max_width_idx(idxs, [](const Contact &c) { return c.first_name; });
        size_t middle_w = max_width_idx(idxs, [](const Contact &c) { return c.middle_name; });
        size_t phone_w = max_width_idx(idxs, [](const Contact &c) { return c.phone_number; });
        size_t address_w = max_width_idx(idxs, [](const Contact &c) { return c.address; });

        last_w = std::max(last_w, (size_t)5) + 2;
        first_w = std::max(first_w, (size_t)5) + 2;
        middle_w = std::max(middle_w, (size_t)6);
        address_w = std::max(address_w, (size_t)7);
        phone_w = std::max(phone_w, (size_t)5);

        std::string spacer((int)last_w + first_w + middle_w + address_w + phone_w + 15, '-');

        stream << spacer << std::endl;

        stream << std::left <<
        std::setw(7)             << "Index"   << std::setw(0) << ""   <<
        std::setw(last_w)        << "Last"    << std::setw(0) << ""   <<
        std::setw(first_w)       << "First"   << std::setw(0) << ""    <<
        std::setw(middle_w)      << "Middle"  << std::setw(0) << " | "  <<
        std::setw(address_w)     << "Address" << std::setw(0) << " | "  <<
        std::setw(phone_w)       << "Phone"   << std::setw(0) << " |"  << std::endl;

        stream << spacer << std::endl;

        for (auto& idx : idxs) {
            auto c = list.contacts[idx];
            stream <<
            std::setw(7)         << idx + 1          << std::setw(0) << ""   <<
            std::setw(last_w)    << c.last_name  + ", "  << std::setw(0)   <<
            std::setw(first_w)   << c.first_name   << std::setw(0) << ""    <<
            std::setw(middle_w)  << c.middle_name  << std::setw(0) << " | "  <<
            std::setw(address_w) << c.address      << std::setw(0) << " | "  <<
            std::setw(phone_w)   << c.phone_number << std::setw(0) << " |"  << std::endl;
        }
    }
    /* Print some or all contacts. If begin is given, start from the beginth record. If n is greater than 0, print up to n records, otherwise print to the end */
    void pretty_print(std::ostream &stream, size_t begin = 0, size_t n = 0) const {
        /* find the max length of each field so I can pretty each column with a fixed width */
        size_t last_w = max_width([](const Contact &c) { return c.last_name; });
        size_t first_w = max_width([](const Contact &c) { return c.first_name; });
        size_t middle_w = max_width([](const Contact &c) { return c.middle_name; });
        size_t phone_w = max_width([](const Contact &c) { return c.phone_number; });
        size_t address_w = max_width([](const Contact &c) { return c.address; });

        last_w = std::max(last_w, (size_t)5) + 2;
        first_w = std::max(first_w, (size_t)5) + 2;
        middle_w = std::max(middle_w, (size_t)6);
        address_w = std::max(address_w, (size_t)7);
        phone_w = std::max(phone_w, (size_t)5);

        std::string spacer((int)last_w + first_w + middle_w + address_w + phone_w + 15, '-');

        stream << spacer << std::endl;

        stream << std::left <<
        std::setw(7)             << "Index"   << std::setw(0) << ""   <<
        std::setw(last_w)        << "Last"    << std::setw(0) << ""   <<
        std::setw(first_w)       << "First"   << std::setw(0) << ""    <<
        std::setw(middle_w)      << "Middle"  << std::setw(0) << " | "  <<
        std::setw(address_w)     << "Address" << std::setw(0) << " | "  <<
        std::setw(phone_w)       << "Phone"   << std::setw(0) << " |"  << std::endl;

        stream << spacer << std::endl;

        size_t end = list.contacts.size();
        if (n > 0) {
            end = std::min(end, begin + n);
        }

        for (size_t idx = begin; idx < end; idx++) {
            auto c = list.contacts[idx];
            stream <<
            std::setw(7)         << idx + 1          << std::setw(0) << ""   <<
            std::setw(last_w)    << c.last_name  + ", "  << std::setw(0)   <<
            std::setw(first_w)   << c.first_name   << std::setw(0) << ""    <<
            std::setw(middle_w)  << c.middle_name  << std::setw(0) << " | "  <<
            std::setw(address_w) << c.address      << std::setw(0) << " | "  <<
            std::setw(phone_w)   << c.phone_number << std::setw(0) << " |"  << std::endl;
        }
    }
    Contact get_contact_interactive(std::istream& in, std::ostream& out, std::ostream& err) {
        std::string  buff, first, middle, last, phone, address;
        out << "First: ";
        getline(in, buff);
        first = trim(buff);
        out << "Middle: ";
        getline(in, buff);
        middle = trim(buff);
        out << "Last: ";
        getline(in, buff);
        last = trim(buff);
        out << "Address: ";
        getline(in, buff);
        address = trim(buff);
        out << "Phone: ";
        getline(in, buff);
        phone = trim(buff);

        return Contact {first, middle, last, phone, address};
    }

    void usage(std::ostream &out) {
        out << std::endl << "[p]rint [start idx] [num records], [s]ort, [q]uit, [h]elp, [x] shuffle, [f]ind <search string>" << std::endl;
        out << "[a]dd, [d]elete <n>th record, [c]ommit to file" << std::endl;
    }
    void interact(std::istream& in, std::ostream& out, std::ostream& err) {
        std::string command_buff;
        std::string command;
        usage(out);

        while (getline(in, command_buff))
        {
            std::string tok;
            std::stringstream ss{command_buff};

            ss >> tok;
            command = tolower(tok[0]);

            if (command == "q") {
                break;
            }
            if (command == "p") {
                size_t begin;
                size_t n;
                if (ss >> begin) {
                    if (ss >> n) {
                        pretty_print(out, begin-1, n);
                    }
                    else {
                        pretty_print(out, begin-1, 1);
                    }
                }
                else {
                    pretty_print(out);
                }
            }
            if (command == "x") {
                shuffle();
                out << "Shuffled." << std::endl;
            }
            if (command == "s") {
                sort_last_name();
                out << "Sorted." << std::endl;
            }
            if (command == "h") {
                usage(out);
            }
            if (command == "f") {
                std::string rest;
                ss >> rest;
                auto matches = list.search(rest);
                pretty_print(out, matches);
            }
            if (command == "c") {
                safe_commit();
                out << "Committed." << std::endl;
            }
            if (command == "a") {
                add_record(get_contact_interactive(in, out, err));
                out << "Added." << std::endl;
            }
            if (command == "d") {
                int n;
                ss >> n;
                remove_record(n - 1);
                out << "Removed " << n << "." << std::endl;
            }
        }

        if (dirty) {
            out << "You have uncommitted changes, would you like to save them? y/N" << std::endl;

            getline(in, command_buff); /* linux convention is that a simple "enter" at this point is N */
            command = tolower(trim(command_buff)[0]);
            if (command == "y") {
                safe_commit();
                out << "Commited. Goodbye." << std::endl;
            }
            else {
                out << "Will not commit. Goodbye." << std::endl;
            }
        }
    }
};

int main(int argc, const char * argv[]) {
    std::string inFileName {"addressBook.csv"};
    if (argc >= 2) {
        inFileName = std::string{argv[1]};
    }
    std::cout << "Welcome to AddressBook. Managing database file " << inFileName << std::endl;
    ContactListManager csm {inFileName.c_str()};
    if (!csm.parsefailure) {
        std::cout << "I parsed " << csm.count() << " records." << std::endl;
        csm.interact(std::cin, std::cout, std::cerr);
    }
    else {
        std::ofstream fh;
        fh.open(inFileName);
        if (fh.good()) {
            std::cout << "Parsing failed, but you can still interactively add contacts and commit " << std::endl;
            csm.interact(std::cin, std::cout, std::cerr);
        }
        else {
            std::cout << "Parsing failed and I can't write to the designated file location. Exiting." << std::endl;
        }
        fh.close();
    }

    return 0;
}

A:

Here are some things that may help you improve your code.
Fix the bugs
The code currently contains this function:
friend std::ostream& operator<< (std::ostream& stream, const ContactListManager& csm) {
    for (auto &c : csm.list.contacts) {
        stream << c.serialize() << std::endl;
    }
    return stream;
}

However, this won't compile on my machine because contacts is a private member of the ContactList class.  This function is a friend of ContactListManager and ContactListManager is a friend of ContactList but in C++ as in life, friendship is not transitive.  That is, a friend of your friend isn't necessarily your friend too.  This can be addressed (if you'll pardon the pun) by simply creating a similar ostream operator<< function for the ContactList class and using that.
Another bug is that because only sorting by last name sets the dirty flag, if one adds or deletes several records, they won't be committed to the file even if explicitly instructed by the user to commit.
Yet another bug is that remove_record is not range checked, so if we attempt to delete record 7 from an empty database, the program segfaults and crashes.
Use the standard form of main()
The current main declaration looks like this:
int main(int argc, const char * argv[]) {

However, the use of const there may bring portability problems because the only explicitly supported signatures for main are these:
int main()
int main(int argc, char *argv[])
int main(int argc, char **argv)

It might work with your particular compiler, but it's not guaranteed on all compilers because it's not standard.  See this question and the related one for details and history.
Don't use std::endl if you don't really need it
The difference betweeen std::endl and '\n' is that '\n' just emits a newline character, while std::endl actually flushes the stream.  This can be time-consuming in a program with a lot of I/O and is rarely actually needed.  It's best to only use std::endl when you have some good reason to flush the stream and it's not very often needed for simple programs such as this one.  Avoiding the habit of using std::endl when '\n' will do will pay dividends in the future as you write more complex programs with more I/O and where performance needs to be maximized.
Reconsider your class design
The ContactListManager has a number of functions that simply "pass through" to the ContactList class, such as this one:
size_t count() {
    return list.count();
}

This strongly suggests that it would probably be better to use inheritance instead of composition here.  In other words, derive the ContactListManager from the ContactList and only override functions which need special behavior.  This will also elimate the need for any friend declaration.
Don't Repeat Yourself (DRY)
The two pretty_print routines contain a lot of duplicated code, but don't need to.  Essentially, there are two distinct pieces: one to find the max width of fields in the collection of records and the other that uses those widths to print the collection of records.  I'd suggest that one could use a pair of functions that do those tasks given a particular collection.  One could either specify the collection by indices as the code currently does, or perhaps more usefully, by predicate.  That is, you could use something like std::for_each
Also, within the print routine itself, the code for printing the header row is almost identical to the code that prints the data records.  I suspect that one could easily factor out a function that would serve both needs.  I'd probably create a static dummy Contact with all of the header names except "Index" and then define a Contact member function that pretty-prints a record, given a list of field widths.
Where practical, eliminate unused parameters
I understand the desire for a consistent interface, which is good, but when the warning are cranked up on the compiler (as they should normally be), it will tell you that the fieldid parameter is not used in get_optional_field(), and err is not used in get_contact_interactive().  Depending on the particulars of the compiler, one way to address the warning and also to make it clear to readers of the code that you are intentionally not using that parameter, might be to simply omit the name in the definition and implementation.  The other obvious alternative is to omit that parameter.
Be careful with signed vs. unsigned
You ask about a compiler warning about possible loss of precision when passing a size_t to setw().  Unfortunately, there's an inherent problem because std::size_t is defined to be an unsigned number, while setw() is defined to take a signed int as a parameter.  For any reasonable field width in this application, there is not going to be any loss of precision because any reasonable number can be converted from one form to the other without loss.  If you wish to support really, really wide fields, you could add code to assert if the size_t value exceeds std::numeric_limits<int>::max().
Understand move semantics
Since C++11, we have "move semantics" to think about.  In the contacts.push_back(c); line you were concerned about, you can explicitly cause a move by using contacts.push_back(std::move(c)); instead or equivalently, contacts.emplace_back(c);
Use standard names
The Contact class has a serialize() function that turns a record into a string.  However, there is already a std::to_string() template that one could use instead, or define a cast operator.  Doing either of these things helps others better understand your code and also enables your classes to be used more generally.  Alternatively, since the only use for this function is printing to a stream, you could define the appropriate ostream &operator<< for the Contact class.
Rethink your search algorithm
The search algorithm is very inefficient.  It searches the entire list five times!  What would make more sense, I believe, is to create a helper function within the Contact class that returns true if the passed string matches any of the fields.  That way, only a single pass through the list would be required.
Omit return 0
When a C or C++ program reaches the end of main the compiler will automatically generate code to return 0, so there is no need to put return 0; explicitly at the end of main.
Note: when I make this suggestion, it's almost invariably followed by one of two kinds of comments:  "I didn't know that." or "That's bad advice!"  My rationale is that it's safe and useful to rely on compiler behavior explicitly supported by the standard.  For C, since C99; see ISO/IEC 9899:1999 section 5.1.2.2.3:

[...] a return from the initial call to the main function is equivalent to calling the exit function with the value returned by the main function as its argument; reaching the } that terminates the main function returns a value of 0.

For C++, since the first standard in 1998; see ISO/IEC 14882:1998 section 3.6.1:

If control reaches the end of main without encountering a return statement, the effect is that of executing return 0;

All versions of both standards since then (C99 and C++98) have maintained the same idea.  We rely on automatically generated member functions in C++, and few people write explicit return; statements at the end of a void function.  Reasons against omitting seem to boil down to "it looks weird".  If, like me, you're curious about the rationale for the change to the C standard read this question.  Also note that in the early 1990s this was considered "sloppy practice" because it was undefined behavior (although widely supported) at the time.
So I advocate omitting it; others disagree (often vehemently!)  In any case, if you encounter code that omits it, you'll know that it's explicitly supported by the standard and you'll know what it means.


Q:

Questions about the calculus AP

I'm not sure if this is the proper place to ask this question, but I figured I'll try anyway.
If I have the option of taking a Calculus AP class, and am thinking of pursuing a career in either genetic counseling, occupational therapy, or special education, is it worth it?
Would such a course help me out?
(An AP test is an exam that tests a person for college level knowledge of a particular subject, and if a person passes the exam, they will be given college credit as if they had actually taken the courses. It is often taken after a year of a high-school class in that subject.)

A:

I'm teaching AP Calculus for the first time this year, and my students are all asking the same question as you.  Here's what I tell them.
If you're going to college next year, and if you will be required to take at least a semester of calculus there (which is a pretty safe bet for nearly everyone but do your own research), AP Calc will do one of two things for you:

You'll take the AP exam and get a good enough grade to place out of a semester of calculus.  Congratulations, you're already one class closer to your degree!
You won't get a good enough grade in the AP exam or decide not to take it altogether.  You'll take Calculus in your first semester of college.  However, you'll retain enough from your AP class that the course will be a breeze for you.  Congratulations, you're now the best friend of all of your classmates and have one less thing to stress you out in your transition to college life!

(The second may not seem like a big prize.  Having been through college, honestly I think it's the better deal.)
The downsides and how to cope with them?

It's not really an easy course, especially when not taught by a great teacher.  As people have said in the comments, lean on the Khan Academy and an AP study guide to help explain things when you didn't get either the skills or the motivation behind them from your class.  From a quick glance, it seems like you know how to ask good questions on Math SE, so that's there for you as well.
Some students want to protect their GPA in their final year so as not to look bad when applying to college.  Honestly, colleges appreciate it when you take risks, and they'll see that you're taking an AP class.  And maybe your school has the sense (as mine does) to give a GPA boost for taking AP classes because they know that the reward of being challenged in a useful class is better than sleepwalking through an easy A elective.


Q:

Facebook App Instance Settings

I have an app that needs to have unique settings to each instance of a user adding it to their page (it is made to be added as a tab).
I have not been able to find any documentation to do this -- does anyone know how? Or does anyone have an example to follow or a place to learn?

SOLUTION
I made a section on the Tab for the app user's page that only shows to admin's of Page. It links to a page in my app sending the page_id to my page. This allows me to now store information (and settings) in my database based off the page_id.
I found that Facebook has a section to go to an App's settings page (which you can set up in your application settings via the Developer App) which also sends the page_id -- but it doesn't send it in an encrypted sense, so I encrypted the page_id with my settings option.
If anyone needs further explanation, feel free to message me I would be happy to help.

A:

I'm pretty sure what you are looking for is the "page" instance. Every page has a Facebook ID just like every user does. For the most part, you can use a page ID anywhere you would a user ID. What you want to do is capture the ID of the page, not the ID of the user adding it to the page (the admin). Scroll almost all the way to the bottom if this URL to see how to grab the page ID:
http://developers.facebook.com/docs/guides/canvas/
Basically, an additional parameter is included call "page" that will contain the page ID. Use that to interact with the page and store any session information.


Q:

Reactjs ERR_INVALID_ARG_TYPE

there!
I bought some template from themeforest and everything works fine with previews version, but with the new one I'm having error like
> TypeError [ERR_INVALID_ARG_TYPE]: The "path" argument must be of type
> string. Received type undefined
>         at validateString (internal/validators.js:125:11)
>         at Object.join (path.js:427:7)
>         at noopServiceWorkerMiddleware (C:\Users\Rade\Desktop\gComet-master\node_modules\react-dev-utils\noopServiceWorkerMiddleware.js:14:26)
>         at Layer.handle [as handle_request] (C:\Users\Rade\Desktop\gComet-master\node_modules\express\lib\router\layer.js:95:5)
>         at trim_prefix (C:\Users\Rade\Desktop\gComet-master\node_modules\express\lib\router\index.js:317:13)
>         at C:\Users\Rade\Desktop\gComet-master\node_modules\express\lib\router\index.js:284:7
>         at Function.process_params (C:\Users\Rade\Desktop\gComet-master\node_modules\express\lib\router\index.js:335:12)
>         at next (C:\Users\Rade\Desktop\gComet-master\node_modules\express\lib\router\index.js:275:10)
>         at launchEditorMiddleware (C:\Users\Rade\Desktop\gComet-master\node_modules\react-dev-utils\errorOverlayMiddleware.js:20:7)
>         at Layer.handle [as handle_request] (C:\Users\Rade\Desktop\gComet-master\node_modules\express\lib\router\layer.js:95:5)
>         at trim_prefix (C:\Users\Rade\Desktop\gComet-master\node_modules\express\lib\router\index.js:317:13)
>         at C:\Users\Rade\Desktop\gComet-master\node_modules\express\lib\router\index.js:284:7
>         at Function.process_params (C:\Users\Rade\Desktop\gComet-master\node_modules\express\lib\router\index.js:335:12)
>         at next (C:\Users\Rade\Desktop\gComet-master\node_modules\express\lib\router\index.js:275:10)
>         at handleWebpackInternalMiddleware (C:\Users\Rade\Desktop\gComet-master\node_modules\react-dev-utils\evalSourceMapMiddleware.js:42:7)
>         at Layer.handle [as handle_request] (C:\Users\Rade\Desktop\gComet-master\node_modules\express\lib\router\layer.js:95:5)

I believe that template is not supposed to have this error, but still I have it. What could be the problem?

A:

You can check this link https://github.com/ionic-team/ionic/issues/20503
To fix this issue simply upgrade to "react-scripts": "^3.4.0"

Overwrite the existing "react-scripts": "^3.x.x" with"react-scripts": "^3.4.0" in your package.json
Delete your node modules
and npm install or yarn install

i hope it will fix it.


Q:

Groovy String concatenation problems with Jenkins

I have a very simple Groovy script:
String test = "";
[0, 1, 2, 3, 4].each {test += it.toString()}
return test

When I enter and execute the script in the Jenkins script console, I get the expected result:
Result: 01234

However, when I execute the same script with curl, I get something else:
curl -X POST -d "script=$(cat test.groovy)" http://my/domain/jenkins/scriptText
Result: 4

Does anyone have an idea where such a difference could come from?

A:

Not sure what's going wrong, but changing into explicit strings worked for me:
curl --show-error -d 'script=test="";[0,1,2,3,4].each{test = "${test}${it}"}; return test' http://my/domain/jenkins/scriptText
Result: 01234

Breaking your example down, and adding appropriate debug gave:
$ curl --show-error -d 'script=test="";[0,1,2,3,4].each{test += it.toString(); println test}; return test' http://my/domain/jenkins/scriptText
0
1
2
3
4
Result: 4

so the test wasn't being added to as a string. using GStrings directly sorted it out.
An alternative is to use inject, though it's still using gstrings:
$ curl --show-error -d 'script=test=[0,1,2,3,4].inject("") {acc, val -> "${acc}${val}"}; return test' http://my/domain/jenkins/scriptText
Result: 01234


Q:

Using vtkCamera explicit projection transform matrix and prop3D visibility

Essentially, I want to employ VTK-engine to render a scene with both precalculated projection and model view transform matrices, together called as "composite projection transform matrix".
For such purpose, we have vtkCamera.SetUseExplicitProjectionTransformMatrix but I cannot make my view props or actors visible using that. I guess it is related to how the vtkRenderer pre-selects visible actor by using their bounding boxes, but in this case near and far clipping ranges are baked into a single matrix, so the renderer cannot even guess that. In the below sample code I also compensate camera's initial modelviewtransform matrix (which is slightly translated from identity matrix), so that the camera would calculate its composite projection the way I want.
import vtk

class Renderer:
    def __init__( self ):
        self.layer0 = vtk.vtkRenderer()
        self.layer0.SetLayer(0)
        self.renWin = vtk.vtkRenderWindow()
        self.renWin.AddRenderer(self.layer0)
        self.iren = vtk.vtkRenderWindowInteractor()
        self.iren.SetRenderWindow(self.renWin)
        self.iren.Initialize()
    def Render( self ):
        self.iren.Render()
    def AddActor( self, actor ):
        self.layer0.AddActor( actor )
    def Start(self):
        self.iren.Start()

def CreateActor( polydata ):
    mapper = vtk.vtkPolyDataMapper()
    mapper.SetInputData( polydata )
    mapper.SetScalarVisibility( 0 )
    actor = vtk.vtkActor()
    actor.SetMapper( mapper )
    return actor

def OBJReader( name ):
    reader = vtk.vtkOBJReader()
    reader.SetFileName( name )
    reader.Update()
    return reader.GetOutput()

# Suzanne by Blender.org
suzanne = OBJReader( 'D:/data/suzanne.obj' )

size = (900,600)

# Create a VTK renderwindow
r = Renderer()
r.renWin.SetSize(size[0],size[1])
r.AddActor( CreateActor(suzanne) )
# Use vtkRenderWindowInteractor to select the camera view
# Then exit the window by pressing 'x'
r.Start()

# Store the current composite projection transform matrix
# i.e., the product of the projection and the modelview matrix
# into X
c = r.layer0.GetActiveCamera()
n, f = c.GetClippingRange()
aspect = size[0]/size[1]
X = c.GetCompositeProjectionTransformMatrix( aspect, n, f )

# Create another VTK renderwindow
r2 = Renderer()
r2.renWin.SetSize(size[0],size[1])
r2.AddActor( CreateActor(suzanne) )

# but this time, construct the camera by using a precomputed
# projection matrix
c2 = vtk.vtkCamera()
if 1:
    # assert that the modelview matrix will be identity matrix
    M = vtk.vtkMatrix4x4()
    M.DeepCopy( c2.GetModelViewTransformMatrix() )
    print( M ) # its not!
    M.Invert() # so invert
    # and concatenate
    Y = vtk.vtkMatrix4x4()
    # Y*M = X*inv(M)*M = X
    vtk.vtkMatrix4x4.Multiply4x4( X, M, Y )

    c2.SetUseExplicitProjectionTransformMatrix(1)
    c2.SetExplicitProjectionTransformMatrix( Y )

    # these should be now the same (in case of explicit, aspect, n and f are ignored)
    print( c2.GetCompositeProjectionTransformMatrix( 1, 0, 0 ) )
    print( X )

else:
    #this works clearly
    c2.DeepCopy( c )

r2.layer0.SetActiveCamera( c2 )
r2.Render()
r2.Start()

A:

After testing, I came to conclusion that one is supposed to use vtkExternalOpenGLCamera

This class extends vtkOpenGLCamera by introducing API wherein the
  camera matrices can be set explicitly by the application.

The composite projection transform matrix X is not readily usable though, but it's clipping range must be changed s.t.
# copy X into numpy matrix for comfort
P = np.zeros( (4,4),dtype=np.double)
for y in range(4):
    for x in range(4):
        P[y][x]=X.GetElement(y,x)
# P maps valid z-values to [n,f] so change that by
# z <- 2.0 * ( z - n )/(f-n) -1.0
# to fit values into the default clipping range [-1,1]
A = np.eye(4,dtype=np.double)
A[2][3]=-n
B = np.eye(4, dtype=np.double)
B[2][2]=2.0/(f-n)
C = np.eye(4, dtype=np.double)
C[2][3]=-1.0
P = np.matmul(C,np.matmul(B,np.matmul(A,P)) )

# then use vtkExternalOpenGLCamera
c2 = vtk.vtkExternalOpenGLCamera()
c2.SetViewTransformMatrix( np.reshape( np.eye(4,dtype=np.double),[-1,1]) )
c2.SetProjectionTransformMatrix( np.reshape( np.transpose(P),[-1,1]) )
r2.layer0.SetActiveCamera( c2 )
r2.Render()

Worth noting, that the matrix P below also works with modelview matrix transform hack mentioned above:
c2 = vtk.vtkCamera()

# P is now back to vtk.vtkMatrix4x4 type

# assert that the modelview matrix will be identity matrix
Mx = vtk.vtkMatrix4x4()
Mx.DeepCopy( c2.GetModelViewTransformMatrix() )
print( Mx ) # its not!
Mx.Invert() # so invert
# Y*M = X*inv(M)*M = X
vtk.vtkMatrix4x4.Multiply4x4( P, Mx, P )

c2.SetUseExplicitProjectionTransformMatrix(1)
c2.SetExplicitProjectionTransformMatrix( P )

but the result is not pretty...
Although the default camera light model of VTK does not work with the baked composite transform, it does work if the projection and model view matrices are put separately into the vtkExternalOpenGLCamera.


Q:

How to address the person being recommended in a recommendation letter?

How should one "address" the person for whom I am writing a recommendation letter in the letter?
Scenario:

I have known John Doe for many years and am familiar with his work. We address each other on a first name basis. I've been asked to write a letter supporting John's application. When I write about him, should I write

Dr [or Mr, in case of undergraduates] Doe's works are well-written ...

or can I get away with

John's works are well-written ...

Personally I feel a bit strange writing Dr Doe for someone I know so well, but I wonder if it is better to err on the more formal side?

For what it is worth, the field is Mathematics. And for future reference, I do not want to limit the question to a particular level of application (for graduate school, fellowships, or for jobs); I suspect that shouldn't make a difference in the answer, but if it does, feel free to indicate.

A:

I have seen both used in recommendation letters, regardless of the strength of the recommendation letter itself. I would, myself, recommend Dr. John Doe / Dr. Doe for most professional relationships, except when it is clear that you have formed a close professional relationship (PhD student, or long-term collaborator or post-doc). In case you go for the surname, I would still use the full name at the first mention:

Dr. John Doe was a student of mine at the University of X, where I teach Y, …. He later joined my research group as a Masters, then PhD student. John is an extremely bright student, …

(Of course, that's merely an example and not a good letter wording, so do not look at the wording itself, only the use of names…)

A:

Since you specifically asked about math, let me say that in my experience (as a mathematician, reading recommendation letters written by other mathematicians), the pattern of

use the applicant's full name once.
use their first name (generally what you would call them in person) after that.

is close to universal amongst mathematicians in the US.  One does find exceptions, usually replacing the applicant's first name with their last name (so, writing "Doe's work has been..."), but they are actually quite rare.


Q:

Separating numbers to 2 arrays Java

I have a question about Java. I made this code to separate negative and positive numbers into 2 arrays and after that to print them. But all the time when I start that I have an error:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 6
at mypackages.MyClass.main(MyClass.java:26)

Here is the code I have written:
package mypackages;

public class MyClass {

public static void main(String[] args) {

   int[] array = {12, 23, -22, 0, 43, 545, -4, -55, 43, 12, 0, -999, -87};

   int counterNeg = 0;
   int counterPoz = 0;

    for (int i = 0; i < array.length; i++) {
        if (array[i] < 0){
            counterNeg++;
        } else if (array[i] > 0){
            counterPoz++;
        }
    }

    int[] arrayNeg = new int[counterNeg];
    int[] arrayPoz = new int[counterPoz];

    for (int j = 0; j < array.length; j++) {
        if (array[j] < 0){
            arrayNeg[j] = array[j];
        } else if (array[j] > 0){
            arrayPoz[j] = array[j];
        } else {
            continue;
        }
    }

A:

You are accessing the arrays arrayNeg and arrayPoz by using the index that goes up to array.length - 1 causing a ArrayIndexOutOfBounds because both arrays are smaller than the original one.
Solution: keep track of where to insert the numbers in to the two downstream arrays:
int[] arrayNeg = new int[counterNeg];
int[] arrayPoz = new int[counterPoz];
int arrayNegCounter = 0;
int arrayPozCounter = 0;

for (int j = 0; j < array.length; j++) {
    if (array[j] < 0){
        arrayNeg[arrayNegCounter] = array[j];
        arrayNegCounter++;
    } else if (array[j] > 0){
        arrayPoz[arrayPozCounter] = array[j];
        arrayPozCounter++;
    } else {
        continue;
    }
}


Q:

Asp.Net Signal R - Detect Changes in Database ? Asp.net Web Forms

So I have a List View inside an Update Panel
Update Panel
    List View
        Email 1
        Email 2
        Email 3
           ...

I'm trying to do an inbox similar to GMAIL in ASP.NET, the only I'm struggling with is how to detect DataBase Changes (ie when a new message is sent) and Push that message into the ListView to simulate that the user has received a new message (just like gmail does)
How do I use SignalR to detect database changes and push them into the List View using SignalR? Is it possible?

A:

If you are using Sql Server follow this link. http://techbrij.com/database-change-notifications-asp-net-signalr-sqldependency
It basically uses SqlDependency to subscribe changes in Sql Server.
If you aren't using Sql Server you have to do this manually. And for view side you can use KnockoutJS or anngular for easy list modification.
//Set up dependency
protected void Application_Start()
{
        //...
   SqlDependency.Start(ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString);
}

protected void Application_End()
{
    SqlDependency.Stop(ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString);
}

SqlDependency dependency = new SqlDependency(command);
dependency.OnChange += new OnChangeEventHandler(dependency_OnChange);


Q:

Error while parsing JSON in python

I am trying to parse a JSON variable json_text and trying to create a list of change_requests but running into below error?can anyone provide guidance on how to fix this?
import sys,os,json
from collections import OrderedDict
def main ():
    change_request_list=[]
    json_text=[OrderedDict([(u'branch', u'wlan-service.lnx.1.1-dev'), (u'change_request_list', [OrderedDict([(u'change_request', u'2028693'), (u'change_request_approval_status', OrderedDict([(u'comment', None), (u'status', None)]))])]), (u'component', u'platform_vendor_qcom-proprietary_ship_wlan_common-tools_wlan-service.lnx.1.1-dev'), (u'description', u'cnss_diag: Capture PKTLOG by default to sdcard'), (u'gerrit', u'1892910'), (u'gerrit_approval_status', OrderedDict([(u'comment', None), (u'status', None)])), (u'owner', u'c_rrajiv'), (u'project', u'platform/vendor/qcom-proprietary/ship/wlan/common-tools'), (u'url', u'https://review-android.quicinc.com/#/c/1892910')]), OrderedDict([(u'branch', u'wlan-service.lnx.1.1-dev'), (u'change_request_list', [OrderedDict([(u'change_request', u'2029177'), (u'change_request_approval_status', OrderedDict([(u'comment', None), (u'status', None)]))])]), (u'component', u'platform_vendor_qcom-proprietary_ship_wlan_common-tools_wlan-service.lnx.1.1-dev'), (u'description', u'pktlog: Close file decription before archiving and creating a new one'), (u'gerrit', u'1895098'), (u'gerrit_approval_status', OrderedDict([(u'comment', None), (u'status', None)])), (u'owner', u'c_rrajiv'), (u'project', u'platform/vendor/qcom-proprietary/ship/wlan/common-tools'), (u'url', u'https://review-android.quicinc.com/#/c/1895098')]), OrderedDict([(u'branch', u'wlan-service.lnx.1.1-dev'), (u'change_request_list', [OrderedDict([(u'change_request', u'2030712'), (u'change_request_approval_status', OrderedDict([(u'comment', None), (u'status', None)]))])]), (u'component', u'platform_vendor_qcom-proprietary_ship_wlan_common-tools_wlan-service.lnx.1.1-dev'), (u'description', u'cnss_diag: Fix copyright header'), (u'gerrit', u'1897531'), (u'gerrit_approval_status', OrderedDict([(u'comment', None), (u'status', None)])), (u'owner', u'c_rrajiv'), (u'project', u'platform/vendor/qcom-proprietary/ship/wlan/common-tools'), (u'url', u'https://review-android.quicinc.com/#/c/1897531')]), OrderedDict([(u'branch', u'wlan-service.lnx.1.1-dev'), (u'change_request_list', [OrderedDict([(u'change_request', u'2032453'), (u'change_request_approval_status', OrderedDict([(u'comment', None), (u'status', None)]))])]), (u'component', u'platform_vendor_qcom-proprietary_ship_wlan_common-tools_wlan-service.lnx.1.1-dev'), (u'description', u'cnss_diag: Printing newly backup packetlog file name.'), (u'gerrit', u'1905895'), (u'gerrit_approval_status', OrderedDict([(u'comment', None), (u'status', None)])), (u'owner', u'c_rrajiv'), (u'project', u'platform/vendor/qcom-proprietary/ship/wlan/common-tools'), (u'url', u'https://review-android.quicinc.com/#/c/1905895')]), OrderedDict([(u'branch', u'wlan-service.lnx.1.1-dev'), (u'change_request_list', [OrderedDict([(u'change_request', u'2033296'), (u'change_request_approval_status', OrderedDict([(u'comment', None), (u'status', None)]))])]), (u'component', u'platform_vendor_qcom-proprietary_ship_wlan_common-tools_wlan-service.lnx.1.1-dev'), (u'description', u'cnss_diag: Configuration for disabling pkt logging on sdcard'), (u'gerrit', u'1905931'), (u'gerrit_approval_status', OrderedDict([(u'comment', None), (u'status', None)])), (u'owner', u'c_rrajiv'), (u'project', u'platform/vendor/qcom-proprietary/ship/wlan/common-tools'), (u'url', u'https://review-android.quicinc.com/#/c/1905931')])]
    for cr in json_text:
        print cr
        change_request =  cr['change_request_list']['change_request']
        change_request_list.append(change_request)
    print change_request_list
if __name__ == '__main__':
    main()

Error:-
Traceback (most recent call last):
  File "json_parsing.py", line 12, in <module>
    main()
  File "json_parsing.py", line 8, in main
    change_request =  cr['change_request_list']['change_request']
TypeError: list indices must be integers, not str

A:

You are missing a [0] between the json key
for cr in json_text:
    print cr
    change_request =  cr['change_request_list'][0]['change_request']
    change_request_list.append(change_request)
print change_request_list


Q:

Ajax callback with 2 parameters (int, List)

Working with jquery.ajax for first time...
I have a class in C#:
public class myValues
{
    string Value1 { get; set; }
    string Value2 { get; set; }
}

Then, my method is as follows:
[WebMethod]
public static string MyMethod(List<myValues> levels)
{
         //loop levels here
}

Now, in client (javascript, jquery) I'm doing an ajax' callback (sending the items within a select):
var levels = [];
//get items from select
$("#Select1 option").each(function () {

            levels.push({
                    Value1: $(this).val(),
                    Value2: $(this).text()
            });

        });

        //with json2.js :
        var jsonText = JSON.stringify({ levels: levels });
        $.ajax({
             type: "POST",
             url: "myPage.aspx/MyMethod",
             data: jsonText,
             contentType: "application/json; charset=utf-8",
             dataType: "json",
             success: function () { alert("it worked"); },
             failure: function () { alert("Uh oh"); }
        });

Everything works perfectly fine here...
But now, I want to change my webmethod to receive a second parameter:
[WebMethod]
public static string MyMethod(List<myValues> levels, int id)
{
         //loop levels here
}

I don't know how to call the method from the client, sending 2 parameters..?

A:

You need to json stringify the id also, for example:
var jsonText = JSON.stringify({ levels: levels, id : 1});


Q:

My iOS Views are off half a pixel?

My graphics are looking blurry unless I add or subtract a half pixel to the Y coordinate.
I know this is a symptom that usually happens when the coordinates are set to sub-pixel values. Which leads me to believe one of my views must be off or something.
But I inspected the window, view controller and subviews, and I don't see any origins or centers with sub-pixel values.
I am stumped, any ideas?

A:

See if somewhere you are using the center property of a view. If you assign that to other subviews, depending on their sizes they may position themselves in half pixel values.
Also, if you are using code to generate the UI I would suggest using https://github.com/domesticcatsoftware/DCIntrospect. This tools allows you in the simulator to look at all the geometry of visible widgets. Half pixel views are highlighted in red vs blue for integer coordinates. It helps a lot.


Q:

OpenCV histogram equalization process using cv::equalizeHist():Need help understanding final step for this

I've a question regarding Histogram Equalization process using cv::equalizeHist()(a function of OpenCV image processing library). In this website:
Histogram equalization process using opencv explained
the histogram equalization process is explained which is:

calculate the histogram H for src.
normalize the histogram so that the sum of histogram bins is 255.
compute the integral of the histogram.
[equation is given in the above website]
transform the image using H' as a look-up table.
[equation is given in the above website]

I'm having problem understanding step number 4. What did the author mean by this line?
Can anyone kindly help me understand how the author got the final equalization result from step number 4?
What method he/she used for step number4? How did he/she transform the image looking at H'?

A:

After some googling I found answer to your question.

Read this wikipedia article.
From source code cvhistogram.cpp (you can actually use the code to implement this function in your project or library) I found in function cvEqualizeHist this line:
CV_CALL( cvLUT( src, dst, lut ));
And finally explanation of function you're looking for in OpenCV: LUT.


Q:

Wait and notify in Consumer and Producer Threads

Just started learning multi-threading. I have 5 producers and 2 consumers in multiple threads. Basically this program adds 100 items into the queue. The producer will stop adding when the queue size is 100. I would like the consumer to notify the producer when the consumer removes all the items from the queue so that the producer can start adding again. Currently the producer will wait but never gets notified by the consumer.
Producer:
public class Producer implements Runnable {

private BlockingQueue sharedQueue;
private final int queueSize;
private Object lock = new Object();

  public Producer(BlockingQueue sharedQueue, int queueSize){
    this.sharedQueue = sharedQueue;
    this.queueSize = queueSize;
  }

  public void run() {
    while(true) {
        if(sharedQueue.size()== queueSize){

                try {
                    synchronized (lock) {
                    sharedQueue.wait();
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
         }

        try {
            sharedQueue.put("Producer: " + sharedQueue.size());
            Thread.sleep(500);
            System.out.println("Producer:  Queue Size " + sharedQueue.size() + " Current Thread " + Thread.currentThread());

            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

consumer:
public class Consumer implements Runnable{

private BlockingQueue sharedQueue;
private final int queueSize;
private final int queueEmpty=0;
private Object lock = new Object();

   public Consumer(BlockingQueue sharedQueue, int queueSize){
    this.sharedQueue = sharedQueue;
    this.queueSize = queueSize;
   }
//Notify awaiting thread if the sharedQueue is empty
   public void run() {
    while (true) {
        if(sharedQueue.size()==queueEmpty){
            synchronized (lock) {
            this.notifyAll();
            }
        }
            try {

                    sharedQueue.take();
                    Thread.sleep(800);
                    System.out.println("Consumer: Queue Size " + sharedQueue.size() + " Current Thread" + Thread.currentThread());

            }catch(InterruptedException e){
                e.printStackTrace();
            }
    }

  }
}

Main class
  public class App{

//A simple program to illustrate how producer and consumer pattern works with blocking queue using executor service
public static void main( String[] args )
{
    final BlockingQueue<String> sharedQueue = new ArrayBlockingQueue<String> (100);
    final int queueSize =100;
    final int producerNum = 5;
    final int consumerNum = 2;

    final ExecutorService executorProducer = Executors.newFixedThreadPool(producerNum);
    final ExecutorService executorConsumer = Executors.newFixedThreadPool(consumerNum);

    for(int i=0;i<producerNum;i++){
        Producer producer = new Producer(sharedQueue,queueSize);
        executorProducer.execute(producer);
    }

    for(int j=0;j<consumerNum;j++){
        Consumer consumer = new Consumer(sharedQueue,queueSize);
        executorConsumer.execute(consumer);
    }

   }
 }

A:

From oracle documentation page:

BlockingQueue implementations are thread-safe. All queuing methods achieve their effects atomically using internal locks or other forms of concurrency control

Since you are already using BlockingQueues, you can get rid of wait() and notify() APIs.
Example code for multiple producer and consumers using BlockingQueue:
import java.util.concurrent.*;

public class ProducerConsumerDemo {

    public static void main(String args[]){

     BlockingQueue<Integer> sharedQueue = new LinkedBlockingQueue<Integer>();

      Thread prodThread1 = new Thread(new Producer(sharedQueue,1));
      Thread prodThread2 = new Thread(new Producer(sharedQueue,2));
      Thread consThread1 = new Thread(new Consumer(sharedQueue,1));
      Thread consThread2 = new Thread(new Consumer(sharedQueue,2));

      prodThread1.start();
      prodThread2.start();
      consThread1.start();
      consThread2.start();
   }

}

class Producer implements Runnable {

    private final BlockingQueue<Integer> sharedQueue;
    private int threadNo;

    public Producer(BlockingQueue<Integer> sharedQueue,int threadNo) {
        this.threadNo = threadNo;
        this.sharedQueue = sharedQueue;
    }

    @Override
    public void run() {
        for(int i=1; i<= 5; i++){
            try {
                int number = i+(10*threadNo);
                System.out.println("Produced:" + number + ":by thread:"+ threadNo);
                sharedQueue.put(number);
            } catch (Exception err) {
                err.printStackTrace();
            }
        }
    }

}

class Consumer implements Runnable{

    private final BlockingQueue<Integer> sharedQueue;
    private int threadNo;
    public Consumer (BlockingQueue<Integer> sharedQueue,int threadNo) {
        this.sharedQueue = sharedQueue;
        this.threadNo = threadNo;
    }

    @Override
    public void run() {
        while(true){
            try {
                int num = sharedQueue.take();
                System.out.println("Consumed: "+ num + ":by thread:"+threadNo);
            } catch (Exception err) {
               err.printStackTrace();
            }
        }
    }
}

How does it work?

Producer Thread 1 puts Integers ranging from 11 - 15into BlockingQueue
Producer Thread 2 puts Integers ranging from 21 - 25 into BlockingQueue
Any of Consumer Threads - Thread 1 or Thread 2 reads values from BlockingQueue (Integer in this example)

Sample output:
Produced:21:by thread:2
Produced:11:by thread:1
Produced:12:by thread:1
Produced:13:by thread:1
Produced:14:by thread:1
Produced:22:by thread:2
Produced:23:by thread:2
Produced:24:by thread:2
Produced:25:by thread:2
Consumed: 21:by thread:1
Consumed: 12:by thread:1
Consumed: 13:by thread:1
Consumed: 14:by thread:1
Consumed: 22:by thread:1
Consumed: 23:by thread:1
Consumed: 24:by thread:1
Consumed: 25:by thread:1
Produced:15:by thread:1
Consumed: 11:by thread:2
Consumed: 15:by thread:1


Q:

CakePHP pagination ignoring page number

I have some simple pagination set up in my controller like so:
public function index() {
    $this->set('items', $this->paginate());
}

In my view I'm using the Paginator helper to output numbered links:
echo $this->Paginator->numbers(array(
    'separator' => '',
    'tag' => 'li',
    'currentTag' => 'a',
    'currentClass' => 'active'
));

This all works fine, however I want to use a custom URL for the paginated links. I added this to my routes.php file:
Router::connect('/things/:page', array('controller' => 'things', 'action' => 'index'), array('page' => '[0-9]+'));

Now the links outputted by the Paginator helper are the way I want. They look like http://mysite.com/things/2, http://mysite.com/things/3 etc.
But when I click the links the Paginator in my controller doesn't seem to recognize it's on a certain page, as I just get the first page's results shown. I'm guessing I need to somehow pass the page number to $this->paginate(), but I don't know what the best method is. Is there a way for Cake to get the page number automatically if I modify my route?
Thanks!

A:

Since the Pagination component by default expect named parameter 'page:1' you need somehow to pass same variable in index.
if you make print of $this->request->params in your controller, you will see that it's missing.
See that example how you can pass named parameters in the Router:
Router::connect(
   '/:controller/:action/*',
   array(),
   array(
    'named' => array(
        'wibble',
        'fish' => array('action' => 'index'),
        'fizz' => array('controller' => array('comments', 'other')),
        'buzz' => 'val-[\d]+'
        )
    )
);

For more info see this section in Cakephp book


Q:

Best way to implement value check in database using PHP

I'm very new to PHP. I'm building a companion webservice for an iPhone application I'm creating.
I have the following DB table that i've created which is filled with triggers.

The basic concept is that for a given currency when the price hits the trigger price I'm going to send a push notification.
Before I can generate the push notification I need an elegant way to validate each entry in this table against the current market price.
On initial thought I was thinking to select each trigger price and each currency and compare against the current market price I have in another variable.
Could anyone tell me the most elegant way to achieve what I'm trying to do? (compare the whole table against market price for various currencies)
Also if you have any php snippets that would be great,
Thanks,
John

A:

Well if the app has a user logged in then you only need to check for the rows for that user, which isn't that bad.
However I would implement the database differently, have a separate currencies table like this:
id             SERIAL
currency_name  VARCHAR(10)
market_price   FLOAT

Then change your main table so that target_price is a FLOAT as well (you could use int if you store the number of cents -- or equivalent -- instead of a dollar value, so 103 instead of 1.03). Finally change currency to be an int that references the other table
currency_id    INTEGER

Then you probably want to add a foreign key constraint to the table:
FOREIGN KEY (currency_id)
    REFERENCES currencies(id)

Now you can update the currencies table as the market_price changes then use SQL to get a list of the rows that need triggered:
SELECT u.id
    FROM users u, currencies c
    WHERE u.currency_id = c.id
      AND u.trigger_price <= c.market_price
;

That's probably the best way, in my opinion.
If you really need to do it in PHP then I'd create an associative array of the market prices where prices['currency_name'] = market price for that currency. And currency name matches the string in the table. Then you're just going to have to go through the whole table and check each match, assuming you've already fetched the table into $result and checked for errors:
while ($row = $result->fetch_assoc()) {
    if (isset($prices[$row->currency) // Sanity check on the prices array
        && ($row->trigger_price <= $prices[$row->currency]))
    {
       // Matching row, do something with it ...
    }
}

If you trust the database to only contain stuff in the currency array you can skip the sanity check. If you only want to check certain currencies you could only select rows that match currencies you have updates for.
I'm also assuming your condition is the trigger price being lower than the current price, you may need to do different logic depending on exactly what you want to do.


Q:

Cambiar tipo de dato TIME a DATE - SQL SERVER

Buen día, tengo una duda ,ocurre que por error cambie el tipo de dato, en mi caso tenía DATETIME, pero al momento de cambiar el dato en el design del SQL por motivos de consulta mas sencilla yo le coloque TIME en vez de DATE por error a la columna FECHA, por lo que las fechas se me borraron y a parte no me deja volver a colocar el tipo de dato DATE, me muestra el mensaje que adjunto a continuación los cuales me indican que no es posible compatible TIME con DATE, como se observa solo tengo el tipo de dato time y solo se visualizan los 00:00 del tiempo, antes de este error me salía la fecha y la horas en cero, como lo podría cambiar a date y en el mejor de los casos recuperar las fechas que estaban en el inicio, se puede? o tengo que importarla otra vez y relacionarla con las otras tablas, ya que originalmente es una tabla de Access . Gracias de antemano , saludos.

A:

No podrás hacerlo directamente, tendrías que pasar primero a datetime y luego a date, algo asi:
ALTER TABLE TU_TABLA ALTER COLUMN NOMBRE_CAMPO DATETIME;
GO
ALTER TABLE TU_TABLA ALTER COLUMN NOMBRE_CAMPO DATE;

Aunque realmente nunca he hecho algo parecido, lo mas seguro es que no puedas recuperar la fecha ya que al cambiar a time la fecha se truncó en el registro original.


Q:

extend xlsxwriter.Worksheet() class

I currently override the xlsxwriter.Workbook, called rpt.Workbook.  Would like to add method to xlsxwriter.Worksheet(), but since xlsxwriter.Workbook() imports Worksheet,not sure how this can be done without major convulsions. Currently, I have to pass the worksheet object as an argument.
Seems like I need to write override methods for xlsxwriter.Workbook() to point to a custom class of xlsxwriter.Worksheet() , but can't figure out how.
Here is the current override rpt.Workbook() being used:
####################################################################
class Workbook(xlsxwriter.Workbook):
####################################################################
    """\nSpreadsheet class provides methods to build a spreadsheet.
    """

    ####################################################################
    def __init__(self,filename=None, options={}):
    ####################################################################
        try:
           filename = rpt.fname(filename)
        except FileNotFoundError as err:
            log.error(err)
        return False
        log.info("Initializing excel file " + filename)
        super().__init__(filename,options)
    ####################################################################
    def add_tab(self,name=None,data=None,header=None,
            srow=0,scol=0,autocol=True):
    ####################################################################
        """\nProvides method to add_worksheet and add_table in 1 call.

             Required Attribute args:
             name = TAB name
             header = list of header names
             data = list of lists for spreadsheet contents

             Optional Attribute args:
                 srow = starting row for table, default 0
                 scol = starting col for table, default 0
                 autocol = True/False, auto set the column sizes

             add_tab also adds the worksheet.header attribute to
             allow the set_col_by_name function to work
        """

        if not data:
            log.warning("data=[][] required")
            return None
        if not header:
            log.warning("header=[] required")
            return False
        columns = []
        for field in header:
            columns.append({ 'header' : field })
        worksheet = self.add_worksheet(name)
        worksheet.header = header
        tableinfo= {
            'data' : data,
            'columns' : columns
            }
        lastcol = scol + (len(header) - 1)
        lastrow = srow + (len(data) + 1)
        worksheet.add_table(srow,scol,lastrow,lastcol,tableinfo)
       #if autocol:
           #self.auto_set_columns(worksheet=worksheet,data=data,scol=scol)
       worksheet.freeze_panes(0,1)
       return worksheet
   ####################################################################
   def auto_set_columns(self,worksheet=None,data=None,header=None,scol=0):
   ####################################################################
        """\nDetermines the max length of each column and then set
              that column width.

             Required Attribute args:
                 worksheet = worksheet object
                 data = list of lists data
             Optional Attribute args:
                 scol = Column start
                 header = row of headers for data list of lists.
                          If header not specified, worksheet
                          must have been created with self.add_tab()
        """
        if not header and worksheet.header:
            header = worksheet.header

        ## table = [] list of lists, combine header and data
        table = []
        table.append(header)        for row in data:
            table.append(row)
        ziptable = list(zip (*table))
        colsizes = []
        for idx,val in enumerate(table[0]):
            size = max(len(s) for s in ziptable[idx])
            colnum = idx + scol
            log.debug("Setting column => {} col size => {} =>  {}".format(colnum,val,size))
            worksheet.set_column(colnum,colnum,size)

I want to add a method to xlsxwriter.Worksheet() called auto_set_columns(). Currently I have to pass the worksheet object (worksheet=worksheet) as an object to get this to work.I would like to utilize worksheet.auto_set_columns() instead. Currently auto_set_columns() is a method of rpt.Workbook.
Would like auto_set_columns() to be an extended method of xlsxwriter.Worksheet.
The script side utilization currently looks like this and works:
excelfile = nashomes + '/nas_homes.xlsx'
spreadsheet = rpt.Workbook(excelfile)
worksheet = spreadsheet.add_tab(name='Nas Homes',data=hrpt.data,header=hrpt.header)
spreadsheet.auto_set_columns(worksheet=worksheet,data=hrpt.data,scol=0)

What I desire, notice the last line changes:
excelfile = nashomes + '/nas_homes.xlsx'
spreadsheet = rpt.Workbook(excelfile)
worksheet = spreadsheet.add_tab(name='Nas Homes',data=hrpt.data,header=hrpt.header)
worksheet.auto_set_columns(data=hrpt.data,scol=0)

Goal desired here is that worksheet object (which is xlsxwriter.Worksheet() ) can have an extended "auto_set_columns" method. However, since the worksheet object is created from a add_worksheet() method in the xlsxwriter.Workbook() class, I can't figure out how to extend xlsxwriter.Worksheet() without major override methods to xlsxwriter.Workbook() also. How can I get xlsxwriter.Workbook() to reference my extended xlsxwriter.Worksheet() when Workbook.add_worksheet() creates the Worksheet object?

A:

How about monkey patching the worksheet before returning it from add_tab?
First create the standalone function outside of any class definitions:
import types

def auto_set_columns(self,data=None,header=None,scol=0):
    if not header and self.header:
        header = self.header

        ## table = [] list of lists, combine header and data
        table = []
        table.append(header)
        for row in data:
            table.append(row)
        ziptable = list(zip (*table))
        colsizes = []
        for idx,val in enumerate(table[0]):
            size = max(len(s) for s in ziptable[idx])
            colnum = idx + scol
            print "Setting column => {} col size => {} =>  {}".format(colnum,val,size)
            self.set_column(colnum,colnum,size)

And then inside your Worksheet.add_tab function, patch in the method before returning:
    ....
    worksheet.freeze_panes(0,1)
    worksheet.auto_set_columns = types.MethodType( auto_set_columns, worksheet )
    return worksheet

Now you should be able to run:
worksheet = spreadsheet.add_tab(name='Nas Homes',data=hrpt.data,header=hrpt.header)
worksheet.auto_set_columns(data=hrpt.data,scol=0)


Q:

how list model sorted by number of DOWN-VOTES cast to related model - laravel, eloquent

Thanks to help from @LukasGeiter I improved on my quotations and books database.
After 4th edit I simplified my problem to this:
I am now able to list certain type of writers and sort the list by their importance and 'likes' & 'dislikes' assigned to a given autor
This is the code which produces my collection:
$targetted = Capacitytype::find($capacity);  // this selects Sci-Fi writers only from among all writers

$rank_entities_by_capacity = Entity::join('entity_capacitytypes', function($q) use ($capacity){
     $q->on('entity_capacitytypes.entity_id', '=', 'entities.id');
     $q->where('entity_capacitytypes.capacitytype_id','=', $capacity);
 })->leftJoin('user_attitudes', function($q) {
                $q->on('user_attitudes.entity_id', '=', 'entities.id');
                $q->where('item_type', '=', 'entity');
            })

->selectRaw('entities.*, SUM(user_attitudes.importance) AS importance'
             , SUM(user_attitudes.attitude) AS attitude'
)
->groupBy('entities.id')
            ->orderBy('importance', 'desc')
            ->take(6)
            ->get();

What I need:
1) I want to sort the list by number of UPVOTES assigned to each listed author by particular user
The code contributed by lucas does the job:
 'SUM(IF(user_id = ' . Auth::user()->id . ', user_attitudes.attitude, 0)) AS karma_current_user'

Now I want another sorting method:
Each author has certain number of quotes  said and books published.
User can UPVOTE and DOWNVOTE these creations
in the table user_attitudes it looks like this:
> id  |  item_id  |  item_type  | entity_id  | importance | attitude (VOTES) | creator_id

> 1   |  51         | entity    | 51         | -1               |100

> 2   |  32         | book      | 51         | -1               |100

> 3   |  33         | book      | 51         | -1               |100

In plain English:
- The entity 51 received a downvote for life-time achievement from user #100 (lukas provided the code already)

also, two books (#32 and #33) written by the same Entity (#51) received DOWN-VOTES for their content.

Thing to do:
I need to list the Entities (Sci-Fi writers in this case) and sort the listing by these DOWN-VOTES assigned to books they authored. IN the above example the author is scored "-2".

Note: the column entity_id duplicates info on related entity - i added it to avoid joining extra pivot table with info who about authorship.

A good real-life example:
To translate my want into StackOverflow model, I now can assign likes to people who are helping me (lukas gets a +1 UP-VOTE in my table user_attitudes.attitude). I can also list all users who received likes from me. This is done.
Now I want to see  a ranking of users sorted by the number of answers they contributed to my own questions. Lukas gets the 1st place on the list with c. 6 answers... etc.
Possible solution:
Possibly I only need to add an extra IF clause in this line
 'SUM(IF(user_id = ' . Auth::user()->id . ', user_attitudes.attitude, 0)) AS karma_for_books'

conditions to add:
IF user_attitudes.item_type = book
IF user_attitudes.entity_id = (entity)....
IF attitude = '-1' // counting downwotes only

I dont know the syntax rules for this task.
Do we need an extra leftJoin?
Aftrer two changes of the DB structure I am confused.
This things might help:
Laravel 4 query builder - with complicated left joins
Laravel Eloquent and Multiple Joins
but it is beyond me...
Any help appreciated. Thank you.
Thx

A:

Using IF inside inside SUM() should work. Try this:
$selects = array(
    // your existing selects
    'SUM(IF(user_attitudes.attitude = -1, 1, 0)) AS dislikes',
    'SUM(IF(user_attitudes.attitude = 1, 1, 0)) AS likes',
    'SUM(IF(user_id = ' . Auth::user()->id . ', user_attitudes.attitude, 0)) AS karma_current_user'
);


Q:

various ways to get session access object in struts2 other than implementing SessionAware interface

guys I'm beginner to Struts2 .i'm trying to use session but i could not create session object by implementing SessionAware So is there is any other way to creates session object other than  SessionAware thanks in advance
any help will be appreciated

A:

Map session = ActionContext.getContext().getSession();

you can use the above method to get session object


Q:

Unit Tests are never discovered

I have the following solution in Visual Studio 2017 Update 3 preview, which consists of a Xamarin.Forms project as NetStandard1.4 and a NetStandard1.4 dotnet Core Services.API project and a NetStandard1.6 dotnet Core unit test project.

The Unit Test project references the services project only. The csproj file looks like this, with the MSTest framework added for unit testing. The issue though is that the tests are never discovered.
csproj
<PropertyGroup>
    <TargetFramework>netstandard1.6</TargetFramework>
    <AssemblyName>FloatSink.Services.Api.Tests</AssemblyName>
    <RootNamespace>FloatSink.Services</RootNamespace>
</PropertyGroup>

<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'">
    <DebugType>full</DebugType>
    <DebugSymbols>True</DebugSymbols>
</PropertyGroup>

<ItemGroup>
    <PackageReference Include="Microsoft.NET.Test.Sdk" Version="15.0.0"></PackageReference>
    <PackageReference Include="Microsoft.TestPlatform.TestHost" Version="15.0.0" />
    <PackageReference Include="MSTest.TestAdapter" Version="1.1.17" />
    <PackageReference Include="MSTest.TestFramework" Version="1.1.17" />
</ItemGroup>

<ItemGroup>
    <ProjectReference Include="..\Services.API\Services.API.csproj" />
</ItemGroup>

Unit Test class
[TestClass]
public class AppBuilderTests
{
    private const string DebugBuild = "Debug build";
    private const string ReleaseBuild = "Release build";

    /// <summary>
    /// Test that the ToString() method returns the string we sent into the constructor
    /// </summary>
    [TestMethod]
    public void ToStringReturnsStringFromCtor()
    {
        // Act
        var build = new AppBuild(DebugBuild);

        // Assert
        Assert.AreEqual(DebugBuild, build.ToString());
    }
}

Finally this is the test output when I build and select Run All from the Test Explorer (which is empty).

[5/26/2017 6:38:23 PM Informational] ------ Load Playlist started ------
[5/26/2017 6:38:23 PM Informational] ========== Load Playlist finished (0:00:00.004501) ==========
[5/26/2017 6:38:24 PM Informational] ------ Discover test started ------
[5/26/2017 6:38:25 PM Informational] ========== Discover test finished: 0
  found (0:00:00.5716028) ==========

Why won't the MSTest unit tests show up in the Test Explorer and allow me to discover/run them?
Update
I changed the debug type from Full to portable and I've also tried this with xUnit and have the same issue. So this isn't specific to MSTest.
csproj with xUnit
<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <TargetFramework>netstandard1.6</TargetFramework>
    <AssemblyName>FloatSink.Services.Api.Tests</AssemblyName>
    <RootNamespace>FloatSink.Services</RootNamespace>
  </PropertyGroup>

  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'">
    <DebugType>portable</DebugType>
    <DebugSymbols>True</DebugSymbols>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="Microsoft.NET.Test.Sdk" Version="15.0.0" />
    <PackageReference Include="xunit" Version="2.2.0" />
    <PackageReference Include="xunit.runner.visualstudio" Version="2.2.0" />
  </ItemGroup>

  <ItemGroup>
    <ProjectReference Include="..\Services.API\Services.API.csproj" />
  </ItemGroup>

</Project>

A:

The problem is that your TargetFramework is set to a .NET Standard version.
Although test projects look like libraries, they have more characteristics of a runnable output - the 15.0.0 test sdk even changes the output type to Exe to trigger generation of assets needed to run the tests. (In 2.0 / 15.3.0 this will change to a new HasRuntimeOutput property).
The fix here is to change the TargetFramework to either some version of net* or netcoreapp* depending on what framework you want to run the tests on.