Q:

Add int and Class objects

I'm trying to add a int and class together like 1 + Currency(1)
I get the error: TypeError: unsupported operand type(s) for +: 'int' and 'Currency'
If I do Currency(1) + 1 it works correctly.
Is there some way to convert the int into a class object or do I need to convert the class to an int object?
class Currency:
    "A general currency class"
    def __init__(self, kr=0, ore=0):
        "Input kr and ore, with default values 0"
        self.ore = round(ore + (kr * 100), 0)
        self.kr = int(self.ore / 100)
        kr_ore = kr + ore / 100

    def __add__(self, other):
        self, other = Currency.__check_type(self, other)
        print(type(self), type(other))

        total = self.ore + other.ore
        self.kr = int(total / 100)
        self.ore = total - self.kr * 100

        return Currency(self.kr, self.ore)

    def __check_type(self, other):
        if type(self) != Currency and type(int) != Currency:
            self = Currency(self)
            other = Currency(other)

        elif type(self) != Currency:
            print("RUNNING")
            self = Currency(self)

        elif type(other) != Currency:
            other = Currency(other)
        return self, other

    __repr__ = __str__

x = 100
y = Currency(1)
print(x+y)

A:

You almost did it, if you printed y+x it would work for your code.
__add__ is called for objects on the left side of the + operator, for right side, the dunder method is called __radd__.
class Currency:
    "A general currency class"

    def __init__(self, kr=0, ore=0):
        "Input kr and ore, with default values 0"

        self.ore = round(ore + (kr * 100), 0)
        self.kr = int(self.ore / 100)
        kr_ore = kr + ore / 100

    def __add__(self, other):
        self, other = Currency.__check_type(self, other)
        print(type(self), type(other))
        total = self.ore + other.ore
        self.kr = int(total / 100)
        self.ore = total - self.kr * 100

    def __radd__(self, other):
        self, other = Currency.__check_type(self, other)
        print(type(self), type(other))
        total = self.ore + other.ore
        self.kr = int(total / 100)
        self.ore = total - self.kr * 100
        return Currency(self.kr, self.ore)

    def __check_type(self, other):
        if type(self) != Currency and type(int) != Currency:
            self = Currency(self)
            other = Currency(other)
        elif type(self) != Currency:
            print("RUNNING")
            self = Currency(self)
        elif type(other) != Currency:
            other = Currency(other)
        return self, other

x = 100
y = Currency(1)
print(x+y)


Q:

Understanding MDX 'ALL'?

I'm new to MDX coming from the world of SQL and I am trying to understand the concept of 'ALL'. I am understanding that 'ALL' is a single member, creating a cube with low granularity as far as that dimension is concerned. Is this correct?
What are some examples of SQL that can help me reason about this concept? Of course, SQL uses tables not cubes, but I'm sure there are some similarities which can help me make the connection? Let me try to create an example.
Let's say I have a table with such a schema representing a cube with 3 dimensions:
myTable (dim1_attribute1,dim1_attribute2, dim2_attribute1,dim2_attribute2,dim2_attribute3,
dim3_attribute1,dim3_attribute2,dim3_attribute3)

What kind of SQL would give me an aggregate with 'ALL' granularity on dim3?

A:

'ALL' means that basically you are taking into account all members of that dimension - you are not slicing cube with some particular member of that dimension. In SQL query equivalent would be to omit dim3 from the where clause altogether, so you are not filtering your resulting aggregation with some particular value from dim3 but you are taking all rows into account.


Q:

Die Maus ist ein Tier, or Die Maus ist eine Tier?

I'm trying to learn German on my own, and I'm not sure if in the phrase "Die Maus ist ein/e Tier", what gives gender to ein/e is the fact that the mouse is feminine, or Tier is a neutral noun. Could anyone help me, please?

A:

The article always depends on the case and gender of the word it refers to. The first article refers to Maus (feminine, Nominativ) and the second one refers to Tier (neutral, Nominativ). So

Die Maus ist ein Tier.
The mouse is an animal.

A:

These have no relation in German. There is no such requirement in German, that these should have the same gender. Thus, "Die Maus ist ein Tier" is correct.


Q:

Conditional replacement of NaN

New to Python here.  I hope my question isn't entirely redundant - if it is, let me know and chalk it up to my inexperience with StackOverflow.
In any case, I'm working with the Titanic dataset from kaggle.com, and I'm looking to use a set of conditional statements to replace NaN 'values' throughout the Age column of the dataframe.  Ultimately, I'd like to generate results based on the following conditions:
1) if age==NaN, and Title==(X or Y or Z), generate a random number in the 0-18 range
2) if age==NaN, and Title==(A or B or C), generate a random number in the 19-80 range
Note: 'Title' is a column with the title of individual listed (i.e. Mr., Mrs., Lord, etc.)
I found a similar situation here, but I haven't been able to adapt it to my case as it doesn't approach conditionality at all.
Here is my most recent attempt (per. the replies as this update)
Attempt 1
import random

mask_young = (df.Age.isnull()) & (df.Title.isin(Title_Young))
df.loc[mask_young, 'Age'] = df.loc[mask_young, 'Age'].apply(lambda x: np.random.randint(0,18))

mask_old = (df.Age.isnull()) & (df.Title.isin(Title_Old))
df.loc[mask_old, 'Age'] = df.loc[mask_old, 'Age'].apply(lambda x: np.random.randint(18,65))

mask_all = (df.Age.isnull()) & (df.Title.isin(Title_All))
df.loc[mask_all, 'Age'] = df.loc[mask_all, 'Age'].apply(lambda x: np.random.randint(0,65))

Result is no error, but no correction to NaN values in 'Age' column

A:

You want to mask your DataFrame and then perform the operation on only the part of the DataFrame that matches your condition.
import numpy as np
import pandas as pd

mask1 = (df.Age.isnull()) & (df.Title == 'Master')
df.loc[mask1, 'Age'] = df.loc[mask1, 'Age'].apply(lambda x: np.random.randint(0,18))

If you really need the functionality of having multiple titles in a list, this can be accomplished by defining the list of titles you care about and then using isin. For example:
list1 = ['Master', 'Sir', 'Mr']
mask1 = (df.Age.isnull()) & (df.Title.isin(list1))


Q:

An identity involving the Bessel function of the first kind $J_0$

Today, computing $\int_{0}^{\pi/2}\sin^2(\sin^2 x)\,dx$, I found an interesting identity:
$$\sum_{k\geq 0}\frac{(-1)^k(4k)!}{(2k)!^3 4^k}=\cos(1)\cdot\sum_{k\geq 0}\frac{(-1)^k}{k!^2 4^k}.$$
How would you prove it?

A:

This answer is due to Giulio Francot, a friend of mine. His solution is extremely close to my original manipulations.

We have:
\begin{eqnarray*}
\int\limits_{0}^{\frac{\pi }{2}}\sin ^{2}(\sin ^{2}(x))dx
&=&\int\limits_{0}^{\frac{\pi }{2}}\frac{1-\cos (2\sin ^{2}(x))}{2}dx \\
&=&\frac{
\pi }{4}-\frac{1}{2}\int\limits_{0}^{\frac{\pi }{2}}\sum\limits_{k\geq 0}
\frac{(-1)^{k}4^{k}}{(2k)!}\sin ^{4k}(x)dx \\
&=&\frac{\pi }{4}-\frac{1}{2}\sum\limits_{k\geq 0}\frac{(-1)^{k}4^{k}}{(2k)!
}\int\limits_{0}^{\frac{\pi }{2}}\sin ^{4k}(x)dx \\
&=&\frac{\pi }{4}-\frac{1}{2}
\sum\limits_{k\geq 0}\frac{(-1)^{k}4^{k}}{(2k)!}\frac{(4k)!}{
(4^{k}(2k)!)^{2}}\frac{\pi }{2} \\
&=&\frac{\pi }{4}-\frac{\pi }{4}\sum\limits_{k\geq 0}\frac{(-1)^{k}}{
((2k)!)^{3}}\frac{(4k)!}{4^{k}}.\tag{1}
\end{eqnarray*}
On the other hand:
\begin{eqnarray*}
\int\limits_{0}^{\frac{\pi }{2}}\sin ^{2}(\sin ^{2}(x))dx
&=&\int\limits_{0}^{\frac{\pi }{2}}\frac{1-\cos (2\sin ^{2}(x))}{2}
dx=\int\limits_{0}^{\frac{\pi }{2}}\frac{1-\cos (1-\cos (2x))}{2}dx \\
&=&\frac{\pi }{4}-\int\limits_{0}^{\frac{\pi }{2}}\frac{\cos (1)\cos (\cos
(2x))}{2}dx-\int\limits_{0}^{\frac{\pi }{2}}\frac{\sin (1)\sin (\cos (2x))}{
2}dx \\
&=&\frac{\pi }{4}-\frac{\cos (1)}{2}\int\limits_{0}^{\frac{\pi }{2}}\cos
(\cos (2x))dx=\frac{\pi }{4}-\frac{\cos (1)}{4}\int\limits_{0}^{\pi }\cos
(\cos (x))dx \\
&=&\frac{\pi }{4}-\frac{\cos (1)\pi }{4}J_{0}(1).\tag{2}
\end{eqnarray*}

A:

Another approach can be this. We have $$\cos\left(x\right)J_{0}\left(x\right)=\sum_{k\geq0}\frac{\left(-1\right)^{k}}{\left(2k\right)!}x^{2k}\sum_{k\geq0}\frac{\left(-1\right)^{k}}{4^{k}k!^{2}}x^{2k}
 $$ and by Cauchy product we get $$=\sum_{k\geq0}c_{k}\left(x\right)
 $$ where $$c_{k}\left(x\right)=\left(-1\right)^{k}x^{2k}\sum_{j=0}^{k}\frac{4^{-j}}{j!^{2}\left(2k-2j\right)!}.
 $$ Now observe that $$\sum_{j=0}^{k}\frac{4^{-j}}{j!^{2}\left(2k-2j\right)!}=\frac{1}{\left(2k\right)!}\sum_{j=0}^{k}\frac{\left(2k\right)!}{j!\left(2k-2j\right)!}\frac{4^{-j}}{j!}=$$ $$=\frac{1}{\left(2k\right)!}\sum_{j=0}^{k}\frac{\left(2k\right)\left(2k-2\right)\cdots\left(2k-2j+2\right)\left(2k-1\right)\cdots\left(2k-2j+1\right)}{j!}\frac{4^{-j}}{j!}=$$ $$=\frac{1}{\left(2k\right)!}\sum_{j=0}^{\infty}\frac{k\left(k-1\right)\cdots\left(k-j+1\right)\left(k-1/2\right)\cdots\left(k-j+1/2\right)}{j!}\frac{1}{j!}=
 $$ $$=\frac{1}{\left(2k\right)!}\sum_{j=0}^{\infty}\frac{\left(-k\right)_{j}\left(-k+1/2\right)_{j}}{j!}\frac{1}{j!}=\frac{1}{\left(2k\right)!}\,_{2}F_{1}\left(-k,-k+1/2;1;1\right)
 $$ where $\left(a\right)_{j}
 $ is the Pochhammer symbol. Then, using the identity $$\,_{2}F_{1}\left(a,b;c;1\right)=\frac{\Gamma\left(c\right)\Gamma\left(c-a-b\right)}{\Gamma\left(c-a\right)\Gamma\left(c-b\right)}
 $$ we have $$\sum_{j=0}^{k}\frac{4^{-j}}{j!^{2}\left(2k-2j\right)!}=\frac{1}{\left(2k\right)!}\frac{\Gamma\left(2k+1/2\right)}{\Gamma\left(k+1\right)\Gamma\left(k+1/2\right)}=\frac{4^{k}\Gamma\left(2k+1/2\right)}{\sqrt{\pi}\left(2k\right)!^{2}}=\frac{\left(4k\right)!}{4^{k}\left(2k\right)!^{3}}
 $$ by Gamma duplication formula. So $$\cos\left(x\right)J_{0}\left(x\right)=\sum_{k\geq0}\frac{\left(-1\right)^{k}\left(4k\right)!}{4^{k}\left(2k\right)!^{3}}x^{2k}
 $$ then your identity with $x=1
 $.
