Q:

CSS nth-child on nested divs with different classes

I have nested divs and I am trying to alternate the background color and the border size.
I have the following HTML

FirstPart

SecondPart

ThirdPart

I want to be able to make the background color to gray when odd .white-bg-alt .white-bg and white when even.
I also want the p.colored-p to be white when .white-bg-alt .white-bg is odd and gray when even.
Here is the CSS I have - but not working, it either gives me all white, or if I modify it, it gives all gray, but not ALTERNATING.
.white-bg-alt .white-bg:nth-child(odd) {
  background-color: #EAEAE3;
  border-top: 0px;
}
.white-bg-alt .white-bg:nth-child(even) {
  border-bottom: 2px;
  background-color: #FFF;
}
.white-bg-alt .white-bg:nth-child(odd) .colored-p {
  background-color: #FFF;
}
.white-bg-alt .white-bg:nth-child(even) .colored-p {
  background-color: #EAEAE3;
}

Any ideas why this isn't working? I was able to do it with Javascript but I'd rather not do any styling inside javascript.

A:

You are targetting the wrong element for nth-child. Currently you are targetting .white-bg but that will always be odd because there is only one of this element within its scope.
Instead you want to alternate between the .white-bg-alt element.
So a simple change to the following will solve your problem:
.white-bg-alt:nth-child(odd) .white-bg {
  background-color: #EAEAE3;
  border-top: 0px;
}
.white-bg-alt:nth-child(even) .white-bg {
   border-bottom: 2px;
   background-color: #FFF;
}
.white-bg-alt:nth-child(odd) .white-bg .colored-p {
   background-color: #FFF;
}
.white-bg-alt:nth-child(even) .white-bg .colored-p {
  background-color: #EAEAE3;
}


Q:

Apache ErrorDocument without redirect?

I have an Apache server that has / forwarding to a Tomcat server. When the Tomcat server is down, I want to display an error message. Here's what I have currently:
ErrorDocument 502 "We're down, sorry :("

I would like to show a relatively rich document (funny picture and stuffs), not just a one sentence message. The issue is, it doesn't appear I can serve documents, only redirect to them. I'm looking at this documentation.
I'd like to keep the same URL, but serve a different HTML file. Any way to do this?
<VirtualHost *:443>
        ServerName ${DOMAIN_NAME}
        ProxyRequests Off

        ProxyAddHeaders On

        ProxyPass /stomp http://tomcat:8080/stomp
        ProxyPassReverse /stomp http://tomcat:8080/stomp

        ProxyPass /.well-known http://mail.${DOMAIN_NAME}:80/.well-known
        ProxyPassReverse /.well-known http://mail.${DOMAIN_NAME}:80/.well-known

        ProxyPassMatch / http://tomcat:8080 retry=0 timeout=10
        ProxyPassReverse / http://tomcat:8080

        SSLCertificateFile /etc/letsencrypt/live/${DOMAIN_NAME}/fullchain.pem
        SSLCertificateKeyFile /etc/letsencrypt/live/${DOMAIN_NAME}/privkey.pem
        Include /etc/letsencrypt/options-ssl-apache.conf

        ErrorDocument 502 ${PROXY_ERROR_MESSAGE}
        ErrorDocument 503 ${PROXY_ERROR_MESSAGE}
</VirtualHost>

A:

If you specific a fully qualified URL for an error document you are implicitly causing a redirect because the browser must be told to "go get the error page somewhere else". However if you do something like:
ErrorDocument /errors/my503.html
The there will be no redirect as long as that URI path is served directly in apache. In your setup because you are proxying '/', you must explicity exclude that document from being proxied back to tomcat like this:

ProxyPass /errors/my503.html !
ErrorDocument /errors/my503.html

You also need to add exclusions for any page components used in the HTML.
If you want to serve custom error pages from actual HTTP error codes that come from tomcat (4xx codes normally), then you should look at the ProxyErrorOverride directive


Q:

Guaranteed elision and chained function calls

Let's say I have the following type:
struct X {
    X& operator+=(X const&);
    friend X operator+(X lhs, X const& rhs) {
        lhs += rhs;
        return lhs;
    }
};

And I have the declaration (assume all the named variables are lvalues of type X):
X sum = a + b + c + d;

In C++17, what are the guarantees I have about how many copies and moves this expression will perform? What about non-guaranteed elision?

A:

This will perform 1 copy construction and 3 move constructions.

Make a copy of a to bind to lhs.
Move construct lhs out of the first +.
The return of the first + will bind to the by value lhs parameter of the second + with elision.
The return of the second lhs will incur the second move construction.
The return of the third lhs will incur the third move construction.
The temporary returned from the third + will be constructed at sum.

For each of the move constructions described above, there is another move construction that is optionally elided.  So you are only guaranteed to have 1 copy and 6 moves.  But in practice, unless you -fno-elide-constructors, you will have 1 copy and 3 moves.
If you don't reference a after this expression, you could further optimize with:
X sum = std::move(a) + b + c + d;

resulting in 0 copies and 4 moves (7 moves with -fno-elide-constructors).
The above results have been confirmed with an X which has instrumented copy and move constructors.

Update
If you're interested in different ways to optimize this, you could start with overload the lhs on X const& and X&&:
friend X operator+(X&& lhs, X const& rhs) {
    lhs += rhs;
    return std::move(lhs);
}
friend X operator+(X const& lhs, X const& rhs) {
    auto temp = lhs;
    temp += rhs;
    return temp;
}

This gets things down to 1 copy and 2 moves.  If you are willing to restrict your clients from ever catching the return of your + by reference, then you can return X&& from one of the overloads like this:
friend X&& operator+(X&& lhs, X const& rhs) {
    lhs += rhs;
    return std::move(lhs);
}
friend X operator+(X const& lhs, X const& rhs) {
    auto temp = lhs;
    temp += rhs;
    return temp;
}

Getting you down to 1 copy and 1 move.  Note that in this latest design, if you client ever does this:
X&& x = a + b + c;

then x is a dangling reference (which is why std::string does not do this).

A:

OK, let's start with this:
X operator+(X lhs, X const& rhs) {
    lhs += rhs;
    return lhs;
}

This will always provoke a copy/move from the parameter to the return value object. C++17 doesn't change this, and no form of elision can avoid this copy.
Now, let's look at one part of your expression: a + b. Since the first parameter of operator+ is taken by value, a must be copied into it. So that's one copy. The return value will be copied out into the return prvalue. So that's 1 copy and one move/copy.
Now, the next part: (a + b) + c.
C++17 means that the prvalue returned from a + b will be used to directly initialize the parameter of operator+. This requires no copying/moving. But the return value from this will be copied from that parameter. So that's 1 copy and 2 moves/copies.
Repeat this for the last expression, and that's 1 copy and 3 move/copies. sum will be initialized from the prvalue expression, so no copying needs to be done there.

Your question really seems to be whether parameters remain excluded from elision in C++17. Because they were already excluded in prior versions. And that's not going to change; the reasons for excluding parameters from elision have not been invalidated.
"Guaranteed elision" only applies to prvalues. If it has a name, it cannot be a prvalue.


Q:

Frequency Analysis in Python -Print letters with frequency rather than numbers with frequency

s=array1 #user inputs an array with text in it
n=len(s)
f=arange(0,26,1)
import collections
dict = collections.defaultdict(int)
for c in s:
    dict[c] += 1

for c in f:
    print  c,dict[c]/float(n)

In the output, c is in numbers rather then letters and I'm not sure how to convert it back to letters.
Also, is there any way to get the frequency/letters into arrays so it'd be possible to plot them in a histogram?

A:

It should be pointed out that you aren't calling map with the right type of arguments (thus the TypeError). It takes a single function and one or more iterables, to which the function is applied to. Your second argument is toChar[i] which would be a string. All iterables implement __iter__. To illustrate:
>>> l, t = [], ()
>>> l.__iter__
<<< <method-wrapper '__iter__' of list object at 0x7ebcd6ac>
>>> t.__iter__
<<< <method-wrapper '__iter__' of tuple object at 0x7ef6102c>

DTing's answer reminded me of collections.Counter:
>>> from collections import Counter
>>> a = 'asdfbasdfezadfweradf'
>>> dict((k, float(v)/len(a)) for k,v in Counter(a).most_common())
<<<
{'a': 0.2,
 'b': 0.05,
 'd': 0.2,
 'e': 0.1,
 'f': 0.2,
 'r': 0.05,
 's': 0.1,
 'w': 0.05,
 'z': 0.05}

A:

If you are using python 2.7 or greater you can use collections.Counter.
Python 2.7+
>>> import collections
>>> s = "I want to count frequencies."
>>> counter = collections.Counter(s)
>>> counter
Counter({' ': 4, 'e': 3, 'n': 3, 't': 3, 'c': 2, 'o': 2, 'u': 2, 'a': 1, 'f': 1, 'I': 1,     'q': 1, 'i': 1, 's': 1, 'r': 1, 'w': 1, '.': 1})
>>> n = sum(counter.values()) * 1.0   # Convert to float so division returns float.
>>> n
28
>>> [(char, count / n) for char, count in counter.most_common()]
[(' ', 0.14285714285714285), ('e', 0.10714285714285714), ('n', 0.10714285714285714), ('t', 0.10714285714285714), ('c', 0.07142857142857142), ('o', 0.07142857142857142), ('u', 0.07142857142857142), ('a', 0.03571428571428571), ('f', 0.03571428571428571), ('I', 0.03571428571428571), ('q', 0.03571428571428571), ('i', 0.03571428571428571), ('s', 0.03571428571428571), ('r', 0.03571428571428571), ('w', 0.03571428571428571), ('.', 0.03571428571428571)]

Python 3+
>>> import collections
>>> s = "I want to count frequencies."
>>> counter = collections.Counter(s)
>>> counter
Counter({' ': 4, 'e': 3, 'n': 3, 't': 3, 'c': 2, 'o': 2, 'u': 2, 'a': 1, 'f': 1, 'I': 1,     'q': 1, 'i': 1, 's': 1, 'r': 1, 'w': 1, '.': 1})
>>> n = sum(counter.values())
>>> n
28
>>> [(char, count / n) for char, count in counter.most_common()]
[(' ', 0.14285714285714285), ('e', 0.10714285714285714), ('n', 0.10714285714285714), ('t', 0.10714285714285714), ('c', 0.07142857142857142), ('o', 0.07142857142857142), ('u', 0.07142857142857142), ('a', 0.03571428571428571), ('f', 0.03571428571428571), ('I', 0.03571428571428571), ('q', 0.03571428571428571), ('i', 0.03571428571428571), ('s', 0.03571428571428571), ('r', 0.03571428571428571), ('w', 0.03571428571428571), ('.', 0.03571428571428571)]

This will also return the (char, frequency) tuple in descending order of frequency.


Q:

How to compare two elements' attribute value and modify its element?

How to compare two elements'attribute value and then modify the attribute? For example, I have a photos of a selection of chairs: red, green, black etc etc and they are ranked by "data-slick-index". when a color is selected, say red, I want to compare the photos's "color-option" attribute, if they match with the selected color (red in this case), I want to deleted the "data-slick-index" attribute of the ones that are not red so they will not show up in thumbnail.

What I have now is this:
$(function() {
  $('li.product-single__thumbnails-item').each(function(){
 var $ColorOfEach = $(this).attr('color-option');
  var $GetSelectedElement = document.getElementById("FeaturedImage-product-template");
  var $SelectedColor = $GetSelectedElement.getAttribute("color-option");

    if ($ColorOfEach != $SelectedColor) {
     $(this).removeAttribute('data-slick-index');
}
});
 });

I dont think it is right because I am removing the attribute from an attribute, not from the actual Li element, can anyone can help me? Thank you!

A:

Replace removeAttribute with removeAttr because its JavaScript
function and you are using jQuery function
2nd your HTML also incorrect Li tag always under UL element

$(function() {
  $('li.product-single__thumbnails-item').each(function() {
    var $ColorOfEach = $(this).attr('color-option');
    var $GetSelectedElement = document.getElementById("FeaturedImage-product-template");
    var $SelectedColor = $mobilemodelselected.getAttribute("color-option");
    if ($ColorOfEach != $SelectedColor) {
      $(this).removeAttr('data-slick-index');
    }
  });
});


Q:

Amortized Analysis: Find the Rate of Travel

A biker can travel at 24kms per hour with the flow of the wind, but only 12kms per hour against the wind. Assuming the biker starts and finishes at the same point.
What is the rider's amortized rate of travel?
I do not understand how the answer is arrived at, I have read my lecture notes but it is a little confusing.
Thanks

A:

I am assuming the biker goes from point A to point B, and then back from point B to point A, and from A-B he is going 24km/hr and from B-A he is going 12km/hr.
Amortized is a fancy term that here essentially means average, so we want to find the average speed that the biker is traveling.
The actual distance that the person travels is not relevant because the distance from A to B is equivalent to the distance from B to A.  For simplicity of the Math, lets say that the distance is 24 kilometers.
We can then say that at a rate of 24km/hr it would take 1 hour to get from A to B.
We can also say that at a rate of 12hm/hr it would take 2 hours to get from B to A.
This means that in total it takes 3 hours to get from A to B back to A.  In this time he has gone twice the distance (which we decided was 24).  That means in total he traveled 48km.
If it took 3 hours to go 48km, that is (48/3)km/hr or just 16km/hr for the average (amortized) rate of speed.
You can see that the distance we decide upon is indeed irrelevant if you plug in x for the distance, and carry it through.


Q:

Can a kineticist voluntarily dismiss their kinetic covers?

Kinetic Cover allows the kineticist to create a small wall. Using the ability is a standard action. The ability description tells the maximum number of kinetic covers that can be created at once.
The power explains how kinetic covers can be destroyed, but specifies no duration or, as far as I can see, a way for the kineticist to dismiss the covers (without destroying them).
Is there a duration after which the covers lapse or a means to dismiss kinetic covers other than destroying or dispelling them?

A:

As written, the kineticist utility wild talent kinetic cover has no listed duration. This is unaddressed by the Occult Adventures FAQ, mentioned as an issue once in the kineticist playtest thread from 2014 (and another user's followup post is of no help), and is unmentioned in class author Mark Seifter's ongoing Ask Me Anything thread. This last would likely be the most direct way to get a semi-official answer as to the duration of kinetic cover until and if Occult Adventures receives errata.
Probably not instantaneous nor permanent yet dismissible
Without a listed duration, kinetic cover is created instantaneously, remaining in place until destroyed. As the created wall is both paper thin with no hardness and pitiful hp and crumbles under 5 lbs. of weight, most creatures can destroy it with ease. This would be fine except that "you can have a number of kinetic covers in existence equal to your Constitution modifier + 1/2 your kineticist level," and if, for example, a kineticist uses all his kinetic covers in a dungeon and teleports away, the kineticist must either hope that dungeon denizens hate walls made of water or whatever and destroy them or return himself or send agents to the dungeon to destroy his own kinetic covers just so he can make more. That's silly.
Were kinetic covers permanent yet dismissible, they become vulnerable to dispel magic effects, but then the kineticist can take a standard action to dismiss a kinetic cover. However, the rules for dismissible effects still require the effect's controller to be "within range of the spell's effect," and the range of kinetic cover is only 30 ft. While better than instantaneous, this isn't much better.
Rounds equal to the kineticist's Constitution modifier? Sure, I guess
The powers cloud, wall, deadly earth, mobile blast, and others have this duration. It's long enough to matter in combat but not long enough to cripple the power were the kineticist instantaneously transported a vast distance from his kinetic covers. Extending the duration to longer rounds runs the risk of the previous covers' existence preventing the current use of any covers, and that would suck. In fact, were I playing a kineticist, I'd argue against the GM trying to impose a more typical duration like 1 min./level or 1 hour/level. A low-level kineticist needs to be able to use his powers, and there's a point when the kinetic cover talent can be a kineticists's only utility power.


Q:

How to index a std_logic_vector by enumeration

I have a std_logic_vector like this:
cntrl_signals:out std_logic_vector(4 downto 0);

One way to have indexes to this vector would be to explicitly define a constant for each.
constant CLK_SIG:integer := 0;
constant EN_SIG:integer := 1;
constant FOO_SIG:integer := 2;
constant BAR_SIG:integer := 3;
constant BAZ_SIG:integer := 4;

The idea is to use these to index the vector.
cntrl_signals <= (CLK_SIG=>1,EN_SIG=>1,others=>0);

My question is if there a nice shorthand way of declaring the indexes (like an enum in C)?

A:

Well you could use enumerations, the best way would be to declare your own vector of std_logic, indexed by the enumeration instead of by integer.
But probably better would be a record instead of a vector :
type Control_Signals is record
   Clk : std_logic,
   En  : std_logic,
   Foo : std_logic,
   Bar : std_logic,
   Baz : std_logic
end record;

EDIT for more information, following comment:
Unimaginative use of std_logic_vector (and VHDL's type system in general) is holding VHDL back...
If this is a top level entity, then std_logic_vector ports allow you to substitute a post-synthesis netlist for your synthesisable design in the top level testbench. Or you may have to comply with antiquated coding style guidelines that insist on std_logic_vector ports.
But in any other circumstance I would declare the record in a package, use that package throughout the design, and make the ports of the record type. The package should include functions to_slv and to_control_sigs for the (rare, if you get it right) occasions when you actually need std_logic_vectors.
The same applies with enumerations:
type Controls is (Clk, En, Foo, Bar, Baz);
type Control_Signals is array(Controls) of std_logic;
My_Bus_Ctrl : Control_Signals := (Clk => '1', En => '1', others => '0');
My_External_SLV_Port <= std_logic_vector(My_Bus_Ctrl);

And of course, enumerations are a bit more powerful than in C; as well as using them as array index types, you can loop over them. Which keeps your loops in line whenever you update the enumeration!
Records or arrays indexed by enumerations both work; I prefer the record as a bit cleaner and more in line with object oriented practice.
In either case it becomes FAR more useful if you use it for entity ports. Declare one record (or array!) for outgoing bus signals (including address and data) and another for incoming signals, because you can't mix directions in a single port... (There are no bidirectional signals in an FPGA these days, so there is no need for a third port)
Now your design is protected against bus structure changes; changing the address width or adding an interrupt signal only changes the record declaration and any actual users; there is no need to add the new signal throughout the hierarchy...


Q:

Running grunt-nodemon once after simultaneous file changes

This is my Gruntfile. I run concurrently nodemon to run my application and watch to watch for changes in my coffeescript.
Coffeescript takes the src files and turns them into JS files (Currently 3, main.coffee, Person.coffee and Car.coffee)
I want my Nodemon to restart everytime once of those file changes, to run it with the latest saved changes.
Here is the problem: When just 1  coffee file is modified, running coffee will recompile all the coffee files, which in turn generate 3 JS files, which in turn makes nodemon restart 3 times. This is not desirable since im working in an application that uses net requests, and I don't want it to spin out of control.
Would it be possible to make nodemon restart just 1 time?
I thought of concatenating  all the JS files, but that messes the modularity of my JS files.
I also thought of "watching" the files 1 by 1, but that can get cumbersome if I reach 50 files.
How can I solve this problem?
module.exports = function(grunt) {
    "use strict";

    grunt.initConfig({

        pkg: grunt.file.readJSON( 'package.json' ),

        coffee: {
            dist: {
                join: true,
                expand: true,
                flatten: true,
                cwd: 'src/dist',
                src: ['*.coffee'],
                dest: 'dist',
                ext: '.js'
            },
        },

        watch: {
            dist: {
                files: ['src/dist/**/*.coffee'],
                tasks: 'coffee'
            },
        },

        concurrent: {
            dev: {
                tasks: ['nodemon', 'watch'],
            options: {
                logConcurrentOutput: true
            }
        }
        },
        nodemon: {
            dev: {
                script: 'dist/main.js',
            },
            options:{
                watch: "dist/**/*.js"
            }
        }
    });

    grunt.loadNpmTasks('grunt-concurrent');
    grunt.loadNpmTasks('grunt-contrib-coffee');
    grunt.loadNpmTasks('grunt-contrib-watch');
    grunt.loadNpmTasks('grunt-nodemon');

    grunt.registerTask("default", ["coffee", "concurrent"]);
};

A:

You probably need to use the delayTime option. The problem is, it doesn't actually wait for all files to finish, it simply waits some amount of time before restarting, thus preventing multiple restarts.
nodemon: {
    dev: {
        script: 'dist/main.js',
    },
    options:{
        watch: "dist/**/*.js",
        delayTime: 2000
    }
}


Q:

Is there a simpler or one line method to get the selected index of a DataGridViewComboBoxCell?

I have a datagrid that contains mostly DataGridViewComboBoxColumn columns as data. The number of columns in the DataGridView varies based on the type of
product being listed. To make editing of each row of the data easier I have created a modal editor to display all the columns as multiple rows and columns
(need to remove the horizontal scrolling forced on the user by the data grid). The data in one row of the datagrid needs to be transferred to the modal editor.
Obviously the controls in the modal editor will not be of type DataGridViewComboBoxCell. They are currently of type ListBox, but in most of
the cases this is easy enough to change to ComboBox.
The controls in the modal editor need to be initiated with the currently
selected values of the DataGridViewComboBox Cells if the user has previously
edited the control.
The way I originally planed to do it was to get the selected index of the
DataGridViewComboBox but that doesn't seem to exist. Is there a method to get
the selected index that does not involve comparing the Cell Value to each of
the items in the DataGridViewComboBoxColumn.items list?
This question refers to the second constructor where it is looping through the list of items to get selected index.
public class ControlTransferData
{
    private List<string> _valueStrings;
    private string _name;
    private bool _hasSelection;
    private int _indexSelected;

    public ControlTransferData()
    {
        _valueStrings = new List<string>();
        _name = null;
        _indexSelected = -1;
        _hasSelection = false;
        Width = 0;
        Height = 0;
    }

    public ControlTransferData(DataGridViewComboBoxColumn CboxCol, DataGridViewCell currentControlToTransfer)
    {
        _valueStrings = new List<string>();
        foreach (string item in CboxCol.Items)
        {
            string itemStringValue = item.ToString();
            if (!string.IsNullOrWhiteSpace(itemStringValue) && !string.IsNullOrEmpty(itemStringValue))
            {
                _valueStrings.Add(itemStringValue);
            }
        }

        if (currentControlToTransfer.Value != null)
        {
            _hasSelection = true;
            int selectedIndex = 0;
            string selectedItem = currentControlToTransfer.Value.ToString();
            foreach (string currentString in _valueStrings)
            {
                if (currentString.CompareTo(selectedItem) == 0)
                {
                    _indexSelected = selectedIndex;
                }
                selectedIndex++;
            }
        }
        else
        {
            _indexSelected = -1;
            _hasSelection = false;
        }

        _name = CboxCol.HeaderText;
        Width = 0;
        Height = 0;
    }

    public string Name { set { _name = value } get { return _name; } }
    public List<string> ValueStrings { set { _valueStrings = value; } get { return _valueStrings; } }
    public bool HasSelection { set { _hasSelection = value; } get { return _hasSelection; } }
    public int IndexSelected { set { _indexSelected = value; } get { return _indexSelected; } }
    public int Width { set; get; }
    public int Height { set; get; }
}

A:

you can use below code:
 myDGV.Columns["SampleColumn"].Index;

This would work in winForms.


Q:

Order of elements in a finite Abelian group

Suppose that $G$ is a finite abelian group and that $x, y \in G$ are of orders $a$ and $b$ respectively.
I'm trying to show that there exist two elements $x'$ and $y'$ of orders $a'$ and $b'$ such that

$a'b'=lcm(a,b)$ and
$gcd(a',b')=1$.

Well the first thing that glaces to my mind is this $x'=x^{\frac{a}{a'}}$ and $y'=y^{\frac{b}{b'}}$. So to make sure it's the answer, I've got to firstly show that $a$ and $b$ are respectively divisible by $a'$ and $b'$, but for (1) and (2) i have no clue. Please can you help me figure this out ?