P.s. I would like to thank Elajan for the inspiration.


Q:

Hive SQL: Other ways to delete rows with a similar ID

I've a table with several columns. Here's an example (with less columns):
PROTOCOL   LINE_FORMAT   SERVICE    MSISDN
c3p0       solid         cyborg     639275487638
r2r2       rounded       amech      639124512070
c3pX       etc..         etc..      639275487638
bxSer      hard          comm       639200020006

Now, MSISDN has occurred twice. Supposedly, the results should only contain one unique MSISDN, regardless of the other data - though that doesn't mean the other data aren't needed.
Here's what I tried:
SELECT max(PROTOCOL), max(LINE_FORMAT), max(NEURALITIC), max(OP_SERVICE1), max(OP_SERVICE2), max(OP_SERVICE3), max(DATESTAMP), max(APP_NAME), max(IMSI), MSISDN, max(OP_ID), max(OP_LOCATION_ID), max(ROAMER_FLAG), max(TAC), max(LOCATION_LAYER1), max(LOCATION_LAYER2), max(LOCATION_LAYER3), max(LOCATION_LAYER4), max(LOCATION_LAYER5), max(SGSN), max(GGSN), max(APN), max(WEBDOMAIN), max(PROBE_NAME), max(FILE_ID), max(RAT), max(OUT_BYTES), min(IN_BYTES), max(TRANSACTION_COUNT)
FROM june21dataloader WHERE NEURALITIC LIKE "%Application Usage%" AND WEBDOMAIN LIKE "%bpiexpressonline.com%" GROUP BY MSISDN;

Now, when I tried that, I'm pretty sure I got unique mobtels - that's because of the 20 million rows of the original, it only returned 2900 or so.
Troubling, when the projected output is at least 6k++
Something's fishy here. Is there something wrong with my query? What would happen if I drop the max()'s?
Now, my question is, what are other ways of doing this job? As far as I tried, DISTINCT doesn't seem to work on a single column only, while GROUP BY keeps on asking for all the column names (and I'm not even sure if it will produce a unique MSISDN).
Thanks.

A:

You could do something like
SELECT * FROM
    (SELECT *, RANK() OVER (PARTITION BY MSISDN ORDER BY <CreatedDateOrSomething>) AS Rank
    FROM <Your_Table>) AS SUBQUERY
WHERE Rank = 1

This will give you one entry for each MSISDN. The rest of the columns will be the data of the entry with the smallest CreatedDateOrSomething
But if the other data really doesn't matter, then why you don't just do
SELECT DISTINCT(MSISDN) FROM <Your_Table>

?


Q:

Etymology of "fixing someone's wagon"

I'm looking for the origin of the expression: "fixing someone's wagon".
As in:

Alice, with malice on her face, exclaimed "Maybe some hijinks will
  teach that scoundrel!"
Bob rolled his eyes and sarcastically responds, "Yea,
  that'll really fix his wagon!"

I've found here and here that it's basically about bringing someone their downfall, but why?
I love the phrase, but I can't figure out how "fixing someone's wagon" equated to ruining their chances of success, or bringing about their downfall, etc.? Were wagon mechanics particularly malicious?

A:

There seems to be an extended metaphor surrounding the phrase that I don't quite get. The very earliest references refer to badly behaving women, with various other references to transportation alongside the wagon bit.
Here's an early and surprising example from the 1945 Congressional Record, Vol 91, part 7, p8893  That appears to talk about spiking an election.

Now we're gettin somewhere - I'm gonna fix your wagon, copywrite 1937.

Gil Rodgers' version of the song: https://youtu.be/uYfC9yya1i0
1934 - All the Skeletons in All the Closets, by Keith Fowler, p211.


Q:

Update the field on closed opportunities

I have a requirement to update the field on closed opportunities(won/lost) without reopening the records.
Please suggest if we do have any way of achieving this task.
Thanks.

A:

Yes you can achieve this.
closed (Lost/Won) opportunity can be updated using workflow.
Create a OnDemand workflow which will update field which you wish and run this on closed opportunity.
try to see if you get field updated.
I just tried it on one of my instance for closed opportunity and I updated description field. It did updated without reopening opportunity.


Q:

Sending POST request with HTTPBuilder without waiting for a response

I have this code:
ApiConsumer(String url) {
    this.baseUrl = url
    this.httpBuilder = initializeHttpBuilder()
    this.cookies = []
}

private HTTPBuilder initializeHttpBuilder() {
    def httpBuilder = new HTTPBuilder(baseUrl)
    httpBuilder.handler.success = { HttpResponseDecorator resp, reader ->
        resp.getHeaders('Set-Cookie').each {
            String cookie = it.value.split(';')[0]
            cookies.add(cookie)
        }
        return convertPlain("${reader}")
    }
    return httpBuilder
}

public def requestXML(Method method, ContentType contentType, String url, String bodyXML) {
    httpBuilder.parser.'application/xml' = httpBuilder.parser.'text/plain'
    httpBuilder.request(method, contentType) { request ->
        uri.path = url
        body = bodyXML
        headers['Cookie'] = cookies.join(';')
    }
}

Basically, with requestXML(...) it sends a XML request to a specified URL using HTTPBuilder for Groovy.
I'm using this code (with other minor functions) to send a request to a service, and it works.
But now I want to reuse it to make a POST request to another service that responds about 30 minutes later because this WPS service runs a program and waits the end of it. How can I send this POST request without waiting for a response?
I need to setup a timeout?
I tried to remove the httpBuilder.handler.success closure with no success.
Also I cannot change the way that the WPS service handle the request.

A:

Try using the AsyncHttpBulder as described here:
Groovy AsyncHttpBulder
For example:
import groovyx.net.http.AsyncHTTPBuilder
import static groovyx.net.http.ContentType.HTML

def http = new AsyncHTTPBuilder(
            poolSize : 4,
            uri : 'http://hc.apache.org',
            contentType : HTML )

def result = http.get(path:'/') { resp, html ->
    println ' got async response!'
    return html
}

assert result instanceof java.util.concurrent.Future

while ( ! result.done ) {
   println 'waiting...'
    Thread.sleep(2000)
}

/* The Future instance contains whatever is returned from the response
   closure above; in this case the parsed HTML data: */
def html = result.get()
assert html instanceof groovy.util.slurpersupport.GPathResult


Q:

Resources suitable for a beginners' course with exponentials

I'm currently involved in developing materials for a new UK tier of examination known as Core Maths.  The course is designed for 16-18 year olds to further their mathematics education but without taking the traditional A level maths (which is seen as the prerequisite for university)
I would be grateful for any suggestions for lesson ideas or resources that cover

Exponentials growth decay in graph or otherwise
Introduction to logarithmic scales

The students taking this course are doing so to support their other academic studies.  It would appropriate therefore to assume only basic knowledge.
For my part (and to give a flavour of what I'm after) I am making a card sort activity involving the graphs of $y=2^x$, $y=3^x$ and $y=2^{-x}$ etc.  Students to compare and contrast formulating generalisations.  If you include the source I will make sure the originator is fully accredited.
I'm not gaining financially (the school I work for was selected to develop good practice).

A:

Exponential growth or decay shows up everywhere in nature:

Temperature gradients (like in a hot water flask)
Diffusion across a membrane (like in osmosis)
Radioactive decay (and use in radiometric dating)
Dampening (like of a vibrating string/pipe)
Attenuation of a signal through a medium (like visibility in water)
Uninhibited population growth (like at the start of virus epidemics)

Exponential scales include:

Loudness in decibels
Octaves and other intervals in music
Earthquake energy on the Richter scale
Amount of information in bytes in powers of 1024
Moore's 'law' (but it is going to fail soon)
Acidity/basicity on the pH scale

They also show up in useful procedures:

Binary search (guess a number, I'll tell you whether you are high or low on each try)
Decimal/binary representation (the number of symbols used compared to the value)
Linearization (of suspected power relations)

I think that's more than enough significant real-world applications.


Q:

Converting string to Numpy datetime

I'm using numpy 1.8.2 and the following code results in the error below:
import numpy as np

data = []
data.append(['2015-01-03 05:00:00', 5, 5.01])
data.append(['2015-01-04 05:00:00', 7, 7.01])
data.append(['2015-01-05 05:00:00', 8, 8.01])
data.append(['2015-01-06 05:00:00', 10, 10.01])

dt = np.dtype('M8', '<f8', '<f8')

np.array(data, dtype=dt)

produces the following output:
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call     last)
<ipython-input-24-a3d77026bff9> in <module>()
  9 dt = np.dtype('M8', '<f8', '<f8')
 10
---> 11 np.array(data, dtype=dt)

ValueError: Could not convert object to NumPy datetime

Is there something I'm doing wrong?
I'm especially confused because
np.datetime64('2015-01-06 05:00:00')

produces the expected output:
numpy.datetime64('2015-01-06T05:00:00-0500')

A:

Yes, what you're sending in the data list is actually this:
>>> data[0]
['2015-01-03 05:00:00', 5, 5.01]

But what you're testing your conversion on is this:
'2015-01-03 05:00:00'

One is a string and the other is a list. Numpy won't, to my knowledge, look inside the list. Bellow code demonstrates the differences.
data = []
data.append('2015-01-03 05:00:00')
data.append('2015-01-04 05:00:00')
data.append('2015-01-05 05:00:00')
np.array(data, dtype=dt)

#output
array(['2015-01-03T05:00:00+0100', '2015-01-04T05:00:00+0100',
       '2015-01-05T05:00:00+0100'], dtype='datetime64[s]')

The way to get your code to work would be to convert just the first element of each list and then append that to a list dates.
for i in range(len(data)):
    date = np.array(data[i][0], dtype=dt)
    data[i][0] = date

This can be done better than a for loop (it could take some time for larger lists). If you have to have such a complex array, isn't it just easier to handle it with a class, or have different multiple arrays each holding it's own data?
    >>> data
[[array(datetime.datetime(2015, 1, 3, 4, 0), dtype='datetime64[s]'), 5, 5.01],
[array(datetime.datetime(2015, 1, 4, 4, 0), dtype='datetime64[s]'), 7, 7.01],
[array(datetime.datetime(2015, 1, 5, 4, 0), dtype='datetime64[s]'), 8, 8.01],
[array(datetime.datetime(2015, 1, 6, 4, 0), dtype='datetime64[s]'), 10, 10.01]]

You started with a list of lists and you get a list of arrays. Optionally you could get an array of arrays if you also did a np.asarray(data) which won't cause an error this time.
I should also probably mention, that the np.dtype, as I saw it being used, is mostly intended to describe the array outline. I believe the idea is that you should first declare a np.dtype and then define an np.array and set its type to your np.dtype. This provides a way to describe arrays such as your own, not to implicitly convert them like you wanted. It helps np.arrays behave as dicts to help coders write a more clean cut explicit code without a lot of indices that others don't know the meaning of. Look at the tutorial example:
dt = np.dtype([('name', np.str_, 16), ('grades', np.float64, (2,))])
x = np.array([('Sarah', (8.0, 7.0)), ('John', (6.0, 7.0))], dtype=dt)
x[1]
#output:
        ('John', [6.0, 7.0])

x[1]['grades']
#output
        array([ 6.,  7.])


Q:

ASP MVC5 public readonly variable changes value when it should not

For my application (which is used to manage some data for customers), I have a public static class Util where I store data that is used on a variety of places. In this class I have the following variable:
public static readonly List<string> PUBLICSALESMANAGERS = new List<string> { "aaaaa", "bbbbb", "ccccc", "ddddd", "eeeee" };

This is a list of people that is the same in every case. Then, depending on the customer you're trying to manage, the sales manager for that customer needs to be added to the list.
In one of my controllers, I then have the following lines of code in some of the actions to do so:
List<string> salesManagers = Util.PUBLICSALESMANAGERS;
salesManagers.Insert(0, customer.SalesManager);
ViewBag.salesManagers = salesManagers;

For some reason, every time this code runs, the insert seems to be updating the Util.PUBLICSALESMANAGERS variable. Because of this, the list keeps getting longer on every request, which should not be the case.
Is there anyone who can help me with this?
Thanks in advance!
EDIT
To avoid try and avoid confusion an example of how it SHOULD work:
When I load customer x, which has sales manager "sssss". My list should now look like: "sssss", "aaaaa", "bbbbb", "ccccc", "ddddd", "eeeee".
When I then load customer y, which has sales manager "mmmmm" I want my list to look like: "mmmmm", "aaaaa", "bbbbb", "ccccc", "ddddd", "eeeee"
And so on...

A:

List(T).Insert(Int32,T) inserts an item at position specified by the first parameter. It doesn't overwrite. What you want is something like
  if (!salesManagers.Contains(customer.SalesManager))
    salesManagers.Insert(0, customer.SalesManager);

UPDATE: After clarification of the question, the way to go is to create a copy of the Util.PUBLICSALESMANAGERS list and modify that.
new List(Util.PUBLICSALESMANAGERS)


Q:

Multi dimensionnal Gaussian Mixture Model

I'm a little confused about the GMM. I need to make clusterization. Actually, I have four dimensions : speed in Km/H, mileAge in Km, acceleration in m/s^2 and braking in m/s(^2). Each of those dimensions appears to be a gaussian. But, for each of this distribution, there is only one gaussian (this is not a mixture of gaussians).
As I understand at the beginnig, because all of my dimensions seems like a gaussian, it was perfect to apply the EM algorythm on it (used by the GMM). But, looking deeper, I start to think that I need to have several gaussian for each dimension.
So my question is : When we talk about "mixture of gaussian", it means to have several gaussians in the same dimension or a mixture of dimensions that contains one gaussian ?

A:

A mixture of Gaussians can be defined as $f(x) = \sum_{i}^{N} p_{i} \exp\big(-\frac{1}{2}(x-\mu_{i})^T\Sigma_{i}^{-1}(x-\mu_{i})\big)$. So it is $N$ Gaussians. The dimension of $x$ and $\mu_{i}$ can be one or bigger than one.


Q:

What are the disadvantages of $http.useApplyAsync?

I am currently exploring $http in angularjs, and I've seen this super-amazing method: useApplyAsync which will synchronize my $http requests, and will make my app faster.
All good, but why by default angularjs is setting it to false? Are there any disadvantages of using it?
EDIT:
I also made a comparison between using useApplyAsync and not using it.
Here I used it: http://jsfiddle.net/vwnLz344/17/
Here I didn't use it: http://jsfiddle.net/vwnLz344/18/
I am unable to see the advantages of it...
What I am searching for is: The Advantages and the Disadvantages  of: useApplyAsync

A:

Probably doesn't make a huge difference with a smaller app - by the sounds of things useApplyAsync will delay processing by ~10ms but aggregates processing of responses so may be slightly faster if say multiple responses come in within that window it might allow them to share a digest cycle avoiding extra overheads.
The default behavior processes each individual response more quickly (I think synchronously) but might require more digest cycles if multiple responses are received in quick succession which might require more processing and hence be slower overall.
So short answer useApplyAsync is probably faster with many rapid requests that update a lot of data, the default behavior is probably faster with less frequent requests.
I'd guess that it's disabled by default as usually if you're firing off that many AJAX requests you probably need to rethink your API (ie provide options for consolidating the requests).
Advantages of enabling useApplyAsync
If multiple responses are received in short succession it might reduce the amount of digest cycles required
Disadvantages of enabling useApplyAsync
It may delay processing of a response by ~10ms whilst waiting to aggregate processing
Why is it disabled by default?
Delaying processing of most AJAX requests by ~10ms for a short window to attempt to process multiple responses concurrently and avoid additional digest cycles is for most use cases less desirable than the few additional digest cycles it might  save by enabling it.
The relevant docs have more info
https://docs.angularjs.org/api/ng/provider/$httpProvider#useApplyAsync

useApplyAsync([value]);
"Configure $http service to combine processing of multiple http
responses received at around the same time via $rootScope.$applyAsync.
This can result in significant performance improvement for bigger
applications that make many HTTP requests concurrently (common during
application bootstrap).
"

https://docs.angularjs.org/api/ng/type/$rootScope.Scope#$applyAsync

$applyAsync([exp]);
Schedule the invocation of $apply to occur at a later time. The actual
time difference varies across browsers, but is typically around ~10
milliseconds.

https://docs.angularjs.org/api/ng/type/$rootScope.Scope#$apply

$apply([exp]);
$apply() is used to execute an expression in angular from outside of the angular framework. (For example from browser DOM events, setTimeout, XHR or third party libraries). Because we are calling into the angular framework we need to perform proper scope life cycle of exception handling, executing watches.


Q:

Block level elements overlaying eachother

With some help I put together the "about_us" section in the following code and it functions exactly as I want it to (ignore the misbehaving text, works fine in the full project). The problem I have is that any object I try to place below the "about_us" section places itself below the first row only, rather than the whole block.
I've given each section a "block" description which, as far as I know, should put them one below the other, leading me to believe I've got something wrong rather than missed something out. Hopefully you can help me identify it. Thanks

.about_us {
 max-width: 1600px;
 min-width: 800px;
 height: 370px;
 margin: 0 auto;
 display: block;
}
.about_us_container {
 display: block;
 width: 100%;
 height: 370px;
}
.about_us_image_clip, .about_us_background {
 display: table-cell;
 width: 50%;
 height: 370px;
 max-height: 370px;
 overflow: hidden;
}
.about_us_img1 {
 background-repeat: no-repeat;
 background-position: center !important;
 background: url(https://picsum.photos/2000/2000);
 background-size: cover;
}
.about_us_img2 {
 background-repeat: no-repeat;
 background-position: center !important;
 background: url(https://picsum.photos/2000/2000);
 background-size: cover;
}
.about_us_img3 {
 background-repeat: no-repeat;
 background-position: center !important;
 background: url(https://picsum.photos/2000/2000);
 background-size: cover;
}
.about_us_heading {
 font-size: 50px;
 font-family: "alexa-std";
 font-style: normal;
 font-weight: 400;
 margin: 4% 4% 0%;
 color: floralwhite;
}
.about_us_description {
 font-size: 20px;
 font-family: alice;
 font-style: normal;
 font-weight: 400;
 margin: 2% 6%;
 text-indent: 40px;
 color: floralwhite;
}
.centre {
 display: block;
 max-width: 1600px;
 margin: auto;
}
.centre img {
 max-width: 1000px;
 width: 100%;
 height: auto;
}

Heading One

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla luctus, dolor in ultricies accumsan, sapien ligula faucibus orci, sed ullamcorper massa libero hendrerit elit. Proin egestas ac augue vitae dapibus. Phasellus quis magna arcu. Curabitur suscipit nulla sit amet leo rutrum, ac bibendum eros gravida. Nunc consectetur elit et est pretium fringilla. Maecenas sed imperdiet orci. Duis bibendum a erat nec dignissim. Aliquam eu libero sit amet nisi ultrices eleifend. Quisque auctor lectus non mi blandit sagittis. Nam gravida mauris augue, sed elementum nulla laoreet facilisis. Ut eleifend bibendum neque et mattis. Vivamus consequat iaculis malesuada. Integer sed aliquet mi.

Heading Two

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla luctus, dolor in ultricies accumsan, sapien ligula faucibus orci, sed ullamcorper massa libero hendrerit elit. Proin egestas ac augue vitae dapibus. Phasellus quis magna arcu. Curabitur suscipit nulla sit amet leo rutrum, ac bibendum eros gravida. Nunc consectetur elit et est pretium fringilla. Maecenas sed imperdiet orci. Duis bibendum a erat nec dignissim. Aliquam eu libero sit amet nisi ultrices eleifend. Quisque auctor lectus non mi blandit sagittis. Nam gravida mauris augue, sed elementum nulla laoreet facilisis. Ut eleifend bibendum neque et mattis. Vivamus consequat iaculis malesuada. Integer sed aliquet mi.

Heading Three

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla luctus, dolor in ultricies accumsan, sapien ligula faucibus orci, sed ullamcorper massa libero hendrerit elit. Proin egestas ac augue vitae dapibus. Phasellus quis magna arcu. Curabitur suscipit nulla sit amet leo rutrum, ac bibendum eros gravida. Nunc consectetur elit et est pretium fringilla. Maecenas sed imperdiet orci. Duis bibendum a erat nec dignissim. Aliquam eu libero sit amet nisi ultrices eleifend. Quisque auctor lectus non mi blandit sagittis. Nam gravida mauris augue, sed elementum nulla laoreet facilisis. Ut eleifend bibendum neque et mattis. Vivamus consequat iaculis malesuada. Integer sed aliquet mi.

A:

Your height settings for the classes .about_us and about_us_container were forcing the images to overlap. I just removed these and the results should be closer to what you had in mind.

.about_us {
  max-width: 1600px;
  min-width: 800px;
  margin: 0 auto;
  display: block;
}

.about_us_container {
  display: block;
  width: 100%;
}

.about_us_image_clip,
.about_us_background {
  display: table-cell;
  width: 50%;
  height: 370px;
  max-height: 370px;
  overflow: hidden;
}

.about_us_img1 {
  background-repeat: no-repeat;
  background-position: center !important;
  background: url(https://picsum.photos/2000/2000);
  background-size: cover;
}

.about_us_img2 {
  background-repeat: no-repeat;
  background-position: center !important;
  background: url(https://picsum.photos/2000/2000);
  background-size: cover;
}

.about_us_img3 {
  background-repeat: no-repeat;
  background-position: center !important;
  background: url(https://picsum.photos/2000/2000);
  background-size: cover;
}

.about_us_heading {
  font-size: 50px;
  font-family: "alexa-std";
  font-style: normal;
  font-weight: 400;
  margin: 4% 4% 0%;
  color: floralwhite;
}

.about_us_description {
  font-size: 20px;
  font-family: alice;
  font-style: normal;
  font-weight: 400;
  margin: 2% 6%;
  text-indent: 40px;
  color: floralwhite;
}

.centre {
  display: block;
  max-width: 1600px;
  margin: auto;
}

.centre img {
  max-width: 1000px;
  width: 100%;
  height: auto;
}

Heading One

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla luctus, dolor in ultricies accumsan, sapien ligula faucibus orci, sed ullamcorper massa libero hendrerit elit. Proin egestas ac augue vitae dapibus. Phasellus quis magna arcu. Curabitur
        suscipit nulla sit amet leo rutrum, ac bibendum eros gravida. Nunc consectetur elit et est pretium fringilla. Maecenas sed imperdiet orci. Duis bibendum a erat nec dignissim. Aliquam eu libero sit amet nisi ultrices eleifend. Quisque auctor lectus
        non mi blandit sagittis. Nam gravida mauris augue, sed elementum nulla laoreet facilisis. Ut eleifend bibendum neque et mattis. Vivamus consequat iaculis malesuada. Integer sed aliquet mi.

Heading Two

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla luctus, dolor in ultricies accumsan, sapien ligula faucibus orci, sed ullamcorper massa libero hendrerit elit. Proin egestas ac augue vitae dapibus. Phasellus quis magna arcu. Curabitur
        suscipit nulla sit amet leo rutrum, ac bibendum eros gravida. Nunc consectetur elit et est pretium fringilla. Maecenas sed imperdiet orci. Duis bibendum a erat nec dignissim. Aliquam eu libero sit amet nisi ultrices eleifend. Quisque auctor lectus
        non mi blandit sagittis. Nam gravida mauris augue, sed elementum nulla laoreet facilisis. Ut eleifend bibendum neque et mattis. Vivamus consequat iaculis malesuada. Integer sed aliquet mi.

Heading Three

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla luctus, dolor in ultricies accumsan, sapien ligula faucibus orci, sed ullamcorper massa libero hendrerit elit. Proin egestas ac augue vitae dapibus. Phasellus quis magna arcu. Curabitur
        suscipit nulla sit amet leo rutrum, ac bibendum eros gravida. Nunc consectetur elit et est pretium fringilla. Maecenas sed imperdiet orci. Duis bibendum a erat nec dignissim. Aliquam eu libero sit amet nisi ultrices eleifend. Quisque auctor lectus
        non mi blandit sagittis. Nam gravida mauris augue, sed elementum nulla laoreet facilisis. Ut eleifend bibendum neque et mattis. Vivamus consequat iaculis malesuada. Integer sed aliquet mi.


Q:

Indexing crashes on custom tokenizer

We are building a Solr plug-in to link our proprietary engine. The intended use is replacing the standard tokenizer altogether. (This is the background: Hybrid search and indexing: words and token metadata in Solr)
When trying to index a test document in the Solr Admin:
id,title
12345,A test title

I am getting an exception where, I suppose, my tokenizer is kicking in.
The configuration changes (schema.xml) are:
    <fieldType name="text_general" class="solr.TextField" positionIncrementGap="100">
      <analyzer type="index">
        <tokenizer class="com.linguasys.carabao.ViaWebTokenizerFactory" url="http://blahblah/carabao/?wsdl"/>
        <filter class="solr.StopFilterFactory" ignoreCase="true" words="stopwords.txt" />
         <filter class="solr.LowerCaseFilterFactory"/>
      </analyzer>
<!--
     <analyzer type="query">
        <tokenizer class="com.linguasys.carabao.ViaWebTokenizerFactory"/>
        <filter class="solr.StopFilterFactory" ignoreCase="true" words="stopwords.txt" />
         <filter class="solr.LowerCaseFilterFactory"/>
      </analyzer>
     <analyzer type="index">
        <tokenizer class="solr.StandardTokenizerFactory"/>
        <filter class="solr.StopFilterFactory" ignoreCase="true" words="stopwords.txt" />
         <filter class="solr.LowerCaseFilterFactory"/>
      </analyzer>
      <analyzer type="query">
        <tokenizer class="solr.StandardTokenizerFactory"/>
        <filter class="solr.StopFilterFactory" ignoreCase="true" words="stopwords.txt" />
        <filter class="solr.SynonymFilterFactory" synonyms="synonyms.txt" ignoreCase="true" expand="true"/>
        <filter class="solr.LowerCaseFilterFactory"/>
      </analyzer>
-->
    </fieldType>
    <fieldType name="family_id_space_delimited_list" class="solr.TextField" positionIncrementGap="100">
          <analyzer type="index">
            <tokenizer class="com.linguasys.carabao.ViaWebTokenizerFactory" url="http://blahblah/carabao/?wsdl"/>
            <!--
            <filter class="com.linguasys.carabao.FamilyIDFilterFactory" />
            -->
          </analyzer>
    </fieldType>

    <fieldType name="role_space_delimited_list" class="solr.TextField" positionIncrementGap="100">
          <analyzer type="index">
            <tokenizer class="com.linguasys.carabao.ViaWebTokenizerFactory" url="http://blahblah/carabao/?wsdl"/>
            <!--
            <filter class="com.linguasys.carabao.RoleFilterFactory" />
            -->
          </analyzer>
    </fieldType>

The web service itself works. (The filters are commented out because they were crashing with some kind of type mismatch error, but that's for later.)
The exception is below. It's not just "what am doing wrong", it's "where do I get more info?"
org.apache.solr.common.SolrException: Exception writing document id 12345 to the index; possible analysis error.
  at org.apache.solr.update.DirectUpdateHandler2.addDoc(DirectUpdateHandler2.java:168)
  at org.apache.solr.update.processor.RunUpdateProcessor.processAdd(RunUpdateProcessorFactory.java:69)
  at org.apache.solr.update.processor.UpdateRequestProcessor.processAdd(UpdateRequestProcessor.java:51)
  at org.apache.solr.update.processor.DistributedUpdateProcessor.doLocalAdd(DistributedUpdateProcessor.java:870)
  at org.apache.solr.update.processor.DistributedUpdateProcessor.versionAdd(DistributedUpdateProcessor.java:1024)
  at org.apache.solr.update.processor.DistributedUpdateProcessor.processAdd(DistributedUpdateProcessor.java:693)
  at org.apache.solr.update.processor.LogUpdateProcessor.processAdd(LogUpdateProcessorFactory.java:100)
  at org.apache.solr.handler.loader.CSVLoaderBase.doAdd(CSVLoaderBase.java:395)
  at org.apache.solr.handler.loader.SingleThreadedCSVLoader.addDoc(CSVLoader.java:44)
  at org.apache.solr.handler.loader.CSVLoaderBase.load(CSVLoaderBase.java:364)
  at org.apache.solr.handler.loader.CSVLoader.load(CSVLoader.java:31)
  at org.apache.solr.handler.UpdateRequestHandler$1.load(UpdateRequestHandler.java:92)
  at org.apache.solr.handler.ContentStreamHandlerBase.handleRequestBody(ContentStreamHandlerBase.java:74)
  at org.apache.solr.handler.RequestHandlerBase.handleRequest(RequestHandlerBase.java:135)
  at org.apache.solr.core.SolrCore.execute(SolrCore.java:1962)
  at org.apache.solr.servlet.SolrDispatchFilter.execute(SolrDispatchFilter.java:777)
  at org.apache.solr.servlet.SolrDispatchFilter.doFilter(SolrDispatchFilter.java:418)
  at org.apache.solr.servlet.SolrDispatchFilter.doFilter(SolrDispatchFilter.java:207)
  at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
  at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
  at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:219)
  at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
  at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:136)
  at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
  at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:610)
  at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
  at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:526)
  at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1078)
  at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:655)
  at org.apache.coyote.http11.Http11NioProtocol$Http11ConnectionHandler.process(Http11NioProtocol.java:222)
  at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1566)
  at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1523)
  at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
  at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
  at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
  at java.lang.Thread.run(Unknown Source)