A:

First note that if $gcd(a,b) = 1$, then you're done and $x = x'$, $y = y'$. If not, let $gcd(a,b) = k$, and choose $x' = x^k$,$ y' = y$. The orders of $x'$ and $y'$ respectively are $\frac{a}{k}$ and $b$.
Since $lcm(a,b) gcd(a,b) = ab$ we have $lcm(a,b) = \frac{a}{k} b = a' b'$ as desired. We also know $gcd(a',b') = 1$, since $k = gcd(a,b)$ was divided from $a$.


Q:

NullReferenceException: Object reference not set to an instance of an object с Юнити и C#

Код:
using UnityEngine;
using System.Collections;

public class Points : MonoBehaviour {
    public Vector3[] point;
    private Vector3[] real_point;
    public GameObject point_object;
    private GameObject[] point_object_inst;

    void Start () {
        Vector3[] real_point = new Vector3[point.Length];
        GameObject[] point_object_inst = new GameObject[point.Length];

        for (int i = 0; i <point.Length; i++)
        {
            real_point[i].z = -point[i].x;
            real_point[i].x = point[i].y;
            real_point[i].y = point[i].z;

           point_object_inst[i] = Instantiate(point_object, real_point[i], Quaternion.identity) as GameObject;
        }

    }

    void Update () {

        for (int i = 0; i < point.Length; i++)
        {
            real_point[i].z = -point[i].x;
            real_point[i].x = point[i].y;
            real_point[i].y = point[i].z;

            point_object_inst[i].transform.position =  real_point[i];
        }

    }
}

собственно в строке real_point[i].z = -point[i].x;  метода update вылезает такое. А ранее и чуть ниже - в
point_object_inst[i].transform.position =  real_point[i];

знаю что это из за того что обращаюсь к null, но как исправить - не могу понять, конкретно для моего случая, потому что "букварь прокурил" о чем очень сожалею. Объектно ореинтированные языки для меня новое и поэтому с инициализацией объектов я туплю- в старом добром фортране просто объявил переменную и живи спокойно) Так вот, прошу популярно объяснить в чем тут ошибка. ПОдобную ошибку в методе Start я исправил инициализировав real_point.

A:

real_point и point_object_inst - члены класса, не будем повторно объявлять их как локальные переменные в методе Start:
void Start () {
  /* убрать Vector3[] */ real_point = new Vector3[point.Length];
  /* убрать GameObject[] */ point_object_inst = new GameObject[point.Length];
  ...


Q:

Issue with creating an intermediate pending order

I have created a custom payment module and currently it calls validateOrder() after the redirection from the payment website, and this method creates the order, sends email etc. But the issue is if user closed the payment website before it can redirect back to the PrestaShop website the order won't be created in this case. So, I want to create an order(say with "pending" status) before I redirect to the payment website and after redirection from the payment website I can simply mark the same payment as done and send mails etc.
Currently for this I was trying to call validateOrder twice, once in hookdisplayPayment(here I set the status as "pending") and once after redirection. But now after redirection I am getting "The cart cannot be loaded, or an order has already been placed using this cart". I think that's because I can't update the same order twice using the same Card Id.
Note that I want to send the emails only once, once the payment is successful. Currently for this I am using a custom payment status with 'send_email' set to 0.
What's a good workaround for this?
I would like to support versions 1.5+ and 1.6+ if that matters.

A:

A better way to do it than my first answer would be to create a override in your module of function validateOrder.
You will modify:
/** @var Order $order */
$order = new Order();

Into:
/** @var Order $order */
$order = new Order($this->currentOrder);

Then test if is loaded object, skip the part where it sets the order fields. If it's not loaded, set the order fields appropriately with the pending status.
Also test if $this->currentOrder is set where the email is sent, if it's not set skip the email part. If it's set it means the order is pending and you should change the status and send the email.
After you override the function, you can call validateOrder twice, before and after redirection.


Q:

How to scale down the size and quality of an BufferedImage?

I'm working on a project, a client-server application named 'remote desktop control'. What I need to do is take a screen capture of the client computer and send this screen capture to the server computer. I would probably need to send 3 to 5 images per second. But considering that sending BufferedImage directly will be too costly for the process, I need to reduce the size of the images.  The image quality need not to be loss less.
How can I reduce the byte size of the image? Any suggestions?

A:

You can compress it with ZIP very easily by using GZIPInputStream and its output counterpart on the other end of the socket.
Edit:
Also note that you can create delta images for transmission, you can use a "transpartent color" for example (magic pink #FF00FF) to indicate that no change was made on that part of the screen. On the other side you can draw the new image over the last one ignoring these magic pixels.
Note that if the picture already contains this color you can change the real pink pixels to #FF00FE for example. This is unnoticable.
An other option is to transmit a 1-bit mask with every image (after painting the no-change pixels to an arbitrary color. For this you can change the color which is mostly used in the picture to result in the best compression ratio (optimal huffman-coding).

A:

Vbence's solution of using a GZIPInputStream is a good suggestion. The way this is done in most commercial software - Windows Remote Desktop, VNC, etc. is that only changes to the screen-buffer are sent. So you keep a copy on the server of what the client 'sees', and with each consecutive capture you calculate what is different in terms of screen areas. Then you only send these screen areas to the client along with their top-left coords, width, height. And update the server copy of the client 'view' with just these new areas.
That will MASSIVELY reduce the amount of network data you use, while I have been typing this answer, only 400 or so pixels (20x20) are changing with each keystroke. This on a 1920x1080 screen is just 1/10,000th of the screen, so clearly worth thinking about.
The only expensive part is how you calculate the 'difference' between one frame and the next. There are plenty of libraries out there to do that cheaply, most of them very mathematical (discrete cosine transform type stuff, way over my head), but it can be done relatively cheaply.

A:

See this thread for how to encode to JPG with controllable compression/quality.  The slider on the left is used to control the level.

Ultimately it would be better to encode the images directly to a video codec that can be streamed, but I am a little hazy on the details.


Q:

Parse SendGrid JSON with PHP

I have some simple JSON data returned by the SendGrid API:
{
   "message":"error",
   "errors":[
      "some errors"
   ]
}

I can access the contents of the "message" section via:
$txt = "{\"message\":\"success\"}";
$newtxt = json_decode($txt, true);
echo $newtxt['message'];

That works okay, but I can't work out how to access the contents of the "errors" section?
Sorry, I realise this is probably a silly question.

A:

If your JSON String is this
$tst = '{
   "message":"error",
   "errors":[
      "some errors"
   ]
}';

Then all you need to so is
$j_array = json_decode($txt, true);
echo $j_array['message'];
echo $j_array['errors'][0];

A better way would be to loop over this array
foreach ($j_array['errors'] as $error ) {
    echo $error . '
';
}

Of course you dont need to convert everything to an array, you can leave it as written i.e. an object containing properties one of which is an array
$jObj = json_decode($txt);
echo $jObj->message;
echo $jObj->errors[0];

Or
foreach ($jObj->errors as $error ) {
    echo $error . '
';
}


Q:

How is Qi Energy used in Buddhist practice?

Ive seen television programmes and videos of buddhist shaolin monks who perfom incredible techniques such as breaking iron bars with their heads, impaling themselves with spears, throwing needles through glasses windows etc.
It was said that these monks create, harness and use Qi Energy which makes it possible for them to perform these techniques. I have two questions:

What is this Qi Energy?
Is it a strong and profound level of concentration like the Jhanas in Theravada Buddhism?

Thank you for your time.
Click on photos for full size

A:

"How is chi used in Buddhist practice?"
Buddha ignored the fascination people had with all this and classified it as "the five elements" knowing that even the slightest attraction to these low physical phenomena would waste people's time and detract from the many more worthwhile goals. You don't have to know anything about chi in Buddhism because in Buddhism the method of true awareness is enough to dissolve all blockages and problems that might come up.
This is why so many uneducated Buddhist monks who didn't know anything about any of the other traditions still won the prize of Enlightenment! One of them was the patriarch of the Zen school, whom other jealous disciples tried to hunt down..
In those times, monks would be all too interested in those things, at the expense of understanding one's True Mind, which is beyond body and mind... If Buddha even mentioned the word chi, there would be a million and one distracting questions popping into people's head at those times--that would probably derail people's focus entirely... which is why Gautama supposedly returned as Padmasambhava and created the Tibetan school--much much later after the heart of Buddhism was established. (Tibetan school by the way is still aligned with Buddhism but has an integrated focus on the wisdom-energies.)
Nonetheless, chi is related to different karmic habits that we have and once these energies are dissolved the personality characteristic is also transformed--and vice versa.
Buddhism aims at a much higher target than physical perfection, beyond even physical immortality, and this is why it is possible in Buddhism to go beyond the body to transform the mind at its root, attaining things that are definitely Buddhist ("non-common supermundane achievements") and other things that are beyond form but common to all spiritual schools ("common supermundane achievements").
Buddhism aims at the highest possible level: transforming the 8th consciousness, the storehouse of karmas from our endless lives... becoming a radiant actualized Buddha helping all beings win Awakening, becoming free from cycles like birth-and-death and suffering. To Buddhism, these super-powers are nothing but wasting time developing tricks, totally distracted from our human and spiritual problem. That is, unless it is for skillful means (see the parable of the burning house).
With that Buddhist warning aside, to answer your first question, there are many different types of chi, based on various organs. This falls within the realm of TCM and there are many uses to knowing such things, especially in diagnosing one's body. I would love to have an intuitive TCM doctor analyze my sitting posture--lots of constructive advice can be gained from that!
So what is chi in related to Buddhist practice and meditation? How can we make use of such learnings to motivate our Buddhist practice?
The Taoists have mapped out a timeline for what the excellent cultivators and Buddhists go through:
jing > chi > shen > emptiness >> Tao
When one practices Buddhism 100% correctly (celibacy + samatha-powered vipassana), this process happens automatically all the way to "seeing the Tao"/bodhisattvahood.
Due to one's celibacy, one has stored up jing (semen) which after 3 months of jhana eventually starts to transform into chi. One will feel less hungry and can fast for a long time. One is qualified to do the things posted in the picture. Eventually after at least a year like this, one's chi will transform to shen. For several years this process will continue, one's sleep needs will drastically reduce. After even more refined letting go, one will be at the stage of "emptiness" free from dualities and one step away from turning around and "seeing the Tao"
Also, the Taoists have fancier, more interesting names than this - I'm just summarizing.
I recommend the dense book "How to Measure and Deepen Your Spiritual Realization" for a complete understanding of this subject of energetics and where your concern on energetics absolutely must stop in order to progress and not subconsciously focus on lower things and hold yourself back from awakening the formless, nondual prajna wisdom.
Whether one is a monastic or a layman, in this day and age there is a lot of confusing bioenergetics fascination so it is important to clear up this matter for yourself because even if I say "just study Buddhism, and keep noting, all that fancy stuff is nothing they will lose it after they die"... you are still curious and vulnerable to false information--especially since you want to be able to do cool things like be free of sexual desire (when your jing is full), no longer need to ingest food (when chi is full), and no longer need to sleep (when shen is full)... at the best false information + fixation might lead to nonbeneficial/retarding practices and at the worst, a painful fiery death (I refer you to the Buddhist story of Hakuin).
2nd question: yes, it is a result of staying in that state. After achieving the 1st jhana on a mental level, one must reside in this state until the body completes transforming. After one's body and mind are in sync (this may take a few months if one achieved jhana/insight quickly), one's state will stabilize (and one can go to even higher states more easily)... and one can feel and train one's chi to do various tricks--beneficial and harmful. One can also ignore those lateral pathways and continue on the Buddhist journey.
Go here for more nondenominational info and definitions.
Also read "Master Huai-Chin Nan - Internal Martial Arts Nei-Gong" to have all your chi-related questions answered, especially related to Buddhist practice.
The dense book I mentioned earlier has excellent case studies as well on how chi manifested in different practitioners' lives.


Q:

What does "[()]" mean when called upon a numpy array?

I just came across this piece of code:
x = np.load(lc_path, allow_pickle=True)[()]

And I've never seen this pattern before: [()]. What does it do and why is this syntacticly correct?

a = np.load(lc_path, allow_pickle=True)
>>> array({'train_ppls': [1158.359413193576, 400.54333992093854, ...],
 'val_ppls': [493.0056070137404, 326.53203520368623, ...],
 'train_losses': [340.40905952453613, 675.6475067138672, ...],
 'val_losses': [217.46258735656738, 438.86770486831665, ...],
 'times': [19.488852977752686, 20.147733449935913, ...]}, dtype=object)

So I guess a is a dict wrapped in an array for some reason by the person who saved it

A:

It a way (the only way) of indexing a 0d array:
In [475]: x=np.array(21)
In [476]: x
Out[476]: array(21)
In [477]: x.shape
Out[477]: ()
In [478]: x[()]
Out[478]: 21

In effect it pulls the element out of the array.  item() is another way:
In [479]: x.item()
Out[479]: 21
In [480]: x.ndim
Out[480]: 0

In
x = np.load(lc_path, allow_pickle=True)[()]

most likely the np.save was given a non-array; and wrapped in a 0d object dtype array to save it.  This is a way of recovering that object.
In [481]: np.save('test.npy', {'a':1})
In [482]: x = np.load('test.npy', allow_pickle=True)
In [483]: x
Out[483]: array({'a': 1}, dtype=object)
In [484]: x.ndim
Out[484]: 0
In [485]: x[()]
Out[485]: {'a': 1}

In general when we index a nd array, e.g. x[1,2] we are really doing x[(1,2)], that is, using a tuple that corresponds to the number of dimensions. If x is 0d, the only tuple that works is an empty one, ().


Q:

How to jump object using arrow key in p5js?

This is my code that I tried. The ball is jumping when I pressing "up arrow key" or "space bar".The problem is that I am unable to move ball little bit forward when ball jumped.Can anybody help me please?
let jumper;

function setup() {
    createCanvas(400, 400);
    jumper = new Jumper();
}

function draw() {
    clear();
    jumper.run();

    push();
    fill(217);
    textFont('Avenir');
    textAlign(CENTER,CENTER);
    textSize(33);
    text('space bar to jump', width>>1, height*0.15);
    pop();
}

function keyPressed() {
    jumper.vel.y = -4;
    jumper.vel.x=+5;
}

A:

I set up a very basic example of what I think you might be working towards:

let jumper;

function setup() {
    createCanvas(400, 400);
    jumper = new Jumper();
}

function draw() {
    clear();
    jumper.run();

    push();
    fill(217);
    textFont('Avenir');
    textAlign(CENTER,CENTER);
    textSize(33);
    text('space bar to jump', width>>1, height*0.15);
    pop();
}

function keyPressed() {
    jumper.x+=5;
}

class Jumper {

  constructor() {
    this.x = 10;
    this.y = height/2;
  }

  run() {
    ellipse(this.x, this.y, 10, 10);
  }

}
<script src="https://cdn.jsdelivr.net/npm/p5@0.10.2/lib/p5.js"></script>

@Dishant was correct in that your code had a typo in where you did jumper.vel.x =+ 5 which is basically just setting the position of the jumper to the x position of 5. When what you want is to actually make the jumper move 5 pixels forward - in my example this done using jumper.x += 5 but you'd of course use jumper.vel.x += 5 as that code wasn't shown in your question!


Q:

How to get data from ListView in Android when I use custom adapter

I have one ListView in my android app where I get some color from database and put some number against it (basically I maintain stock for each color) which I need to save in database. For colors I use Color entity class (Stock) and I need to save it in some different entity.
My custom adapter code
public class ColorStockListViewAdapter extends ArrayAdapter<Color> {

Context context;
int resourceId;

public ColorStockListViewAdapter(Context context, int resourceId,
        List<Color> items) {
    super(context, resourceId, items);
    this.context = context;
    this.resourceId = resourceId;
}

/* private view holder class */
private class ViewHolder {
    // ImageView vehicleImageView;
    TextView colorDesc;
    SeekBar seekBar;
    EditText countText;
}

public View getView(int position, View convertView, ViewGroup parent) {
    ViewHolder holder = null;
    Color rowItem = getItem(position);

    LayoutInflater mInflater = (LayoutInflater) context
            .getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
    if (convertView == null) {
        convertView = mInflater.inflate(resourceId, null);
        holder = new ViewHolder();

        holder.colorDesc = (TextView) convertView
                .findViewById(R.id.colorCode);

        holder.seekBar = (SeekBar) convertView
                .findViewById(R.id.countSeekBar);
        holder.countText = (EditText) convertView
                .findViewById(R.id.countEditText);

        holder.seekBar.setTag(holder.countText);
        holder.countText.setTag(holder.seekBar);

        convertView.setTag(holder);
    } else {
        holder = (ViewHolder) convertView.getTag();
    }

    holder.colorDesc.setText(rowItem.getDescription());
    holder.countText.setText("0");

    return convertView;
}
}

My ListView layout is
<ListView
    android:id="@+id/colorStockList"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_below="@id/vehicleOption"
    android:divider="#b5b5b5"
    android:dividerHeight="1dp" >

and inner layout in list
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:padding="5dip" >

<TextView
    android:id="@+id/colorCode"
    android:layout_height="wrap_content"
    android:layout_width="0dp"
    android:gravity="start"
    android:layout_weight="1"
    android:textAppearance="?android:attr/textAppearanceMedium" />

<SeekBar
    android:id="@+id/countSeekBar"
    android:layout_width="0dp"
    android:layout_weight="4"
    android:layout_height="wrap_content"
    android:layout_margin="10dp"
    android:progress="0"
    android:secondaryProgress="0" />

<EditText
    android:id="@+id/countEditText"
    android:layout_height="50dp"
    android:layout_width="0dp"
    android:layout_weight="1"
    android:gravity="end"
    android:inputType="number" />

</LinearLayout>

Now I need to get values for all colors and save them on click of a button.
Now the problem is, I'm not sure how to get all data (countEditText) for each color (colorCode). I tried many ways but still not getting it. I even referred to many such questions on stackoverflow but I think my limited android knowledge didn't help me much here. just to highlight again, I'm not capturing data on row click but click of separate button.
EDIT This is the method where I'm trying to get ListView data
public void addStock(View view){

    int count = listView.getCount();

    for(int i = 0; i < count; i++){
        // I get color object here, so not sure how to get EditText view value I have in my list
        Color color = (Color) listView.getItemAtPosition(i);
    }

    for(int i = 0; i < adapter.getCount(); i++){
        // I get color object here, so not sure how to get EditText view value I have in my list
        Color color = adapter.getItem(i);
    }

    // My AsyncTask to save data.
    new StockTask().execute();
}

A:

Ok I'm finally able to get around this. Here's my updated method addStock
public void addStock(View view){

    List<Stock> stockList = new ArrayList<Stock>();
    Stock stock;

    int count = listView.getCount();

    for(int i = 0; i < count; i++){
        Color color = (Color) listView.getItemAtPosition(i);

        // Here's the critical part I was missing
        View childView = listView.getChildAt(i);
        EditText editText = (EditText) childView.findViewById(R.id.countEditText);
        String colorCount = editText.getText().toString();

        stock = new Stock();
        stock.setColorCode(color.getCode());
        stock.setCount(Integer.valueOf(colorCount));

        stockList.add(stock);
    }

    new StockTask().execute(stockList);
}


Q:

Can't extract mp3 audio from video with ffmpeg

My input is a .mp4 video file.
Try #1
ffmpeg -i pipe:0 -y -map a media/73.mp3

Error:
ffmpeg version 3.3.3 Copyright (c) 2000-2017 the FFmpeg developers
  built with Apple LLVM version 8.1.0 (clang-802.0.42)
  configuration: --prefix=/usr/local/Cellar/ffmpeg/3.3.3 --enable-shared --enable-pthreads --enable-gpl --enable-version3 --enable-hardcoded-tables --enable-avresample --cc=clang --host-cflags= --host-ldflags= --enable-libmp3lame --enable-libx264 --enable-libxvid --enable-opencl --enable-videotoolbox --disable-lzma --enable-vda
  libavutil      55. 58.100 / 55. 58.100
  libavcodec     57. 89.100 / 57. 89.100
  libavformat    57. 71.100 / 57. 71.100
  libavdevice    57.  6.100 / 57.  6.100
  libavfilter     6. 82.100 /  6. 82.100
  libavresample   3.  5.  0 /  3.  5.  0
  libswscale      4.  6.100 /  4.  6.100
  libswresample   2.  7.100 /  2.  7.100
  libpostproc    54.  5.100 / 54.  5.100
[mov,mp4,m4a,3gp,3g2,mj2 @ 0x7f977d800000] stream 1, offset 0xa8: partial file
[mov,mp4,m4a,3gp,3g2,mj2 @ 0x7f977d800000] Could not find codec parameters for stream 0 (Video: h264 (avc1 / 0x31637661), none(smpte170m/smpte170m/bt709), 320x176, 300 kb/s): unspecified pixel format
Consider increasing the value for the 'analyzeduration' and 'probesize' options
Input #0, mov,mp4,m4a,3gp,3g2,mj2, from 'pipe:0':
  Metadata:
major_brand     : mp42
minor_version   : 0
compatible_brands: mp42isomavc1
creation_time   : 2012-03-13T08:58:06.000000Z
encoder         : HandBrake 0.9.6 2012022800
  Duration: 00:00:10.03, bitrate: N/A
Stream #0:0(und): Video: h264 (avc1 / 0x31637661), none(smpte170m/smpte170m/bt709), 320x176, 300 kb/s, 25 fps, 25 tbr, 90k tbn, 180k tbc (default)
Metadata:
creation_time   : 2012-03-13T08:58:06.000000Z
  encoder         : JVT/AVC Coding
Stream #0:1(und): Audio: aac (mp4a / 0x6134706D), 48000 Hz, stereo, fltp, 160 kb/s (default)
Metadata:
  creation_time   : 2012-03-13T08:58:06.000000Z
Stream #0:2(und): Audio: aac (mp4a / 0x6134706D), 48000 Hz, stereo, fltp, 160 kb/s
Metadata:
  creation_time   : 2012-03-13T08:58:06.000000Z
Stream #0:3(und): Subtitle: mov_text (text / 0x74786574), 0 kb/s
Metadata:
  creation_time   : 2012-03-13T08:58:06.000000Z
Stream mapping:
  Stream #0:1 -> #0:0 (aac (native) -> mp3 (libmp3lame))
  Stream #0:2 -> #0:1 (aac (native) -> mp3 (libmp3lame))
[mov,mp4,m4a,3gp,3g2,mj2 @ 0x7f977d800000] stream 1, offset 0xa8: partial file
pipe:0: Invalid data found when processing input
Finishing stream 0:0 without any data written to it.
Finishing stream 0:1 without any data written to it.
[mp3 @ 0x7f977b846800] Invalid audio stream. Exactly one MP3 audio stream is required.
Could not write header for output file #0 (incorrect codec parameters ?): Invalid argument
Error initializing output stream 0:1 --
Conversion failed!

Try #2
ffmpeg -i pipe:0 -y -vn -acodec copy media/72.mp3

Error:
[...]
[mp3 @ 0x7febed835200] Invalid audio stream. Exactly one MP3 audio stream is required.
Could not write header for output file #0 (incorrect codec parameters ?): Invalid argument

Try #3
ffmpeg -i pipe:0 -y -codec:a libmp3lame -qscale:a 2 media/74.mp3

No error with ffmpeg, but the file is invalid (it's size is 334 bytes)

Try #4
ffmpeg -i pipe:0 -y -vn -acodec mp3 media/78.mp3

No error with ffmpeg, but the file is invalid (it's size is 334 bytes)

Try #5
ffmpeg -f mp4 -i pipe:0 -y media/80.mp3

No error with ffmpeg, but the file is invalid (it's size is 334 bytes)

What am I doing wrong? This seems like a fairly easy thing to do...

A:

Try this for extract .mp3:
ffmpeg -i video.mp4 -map 0:a -acodec libmp3lame out.mp3

And maybe this useful for extract .m4a:
ffmpeg -i video.mp4 -map 0:a -c copy out.m4a

A:

FFmpeg can't update metadata in WAVE files when output is written over a non-seekable protocol like a pipe. Quicktime seems to rely on metadata to determine file validity. You have to write to file or some other seekable protocol.

Please refer to this question.


Q:

How to atomically add a sequentially increasing id to a set of name/id pairs

I need to assign sequentially increasing ids to a set of names. This boils to:
A field that contains the next id to be generated: curId
A set myset containing the name/value pair, where the value is the id and the name is the name
The problem:
I need to atomically:
1. Check if myset contains 'name'. If not,
2. Generate a new id using $inc.
3. Insert the name/id pair in myset.
I can't find a way to do this in mongodb, at least without introducing race conditions. Suggestions welcome.
Update
Sample document (what it should look like).
Before adding 'c':
{

    "mySet": [
        {
            "name": 'a',
            "value" : 1
        },
        {
            "name": 'b',
            "value" : 2
        }
    ]
}

After adding 'c'. 3 is returned since that is the id assigned to 'c'.
{

    "mySet": [
        {
            "name": 'a',
            "value" : 1
        },
        {
            "name": 'b',
            "value" : 2
        },
        {
            "name": 'c',
            "value" : 3
        }
    ]
}

Trying to add 'c' again.
Nothing happens since 'c' is already present. But '3' is returned since that is the id for 'c'.

A:

Here is a simple way to do it, it involves maintaining the counter corresponding to the nextId to be used inside the document with this set, and it involves a simple find query and an update.  Starting with an empty document:
{
  "curId": 1,
  "mySet" : [  ]
}

The process that wants to add the next "name" (variable Name) does the following two operations:
var Name = "a";
var curId = db.coll.findOne({"mySet.name":{"$ne":Name}},{"_id":0,"curId":1}).curId;

/* curId variable is now 1 */
var result = db.coll.update(
    { "mySet.name" : {"$ne":Name}, "curId":curId },
    { "$push": {"mySet" : {"name":Name,"value":curId} }, "$inc":{"curId":1} }
);

if (result.nModified == 0) {
   print("We lost - someone else must have gotten there first");
}

The critical parts here are:

the find query and the update query are conditional on Name not already being in mySet array "names".
the update query also contains the previously read value of curId to ensure that no other thread has updated the record since we read it.
the curId field is only incremented on successful $push to array not on previous read of curId - until we have successfully used the curId value available, we don't want to increment it.


Q:

Who are "the least of these my brothers" in Matthew 25?

In Matthew 25:31-46, Jesus teaches that when the Son of Man comes in his glory, he will separate sheep and goats along certain lines, saying: "Truly, I say to you, as you did it to one of the least of these my brothers, you did it to me." (ESV v40) And again, "Truly, I say to you, as you did not do it to one of the least of these, you did not do it to me." (ESV, v45)
To whom is the King referring when he says "the least of these my brothers?" Does the word "these" refer to a particular group of persons present or is "the least of these" an idiom?

A:

"Brothers" in Greek
The Greek word for "brothers" here is adelphoi (Strongs G80).  This means literally "brothers".  However, it can also mean "countryman" or "followers".
The NET Bible (which uses the most current translation, taking advantage of the latest in linguistic scholarship) translates this as "brothers and sisters".  The footnote for this says of this word:

Grk “brothers,” but the Greek word may be used for “brothers and sisters” (cf. BDAG 18 s.v. ἀδελφός 1, where considerable nonbiblical evidence for the plural ἀδελφοί [adelfoi] meaning “brothers and sisters” is cited). In this context Jesus is ultimately speaking of his “followers” (whether men or women, adults or children), but the familial connotation of “brothers and sisters” is also important to retain here.

They show that Jesus is clearly speaking of his followers here even though they retain the familial connection.
Contextual Analysis
If we look at the entire context that you site (verses 31-46) we can see that there is strong support for Jesus meaning "followers" when he says brothers
The parable is talking about a King that separates out everyone on earth into two groups: the sheep and the goats.  On his right will be the sheep that will enter heaven and on his left, the goats who get sent to eternal punishment.
In verses 34-36, Jesus says that the sheep helped him out when he was in need. Verses 37-39 are the sheep asking "When did we see you?"
Jesus replies with verse 40 (as you mention in the question) saying that if you did it to the "least of my adelphoi" (brothers or followers), then you did it to me.
Following the story down further, the opposite is true with the goats.  However, when the goats ask "When did we see you?", the King (in the parable) replies:

Matthew 25:45b (NIV)
'Truly, I say to you, as you did not do it to one of the least of these, you did not do it to me.'

This response shows further support for the translation of "brothers" as followers because here the King is indicating that whoever did not help the least of the "these" (implying the "goats") did not help him.
Additional support
We can see this theme played out elsewhere, showing that these "brothers" are followers of Jesus:

Matthew 10:40-42 (NIV)
40 “Anyone who welcomes you welcomes me, and anyone who welcomes me welcomes the one who sent me. 41 Whoever welcomes a prophet as a prophet will receive a prophet’s reward, and whoever welcomes a righteous person as a righteous person will receive a righteous person’s reward. 42 And if anyone gives even a cup of cold water to one of these little ones who is my disciple, truly I tell you, that person will certainly not lose their reward.”

This is Jesus speaking to his disciples.  Clearly, there's additional support for interpreting this passage later in Matthew (and the word adelphoi) as "followers".
"Least of"
It's interesting that Jesus uses this phrase.  It seems to indicate that there is a "sorting order" or a way to organize his followers.  If this is true, this means that while any one of his followers are still considered his followers, there are some that he considers "greater" than others and one in particular that he considers the "greatest".  We can see this in opposition of the phrase "the least of".
Summary
Clearly, "the least of my brothers" is referring to the followers of God.  This parable encourages us to help out other Christians since that would be directly helping out God.

A:

In exegesis: Matthew writes to a Jewish mindset and answers unwritten questions in regard to the widely anticipated coming kingdom of God. Many Jews understood Daniel 2, 7 and 9 correctly in view of the timing of God's plan to restore the Davidic kingdom in the Messiah. The angel Gabriel tells Mary this in Luke 1:30-33 "He will receive the throne of His father (ancestor) David, and He will rule over the house of Jacob, and of His kingdom (sovereignty) there'll be no end."
What they didn't grasp was the nature of that kingdom, which would not be political like Rome, Greece, or the empires preceding them. The nature of the kingdom Jesus came to establish was universal sovereignty through a Jewish throne, but it was a kingdom of sacrificial service which reflects Matthew 6:9-11. Notice "forgive us our sins..."
Matthew 8:11-12 illustrates the loss of the kingdom by the disobedient Jews, ones who reject God's heavenly administration through the Son. They reject Jesus as the Messiah. The Jews who did receive and accept Him would receive the promised kingdom. Throughout Matthew's gospel there are distinctions of obedient and disobedient Jews. They are wheat and chaff, wise/foolish builders, fertile/unfruitful soil, wheat/tares, and sheep and goats. Matthew is not writing to translate Jesus' ministry into 21st century Western Christendom. He's writing to convince and reassure Jews that Jesus of Nazareth really was who He claimed, the anticipated Messiah of Jehovah.
So, when coming to Matthew 25 the setting shouldn't be ignored. Matthew 25:31-46 is about Jesus as the Jews inaugurated King. It will be Jesus who divides the sheep from the goats. It will be Jesus whom the sheep have served if they've "received" testimony to Jesus being their King. It will be the sheep that inherit the kingdom from Jesus. Notice, that the sheep did not know they were serving the King by serving His "brethren." Pharisees and Sadducees would obviously not have received anyone or served anyone coming in Jesus' authority. They are examples of goats. The goats don't inherit the kingdom.
Go back through the gospel. The chaff, foolish builder, unfruitful soil, and tares all refer to Jews who will not believe Jesus to be the Messiah. Now they are likened as goats, insulting. ....This passage in Matthew 25 is not teaching Christians to be benevolent. There are plenty of other passages for that. This passage is teaching Jews who will inherit the Davidic kingdom (God's kingdom) when Jesus is inaugurated. He's inaugurated at Pentecost after His ascension. Matthew 25:31-46 speaks figuratively of classifying disobedient Jews from obedient/discerning Jews. The story is parabolic nature and not futuristically literal.


Q:

Java result 1 error

I wanted to create a midi file which consist of these notes. I took this code from internet. If i can find out the problem to this i can go further. When i run this application i only get an error call "java result 1" error. What i need is after i run this there there should be a midi file generated which consist of the notes which i have passed. The complete code is available.
public class CreateSequence{
  private static final int VELOCITY = 64;
  public static void main(String[] args) {
    if (args.length != 1) {
        printUsageAndExit();
    }
    File outputFile = new File(args[0]);
    Sequence    sequence = null;
    try {
        sequence = new Sequence(Sequence.PPQ, 1);
    } catch (InvalidMidiDataException e) {
        e.printStackTrace();
        System.exit(1);
    }
    Track track = sequence.createTrack();

    // first chord: C major
    track.add(createNoteOnEvent(60, 0));
    track.add(createNoteOnEvent(64, 0));
    track.add(createNoteOnEvent(67, 0));
    track.add(createNoteOnEvent(72, 0));
    track.add(createNoteOffEvent(60, 1));
    track.add(createNoteOffEvent(64, 1));
    track.add(createNoteOffEvent(67, 1));
    track.add(createNoteOffEvent(72, 1));

    // second chord: f minor N
    track.add(createNoteOnEvent(53, 1));
    track.add(createNoteOnEvent(65, 1));
    track.add(createNoteOnEvent(68, 1));
    track.add(createNoteOnEvent(73, 1));
    track.add(createNoteOffEvent(63, 2));
    track.add(createNoteOffEvent(65, 2));
    track.add(createNoteOffEvent(68, 2));
    track.add(createNoteOffEvent(73, 2));

    // third chord: C major 6-4
    track.add(createNoteOnEvent(55, 2));
    track.add(createNoteOnEvent(64, 2));
    track.add(createNoteOnEvent(67, 2));
    track.add(createNoteOnEvent(72, 2));
    track.add(createNoteOffEvent(64, 3));
    track.add(createNoteOffEvent(72, 3));

    // forth chord: G major 7
    track.add(createNoteOnEvent(65, 3));
    track.add(createNoteOnEvent(71, 3));
    track.add(createNoteOffEvent(55, 4));
    track.add(createNoteOffEvent(65, 4));
    track.add(createNoteOffEvent(67, 4));
    track.add(createNoteOffEvent(71, 4));

    // fifth chord: C major
    track.add(createNoteOnEvent(48, 4));
    track.add(createNoteOnEvent(64, 4));
    track.add(createNoteOnEvent(67, 4));
    track.add(createNoteOnEvent(72, 4));
    track.add(createNoteOffEvent(48, 8));
    track.add(createNoteOffEvent(64, 8));
    track.add(createNoteOffEvent(67, 8));
    track.add(createNoteOffEvent(72, 8));

    //Now we just save the Sequence to the file we specified.
    //The '0' (second parameter) means saving as SMF type 0.
    //Since we have only one Track, this is actually the only option
    //(type 1 is for multiple tracks).
    try {
        MidiSystem.write(sequence, 0, outputFile);
    } catch (IOException e) {
        e.printStackTrace();
        System.exit(1);
    }
  }

  private static MidiEvent createNoteOnEvent(int nKey, long lTick) {
    return createNoteEvent(ShortMessage.NOTE_ON, nKey, VELOCITY, lTick);
  }

  private static MidiEvent createNoteOffEvent(int nKey, long lTick) {
    return createNoteEvent(ShortMessage.NOTE_OFF, nKey, 0, lTick);
  }

  private static MidiEvent createNoteEvent(int nCommand, int nKey,
                                           int nVelocity, long lTick) {
    ShortMessage message = new ShortMessage();
    try {
        message.setMessage(nCommand, 0, nKey, nVelocity); // 0 always on channel 1
    } catch (InvalidMidiDataException e) {
        e.printStackTrace();
        System.exit(1);
    }
    MidiEvent event = new MidiEvent(message, lTick);
    return event;
  }

  private static void printUsageAndExit(){
        out("usage:");
        out("java CreateSequence <midifile>");
        System.exit(1);
  }

  private static void out(String strMessage) {
    System.out.println(strMessage);
  }
}

This is the output
   usage:
   java CreateSequence <midifile>
   Java Result: 1

A:

You need to pass the output file name as an arg. It's exiting with Code 1 because it calls printUsafeAndExit() if you don't run it with the correct arg count. Try running it as:
java CreateSequence output.mid

If you have trouble passing args (can be confusing for beginners if you're using an IDE like Eclipse), just dele this check:
if (args.length != 1) {
    printUsageAndExit();
}

And hardcode the output file:
File outputFile = new File("output.mid");


Q:

firstResponder in NSViewController

I've got two classes. ManagingViewController, a subclass of NSViewController, and ViewController, a subclass auf ManagingViewController. In Viewcontroller I've got a NSTextField which I want to become the firstResponder, but I didn't manage that.
So it is nearly the same like the Chapter 29 in Hillegass' book Cocoa Programming for Mac OS X  (Download of the book's examples) except of an NSTextField which is set to firstResponder.
Can anybody point me to the correct way?

A:

You need to set the text field as the first responder by using -[NSWindow makeFirstResponder:].
Since this is an NSWindow method, it only makes sense after you’ve added the corresponding view to the window, i.e., after you’ve added the view as a subview inside the window view hierarchy. In the book’s example, this happens when you set the view as the content view of the box inside the window. For example:
- (void)displayViewController:(ManagingViewController *vc) {
    // Try to end editing
    NSWindow *w = [box window];
    …

    // Put the view in the box
    NSView *v = [vc view];
    [box setContentView:v];

    // Set the first responder
    if ([vc class] == [ViewController class]) {
        [w makeFirstResponder:[(ViewController *)vc myTextField]];
    }
}

This assumes ViewController exposes a getter method called -myTextField.
You can make this more generic by having your view controllers expose a method that returns the object that the view controller recommends as the first responder. Something like:
@interface ManagingViewController : NSViewController
…
- (NSResponder *)recommendedFirstResponder;
@end

@implementation ManagingViewController
…
- (NSResponder *)recommendedFirstResponder { return nil; }
@end

And, in your concrete subclasses of ManagingViewController, have -recommendedFirstResponder return the object that should be the window’s first responder:
@implementation ViewController
…
- (NSResponder *)recommendedFirstResponder { return myTextField; }
@end

Having done that, you can change your -displayViewController: to something like:
- (void)displayViewController:(ManagingViewController *vc) {
    // Try to end editing
    NSWindow *w = [box window];
    …

    // Put the view in the box
    NSView *v = [vc view];
    [box setContentView:v];

    // Set the first responder
    NSResponder *recommendedResponder = [vc recommendedFirstResponder];
    if (recommendedResponder) [w makeFirstResponder:recommendedResponder];
}


Q:

How can I check if something in html is set to false or true using beautifulsoup?

So I have a html file and I wanna check some values in it.
For example: data-online="false", data-channel="123breakmefree"
So I wanna check if 'data-online' is set to true or false and what channel is marked in data-channel. And if channel is something else than '123breakmefree'.
Thanks!
P.S: English is not my main language so I could not find anything on that by googling.

A:

This code shows how to load a html string, get a tag and then the attributes:
from bs4 import BeautifulSoup

html = '
test text
'

s = BeautifulSoup(html)
tag = s.find(id='my-tag')

print tag.attrs
print tag['data-online']
print tag['data-channel']


Q:

Why is my meat grinder getting clogged with sinew?

Last Christmas, I got a meat grinder and I've stared experimenting with sausage making. My previous batches have been around a pound of pork, and I noticed that it seemed to slow down as I went. Today, I pushed through five pounds of chicken thighs and pork fat, which was a huge chore -- almost immediately, it the grinding would slow, and after maybe a half pound, I needed to take the blade out and clean the sinew out of the die. I could then go back and grind maybe a half pound again, before things clogged up.
Is this normal? I can't really imagine it is, or no one would ever grind meat.
I've tried the blade both ways -- one way is definitely the correct way; the other way doesn't cut at all.
I've cut the meat into cubes about the diameter of my thumb -- definitely smaller than the augur spacing.
I know, this isn't the world's best grinder (it's a "Back to Basics" brand). Does my blade need sharpening already? Is there some basic meat grinder technique I'm missing? Is the grinder just crap?

A:

Is this normal?

Yes, it is. Sinew and other connective tissues (silverskin/fascia, ligaments) are very tough stuff; you need to remove as much as possible by hand before grinding.
Sinew and ligaments are strong, whitish strands or "cables" connecting bones to muscles and to other bones, respectively. They'll be in the same place on every piece of a particular cut of meat: a poultry drumstick has an easily-identifiable piece of sinew -- actually the "Achilles' tendon" -- heading from the fleshy part to the exposed end of the bone.
Silverskin is a connective boundary between muscles. It's a thin, clingy, and annoying sheet, translucent silvery white, that you will find on the surface, and defining the divisions of, various cuts of meat. It might make it through the grinder if your blade is nice and sharp and the piece isn't too big, but it's best to take it off (your teeth can't deal with it much better than the grinder can). You'll need a thin, sharp, narrow blade for this: a filet/boning knife, sometimes a good paring kife.
Essentially, anything that's not fat or muscle needs to be taken out before the meat goes into the grinder.
Chicken thighs have a lot of connective tissue. Some of it is hidden inside the muscle segments on the underside of the thigh; make sure you cut those open.
Depending on the particular piece of meat you have, you may end up with what seem like extremely small bits after this process. Even a nice pork shoulder can result in 1/4" or thinner pieces after the internal connective tissue is removed. This won't have any real effect on the grinding process; the only thing to watch out for is thorough and even mixing if you end up with many different sizes and are marinating/curing the meat before grinding.
You can grind without removing all the tissue (it gets frustrating sometimes), but you'll have to be prepared to stop the grinder and clean the blade and plate frequently -- the instant you notice that the meat is not coming out of the plate in clean, cohesive, and separate lines. If you see any signs of smearing or over-grinding (the grind will start to be too fine and become pink as the fat and meat combine), stop and clear the blade. Otherwise, the mixture won't emulsify properly, the fat will melt out when you cook it, and the sausage will be dry.

Does my blade need sharpening already?

It may very well, but this still won't help with sinew and ligaments.
You should treat your grinder blade the same way you treat your kitchen knives -- maintain its edge, rather than waiting for it to become completely dull. I'd say that I put my blade onto a sharpening stone every 50 lbs. or so. The nice thing is that it's extremely easy -- you are grinding all the arms of the blade at the same angle: flat. The plate also needs to be maintained by grinding the surface where it meets the blade (the edges of the holes should be sharp), but I'd say that this can be done much less freqently. The blade and the plate can both be maintained quite successfully and easily with a piece of fine (800 grit) wet-dry sandpaper slapped on a table.

A:

I initially had problems with this on my Kitchenaid grinder attachment when I did not properly tighten the ring that holds the die and cutter together. Because they weren't mating as tightly as they should have, the sinew wasn't getting sliced, and would eventually bunch up and clog things.
Assuming your grinder assembles the same way, the first thing I'd check is that you're assembling things properly and tightening things down firmly enough.
And of course, other tips about trimming as much sinew and silverskin in advance as possible are spot on.

A:

I've done a lot of grinding of wild game for over 30 years and used all kinds of grinders both electric and manual.
For manual grinders, try attaching a steering wheel from a car as this will give you more torque and make it ten times easier to grind.
On electric grinders such as the Kitchen Aid meat grinding attachment, be sure to use the coarse grinding plate first and then regrind the meat a second time with the fine grinding plate. This is much faster than stopping to remove sinew all the time and sometimes the coarser ground meat is fine if the cut of meat you are grinding is tender anyway.


Q:

How to read a UITextView paragraph by paragraph using VoiceOver?

I am writing an app for people with blindness and would like to put some instruction on its home page. The instruction is a multi-paragraph static text piece. I put it in a UITextView.
I would like blind users to be able to read the instruction paragraph by paragraph using VoiceOver. However, when users move VoiceOver focus onto the UITextView, VoiceOver always read the instruction as a whole piece. My devices are iPad 2 and iPhone 5s with iOS 7.
So, is there any way I can set up my UITextView so that VoiceOver users can read the text piece paragraph by paragraph? If that is impossible with a UITextView, what are some other options? Do I really have to use a UITableView?
Thank you!
Joe

A:

VoiceOver users, not you, determine how much text is read at once. You could override this by subclassing UITextView and implementing the UIAccessibilityContainer informal protocol. However, this would be unintuitive for VoiceOver users so I recommend you avoid it. Some VoiceOver users can listen to lots of text read extremely quickly, and it would be frustrating for them if you artificially forced the reading to stop between paragraphs.
TTTAttributedLabel, an open-source label library that supports hyperlinking, overrides these methods to make links accessible. You may wish to review the relevant source code if you decide to proceed with this implementation against my advice.


Q:

Pass anonymous multiline function as an argument to another function

Suppose there is a function that getting two functions as a parameters:
function do_until([scriptblock] $f, [scriptblock] $p, [System.TimeSpan] $timeout = (New-Timespan -Minutes 5), [System.TimeSpan] $delay = (New-Timespan -Seconds 5))
{
    $timer = [diagnostics.stopwatch]::StartNew()
    do
    {
        $f.Invoke()
        Start-Sleep $delay.Seconds
    } until ($p.Invoke() -or $timer.elapsed -ge $timeout)
}

This works:
do_until { "hi!" } { 1 -gt 2 } (New-Timespan -Seconds 10) (New-Timespan -Seconds 1)

This fails
do_until
{
    "hi!"
    "and again!"
} { 1 -gt 2 } (New-Timespan -Seconds 10) (New-Timespan -Seconds 1)

with error
At C:\c\powershell\functions.ps1:15 char:3
+ } { 1 -gt 2 } (New-Timespan -Seconds 10) (New-Timespan -Seconds 1)
+   ~
Unexpected token '{' in expression or statement.
At C:\c\powershell\functions.ps1:15 char:15
+ } { 1 -gt 2 } (New-Timespan -Seconds 10) (New-Timespan -Seconds 1)
+               ~
Unexpected token '(' in expression or statement.
At C:\c\powershell\functions.ps1:15 char:42
+ } { 1 -gt 2 } (New-Timespan -Seconds 10) (New-Timespan -Seconds 1)
+                                          ~
Unexpected token '(' in expression or statement.
    + CategoryInfo          : ParserError: (:) [], ParseException
    + FullyQualifiedErrorId : UnexpectedToken

How to pass this anonymous multiline function as an argument to do_until?

A:

PowerShell is interpreting do_until as a complete command on a line of its own. Instead:
1) Start the scriptblock on the same line as the function call (an opening { does not form a complete expression, so PowerShell will continue parsing to the following lines).
do_until {
  "hi!"
  "and again!"
} { 1 -gt 2 } (New-Timespan -Seconds 10) (New-Timespan -Seconds 1)

2) Use the ` escape character to inform PowerShell about the multi-line command.
do_until `
{
  "hi!"
  "and again!"
} { 1 -gt 2 } (New-Timespan -Seconds 10) (New-Timespan -Seconds 1)

3) Save the scriptblock to a variable before calling the function (like an opening {, PowerShell will continue parsing after an incomplete = assignment).
$action =
{
  "hi!"
  "and again!"
}

do_until $action { 1 -gt 2 } (New-Timespan -Seconds 10) (New-Timespan -Seconds 1)


Q:

boost::asio::streambuf -- linker error

I'm having trouble getting a boost program to compile.  The example I'm trying to compile is here:  http://rosettacode.org/wiki/Web_scraping#C.2B.2B
This is what happens when I try to compile:
  % g++ -Wall test.c -lboost_regex  -lboost_system -lboost_thread
    /tmp/ccJSxOji.o: In function `boost::exception_detail::error_info_injector<std::length_error>::error_info_injector(boost::exception_detail::error_info_injector<std::length_error> const&)':
    test.c:(.text._ZN5boost16exception_detail19error_info_injectorISt12length_errorEC2ERKS3_[_ZN5boost16exception_detail19error_info_injectorISt12length_errorEC5ERKS3_]+0x53): undefined reference to `std::length_error::~length_error()'
    /tmp/ccJSxOji.o: In function `boost::exception_detail::error_info_injector<std::length_error>::~error_info_injector()':
    test.c:(.text._ZN5boost16exception_detail19error_info_injectorISt12length_errorED2Ev[_ZN5boost16exception_detail19error_info_injectorISt12length_errorED5Ev]+0x2e): undefined reference to `std::length_error::~length_error()'
    collect2: ld returned 1 exit status

I think I've narrowed the problem down to this line:
boost::asio::streambuf response ;

I'm using gcc 4.6.0, linux of course:
% gcc -v
Using built-in specs.
COLLECT_GCC=gcc
COLLECT_LTO_WRAPPER=/usr/lib/gcc/i686-pc-linux-gnu/4.6.0/lto-wrapper
Target: i686-pc-linux-gnu
Configured with: /build/src/gcc-4.6-20110429/configure --prefix=/usr --libdir=/usr/lib --libexecdir=/usr/lib --mandir=/usr/share/man --infodir=/usr/share/info --with-bugurl=https://bugs.archlinux.org/ --enable-languages=c,c++,ada,fortran,go,lto,objc,obj-c++ --enable-shared --enable-threads=posix --with-system-zlib --enable-__cxa_atexit --disable-libunwind-exceptions --enable-clocale=gnu --enable-gnu-unique-object --enable-linker-build-id --with-ppl --enable-cloog-backend=isl --enable-lto --enable-gold --enable-ld=default --enable-plugin --with-plugin-ld=ld.gold --disable-multilib --disable-libstdcxx-pch --enable-checking=release
Thread model: posix
gcc version 4.6.0 20110429 (prerelease) (GCC)

Possibly related thread:
Code using boost::asio::streambuf causes segfault

A:

I hate to answer my own question, but as it turns out, I was bitten by this:  /usr/lib/libstdc++.so.6: version `GLIBCXX_3.4.15' not found
I did some more digging:
 % ldd /usr/lib/libboost_regex.so
/usr/lib/libboost_regex.so: /usr/lib/libstdc++.so.6: version `GLIBCXX_3.4.15' not found (required by /usr/lib/libboost_regex.so)
        linux-gate.so.1 =>  (0xb77b3000)
        libicuuc.so.46 => /usr/lib/libicuuc.so.46 (0xb7553000)
        libicui18n.so.46 => /usr/lib/libicui18n.so.46 (0xb7389000)
        libicudata.so.46 => /usr/lib/libicudata.so.46 (0xb650a000)
        librt.so.1 => /lib/librt.so.1 (0xb6501000)
        libstdc++.so.6 => /usr/lib/libstdc++.so.6 (0xb6412000)
        libm.so.6 => /lib/libm.so.6 (0xb63e8000)
        libgcc_s.so.1 => /usr/lib/libgcc_s.so.1 (0xb63cc000)
        libpthread.so.0 => /lib/libpthread.so.0 (0xb63b1000)
        libc.so.6 => /lib/libc.so.6 (0xb624b000)
        libdl.so.2 => /lib/libdl.so.2 (0xb6246000)
        /lib/ld-linux.so.2 (0xb77b4000)

% ldd /usr/lib/libboost_date_time.so
/usr/lib/libboost_date_time.so: /usr/lib/libstdc++.so.6: version `GLIBCXX_3.4.15' not found (required by /usr/lib/libboost_date_time.so)
        linux-gate.so.1 =>  (0xb78cf000)
        librt.so.1 => /lib/librt.so.1 (0xb788f000)
        libstdc++.so.6 => /usr/lib/libstdc++.so.6 (0xb77a1000)
        libm.so.6 => /lib/libm.so.6 (0xb7777000)
        libgcc_s.so.1 => /usr/lib/libgcc_s.so.1 (0xb775b000)
        libpthread.so.0 => /lib/libpthread.so.0 (0xb773f000)
        libc.so.6 => /lib/libc.so.6 (0xb75d9000)
        /lib/ld-linux.so.2 (0xb78d0000)

In sum, my gcc-libs were out of date.  To fix it, I did:
# pacman -Q -o /usr/lib/libstdc++.so.6
/usr/lib/libstdc++.so.6 is owned by gcc-libs 4.6.0-5

# pacman -S gcc-libs

Thanks to everyone who commented, you got me thinking in the right direction.


Q:

How to show dialog when lwjgl game crashes (java)

I am using LWJGL to make my new game.
Quick Question:
When my game crashes with something like this:

Exception in thread "main" java.lang.NullPointerException
      at engineTester.MainGameLoop.main(MainGameLoop.java:376)
  C:\Users\Kojo Ofori\AppData\Local\NetBeans\Cache\8.1\executor-snippets\run.xml:53: Java returned: 1

How do I get it to print it in dialog so that when someone runs it and it crashes they will be able to see it as a dialog that is has crashed
Hope it made sense

A:

I recommend using an UncaughtHandler to catch any exceptions that aren't handled and would actually crash the game. You weren't specific as to which version of LWJGL you are using, but if you are using LWJGL 2 it has a Sys class that lets you display an alert.
Sys.alert(Title, Message)
Unfortunately LWJGL 3 removed this class and GLFW doesn't seem to support creating message boxes at this time.
Set UncaughtHandler (First line in Main method)
Thread.setDefaultUncaughtExceptionHandler(UncaughtHandler.instance);

My UncaughtHandler class:
public class UncaughtHandler implements Thread.UncaughtExceptionHandler{
    public static UncaughtHandler instance = new UncaughtHandler();

    @Override
    public void uncaughtException(Thread t, Throwable e) {
        Sys.alert("Uncaught Exception!", e.getMessage());
    }
}

A:

You can use try ...catch and catch the exception (in a baseclass / superclass), send the user an error code that he can report and log a more detailed error. Depending on your configuration:
 ...
    try {
        /* game is playing() */
    }
    catch (MyGameException gameException) {
       logging.log(gameException.log());
       sendErrorCodeToTheUser(gameException);
    }

I had a similar discussion with a colleague that a user can report an error code 1-10 or 1-1000 while the programmers can have a detailed log where the nullpointer was.


Q:

Getting ID of newly added item into Sharepoint List from Silverlight

I am adding item into Sharepoint List from the Silverlight Application using Sharepoint' list.asmx web service. I need to know the ID of this newly created item. The UpdateListItemsCompleted's e.Result (XElement) is returned having the following XML fragment. How can I extract the ID of this item. I am not good in XLinq!
<Results xmlns="http://schemas.microsoft.com/sharepoint/soap/">
  <Result ID="1,New">
    <ErrorCode>0x00000000</ErrorCode>
    <ID />
    <z:row
        ows_ID="4"
        ows_ContentTypeId="0x010046B4975C5FD8144EBBE658917B8CB92B00EAD628BF07FAF14DA2C983B981A32E7A"
        ows_ContentType="Item" ows_Title="My Test Entry From Silverlight"
        ows_Modified="2009-12-23 14:53:55" ows_Created="2009-12-23 14:53:55"
        ows_Author="3;#Khurram Aziz" ows_Editor="3;#Khurram Aziz"
    />
  </Result>
</Results>

A:

Edit: I read the XML too hastily..
Try..
           e.Result.Elements()
                    .Where(c => c.Name.LocalName == "Result").First().Elements()
                        .Where(c => element.Name.LocalName == "row").First().Attribute("ows_ID").Value;


Q:

How to deploy angular universal app in azureDevOps app service

I'm facing a problem deploying an angular universal app in azure web service I followed this step https://stackoverflow.com/a/53616516/10979521 but a got an error says
##[error]Error: Publish using webdeploy options are supported only when using Windows agent.

I guess the issue occurs in creating an app service, in my app service settings
    (
           *publish  (code)
           *runtime stack (.NET Core 2.2)
            *Operating System (Windows)
    )
# Node.js with Angular
# Build a Node.js project that uses Angular.
# Add steps that analyze code, save build artifacts, deploy, and more:
# https://docs.microsoft.com/azure/devops/pipelines/languages/javascript

trigger:
- master

pool:
  vmImage: 'ubuntu-latest'

steps:
- task: NodeTool@0
  inputs:
    versionSpec: '10.x'
  displayName: 'Install Node.js'

- script: |
    npm install -g @angular/cli
    npm install
    npm run build:ssr
  displayName: 'build the project'

- task: CopyFiles@2
  displayName: 'Copy dist files to staging'
  inputs:
    SourceFolder: '$(Build.SourcesDirectory)/dist'

    TargetFolder: '$(Build.ArtifactStagingDirectory)/app/dist'

- task: CopyFiles@2
  displayName: 'Copy server.js to the root'
  inputs:
    SourceFolder: '$(Build.ArtifactStagingDirectory)/app/dist'

    Contents: server.js

    TargetFolder: '$(Build.ArtifactStagingDirectory)/app'

- task: DeleteFiles@1
  displayName: 'Delete the dist/server.js'
  inputs:
    SourceFolder: '$(Build.ArtifactStagingDirectory)/app/dist'

    Contents: server.js

- task: AzureRmWebAppDeployment@3
  displayName: 'Azure App Service Deploy: website'
  inputs:
    azureSubscription: 'my subscription'
    WebAppName: 'my website'
    Package: '$(Build.ArtifactStagingDirectory)/app'
    GenerateWebConfig: true
    WebConfigParameters: '-Handler iisnode -NodeStartFile server.js -appType node'
    UseWebDeploy: true
    RemoveAdditionalFilesFlag: true

A:

Edit 2 (9/3/2020)
Microsoft is moving away from release pipelines.
"Classic Release Pipelines"
https://docs.microsoft.com/en-us/azure/devops/pipelines/release/?view=azure-devops
New "Pipelines"
https://docs.microsoft.com/en-us/azure/devops/pipelines/create-first-pipeline?view=azure-devops&tabs=java%2Cyaml%2Cbrowser%2Ctfs-2018-2
Edit:
I realized after I typed this up that maybe your problem is you have "UseWebDeploy: true" and maybe you can fix your problem by setting this to false.  Below is a screenshot taken from the same task setup in a release pipeline.

I still think your best option is to remove the deploy task from your build pipeline as outlined below since build pipelines are not meant to be used in this way.  But that is up to you.
Original Answer:
Remove this part from your build pipeline:
- task: AzureRmWebAppDeployment@3
  displayName: 'Azure App Service Deploy: website'
  inputs:
    azureSubscription: 'my subscription'
    WebAppName: 'my website'
    Package: '$(Build.ArtifactStagingDirectory)/app'
    GenerateWebConfig: true
    WebConfigParameters: '-Handler iisnode -NodeStartFile server.js -appType node'
    UseWebDeploy: true
    RemoveAdditionalFilesFlag: true

Add a publish step to the end of you build.yml file.  This will allow your release pipeline to pick up the artifacts from your build.
- task: PublishBuildArtifacts@1

Setup a release pipeline to deploy your build.

Create a new pipeline
Add the artifact from your build

Then add a stage (ie Dev, QA, Production)
Select "empty job"
Edit the stage and add tasks
Add the Azure App Service task

Update the version number on the Azure App Service Deploy to version 3 (the same one you are using in your yaml - AzureRmWebAppDeployment@3).
Fill in the values in the task the same way you have it in your yaml.

The default value for the "Package or folder" option probably isn't correct.  You can use the 3 dots on the right to navigate and select the correct folder.  If you click this and see nothing then this is most likely because you haven't kicked off a build yet with the above "PublishBuildArtifact@1" change.

Keep working your way down and expanding the options to find your other configuration settings.

If you are having trouble with anything you can verify the task is setup properly by scrolling to the top of the task and clicking "View YAML".  Then you can compare to your original yaml.

Hopefully this helps.


Q:

android calculate difference between constant date and now

What is the best way to calculate the difference between 01.01.2013 and now so the result looks like 25 days 16 hours 18 minutes 43 seconds?

A:

String dateStop = "01.01.2013";
long now = System.currentTimeMillis():

SimpleDateFormat format = new SimpleDateFormat("dd.MM.yyyy");

Date d1 = null;
Date d2 = null;
try {
     d1 = new Date (now);
     d2 = format.parse(dateStop);
} catch (ParseException e) {
     e.printStackTrace();
}

long difference = d2.getTime() - d1.getTime();
long differenceBack = difference;
differenceBack = difference / 1000;
int secs = differenceBack % 60;
differenceBack /= 60;
int mins = differenceBack % 60;
differenceBack /= 60;
int hours = differenceBack % 24;

difference is in milliseconds. Then you can simply di some math to calculate days/hours/mins/seconds


Q:

Logged into AWS forums but creating new thread prompts forum signup?

I am logged into the AWS forums and have previously created an AWS Nickname posting which I used to create a post before.
Currently, the AWS forums show me as logged in, but when I try and create a new thread it says I need to pick an "AWS Nickname" and "Forum Email". If I try and put my Nickname I created before it says that Nickname is already in use, and if I try and use my email, it says that email is already registered.
How is it possible for the forums to recognize my nickname?
I have tried logging in and logging out with no success.

A:

Got this exact issue. This is what I did

Login to the AWS Management console. Make sure to switch to your main account (This didn't work for me while I was assuming a "role").
On the upper right click Support > Forums
You should automatically be logged into the forums & post as usual

You'll know it works if the welcome header looks like:
Welcome, <username> | Logout | Your Stuff | Private Messages () | Forums Help

When I was experiencing the error, the welcome header looked like this:
Welcome | Logout | Forums Help

Hope this helps!


Q:

C# MVC generic repository class with interface

How can I achieve something like the following example?
public interface IGenericRepository {
   int id { get; }
   T GetById<T>() where T : class
}

public class GenericRepository : IGenericRepository {
   //Some code here

   public T GetById<T>(int tid) where T : class
   {
       return from tbl in dataContext.GetTable<T> where tbl.id == tid select tbl;
   }
}

and I would like to use this as follows:
GenericRepository gr = new GenericRepository();
Category cat = gr.GetById<Category>(15);

Of course this code does not work since if I define T : class then the tbl.id part won't work. But of course, there should be a way to realize this.
UPDATE
Considering driis' answer, I am doing the following, but I still can't get this working:
public interface IEntity
{
    int id { get; }
}

public interface IGenericRepository : IEntity
{
    T GetById<T>(int id);
}

public class GenericRepository : IGenericRepository
{
    public T GetById<T>(int id) {
    return from tbl in dataContext.GetTable<T> where tbl.id == tid select tbl;
    }
}

At this point tbl.id works, but dataContext.GetTable<T> is giving me a error.

A:

You can constrain T to be a type that contains an ID, you will likely want an interface for it:
public interface IEntity
{
    int Id { get; }
}

Then declare your generic method as:
public IQueryable<T> GetById<T>(int tid) where T : IEntity
{
   return from tbl in dataContext.GetTable<T> where tbl.id == tid select tbl;
}

Of course you will need to implement IEntity for all entities. I am guessing you are using Linq2Sql or similar, in which case you can just make a partial class definition that includes the interface implementation.


Q:

Call a jQuery function when a button is being clicked

I'm trying to set jQuery a function on its own, and call the function when a click event triggers. Here's the code I've managed to come up with:
HTML:
<input type="text" class="form-control email_input" name='email' id="reserve_email_1" placeholder="Email">
                <span class='input-group-btn'>

                  <button type="submit" id="subscribe_1" class="btn btn-success subscribe_button">Send now</button>

</span>

JS:
$(document).ready(function(){
$('.subscribe_button').click(function(){
$.fn.Subscribe();
 });

 $.fn.Subscribe = function(){
  var email = $(this).parent().siblings('.email_input').val();
  alert(email);
}

});

But no matter what values I have in the email input, it would not pop up in the alert. I tested and don't think it's the wrong traversing order, but rather the first function failed to call the 2nd function. Any advice on why it would happen?
Best,

A:

Subscribe is a plugin method, so you need to invoke it like a jQuery plugin like(so that the method will get proper context value for this)
$('.subscribe_button').click(function () {
    $(this).Subscribe();
});

Demo: Fiddle


Q:

Is there a way to run ILASM from F# code?

I am making a compiler from (a small subset of) Java to CIL (MSIL) in F# and I was thinking about writing some unit tests for the actual compilation part. Is there a way I could run ilasm on the generated IL code and the run the .exe file from a unit test? I am using NUnit.
Concretely, is there a way to do the following?
[<Test>]
member this.TestSimpleMain () =
            let fileName = __SOURCE_DIRECTORY__.Replace("code", "examples\SimpleMain.cil")
            // run ilasm on fileName -> should produce ...\SimpleMain.exe
            let actualResult = // run ...\SimpleMain.exe file
            Assert.That(actualResult , Is.EqualTo("Program returned value 5!")))

A:

If you want to use ilasm make sure you create SimpleMain.cil in IL assembly format (text representation of CIL).
Then you should create PE (exe/dll) file from your il file.
here is an example for the nunit test with output and exit code verification:
[<Test>]
member this.TestSimpleMain() =
    // Code that creates SimpleMain.il

    let p1 = new System.Diagnostics.Process()
    p1.StartInfo.FileName <- "C:/Windows/Microsoft.NET/Framework64/v4.0.30319/ilasm.exe"
    p1.StartInfo.Arguments <- "SimpleMain.il /exe /output=SimpleMain.exe"
    p1.Start()
    p1.WaitForExit()

    let p2 = new System.Diagnostics.Process()
    p2.StartInfo.FileName <- "SimpleMain.exe"
    p2.StartInfo.RedirectStandardOutput <- true // For output verification
    p2.Start()
    p2.WaitForExit()

    let resultA = p2.ExitCode // For exit code verification
    let resultB = p2.StandardOutput.ReadToEnd() // For output verification
    Assert.That(result, Is.EqualTo(expectedResult))