Caused by: java.lang.IllegalArgumentException: input AttributeSource must not be null
  at org.apache.lucene.util.AttributeSource.<init>(AttributeSource.java:94)
  at org.apache.lucene.analysis.TokenStream.<init>(TokenStream.java:106)
  at org.apache.lucene.analysis.TokenFilter.<init>(TokenFilter.java:33)
  at org.apache.lucene.analysis.util.FilteringTokenFilter.<init>(FilteringTokenFilter.java:70)
  at org.apache.lucene.analysis.core.StopFilter.<init>(StopFilter.java:60)
  at org.apache.lucene.analysis.core.StopFilterFactory.create(StopFilterFactory.java:127)
  at org.apache.solr.analysis.TokenizerChain.createComponents(TokenizerChain.java:67)
  at org.apache.lucene.analysis.AnalyzerWrapper.createComponents(AnalyzerWrapper.java:102)
  at org.apache.lucene.analysis.Analyzer.tokenStream(Analyzer.java:180)
  at org.apache.lucene.document.Field.tokenStream(Field.java:554)
  at org.apache.lucene.index.DefaultIndexingChain$PerField.invert(DefaultIndexingChain.java:597)
  at org.apache.lucene.index.DefaultIndexingChain.processField(DefaultIndexingChain.java:342)
  at org.apache.lucene.index.DefaultIndexingChain.processDocument(DefaultIndexingChain.java:301)
  at org.apache.lucene.index.DocumentsWriterPerThread.updateDocument(DocumentsWriterPerThread.java:222)
  at org.apache.lucene.index.DocumentsWriter.updateDocument(DocumentsWriter.java:450)
  at org.apache.lucene.index.IndexWriter.updateDocument(IndexWriter.java:1507)
  at org.apache.solr.update.DirectUpdateHandler2.addDoc0(DirectUpdateHandler2.java:240)
  at org.apache.solr.update.DirectUpdateHandler2.addDoc(DirectUpdateHandler2.java:164)
  ... 35 more
",

A:

You need to verify what happens when yourTokenizer.create(java.io.Reader reader) is invoked. From the stack trace it looks like this method is returning null, and this value is propagated all the way up to AttributeSource.<init>(AttributeSource.java:94). At this point returning null is illegal hence the exception.
The best way for you to find out what's going on is to enable debugger and stop at the above mentioned line.


Q:

Dracut-Kernel update required but won't when running Yum on Centos 6.6

I'm a fair newbie when it comes to Linux, but I'm having problems updating a small Centos 6.6 box that's been working fine and updating previously.
When running yum update I get the error below. I've tried running yum -clean all as per another post on a similar issue but that hasn't helped.
--> Processing Dependency: dracut-kernel >= 004-388.el6 for package: kernel-2.6.32-573.1.1.el6.x86_64
--> Finished Dependency Resolution
Error: Package: kernel-2.6.32-573.1.1.el6.x86_64 (updates)
           Requires: dracut-kernel >= 004-388.el6
           Installed: dracut-kernel-004-256.el6.noarch (@anaconda-CentOS-201112091719.x86_64/6.2)
               dracut-kernel = 004-256.el6
 You could try using --skip-broken to work around the problem
 You could try running: rpm -Va --nofiles --nodigest

A:

Yum clean had been tried (as detailed in my original post) but didn't help.
I eventually found a line exclude=dracut in yum.conf which is bizarre as I certainly didn't put it there and only I have access to the machine.  I presume something has automatically added it for some reason, but problem solved now anyway.


Q:

Flutter - Base64 class not found

I have a little doubt that maybe you can help me. The problem is the following:
I'm creating an entity(Product) in Flutter with local data stored in a json.The entity has three images,
which I converted from file to Base64 and put them in the json ...
the json grew quite a lot for that reason, but I wanted to reproduce as best as possible
the scenario where the application should react once I use a BD SQlite that contains images stored in Base64.
As you can see in some examples it is better to declare the attributes where I will save the images as Uint8List
and then with the method : Image.memory(product.mainImage) would get the image. But when I try to call the Base64
class I don't find it and when I put the import supposedly where the class is, the VSCode tells me that "import"
 is not used ... and suggests I remove it. Thank you for your attention and I hope you can help me.
My Json
{
 "products" : [
 {
  "id" : 1,
  "name":"Perfumes y aseo personal",
  "description" : "Perfumes y aseo personal",
  "mainImage": "/9j/4AAQSkZJRgABAQEAYABgAAD....",
  "firstImage": "/9j/4AAQSkZJRgABAQAAAQABA...",
  "secondImage": "/9j/4AAQSkZJRgABAQEAYABgA..."
 },
 .....

My Code
import 'dart:async';
import 'dart:typed_data';

class Product {

 int id;
 String name;
 String description;
 Uint8List mainImage;
 Uint8List firstImage;
 Uint8List secondImage;

 Product({this.id,this.name,this.description,this.mainImage,this.firstImage,this.secondImage});

 Product.fromMap(Map<String,dynamic> map)
 :id = map["id"],
  name = map["name"],
  description = map["description"],
  mainImage = No found -> Base64.decode(map["main_image"]),
  firstImage = No found -> Base64.decode(map["first_image"]),
  secondImage = No found -> Base64.decode(map["second_image"]);

}

A:

You have to import dart:convert and use base64 instead of Base64.


Q:

Sorting a List> Uppercase and Lowercase

var parameters = new List<KeyValuePair<string, string>>();
parameters.Add(new KeyValuePair<string, string>("AC", "123"));
parameters.Add(new KeyValuePair<string, string>("Ab", "123"));
parameters.Add(new KeyValuePair<string, string>("Db", "123"));
parameters.Add(new KeyValuePair<string, string>("CD", "123"));

var sortParameters = parameters.OrderBy(x => x.Key).ToList();

this is my source,
Result is
Ab
AC
CD
Db

but I need result
AC
Ab
CD
Db

sort by Uppercase and Lowercase.
How can I fix it.

A:

Here is the simple solution.
SortedDictionary<string, string> parameters = new SortedDictionary<string, string>(StringComparer.Ordinal);
        parameters.Add("AC", "123");
        parameters.Add("Ab", "123");
        parameters.Add("Db", "123");
        parameters.Add("CD", "123");


Q:

Merge tags software and software-rec?

There are now questions tagged software and software-rec. All software questions look like they're software recommendations and should be tagged software-rec for compatibility with Super User. I'm not sure whether software should be a synonym of software-rec or if it has some independent legitimate use here (in which case the questions should be retagged).

A:

All the software posts do seem to be recommendations, except for List installed packages in Fedora. I dropped the tag from that one and merged software → software-rec:

updating post history, 8 rows affected
  updating posts, 7 rows affected
  updating PostTags associations, 7 rows affected
  removing/renaming old tag, 1 rows affected
  updating count for master tag, 1 rows affected
  merge of [software-rec] and [software] complete!

I'm not sure if it should be a synonym or not, so I didn't make one for now


Q:

Testing breeze application

I am doing an application with durandal, breeze, and knockout. I have started to implement some test. The first problem that I have had is to decide what I should test and what not. I know that I should test everything, but it is not always possible in a little company.
My second problem is how I can test my calls to the server. I have seen some information in the breeze page about testing. Also I have seen the DocCode example. But I would like to know more opinions about how I can do that.
My questions are:

What do I should test in the breeze calls?
I would like to test this, emulating the backend. Is it possible? Any example?
Any advice or comment would be great

A:

Wow ... that's a big question!
There's is a little on this subject in the documentation. Not nearly enough to be sure.
I'm guessing that you are fairly new to JavaScript testing. If you've seen DocCode, you know that we use QUnit around here. Many prefer Jasmine, Mocha or something else; I can only speak to QUnit.
First step is learn QUnit. It's not hard. QUnit's own intro is good. I like Ben Alhman's slide deck.
Next I'd practice with small tests of your business logic that does NOT go over the wire. Could be any interesting logic in a ViewModel or perhaps some calculated property in a model (entity) object.
You can test a VM's interaction with a "DataContext" quite easily without going over the wire.  Create a "FakeDataContext" and inject that into your tests instead of the real one. Alternatively you could "monkey patch" the real "DataContext" in strategic places that turn it into a fake.
When faking the DataContext, I find it useful to leverage Breeze's ability to confine queries to the local cache. The local cache serves as an in-memory surrogate for data that would otherwise have been retrieved from the server.
This can be as simple as setting the FetchStrategy of the manager's default QueryOptions ... perhaps like this

var queryOptions = new QueryOptions({
    mergeStrategy: MergeStrategy.PreserveChanges,
    fetchStrategy: FetchStrategy.FromCache
});

var entityManager = new EntityManager({
    serviceName: "yourEndpoint",
    queryOptions: queryOptions
});

Now your queries will all be directed to the cache (unless they have an explicit QueryStrategy of their own).
Now make it useful by populating the cache with test data. There are numerous examples of faked entities in DocCode. Here's an example of a faked Customer:

   var testCustomer = manager.createEntity('Customer', {
       // test values
       CustomerID: testCustomerID,
       CompanyName: testCustomerName,
       ...
    }, breeze.EntityState.Unchanged); // as if fetched from the database

If I need the same test data repeatedly, I write a "Data Mother" that populates an EntityManager with test data for me.
I can do a lot of testing this way without ever hitting the server. The whole time I'm working with the Breeze entities in JavaScript ... much as I do in production code. I don't have to learn a mocking library or inject another tool.
Another approach - harder, lower level, but more powerful - is to replace the Breeze default AJAX adapter with a fake that returns test JSON values as if they had come from the server. You can use a tool like Fiddler to make fake JSON from actual payload snapshots. You can also use this trick for simulating server-side save behavior.
Update 3 May 2013
The DocCode Sample includes a new TestAjaxAdapter for simulating server responses as I just described. Check out the testAjaxAdapter.js and see how to use it in testAjaxAdapterTests.js.  This particular version of DocCode is only on GitHub right now but it will be published officially in the release immediately after v.1.3.2.
... end of update; back to original post ...
Does faking the JSON stream within your fake AJAX adapter seem like too much of a PITA?
Break out your mad Breeze skills and write a custom JsonResultsAdapter to create those fakes. Have your fake AJAX adapter return an empty array for every query request. Then you can do anything you want in the extractData and visitNode methods of your JsonResultsAdapter.
I trust it is obvious that you can fake your server-side controller too. Of course your tests will still make trips "over the wire" to reach that controller.
Hope these clues are sufficient to get you headed in a satisfactory direction.
Update 30 April 2013
Breeze will need metadata to do its thing. Your metadata comes from the server. Calling the server for metadata would seem to defeat the purpose of running tests entirely disconnected.
So true. Now I'm not a stickler on this point. I don't mind hitting the server for metadata at the top of a test module ... exactly once ... and then running the rest of my tests without going to the server for metadata. But if you're a purist or you just don't want to do that, you can write the server-side metadata to a JavaScript file on the server and load that script statically on your test runner's HTML page just like any other script.
For an example of this technique, look at App_Data/WriteMetadataScriptFiles.cs which generates a JavaScript file for the Northwind model in the forthcoming (later this week) v.1.3.2 DocCode sample. The DocCode tests load JavaScript files dynamically with require.js. The metadataTests.js test file shows how to load the generated northwindMetadata.js with require. You don't have to be that clever if you're not using require.js.
Note to self: write some samples illustrating these techniques.


Q:

Padding Image to middle of text and push down all inline elements

I am trying to lower the image to the middle of text inside of anchor element

testttttt

as you can see the Image has style="padding-top:5px;" but instead of lowering the image only, it's pushing the text too.
I can't use float because its suppose to work on email clients.
Thanks for any help
Baaroz

A:

Apply vertical-align: middle; to your image...

    testttttt

fiddle


Q:

What is a reasonable approach to deal with other Arqade users that seem to be ratting on you?

What should I do if I believe users are just saying things to make me look bad? This happened with NoneOfYourBuisness and now it's happening with me. I don't want to delete my account because I want to help people. What should I do?
I'm done.

A:

I'll be blunt: I've noticed a pattern with your contributions, and I don't like what I see.  You tend to post several questions and answers within a very small period of time.  This means your overall quantity is high, but your average quality is incredibly low.  If the serial downvoting script is getting triggered because a single user is posting such quantity of low quality contributions in a short period of time, I'm of the opinion that we, as a community, need to do something.  My view is that the problem is your contributions.
You also like to answer bounty questions with answers that don't source anything, and very often turn out to be wrong.  That tells me you're not here to help, but to gain rep.  This is not the focus you should have, as rep will happen organically with high quality contributions.  It will come even faster, actually, than just flooding the site with lots of low quality questions and answers.

I've taken the liberty of going through a few of your contributions to give some critique on them:
What are the rules of spawning zombie pigmen from nether portals? +1/-5
I honestly have no idea if this answer is correct or not; I haven't voted on it at all.  I've tried to point you in the right direction, but you seem to focus more on appeasing the commenters than providing correct information.
You then deleted it and re-posted it, which is exactly the wrong thing to do.  Your duplicate answer I did downvote, because you didn't re-post it to make it better.  You reposted it to get rid of the downvotes already on it.  That's a straightforward abuse of the system, and a classic example of bounty hunting.
How do I pick up an Ectoplasmer in Runescape +0/-0
This one's kinda borderline.  You've shown what you've tried, so that's good.  What's bad is that you've repeated the title in the body, and without that, your question is a one-liner.  We like a little more context and effort shown than just that.  It doesn't need to be much, but if your entire question can fit into a single line, that's usually a good indicator that you need to flesh it out a little more.
What are the actual names of the stages in Centipede? +3/-5
This one I did downvote, because I see no usefulness at all to it.  Add in the lack of effort prior to asking, and we have the reason why this is at a negative score.  Doing a little bit of research before asking would've prevented this.
Why is my level decreasing during inactivity? +1/0
This one's alright.  It displays a misunderstanding of how the system works, which gets resolved in the answer.  We specialize in ensuring people get their facts straight when they misunderstand them.  You could flesh this out a bit more, but adding more details would've probably indicated that what you think is happening, wasn't.
Is it possible to fire a lock-on Rocket Launcher in “Dumbfire” mode? +4/-12
This one is out and out wrong.  You did barely any research before answering, and didn't provide a source for your information at all.  Most likely because I believe you didn't actually do any.  If anything, this answer should be deleted.
How can I easily select an enemy colony with a large space station in orbit? (10K only)
You answered this question with zero research.  You don't play the game at all, as the answer makes rather obvious.  This, too, was a case of bounty hunting.

For the most part, you ARE gaining rep, in spite of your contributions.  If you want to be a valued member of the community, try to follow these steps:

Put more effort into your questions.  They should be more than one line.  They should tell us what you tried.  They should not be easily Googled.
Put a lot more effort into your answers.  When possible, include a link to where you pulled it from.  If you tested it in game, tell us how you tested it.
Don't answer questions of games you don't play.  If you do, try to put more than five minutes of research into doing so.
Focus on helping people with high quality contributions.  A few paragraphs would not be amiss.  Add in some sources if you can.

All of this boils down to investing effort into your contributions.  We WANT users that spend time making the best answers they can.  We DON'T want users that answer stuff solely to gain rep.

A:

I'm Grace Note, a Stack Exchange Community Manager. I'd like to address the portions of this question that have yet to be addressed by the community... which is to say the whole of it. Let's dispense with specifics of an individual and march onwards to the inquiry given!
I want to start off that at its core, our model behaves like an adaptation of the golden rule of debates - Never target a person, always target the argument. In our case, we'd sub "argument" for "contribution", being questions and answers. Users themselves only have reputation, which can only exist in a positive value. Votes can only be applied to contributions, and the reasoning behind votes should likewise follow suit. The first response to receiving downvotes should be to check if there is work to be done to reverse them. Most users on the network operate within our guidelines.
For the above reasons, thus, personal defamation isn't all that tolerable. In some cases, if not meant to be explicitly malicious, users may go overboard in their treatment without realizing the harm they're causing. If, be it in comments or chats, you feel that users reach a point where they are attacking not your content, but you as a person, then this is not appropriate. What are reasonable approaches to this?

Flag obvious toxicity. If comments are unquestionably rude against your person, you can flag them as such.
Collect evidence. This is an extremely important portion of handling treatment by other users outside of the direct context that it happens (like if there are comments across multiple posts in multiple weeks). Samples and links to specific incidents of maltreatment are much more valuable than verbal testimonials. By providing these samples, it illustrates the reality of the situation, though take care to listen to if the reality had been intended otherwise.
Talk it out. Make it known that it feels like people are insulting or humiliating you. Explain how you feel and try to reason with the community. I've been with this community from the start - we may be ornery folk when it comes to maintaining our quality, but we are all reasonable people and are open to discussion and explaining our position. It stands for this reason that we as a community should offer the same respect back when approached in this manner, and talk things through calmly. No matter how frustrating a situation is for either side, anger never really makes a problem go away, it only has no impact or aggravates the situation for worse.
Ask for moderator mediation. If you find yourself at an impasse with the community, or if you have some hesitance about the interpretation of events, the moderator team on Arqade is able to intervene as an impartial observer to overlook the turn of events and try to soften things out. The Community Team from Stack Exchange (which includes myself) is also available to mediate the situation.

Our focus as a network is on content, not people. But this applies to how the mechanics of the site work, and while we're in the realm of the mechanics, we all do our best to follow this. But when we're outside the realm of the mechanics, we're still a community, and one of people. We all have the capability of offering each other due respect, so let us exercise this in our engagements, on both sides of any of these kinds of encounters.

A:

For the record, I like you. You seem to be a pretty decent member of this community, you actively try and find out what it is that you're doing wrong so you can fix it (such as this question here), and you seem to love minecraft, which in my books is a big plus :).
However, as other people are saying, your questions & answers could use some improvement. I'm going to lay out how I write questions and answers as an example - there are other ways to phrase your Q&As, but generally this is what works for me:
Questions

Title: It generally should be phrased as a question. Also, people shoud be able to read your title and instantly know what the problem is. Compare

Problem with Redstone, to
How can I get three Pistons to activate using the same Redstone line?

Body: The body should be composed of three main sections: Context, Research and Question. This is kind of like writing a short essay, with an Introduction, Body (which shows research) and Conclusion:

Context: Where does this problem occur?
Research: What have you done to try and solve the problem, or what have you found whilst researching? If it's a technical problem, list some specifications (Java version number, amount of RAM, CPU speed etc)
Question: Pretty much should sum up what you've just described. "Even with all this info at my disposal, my Pistons still won't activate. Is there something I'm missing?"

Example (bold are links):

How do I do the thing?
In Awesome Game Title 2: Extreme Edition, there is a section of the level where X happens. You can get here by opening 3 doors, talking to Mr Z, and performing a somersault into this wall.
Here is some stuff online, that relates to the question about the thing.
  I've also tried blorking the thing, sporking the thing, and even torqing the thing, but to no avail.
Even knowing XYZ about the thing, it still doesn't Blork correctly. Is there something I'm missing?

As a real-world example: Is it possible to stop the Madman from escaping his yacht?
Answers
Generally, I try to remember that we are trying to solve a problem the user is facing. Even if the answer is "No, it's not possible", I at least try and find a workaround solution that may help them. In some cases, it even may be exactly what they're after anyway, and they just couldn't phrase it that way in the question themselves!
Again, this can be a lot like writing an essay (Introduction, Body, Conclusion), however, if the answer boils down to Yes/No, I generally put that in the first sentence. After all, that's what they're after. In any case, just make sure to back up your answer with links, and quotes (and links to the quotes). Images and videos are nice, but should only add to your answer, not be the sole source of it.
Examples (bold are links again):
Q: How do I do the thing?
A:

You've got to have the Sword of Neverending Awesome before attempting to Blork the Thing. Otherwise, Mr Z won't open the fourth door, which is key to all of this.
To get the Sword of Neverending Awesome, head to QwertyTown, and order a mead from the local innkeeper. Perform 5 somersaults, one on each table in the Pub. You'll get the achievement "Move your body" (If you haven't already), and one of the QwertyTownians will present you with the sword.
Here is a short video, detailing the process: (Video embed)

Or:
Q: Is it possible to jump the mountain?
(This question technically calls for a Yes/No answer)
A:

Yes, it is possible. You'll need the Boots of Extreme Comfiness, and need to have levelled your charater's Springiness attribute to 11.

(Most people would stop here, however, as I mentioned earlier, we're here to solve a problem the user is facing. I would then continue:

You can get the boots from the Shopkeeper in QwertyTown on Tuesdays and Thursdays. Here's the wiki link for the boots.
As for levelling your character's springiness, I've found it easiest to complete the training grounds in the Krazy Kaverns first (an instant +5 to both Springiness and Awesomeness). The rest you can gain through side quests. See the attributes wiki, which lists ways to increase stats quickly

Some examples:

How to password protect my ps3 console
Why do my neighbour deals keep ending prematurely?
Animals won't spawn, even though on an older map they will
What is the fastest way to get money in GTA San Andreas?

Every answer is different of course. This is just a general guide.
One last point: Humor can go a long way (but shouldn't be the entire focus of the question/answer). See:

Q: How much of my money does my Mum spend when she buys me things?
A: Any way to make your crew stop attacking a system?


Q:

Scroll to top of element when fixed html,body

I've been searching around and cannot seem to find an answer.
When making an app that has a fixed html and body but a scrollable div:
html, body { width: 100vw; height: 100vh; overflow: hidden; }
.inside { height: calc( 100vh - 8em ); overflow-y: scroll; }

When I am trying to scroll to the top of a div that outputs a response message, it seems to only move up ~200px but not all the way to the top:

So to explain the GIF above, when the user scrolls to the bottom, and submits the form it only moves up a little bit of the form. I then scrolled to the top manually to show the #response div (green bar). When the GIF refreshes, you can see it just ends on the initial nudge up a little.
My jQuery from the ajax is:
$( ".inside" ).animate({
    scrollTop: $( "#response" ).top
}, "slow" );

A:

The only way I have had success is instead of having $( ".inside" ).animate({ is to have $( "*" ).animate({


Q:

Mosquitto prevent duplicate login

I want to prevent user from duplicate login.
Currently I use mosquitto with signing different PKI for each client, but even if I turn on off the allow_annonymous flag, the user can still connect the mosquitto server without username and password. (So user can duplicate login with one PKI)
Is there a way to ensure PKI can only login in one session? Is set the username/password file can prevent duplicate login? Or other way to disable duplicate login?
Thanks

A:

No, there is no way to limit the number of connections based on the username (or certificate cn)
Best you could do is ensure that each user uses the same client_id, since only on connection is allowed per client_id when a second tried to connect it will disconnect the first


Q:

IIS on 64-bit Windows Server 2012 won't run ElasticBeanstalk-Deployed WCF Application

I have an application written in WCF and deployed on IIS using AWS ElasticBeanstalk from within Visual Studio.
When I run target the uri of the WCF application (for testing) on a web browser, I get the error message that one of my DLLs or its dependency cannot be found. The DLL is a 64-bit binary and IIS is running a 64-bit windows operating system. The WCF project itself is also configured to target a 64-bit machine.
When I look into the folder of the deployed application on the server, I see the .svc file, wen.config file and the a bin folder. The bin folder indeed contains the dll in question even though IIS reports that it can't find it.
Should it be looking for it in bin/x64 folder instead, since I am only 'almost' sure that the application is being deployed as 64-bit. I have also tried enabling and disabling the Allow32Bit option on IIS, still no effect.
Please could you kindly tell me what I am doing wrong and guide me?
Thanks..

A:

The problem is now resolved. It was dependency issues on native libraries which IIS could not detect automatically. Dependency Walker proved helpful in finding this out.


Q:

¿Cuál es la diferencia entre agrio, ácido y amargo?

Estuve investigando sobre los 5 sabores básicos que puede sentir el humano.
En particular los que me interesa traducir y llegar a consenso son, en inglés, bitter y sour. Sour está asociado al limón, por lo tanto sí o sí va con ácido. Por eliminación, bitter es amargo.
En el artículo de wiki en español de sabor ácido, se menciona agrio como sinónimo, pero no amargo.
En el de sabor amargo no se menciona ni ácido ni agrio.
Todo esto parece indicar que el problema está resuelto:

Sour: ácido, agrio.
Bitter: amargo.

Pero prueben estas traducciones de Google 'amargo'. ¡No debería aparecer ácido! Contradicción.
Ahora vean esta entrada de 'amargo', citando amargar como sinónimo (incorrectamente) de acidular y agriar.
Mi pregunta es, en español, ¿somos coherentes en este sentido, o no somos tan rigurosos?
Nótese que comentaron @Rodrigo y @Rafael que acido y amargo NO son lo mismo como sabores, pero como adjetivos de personas, peyorativos, sí pueden usarse similarmente. Lo cual no explica la entrada del diccionario de mas arriba.
La traduccion de Google contradictoria con mis ideas la dejo como evidencia de que hay tendencia a confundir/no ser rigurosos en la diferencia, aunque reconozco, no es nada autoritario.

A:

Quizá las diferencias son tan imperceptibles de manera consciente, que solo pueden matizarse a muy bajo nivel.
He añadido aquí una respuesta que he encontrado en Yahoo Answers

El sabor amargo es uno de los cinco sabores básicos es el más
  necesitado de hábitos para que sea gusto adquirido y es debido a que
  es quizás el más desagradable de los cinco. Se detecta mediante las
  papilas gustativas ubicadas en la parte posterior de la lengua. Los
  investigadores de la biología evolutiva han sugerido que este sabor es
  interpretado como desagradable en muchas culturas debido al mecanismo
  de defensa que muestra la necesidad de sobrevivir evitando los
  envenenamientos, esto es así debido a que la mayoría de los venenos
  son amargos en su sabor.[1] [2] Se ha descubierto a comienzos del
  siglo XXI que los receptores de la sensación de amargo son unos
  sensores denominados T2R.
El sabor ácido (a menudo se identifica también con el sabor agrio) es
  uno de los cinco sabores básicos detectado por las papilas gustativas
  de la lengua ubicadas a ambos lados de la parte posterior de la misma.
  Los sensores de las papilas gustativas detectan mediante canales
  iónicos los iones oxonio (H3O+) que se forman al haber ácidos en
  presencia de agua. Al igual que el sabor amargo, el ácido es
  considerado como una 'alarma' por el cerebro ya que algunas sustancias
  venenosas y perjudiciales poseen sabores ácidos.[1] Los sensores
  específicos en la lengua que detectan el sabor ácido se denominan
  TAS2R.[2] [3]

La diferencia radicará pues en su composición química y en los mecanismos del cerebro para diferenciar ambos sabores según estas composiciones.
Posiblemente por esto, por ser unos matices difíciles de apreciar que usamos los dos manera de manera indistinta.
Resumiendo:

Ambos son sabores básicos.
Ambos son detectados por las mismas papilas gustativas.
Ambos son una alerta de posibles sustancias venenosas. Y sabiendo esto, tampoco sería necesario matizar por qué razón lo son. El cerebro busca la solución más rápida al problema de la supervivencia. Los detalles están de más.

Pero:

Ambos tiene propiedades químicas diferentes y por ello tenemos receptores distintos para detectarlas.

En cuanto a Agrio:
Por más que leo, agrio no se contempla como sabor básico, sino como un matiz del sabor que indica acidez. Si buscas en Wikipedia por Agrio, ¡¡te redirige a ácido!! :-)
Cuanto más leo al respecto más me convence la idea de que es un matiz del sabor y no un sabor en sí mismo. Se emplea para describir el sabores de cítricos los cuales también describiríamos como ácidos.
La línea que separa estos tres conceptos es muy, muy fina.


Q:

How to select all " that don't have any space in its back and front?

Here is my current pattern:
/([^\s])"([^\s])/

And here is the current example:
$str = 'this i"s a "test" word i"s"s';

And there is the current result: (replaced with $1$2)
$str = 'this is a "test" word is"s';

And here is the expected result:
$str = 'this is a "test" word iss';

How can I do that?

A:

Use this lookahead and lookbehind regex for search:
/(?<!\s)"(?!\s)/

and replace with empty string.
RegEx Demo
RexEx Details:

(?<!\s): Negative lookbehind to assert that we don't have a whitespace at previous position
": Match a double quote
(?!\s): Negative lookahead to assert that we don't have a whitespace ahead.


Q:

System.Reflection - How can I get the PropertyInfo of the sublevel Types?

I have got three classes as follows:
public class TestA
{
    public string Str1 { get; set; }
    public string Str2 { get; set; }
    public List<TestB> LstTestBs { get; set; }
    public TestC ObjTestC { get; set; }
}

public class TestB
{
    public string Str3 { get; set; }
    public string Str4 { get; set; }
}

public class TestC
{
    public string Str5 { get; set; }
}

I have tried:
var prop = typeof (TestA).GetProperties();

But, it is giving only the PropertyInfo for the four members inside TestA. I need to get the PropertyInfo for all the members in the TestA, TestB and TestC classes.
Please help...
Thanks in advance,
San

A:

Thanks for the help everyone.
I have got the answer.
        var prop = typeof (TestA).GetProperties();

        for (int i=0;i<prop.Count();i++)
        {
            var propertyInfo = prop[i];
            if (propertyInfo.PropertyType.Namespace != "System")
            {
                if (propertyInfo.PropertyType.IsGenericType &&
                    propertyInfo.PropertyType.GetGenericTypeDefinition() == typeof (List<>))
                {
                    Type itemType = propertyInfo.PropertyType.GetGenericArguments()[0];
                    var listObjectProperties = itemType.GetProperties();
                    prop = prop.Union(listObjectProperties).ToArray();

                }
                else
                {

                    var childProp = propertyInfo.PropertyType.GetProperties();
                    prop = prop.Union(childProp).ToArray();
                }
            }
        }


Q:

setDirection GridWorld Greater than 360 degrees

On the AP Quick Reference Code, it states "public setDirection(int newDirection) sets the direction of this actor to the angle between 0 and 359 degrees that is equivalent to newDirection"
However, in one of the released exam multiple choice questions, it states that you can set the direction by calling setDirection(getDirection + RIGHT);, however, what if the angle becomes greater or equal to 360 degrees? an example being 390 degrees.
Will this generate a run-time error, or will it just %360 and get the correct reference angle?

A:

I have figured out the answer to my question. Upon compiling the GridWorld Case Study, I can confirm that any integer value (so long as it is a valid integer) can work in the setDirection(new Location); method.


Q:

Display an image using dojo programmatically

I'm trying to display an image using dojo programmatically. I've tried "dijit/Dialog" and "dojox/image/Lightbox".
When I use the Dialog the image dialog displays some characters instead of image.
And when i Use the Lightbox, the image always displays second time.
imageDialog = new Dialog({
  title:  "my image",
  preload: false,
  href: "/ajax/fileStreamer"
});
imageDialog.show();

The above code displays only some characters. If i give a relative path to an image, the result is same.
With Lightbox, if it's relative path then image displays. But with image stream it displays on second click.

A:

Lightbox assumes the file is an image so adds internally the  tag to the href attribute, whereas Dialog does not, hence the need to use the content attribute including manually the  tag instead. Depending on what you wish to achieve, you have several options (increasing complexity / fancyness):
With ContentPane:
        require(['dijit/layout/ContentPane'], function (ContentPane) {
            var theImage = new ContentPane({content: ''}, 'theImage');
            theImage.startup();
        });

with Dialog (extends ContentPane):
        require(['dijit/Dialog'], function (Dialog) {
            var theImage = new Dialog({title: 'the image', content: ''});
            theImage.startup();
            theImage.show();
        });

with Lightbox (needs Lightbox css, uses LightboxDialog internally which extends Dialog):
        require(['dojox/image/Lightbox'], function (Lightbox) {
            var theImage = new Lightbox({title: 'the image', href: 'yourimageurl'});
            theImage.startup();
            theImage.show();
        });

with LightboxDialog (idem Lightbox, exposes the LightboxDialog instance):
        require(['dojox/image/Lightbox'], function (Lightbox) {
            var theDialog = new dojox.image.LightboxDialog({});
            theDialog.startup();
            theDialog.show({title: 'the image', href: 'yourimageurl'});
        });


Q:

Show that E(nx)=E(ny) => x=y

For every natural number $n$
Show that : $E(nx)=E(ny) \implies x=y$
Such that $E(x)$ is the integer part of $x$
By definition :
$E(nx) \le nx<E(nx)+1$
$E(ny) \le ny<E(ny)+1$
So $-1 \le n(x-y)<1$
Here I'm stuck !
Edit 1:
Should I think about $x=E(x)+r$  $0<r<1$

A:

As it has already been pointed out in the comments, from your last equation follows:
$$|x-y| \le \frac{1}{n} ~ \forall n \in \mathbb{N} \implies |x-y| = 0 \iff x=y$$
Because the absolute value is a norm and then the last equality follows.


Q:

Reference for LPV controls

I am looking for a good mathematical introduction to LPV (Linear Parameter Varying) methods in control theory. I would like it to be more on the mathematical side of things, instead of something aimed only at engineers, if possible. Does anybody have such a reference (better if available online)?

A:

For an LPV approach based on a set of linear models defined on a grid of parameter values you should look at:

F. Wu, Control of linear parameter varying systems. Ph.D. Dissertation, University of California at Berkeley, 1995. (http://www.mae.ncsu.edu/wu/paper/PhDthesis.ps)

For an LPV approach where the system can be modeled using a linear fractional representation you should look at the following papers:

A. Packard, "Gain scheduling via linear fractional transformations," Systems and Control
Letters, vol. 22, no. 2, pp. 79-92, 1994.
P. Apkarian and P. Gahinet, "A convex characterization of gain-scheduled H∞ controllers,"
IEEE Transactions on Automatic Control, vol. 40, no. 5, 1995.
(http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.55.9110&rep=rep1&type=pdf)
P. Apkarian and P. Gahinet, "Erratum to "A convex characterization of gain-scheduled H∞
controllers"," IEEE Transactions on Automatic Control, vol. 40, no. 9, 1995.

The references above provide all the details you need to (1) understand how stability and performance are framed in these two approaches to LPV, and (2) implement algorithms to synthesize stabilizing LPV controllers.
An overview of techniques to derive LPV models from nonlinear systems is provided in this paper:

A. Marcos and G. Balas, "Development of Linear-Parameter-Varying Models for Aircraft," Journal of Guidance, Control, and Dynamics, Vol. 27, No. 2, March–April, 2004.

For details on model reduction for LPV systems, see:

G. Woods, "Control of parameter-dependent mechanical systems", Ph.D. Dissertation, University of Cambridge, 1995.

Finally, a recent survey of LPV modeling, identification and control can be found in the following book:

J. Mohammadpour and C. W. Scherer, eds., Control of Linear Parameter Varying Systems
with Applications. Boston, MA: Springer US, 2012.
M. Lovera, M. Bergamasco, and F. Casella. "LPV modelling and identification: An overview." Robust Control and Linear Parameter Varying Approaches. Springer Berlin Heidelberg, 2013.

I hope this helps.


Q:

Angular 5 prevent adding props to class

I have this class
export class Alpha {
     propAlpha?:string;

     constructor(){
     }

     setProp(key: string, value: string) {
        this[key] = value;
     }

}

Some rest call gives me an object (response) like this:
{
    propAlpha: "foo",
    _someUnwanted: "bar"
}

I need to push only valid props of this object into Alpha, so I did
let myAlpha = new Alpha();
_.each(Object.keys(response), key => {
    validProp(response[key]) && myAlpha.setProp(key, response[key]);
    /**
     * validProp() checks if value matches some criteria.
     * So even if "propAlpha" is in "Alpha" it may be
     * excluded for some other reason!
     */
});

the problem is that _someUnwanted is added to my class.
How can I prevent that?
I'd need to check which keys are in Alpha..
maybe like this?
if(key in myAlpha) {
   myAlpha.setProp(key, response[key]);
}

A:

Different approach that doesn't require declaring separate enum is to declare class members inside it's constructor. Then your Alpha class would look like this:
export class Alpha {
     constructor(public propAlpha?: string){}

     setProp(key: string, value: string) {
        if (key in this) this[key] = value;
     }
}

assigning properties wouldn't change
_.each(Object.keys(response), key => {
    validProp(response[key]) && myAlpha.setProp(key, response[key]);
});


Q:

What is the Max length of a resource name?

In my XCode project, I added a Sounds folder to my Resources folder.  Into the Sounds folder, I dropped a couple of MP3 files with fairly long names (25-30 chars).  I like to be descriptive.  However, the following code chokes with an UNCAUGHT EXCEPTION:
fileURL = [[NSURL alloc] initFileURLWithPath:[mainBundle pathForResource:@"really_really_long_name_for_real" ofType:@"mp3"]];

If I change the name of the resource to "blah.mp3" and the corresponding code line to:
fileURL = [[NSURL alloc] initFileURLWithPath:[mainBundle pathForResource:@"blah" ofType:@"mp3"]];

everything works fine.
Is there a max length for a name of a resource?

A:

I don't think there is such type of limitation on resource names because in my current project I am saving images to the documents folder which are named by concatenating more than 7 to 8 words which makes my name around 60-70 characters long, and everything is working fine for me. So I think the problem would the use of special characters you have used in naming your files. So just check for these special characters.
Thanks,
Madhup


Q:

Missing styles, Using CardView in android studio

With CardView as root layout in xml file(for a custom view), i get an error from android studio-
    Missing styles. Is the correct theme chosen for this layout?  Use the Theme combo box above the layout to choose a different layout, or fix the theme style references.  Failed to find style with id 0x7fff000e in current theme .I tried choosing different themes for the layout, none worked it seems.I am using the new appCompatActivity in my app.any theme works fine with the old ActionBarActivity.

A:

Adding the elements below to the AppTheme helped me to solve a similar problem
    <item name="colorPrimary">@color/primary</item>
    <item name="colorPrimaryDark">@color/primary_dark</item>
    <item name="colorAccent">@color/accent</item>

A:

I guess this is a bit ate for your question but just in case someone needs it:
Mine was solved after restarting android studio using the below option:

File -> Invalidate Caches/Restart...


Q:

Sweet Alert and ajax calls based on id on php while loop

I have a php page with a php while loop in which i get user details along with id. The loop creates buttons which when clicked i need to know the details of each used based on their ID as in image below.
http://tinypic.com/r/znl8w9/9
<button class='btn btn-success' value="<?php echo $id ;?>" onclick="javascript:getDetails();">View Details</button>

I need to display the details in a javascript sweetalert modal window.
function getDetails() {
  swal({
    title: "User Details",
    text: User Details here!",
    confirmButtonColor: "#00B4B4",
    imageUrl: "<?php echo $image; ?>"
  });
};

How can i get the details of each user id in the sweetalert modal by clicking on the loop generated buttons. Can we get the ID of each user via button and pass it to sweetalert and then do a ajax request to a different page and pull out details from database based on the ID and display it.
Or is there any other way to do it ??
Please is it possible? If so how ?? I am a newbie and sorry if i overlooked something.

A:

Step 1, add a class to buttons, for example user-details and remove attribute onclick. Also add data-* attributes with your details, example:
<button class='btn btn-success user-details' data-name="John Doe 1" data-image="https://png.icons8.com/contacts/ios7/50/e67e22">View Details</button>

Step 2, bind an event handler to these buttons, note these attributes being used (you can add how many you want):
$('.user-details').click(function(e) {
    e.preventDefault();

    var name = $(this).attr('data-name');
    var image = $(this).attr('data-image');

    swal({
        title: "User Details",
        text: "User Details: " + name,
        confirmButtonColor: "#00B4B4",
        imageUrl: image,
    });
});

This is pretty all you need, you can try a demo here.


Q:

How to upgrade the ant built into eclipse?

I use ANT for all my builds and I also use eclipse as my IDE and I would like to be able to use the latest version of ANT in my eclipse, frequently the ANT that ships with eclipse is a point release behind. so my questions are.

Is there an easy way to get the eclipse ant plug-in to use the latest version of ANT?
Is there any easy way to add extra custom ant libraries to the built in eclipse ANT plug in, as I would like to be able to add things like the subversion task to my ant build and have it accessible from within eclipse.

A:

Download and unpack the latest ant build anywhere on your hard disk, then run Eclipse, and go to
Window > Preferences > Ant > Runtime

and click on the button called
Ant Home

Browse to the ant folder that you just unpacked, and choose that folder. Now Eclipse will use this version of ant instead of the built-in ant. I use this way, and actually prefer it, because now I have the same ant version in command line and in Eclipse
In the same window you can add any other jars with 3rd party ant tasks, and they will be used by ant (just 'add jars'/'add external jars')


Q:

Embed finite field in algebraic closed field

Let  $\Omega$ be an algebraic closed field of characteristic $p$, then for any field $F$ of $q$ ($=p^a$) elements, $F$ can be embedded in $\Omega.$

I need above property to proof that every finite fields with the same order are isomorphic, but I don't know how to proof the above property.
Here is what I think: Every elements in $F$ satisfy the equation $x^q=x$. Now $x^q=x$ can be solved in $\Omega$, and its solutions form a subfield in $\Omega$. But I don't see why $F$ must isomorphic to such subfield.
So how to proof the property above?
BTW, it's known that there is an unique subfield of $q$ elements in $\Omega$, I
don't know whether it helps or not.

A:

Lemma: Let $K/k$ be an algebraic field extensions and let $\phi: k \to C$ be a ring homomorphism where $C$ is an algebraically closed field. Then there exists a ring homomorphism $\sigma : K \to C$ which extends $\phi.$
Proof: Let $\mathcal F$ be the set of pairs $(F, f)$ where $k \subseteq F \subseteq K$ is a field and $f: F \to C$ is a ring homomorphism such that $f|_k = \phi.$ Since $(k, \phi ) \in \mathcal F,$ it is non-empty. Define a relation on $\mathcal F$ as follows: $(F, f) \leq (F', f') \Leftrightarrow F \subseteq F'$ and $f'|_F = f.$ This will give a partial order relation on $\mathcal F.$ Show that every chain has an upper bound and hence by Zorn's Lemma, it has a maximal element, say, $(F, \sigma).$ We claim that $F = K.$ If not, then there exists a $x \in K$ such that $x \notin F.$ Let $g(X) \in F[X]$ be the minimal polynomial of $x$ over $F.$ Note that $F(x) \cong F[X]/(g(X)).$ For any $p(X) \in F(X),$ let $p^{\sigma}(X)$ be a polynomial in $C[X]$ obtained by applying $\sigma$ to the coefficients of $p(X).$ Now $g^{\sigma}(X)$ has a root in $C,$ say $\alpha.$ Define a map $\psi : F[X] \to C$ by $p(X) \mapsto p^{\sigma}(\alpha).$ Then this amp induces a map $\overline{\psi}: F[X]/(g(X)) \to C.$ Using $F(x) \cong F[X]/(g(X))$ we see that the pair $(F(x), \overline{\psi}) \in \mathcal F$ and $(F, \sigma) \leq (F(x), \overline{\psi}),$ contradicting the maximality of $(F, \sigma).$ Hence $F = K.$
Now we use the above Lemma in this case. As you have already noted that $F$ is an algebraic extension of $\mathbb Z/ p\mathbb Z$ and we have an inclusion $\mathbb Z/ p\mathbb Z \to \Omega.$ So it has an extension $F \to \Omega.$


Q:

Run specific JMH benchmarks from jar

I have a several heavy benchmark classes annotated with @Benchmark. After bulding jar with benchmarks I can run all of them with following command
java -Xmx4G -jar benchmarks.jar -f 1 -wi 3 -i 10

How to specify benchmarks to run, if I don't want to run all of them?

A:

When in doubt, ask for command line help. In fact, running the JAR with -h yields:
Usage: java -jar ... [regexp*] [options]
 [opt] means optional argument.
 <opt> means required argument.
 "+" means comma-separated list of values.
 "time" arguments accept time suffixes, like "100ms".

  [arguments]                 Benchmarks to run (regexp+).

So, supplying a regular expression as the filter helps.

A:

This is the exact command:
java -Xmx4G -jar benchmarks.jar YourClass -f 1 -wi 3 -i 10


Q:

What is meaning of  in OData Metadata?

After I went through OData doc, I still do not understand the meaning of <FunctionImport>.

What is that used for?
Some one said that "Function imports are used to perform custom operations on a JPA entity in addition to CRUD operations. For example, consider a scenario where you would like to check the availability of an item to promise on the sales order line items. ATP check is a custom operation that can be exposed as a function import in the schema of OData service."

But I think above requirement can be achieved by general <Function> also, right?

What is the difference between <FunctionImport> and <Function> exactly?

I do appreciate anyone's help!
Thanks

A:

There are three types of functions in OData:

Functions that are bound to something (e.g. an entity). Example would be

GET http://host/service/Products(1)/Namespace.GetCategories()

such function is defined in the metadata using the <function> element and with its isBound attribute set to true.
Unbound functions. They are usually used in queries. E.g.

GET http://host/service/Products?$filter(Name eq Namespace.GetTheLongestProductName())

such function is defined in the metadata using the <function> element with its isBound attribute set to false
Function imports. They are the functions that can be invoked at the service root. E.g.

GET http://host/service/GetMostExpensiveProduct()

Their concept is a little bit similar as the concept of static functions in program languages, and they are defined in metadata using the <functionimport> element.

Similar distinguishing applies to <action> and <actionimport> as well.

A:

OK, I got the answer by myself.
<OData Version 4.0 Part 1: Protocol Plus Errata 02>:
Operations allow the execution of custom logic on parts of a data model. Functions are operations that do not have side effects and may support further composition, for example, with additional filter operations, functions or an action. Actions are operations that allow side effects, such as data modification, and cannot be further composed in order to avoid non-deterministic behavior. Actions and functions are either bound to a type, enabling them to be called as members of an instance of that type, or unbound, in which case they are called as static operations. Action imports and function imports enable unbound actions and functions to be called from the service root.


Q:

Функция не видит переменную-массив python

в результате выполнения кода возникает ошибка NameError
не видит массив numbers. пробовала через global (как в коде), но не помогает.
Если прописать просто методы без класса - работает. но в этом случае нужен класс
class MyWin(QtWidgets.QMainWindow):

    ...

    numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 'A', 'B', 'C', 'D', 'E', 'F']
    def checking(self):

        def changeEnable(firstIndex = 0, param = False):
            global numbers
            for i in range(firstIndex, len(numbers)):
                getattr(self.ui, "pb_%s" %(numbers[i])).setEnabled(param)

        changeEnable(0, True)
        ...

A:

Попробуйте так:
class MyWin(QtWidgets.QMainWindow):

    ...

        self.numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 'A', 'B', 'C', 'D', 'E', 'F']

    def checking(self):

        def changeEnable(firstIndex = 0, param = False):
            # global numbers
            for i in range(firstIndex, len(self.numbers)):
                getattr(self.ui, "pb_%s" %(self.numbers[i])).setEnabled(param)

        changeEnable(0, True)
        ...


Q:

Can AtomicInteger replace synchronized?

The javadoc for the java.util.concurrent.atomic package says the following:

A small toolkit of classes that
  support lock-free thread-safe
  programming on single variables.

But I don't see any thread-safe (synchronized or Lock) code inside any of the AtomicInteger or AtomicBoolean classes.
So, are these 2 the same:
1.
int i;
synchronized(this){i++;}

2.
AtomicInteger i = new AtomicInteger();
i.getAndIncrement();

Update: Thanks for the answers. Is volatile needed when I use AtomicInteger?

A:

They would offer the same atomicity.  The only thing you must be aware of is any time you read i you must wrap it with synchronized also
synchronized(this){ return i;}

Edit to answer your edit:
Volatile is not necessary for your AtomicInteger.  To prove that declare the AtomicInteger final.  The only reason you would need the AtomicInteger to be volatile is if the AtomicInteger field itself changes.  Similar to:
volatile AtomicInteger i = new AtomicInteger(0);

public void work(){
    i.incrementAndGet();
    //...do some other stuff
    i = new AtomicInteger(10);//because the field i is changing the field needs to be volatile
}

As you can imagine that shouldn't be the case, so you shouldn't have to worry about the field being volatile.

A:

They are equivalent functionally, but there is a subtle difference. synchronized has the overhead of acquiring and releasing the monitor on this, while AtomicInteger is implemented with a native method call, so it will be significantly faster.

A:

Yes, they're functionally equivalent.
If you're in an ultra-high contention environment, you may see performance differences, but that's highly unlikely.


Q:

Is there a way to use Selenium WebDriver without informing the document that it is controlled by WebDriver?

I'm automating an Web page who call a CAPTCHA to validate the login, but I noticed that this page only request this CAPTCHA when I'm using my automatized test code, when I do it manually it don't request.
I asked to developer team to disable it on the QA environment, but it's not possible by a security code.
I need to know if there is a way to don't say to browser that I'm using automated test on this page.
Can you help me, please?

A:

No, there is no way to conceal that you are runing automated test.
WebDriver Interface
When using the WebDriver interface the webdriver-active flag is set to true as the user agent is under remote control. It is initially false.
WebIDL
Navigator includes NavigatorAutomationInformation;

Note that the NavigatorAutomationInformation interface should not be exposed on WorkerNavigator.
WebIDL
interface mixin NavigatorAutomationInformation {
    readonly attribute boolean webdriver;
};

webdriver

Returns true if webdriver-active flag is set, false otherwise.

Example

For web authors :
navigator.webdriver

Defines a standard way for co-operating user agents to inform the document that it is controlled by WebDriver, for example so that alternate code paths can be triggered during automation.

The above mentioned implementation is based on a couple of Security Considerations as follows:

A user agent can rely on a command-line flag or a configuration option to test whether to enable WebDriver, or alternatively make the user agent initiate or confirm the connection through a privileged content document or control widget, in case the user agent does not directly implement the HTTP endpoints.
It is strongly suggested that user agents require users to take explicit action to enable WebDriver, and that WebDriver remains disabled in publicly consumed versions of the user agent.
It is also suggested that user agents make an effort to visually distinguish a user agent session that is under control of WebDriver from those used for normal browsing sessions. This can be done through a browser chrome element such as a door hanger, colorful decoration of the OS window, or some widget element that is prevalent in the window so that it easy to identify automation windows.

Reference
You can find a couple of detailed discussion in:

Distil detects WebDriver driven Chrome Browsing Context
Selenium webdriver: Modifying navigator.webdriver flag to prevent selenium detection
Akamai Bot Manager detects WebDriver driven Chrome Browsing Context