text:
Q: Beginner wondering if his code is 'Pythonic' This is really the first thing that I have written in python.  I come from Java background.  I don't want to just learn how to program java code with Python syntax.  I want to learn how to program in a pythonic paradigm.
Could you guys please comment on how I can make the following code more pythonic?
from math import sqrt

# recursively computes the factors of a number
def factors(num):
    factorList = []
    numroot = int(sqrt(num)) + 1
    numleft = num
    # brute force divide the number until you find a factor
    for i in range(2, numroot):
        if num % i == 0:
            # if we found a factor, add it to the list and compute the remainder
            factorList.append(i)
            numleft = num / i
            break
    # if we didn't find a factor, get out of here!
    if numleft == num:
        factorList.append(num)
        return factorList
    # now recursively find the rest of the factors
    restFactors = factors(numleft)
    factorList.extend(restFactors)

    return factorList

# grabs  all of the twos in the list and puts them into 2 ^ x form
def transformFactorList(factorList):
    num2s = 0
    # remove all twos, counting them as we go
    while 2 in factorList:
        factorList.remove(2)
        num2s += 1
    # simply return the list with the 2's back in the right spot
    if num2s == 0: return factorList
    if num2s == 1:
        factorList.insert(0, 2)
        return factorList
    factorList.insert(0, '2 ^ ' + str(num2s))
    return factorList

print transformFactorList(factors(#some number))

A: A few comments:

*

*I would replace range() with xrange(); when you call range(), it allocates the entire range all at once, whereas when you iterate over xrange(), it returns each result one at a time, saving memory.

*Don't put expressions after conditionals on the same line (if num2s -- 0: return factorList). It makes it harder to see at a glance what it's doing (that it's a block).

*Don't be afraid to use modules. The [sympy][1] module already has code to compute factors, which may simplify your code by eliminating most of it.

*Python's string formatting is simple and effective.

For example:
factorList.insert(0, '2 ^ ' + str(num2s))

could be changed to
factorlist.insert(0, '2 ^ %s' % num2s)

All in all, I don't find your code to be extensively un-pythonic. Just make sure you want to use floor division, because that's what tends to happen by default with integer values. Otherwise, you'll need to fix up the division operator:
from __future__ import division

A sometimes-frustrating caveat of the language.

A: from itertools import takewhile

def transform_factor_list(factor_list):
    num_2s = len(list(takewhile(lambda e: e == 2, factor_list)))
    if num_2s > 1:
        factor_list[:num_2s] = ["2 ^ %i" % (num_2s, )]
    return factor_list

That's what I would make out of the second function.
Most pythonic changes:

*

*PEP-8 compatible naming

*slicing (and assigning to slices)

*iterators

*string formatting

The function assumes that the input is ordered, which is fulfilled by factors.
Edit: removed special cases for some lists, more compact this way

A: Based on chris's answer, slightly simplified:

*

*for instead of external while

*internal while to preserve ability to use same divisor repeatedly

*use itertools.groupby simplifies compress() by much

*fix a small bug in tostring()

HTH:
import itertools

def factorize(n):
    # ideally an iterator of prime numbers
    # this'll work though
    divisors = itertools.count(2)

    for divisor in divisors:
        # This condition is very clever!
        # Note that `n` is decreasing, while `divisor` is increasing.
        # And we know that `n` is not divisible by anything smaller,
        # so this stops as soon as the remaining `n` is obviously prime.
        if divisor**2 > n:
            yield n
            break

        while n % divisor == 0:
            yield divisor
            n //= divisor

def compress(factors):
    for (factor, copies) in itertools.groupby(factors):
        # The second object yielded by groupby is a generator of equal factors.
        # Using list() to count its length.
        power = len(list(copies))
        yield (factor, power)

def tostring(compressed):
    return ' * '.join("%d**%d" % (factor, power) for (factor, power) in compressed)

# test
assert tostring(compress(factorize(12))) == '2**2 * 3**1'

A: Don't be afraid of list comprehensions.  Switching from Java to Python and discovering them was a good day.
For the factors function, maybe something like this:
def factors(num):
    return [i for i in xrange(1, num+1) if num % i == 0]

Probably not the best code but it's short and easy to understand.
Good luck with Python, it's a great language.

A: this is how I'd do this...
import itertools
import collections

def factorize(n):
    # ideally an iterator of prime numbers
    # this'll work though
    divisors = itertools.count(2)

    divisor = divisors.next()
    while True:
        if divisor**2 > n:
            yield n
            break

        a,b = divmod(n, divisor)

        if b == 0:
            yield divisor
            n = a
        else:
            divisor = divisors.next()

def compress(factors):
    summands = collections.defaultdict(lambda: 0)

    for factor in factors:
        summands[factor] += 1

    return [(base, summands[base]) for base in sorted(summands)]

def tostring(compressed):
    return ' * '.join("%d**%d" % factor for factor in compressed)

A: There is an excellent primer by David Goodger called "Code Like a Pythonista" here.  A couple of things from that text re naming (quoting):

*

*joined_lower for functions, methods,
attributes

*joined_lower or ALL_CAPS for
constants

*StudlyCaps for classes

*camelCase only to conform to
pre-existing conventions

A: Just use 'import math' and 'math.sqrt()' instead of 'from math import sqrt' and 'sqrt()'; you don't win anything by just importing 'sqrt', and code quickly gets unwieldy with too many from-imports. Also, things like reload() and mocking out for tests break a lot faster when you use from-import a lot.
The divmod() function is a convenient way to perform both division and modulo. You can use for/else instead of the separate check on numleft. Your factors function is a natural candidate for a generator. xrange() was already mentioned in another answer. Here's it all done that way:
import math

# recursively computes the factors of a number as a generator
def factors(num):
    numroot = int(math.sqrt(num)) + 1
    # brute force divide the number until you find a factor
    for i in xrange(2, numroot):
        divider, remainder = divmod(num, i)
        if not remainder:
            # if we found a factor, add it to the list and compute the
            # remainder
            yield i
            break
    else:
    # if we didn't find a factor, get out of here!
        yield num
        return
    # now recursively find the rest of the factors
    for factor in factors(divider):
        yield factor

Using a generator does mean you can only iterate over the result once; if you simply want a list (like you do in translateFactorsList) you will have to wrap the call to factors() in list().

A: Here's what jumps out at me:
def transformFactorList(factorList):
    oldsize = len(factorList)
    factorList = [f for f in factorList if f != 2]
    num2s = oldsize - len(factorList)
    if num2s == 0:
        return []
    if num2s == 1:
        return [2]+factorList
     return ['2 ^ %s' % num2s] + [factorList]

The form [f for f in factorList if f != 2] is called a list-comprehension.

A: Since this post seems to be resurrected by Casey (lol), I'll add in my 2 cents.
Go over everything in PEP-8. It helped me out substantially when I had code formatting issues.

A: I'd use a list comprehension to get the twos out:
def transformFactorList(factorList):
    twos = [x for x in factorList if x == 2]
    rest = [x for x in factorList if x != 2]
    rest.insert(0, "2 ^ %d" % len(twos))
    return rest

Note that this will give you 2^0 and 2^1, which your code didn't. What you're doing with the twos seems arbitraty (sometimes you get a string, sometimes a number, sometimes nothing), so I figured that would be fine. You can change that easily if you want:
def transformFactorList(factorList):
    twos = [x for x in factorList if x == 2]
    rest = [x for x in factorList if x != 2]
    if twos:
        rest.insert(0, 2 if len(twos)==1 else "2 ^ %d" % len(twos))
    return rest

A: One other thing you might want to look at is the docstring.  For example, the comment for this function:
# recursively computes the factors of a number
def factors(num):

Could be converted into this:
def factors(num):
    """ recursively computes the factors of a number"""

It's not really 100% necessary to do it this way, but it's a good habit to get into in case you ever start using something along the lines of pydoc.
You can also do this:
docstring.py
"""This is a docstring"""

at the command line:
>>> import docstring
>>> help(docstring)

results:
Help on module docstring:

NAME
    docstring - This is a docstring

FILE
    /Users/jason/docstring.py

A: Using recursion (where not necessary) is not pythonic. Python doesn't have tail recursion elimination and flat is better than nested.
When in doubt, try import this
update: by popular request, here goes the iterative factorization (sigh):
"""returns an iterator of tuples (factor, power) such that
reduce(operator.mul, (factor**power for factor, power in factors(n))) == n """
def factors(n):
    i = 2
    while n > 1:
        p = 0
        while n > 1 and n % i == 0:
            p += 1
            n /= i
        if p:
            yield (i, p)
        i += 1


text:
Q: How can I populate a form with an @Input() value that is of type object? This is the ts with the input that i was mentioning
 @Input() event: ClassEvent //this is the input
  start-date: FormControl;
  end-date: FormControl;
  class : FormControl;
  myForm: FormGroup;

And this is a part of the form
 <div class="form-group">
 <select id="location_id" formControlName="class"
                required>
                <option value="" disabled selected>Classes</option>
                <option *ngFor="let class of classList">
                    {{class.name}}</option>
            </select>
        </div>
    </div

A: I think patchValue is what you're after. It's a method you'll find on your FormGroup.
As an example...
ngOnInit(){
  // ...
  myForm.patchValue(selectedEvent);
}

More information here - https://angular.io/guide/reactive-forms

redpajama_set_name: RedPajamaStackExchange


text:
Q: not on a query in RoR In Ruby on rails 3 I want to query on a has_many field of a model as follows:
@project.items.where(:status => 1)
The problem is I'm trying to get the exact opposite result than this. What i want is all items of @project where the status is not 1. Been looking for the answer to this for a while, anyone?

A: There are many ways to accomplish what you are trying to do, however, some are better than others. If you will always be searching for a hardcoded number (i.e. 1 in this case), then the following solution will work:
@project.items.where('status != 1')

However, if this value is not hard-coded, you are openly vulnerable to SQL injection as Rails will not (cannot) escape this kind of query. As a result, it is preferred among Rails developers to user the following syntax for most custom conditions (those that can't be constructed via Hash):
@project.items.where(['status != ?', 1])

This syntax is slightly confusing, so let me go over it. Basically you are providing the where clause an Array of values. The first value in the array is a String representing the query you want executed. Anywhere you want a value in that string, you place a ?. This serves as a placeholder. Next, you add an element for every question mark in you query. For example, if I had the following:
where(['first_name = ? AND last_name = ?', params[:first_name], params[:last_name]]

Rails will automatically match these up forming the query for you. In that process, it also escapes potentially unsafe characters, preventing injection.
In general, it is preferred to use the Array syntax, even for a hardcoded value. I've been told that pure string conditions in Rails 3.5 will raise a warning (unverified), so it doesn't hurt to get in the process of using the Array syntax now.


text:
Q: Dictionary key value pair question I have a dictionary  pair
i make an object of dictionary "paramList", now i have added key and value pair to that object, now i want to know if on the some other page i pass the object paramList in some method and on that page i know the key and i want to access it's corresponding value then how can i do that
I have object like this
 Dictionary<string, object> paramList = new Dictionary<string, object>();
 paramList.Add("@courseId", course_id);
 paramList.Add("@passoutYear", passoutYear);
 paramList.Add("@currentBacklog", currentBacklog);
 paramList.Add("@sex", sex);

now if i know the key @key and want to know it's corresponding value i also have the object

A: If I understand your question correctly, you want to know if the key exists in the dictionary and then retrieve the value.
Perhaps the simplest way is using TryGetValue
string key = "@key";
object value = null;
if (paramList.TryGetValue(key, out value))
{
    // the key exists and the related value is now in value
}
else
{
    // the key does not exist
}

A: //First check if the key exists in the dictionary and then get the item.
if(paramList.ContainsKey("some-key"))
{
 object value = paramList["some-key"];
}

Edit
Or maybe with an extension method. (To not do a double lookup).
static class DictionaryExtensions
{
    public static TValue GetValueOrDefault<TKey,TValue>(this IDictionary<TKey,TValue> dict, TKey key)
    {
        TValue value;
        if(dict.TryGetValue(key, out value))
            return value;
        return default(TValue);
    }
}

//Example usage
paramList.GetValueOrDefault("mykey") ?? "mykey didn't exist";

A: Just for your information, you can also initialize your dictionary using next approach:
Dictionary<string, object> paramList = new Dictionary<string, object>
{
    { "@courseId", course_id },
    { "@passoutYear", passoutYear },
    { "@currentBacklog", currentBacklog },
    { "@sex", sex },
};

It's called "collection initializer"


text:
Q: Determining if a vector is in the row space of a matrix If I am asked to determine whether the vector
$x = [1, 1, -2, 1, -1]$
is in the row space of the matrix
$A=
\begin{bmatrix}
    1 & 1 & -2 & 2 & 0 \\
    1 & 2 & 2 & -6 & 0 \\
    2 & 3 & 0 & -4 & 0 \\
    0 & 0 & 0 & 1 & 1
\end{bmatrix}
$
can I just show show that the equation $A^T=x^T$ has a consistent solution?
(i.e. Does showing that $x^T$ is in the column space of $A^T$ also show that $x$ is in the row space of $A$?)


text:
Q: PhoneGap doesnt trigger error callback on 401 error I am using PhoneGap in one of my mobile app, using AngularJS and Ionic framework.
I have implemented OAuth 2.0, successfully getting access_token and all.
But while calling any Google API, It doesnt trigger error callback on 401 error code.
 $http.get('https://www.googleapis.com/oauth2/v2/userinfo').success(function (data, status) {
    console.log('success call userinfo ' + JSON.stringify(data));
    console.log(data);
}).error(function (error) {
    console.log('error call userinfo ' + JSON.stringify(error));
    console.log(data);
});

However in code, success callback is always called whether it 200,404,401 HTTP codes.
How can I overcome this problem? I want to intercept error callback and do something, while on fiddle, same code runs successfully. I think PhoneGap is appending something to headers.
PS: I have added < access uri="*" subdomains="true" /> to config.xml too.

A: Issue resolved, Seems like problem was with AngularJS version 1.2.2, Now upgraded to AngularJS 1.2.9, Working fine.


text:
Q: var not receiving correct value inside a function - Javascript I have this function called getQuotes(), and a console.log() at the end of it that shows the correct value of currentQuote.
function getQuote() {
      $.ajax({
            headers: {
              "X-Mashape-Key": "xxx",
              Accept: "application/json",
              "Content-Type": "application/x-www-form-urlencoded"
            },
            url: 'https://andruxnet-random-famous-quotes.p.mashape.com/?cat=movies',
            success: function(response) {
                  var r = JSON.parse(response);
                  currentQuote = r.quote;
                  currentAuthor = r.author;
                  console.log(currentQuote);
            }
      });
};

The point is: when I call getFunction() (like code below), then show a console.log of my variable currentQuote, it is not receiving the correct value, it still an empty string as declarated. What am I doing wrong ?
$(document).ready(function() {
    var currentQuote='';
    var currentAuthor='';
    getQuote();
    console.log(currentQuote);
});

A: Because getQuote() uses an Ajax call, when you call getQuote(), the operation proceeds asynchronously. That means that when getQuote() returns, the results are not yet available. You can fix this by supplying a call-back function as an argument to getQuote() and calling that function from the success function:
function getQuote(callback) {
    $.ajax({
        headers: {
          "X-Mashape-Key": "xxx",
          "Accept": "application/json",
          "Content-Type": "application/x-www-form-urlencoded"
        },
        url: 'https://andruxnet-random-famous-quotes.p.mashape.com/?cat=movies',
        success: function(response) {
              var r = JSON.parse(response);
              callback(r.quote, r.author); // Report success to the caller
        }
    });
};

Then:
$(document).ready(function() {
    getQuote(function(currentQuote, currentAuthor) {
        console.log(currentQuote);
    });
});

This also eliminates the need for global currentQuote and currentAuthor variables. (Although you could always assign those in the callback, if the values are needed elsewhere.)
Alternatives
You can return a Promise from getQuote and modify the Ajax call to call the promise's resolve method. This is described in the accepted answer in the thread to which this is a duplicate.
Because you are using jQuery, another alternative to passing a call-back function is to return the ajax object itself, which has a convenient done(result) property:
function getQuote() {
    return $ajax({
        headers: {
          "X-Mashape-Key": "xxx",
          "Accept": "application/json",
          "Content-Type": "application/x-www-form-urlencoded"
        },
        url: 'https://andruxnet-random-famous-quotes.p.mashape.com/?cat=movies',
    });
}

And then use:
$(document).ready(function() {
    getQuote().done(function(result) {
        if (result) {
            var r = JSON.parse(response);
            console.log(r.quote);
        }
    });
}};

This is also described in the duplicate thread. See the docs for $ajax() for more information.

A: You have two separate issues.
First, remove the final console.log from your document-ready callback, and allow the success callback on your AJAX request to do the logging for you.
Second, you have two sets of currentQuote and currentAuthor variables: a set of global ones and a set that is locally-scoped to your document-ready callback. You should explicitly define each variable as a global property, like so, to prevent collisions:
$(document).ready(function() {
    window.currentQuote = ''
    window.currentAuthor = ''
    getQuote()
});

function getQuote(cb) {
    $.ajax({
        headers: {
            "X-Mashape-Key": "xxx",
            Accept: "application/json",
            "Content-Type": "application/x-www-form-urlencoded"
        },
        url: 'https://andruxnet-random-famous-quotes.p.mashape.com/?cat=movies',
        success: function (response) {
              var r = JSON.parse(response)
              window.currentQuote = r.quote
              window.currentAuthor = r.author
              console.log(currentQuote)
        }
    })
}

If you want to do more than just log the quotes and authors, there are a few ways to make your life a little easier: callbacks and Promises.
A callback is a function that is passed as a parameter to another (asynchronous) function and is called with some "return" value (like your quote and author) when the async process has completed. Here, I'm using resolve as the callback function.
$(document).ready(function() {
    getQuote(function (quote, author) {
        // callback -- do stuff with `quote` and `author`
        console.log(quote, author)
    })
})

function getQuote(resolve) {
    $.ajax({
        headers: {
            "X-Mashape-Key": "xxx",
            Accept: "application/json",
            "Content-Type": "application/x-www-form-urlencoded"
        },
        url: 'https://andruxnet-random-famous-quotes.p.mashape.com/?cat=movies',
        success: function (response) {
              var result = JSON.parse(response)
              resolve(r.quote, r.author)
        }
    })
}

Promises are a more modern way to handle async code, but they are also less widely supported by default (This can be remedied with a polyfill). Promises are outside of the scope of this answer, but if you want more information then I would suggest checking out the Promise page on the Mozilla Development Network.


text:
Q: qqplot would not graph. Error in converting dataframe into a vector data = read.csv("HeatofCombustion.csv", header=T)
attach(data)
library(lattice)
x = data[ , "Qc"]
qqplot(x=qexp(x), y=data, main="Exponential Q-Q Plot",
       xlab="Theoretical Quantiles", ylab= "Your Data Quantiles")

Errors:
Error in `[.data.frame`(x, order(x, na.last = na.last, decreasing = decreasing)) :
  undefined columns selected
In addition: Warning messages:
1: In qexp(x) : NaNs produced
2: In xtfrm.data.frame(x) : cannot xtfrm data frames

Why does this happen? I thought I have already converted dataframe into a vector by using x = data[ , "Qc"]
I am trying to graph an exponential Q-Q plot in R. Many thanks.
Data view:

Actual data for variable Qc (heat capacity):
Qc = c(17.39, 6.68, 23.31, 47.74,
19.53, 45.8, 26.75, 26.86, 29.62, 28.39, 34.21, 43.65, 24.13,
31.37, 25.42, 27.91, 30.9, 31.07, 38.35, 29.18, 26.45, 25.27,
26.92, 24.97, 39.84, 29.38, 31.53, 31.06, 18.71, 29.92, 32.5,
31.07, 31.48, 31.23, 31.15, 31.65, 26.03, 28.61, 30.65, 34.39,
30.28, 30.63, 34.89, 26.5, 29.59, 29.06, 26.54, 25.92, 33.64)

A: This function is perhaps a little too fancy, but should do what you want. (The qfun.args/do.call nonsense is to allow you to include extra shape parameters for the target distribution, which doesn't seem to be necessary here — because of the way that Q-Q plots are assessed, changes in scale and location parameters don't affect their appearance much.)
It's basically just encapsulating and generalizing the chi-squared example shown in ?qqplot ... to generate the x-variable, you use ppoints() to generate an appropriate set of equally spaced quantile points, then the quantile (q*) function of your target distribution to convert those to theoretical quantiles.
qfun <- function(y, qfun = qnorm, qfun.args = NULL, ...) {
    n <- length(y)
    qqplot(do.call(qfun,
                   c(list(ppoints(n)), qfun.args)),
           xlab = "",
           y, ...)
    qqline(y,
           distribution = function(p) do.call(qfun, c(list(p), qfun.args)),
           probs = c(0.1, 0.6), col = 2)
}

Try it out:
qfun(Qc, main = "Gaussian")
qfun(Qc, qexp, main = "Exponential")

library(VGAM)
qfun(Qc, qgumbel, main = "Gumbel")


text:
Q: Odd Javascript/PHP behavior with AJAX Post I have a function that sends a post request to a php website. I get 2 different behaviors by simply changing the capitalization of a variable. The variable in question is the 'action' variable and either being set to "deleteIndexMain" or "deleteIndexmain" If the action variable is set to "deleteIndexmain" I get the popup displaying the html that the php returns. If I set the variable to "deleteIndexMain" I get no popup. (meaning it appears to be a javascript issue?
Here is the java script code:
function deleteMe(v,r)
            {
                if(confirm("Are you sure"))
                {
                    var xhttp = new XMLHttpRequest();
                    xhttp.onreadystatechange = function()
                    {
                        if(xhttp.readyState == 4 && xhttp.status == 200)
                        {
                            alert(xhttp.responseText);
                            document.getElementById("indexmaintable").deleteRow(r);
                        }
                    };
                    xhttp.open("POST", "includes/control.php", true);
                    xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
                    xhttp.send("action=deleteIndexMain&file="+v);
                }

            }

and here is the php code:
<?php
    //Todo make sure  to authenticate!

    session_start();
    require_once("config.php");

    function deleteIndexMain($file)
    {
        unlink($file);
        $query = 'DELETE FROM indexmain WHERE linklocation="'.$file.'"';
        $db->query($query);
    }

    print_r($_POST);
    if(isset($_POST) && $_POST['action'] == "deleteIndexMain")
    {
        echo 'Deleting '.$_POST['file'];
        deleteIndexMain($_POST['file']);
    }

?>

A: String comparison with == is case-sensitive. If you want to perform a case-insensitive comparison, you can use strcasecmp():
if(isset($_POST) && strcasecmp($_POST['action'], "deleteIndexMain") == 0)

Notice that strcasecmp doesn't return a boolean, it returns a number that indicates whether the first string is less than, equal to, or greater than the second. So you have to use == 0 to test if the strings are equal.
Or you can convert everything to a single case with strtolower() before comparing normally.
if(isset($_POST) && strtolower($_POST['action']) == "deleteindexmain")


text:
Q: Is a flask config file persistent? If I create a variable in a Flask config file, will the actual config file be updated when I update the variable in the app?

A: No.  The config file is read once, and never written to.  If you change the file, or change the config, you will need to read or write those changes yourself.
This is trivial to verify by making a change and viewing the file afterwards.
Reading config from a file is just one way you can configure your app, and Flask doesn't try to provide an api for writing back to arbitrary config sources.


text:
Q: Using Graph API to Add Keys to Service Principals I am trying to use this endpoint to create a service principal and simultaneously create a key, which according to MS documentation(link) should be possible
"Create servicePrincipal and Update servicePrincipal operations can continue to be used to add and update key credentials for any servicePrincipal with or without a user's context."
POST
https://graph.microsoft.com/v1.0/servicePrincipals
My body looks like this:
{
  "appId": "65415bb1-9267-4313-bbf5-ae259732ee12",
              "keyCredentials": [{
                "key"         : "redacted",
                "type"        : "Symmetric",
                "usage"       : "Verify"
            }]
}

but Postman is throwing this error:
Cannot convert the literal 'redacted' to the expected type 'Edm.Binary'.
Has anyone run into this issue? Or better yet, has anyone been able to create a service principal for an app registration using the graph API and also create/add the key? The post to this endpoint works fine when only including the APPID in the body.
Tried using both the direct endpoint:
POST
https://graph.microsoft.com/v1.0/servicePrincipals/$Id/addKey

and also the standard one to add the service principal
POST
https://graph.microsoft.com/v1.0/servicePrincipals

I would expect them to succeed and create the serviceprincipal/add the key

A: The key property of keyCredential should contain the certificate's raw data in byte array converted to Base64 string.
You are using the correct endpoint, but you need to convert certificate's raw data to Base64 string.
POST https://graph.microsoft.com/v1.0/servicePrincipals

Body
{
    "appId": "65415bb1-9267-4313-bbf5-ae259732ee12",
    "keyCredentials": [{
        "key": "<certificate_raw_data_in_base64>",
        "type": "Symmetric",
        "usage": "Verify"
    }]
}

Documentation
keyCredential - properties

A: There is no API to add the key simultaneously while creating the service principle, As per the doc , you have to create the service principle first using the App Id .
POST https://graph.microsoft.com/v1.0/servicePrincipals
Content-type: application/json
{
"appId": "65415bb1-9267-4313-bbf5-ae259732ee12"
}
Once the SP created you will get the empty "keyCredentials": [] in response, doc - https://learn.microsoft.com/en-us/graph/api/serviceprincipal-post-serviceprincipals?view=graph-rest-1.0&tabs=http#response-1
Now you will follow the same Doc to add key.
POST https://graph.microsoft.com/v1.0/servicePrincipals/{id}/addKey
Content-type: application/json
{
    "keyCredential": {
        "type": "AsymmetricX509Cert",
        "usage": "Verify",
        "key": "MIIDYDCCAki..."
    },
    "passwordCredential": null,
    "proof":"eyJ0eXAiOiJ..."
}

Request body required 3 property keyCredential , passwordCredential , proof ,
!]3
Hope this helps
Thanks


text:
Q: difference seen in difftime and strftime values I'm seeing a difference in time functions and was wondering what was the reason.
currently, I'm using localtime, mktime, strftime and difftime:
time_t ltime;
ltime = time(NULL);
StartTM = localtime(&ltime);
time_t time1 = mktime(StartTM );
char startbuffer [128];
strftime( start_buffer, 128, "%H:%M:%S", StartTM );
<<Do some stuff, take some time >>>
time_t ttime;
ttime = time(NULL);
StopTM = localtime(&ttime);
time_t time2 = mktime(StopTM );
char stop_buffer [128];
strftime( stop_buffer, 128, "%H:%M:%S:", StopTM );
double wtinsec = difftime(time2, time1);

Executed, the output looks like this:
Stop buffer=08:46:18
Start buffer=08:44:11
wtinsec=129
Subtracting start from stop by hand, the length of time is 2:07, however the total number of seconds (difftime) says 2:09.  As both times are using the same raw data (time1, time2) for both calculations, my initial thoughts was combination of lack of precision in the strftime conversion and difftime is the cause of this.
But the difference is not constant.  If the time between the 2 local calls is small (like 10 seconds) there is no difference.  However, as the time between the 2 time calls gets longer, the difference in time totals becomes larger.  At 2 mins, its 2 seconds at 5 mins its 4 seconds and so on...
Any reason why this is happening and is there anything more accurate (in C++) preferably in micro/milliseconds that can track time of day and subtract one from another?
Thanks.

A: The values in ltime and time1 should be identical; the round trip through localtime() and mktime() should give you the answer you started with.  Similarly, of course, for ttime and time2.
This C code demonstrates the expected behaviour.  You need to look hard at your code to find out what is going wrong.
#include <stdio.h>
#include <time.h>
#include <unistd.h>

int main(void)
{

    time_t     ltime = time(NULL);
    struct tm *start = localtime(&ltime);
    time_t     time1 = mktime(start);
    char startbuffer[128];
    strftime(startbuffer, sizeof(startbuffer), "%H:%M:%S", start);
    printf("lt = %10lu, t1 = %10lu, time = %s\n",
           (unsigned long)ltime, (unsigned long)time1, startbuffer);

    sleep(10);

    time_t     ttime = time(NULL);
    struct tm *finis = localtime(&ttime);
    time_t     time2 = mktime(finis);
    strftime(startbuffer, sizeof(startbuffer), "%H:%M:%S", finis);
    printf("lt = %10lu, t1 = %10lu, time = %s\n",
           (unsigned long)ttime, (unsigned long)time2, startbuffer);

    printf("diff time = %.2f\n", difftime(time2, time1));

    return(0);
}

Sample output (from Mac OS X 10.7.5):
lt = 1358284665, t1 = 1358284665, time = 13:17:45
lt = 1358284675, t1 = 1358284675, time = 13:17:55
diff time = 10.00

I recommend looking at the values in your code, similar to the way I did.  You might (or might not) print out the contents of the struct tm structures.  It would be worth making a function to handle the 7-line block of repeated code; you'll need it to return time1 and time2, of course, so you can do the difference in the 'main' code. Also remember that localtime() may return the same pointer twice; you can't reliably use the start time structure after you've called localtime() with the finish time.


text:
Q: VBA: Array & countif All,
I am struggling on the approach to take for the following case in Excel VBA:
From different sheets I created an array in VBA (4 columns: key, type, date of activity A, date of activity B), e.g.:

I decided not to use a dictionary, because the size of the array (the # of cars) is given. I also didn't use simple copy-paste macros + countif.
First of all, do you agree an array in VBA is the best approach?
Now I want to have summarized results per activity in a table like this:

So now I am struggling what the best approach is:
1) Looping over the lines in the array and paste the values one by one in the table
2) Looping over the cells in the table and find corresponding cars
3) Copying to a separate sheet and use countif in the table
4) ...
Could you please help in advising? Hopefully the problem is clear.

A: Add some helper columns in (You can hide these later if you wish)

In Cell D2 the formula is =MONTH(C2), Cell E2 is =YEAR(C2) and the same for G and H but on column F
Then in your result table I've used the formula
=COUNTIFS($B$2:$B$4,$A8, $D$2:$D$4,MONTH(B$7),$E$2:$E$4,YEAR(B$7))

For Activity A, the same formula can be used for Activity B (But using columns G and H instead of D and E to get your results. No need for VBA

Update with vba approach
You can also try this VBA approach. You'll need to pay attention to the comments in all caps and update for your input and output. The code will take your input array and assume everything after column 2 is an Activity Date. It will then compile the results and write back to the sheet. This can work on any range of dates as it'll auto detect the first and last date (populating all dates in the year) and also any number of activities. There's a lot of loops going on here due to the flexibility of it all, but as it's all being handled in arrays/dictionaries (i.e. in memory) you shouldn't get a performance issue. You could probably do it in fewer but this should handle it in seconds no matter the data set size so gain over effort really isn't worth it.
Option Explicit
Public Sub GenerateResults()
    Dim arr As Variant, tmp As Variant, Dates() As Double, Results As Object
    Dim i As Long, j As Long, StartRow As Long, ResultsSeparator As Long
    Dim StartYear As Long, EndYear As Long, yr As Long, mo As Long
    Dim c

    ' ******UPDATE TO POINT AT YOUR ARRAY******
    With Sheet1
        arr = Range(.Cells(1, 1), .Cells(4, 5)).Value2
    End With

    Set Results = CreateObject("Scripting.Dictionary")

    For j = 3 To UBound(arr, 2)
        If StartYear < Format(WorksheetFunction.Min(Application.Index(arr, 0, j)), "yyyy") Then
             StartYear = Format(WorksheetFunction.Min(Application.Index(arr, 0, j)), "yyyy")
        End If
        If EndYear < Format(WorksheetFunction.Max(Application.Index(arr, 0, j)), "yyyy") Then
            EndYear = Format(WorksheetFunction.Max(Application.Index(arr, 0, j)), "yyyy")
        End If
    Next j

    ' 1 to 12 for months in the year, 1 to 2 for each activitity. This could be adapated for more then 12 months
    ReDim Dates(1 To (1 + EndYear - StartYear) * 12, 1 To UBound(arr, 2) - 2)

    For i = LBound(arr) To UBound(arr)
        Set tmp = Nothing
        ' Add to dictionary if colour not in array
        If Not Results.exists(arr(i, 2)) Then Results.Add Key:=arr(i, 2), Item:=Dates
        ' Assign your data to a temporary array so we can change it
        tmp = Results(arr(i, 2))
        ' Update data with activity dates
        For j = LBound(Dates, 2) To UBound(Dates, 2)
            tmp(12 * (Year(arr(i, 2 + j)) - StartYear) + Month(arr(i, 2 + j)), j) = tmp(12 * (Year(arr(i, 2 + j)) - StartYear) + Month(arr(i, 2 + j)), j) + 1
        Next j
        ' Write data back to dictionary
        Results(arr(i, 2)) = tmp
    Next i

    Application.ScreenUpdating = False
    ' ******CHANGE TO WHERE YOUR WANT YOUR RESULTS******
    ' Starting row of results (change to your output)
    StartRow = 7
    ' How many rows do you want between Activity A and B etc.
    ResultsSeparator = 3

    With Sheet1
        For j = LBound(Dates, 2) To UBound(Dates, 2)
            With .Cells(StartRow + (j - 1) * (ResultsSeparator + Results.Count), 1)
                .Value2 = UCase("Activity " & Split(.Cells(1, j).Address, "$")(1))
                .Font.Bold = True
            End With
        Next j
        StartRow = StartRow + 1
        For j = LBound(Dates, 1) To UBound(Dates, 1)
            yr = StartYear + IIf(j Mod 12 = 0, (j / 12) - 1, WorksheetFunction.RoundDown(j / 12, 0))
            mo = IIf(j > 12, j - 12 * IIf(j Mod 12 = 0, (j / 12) - 1, WorksheetFunction.RoundDown(j / 12, 0)), j)
            For i = LBound(Dates, 2) To UBound(Dates, 2)
                With .Cells(StartRow + (i - 1) * (ResultsSeparator + Results.Count), 1 + j)
                    .Value2 = DateSerial(yr, mo, 1)
                    .NumberFormat = "mmm-yy"
                End With
            Next i
        Next j
        StartRow = StartRow + 1
        ' Loop through dictionary
        For Each c In Results.keys
            ' Write back results for Activity A
            For j = LBound(Dates, 2) To UBound(Dates, 2)
                With .Cells(StartRow + (j - 1) * (ResultsSeparator + Results.Count), 1)
                    .Value2 = c
                    Range(.Offset(0, 1), .Offset(0, UBound(Results(c), 1))) = Application.Transpose(Application.Index(Results(c), 0, j))
                End With
            Next j
            ' Increase Row
            StartRow = StartRow + 1
        Next c
    End With
    Application.ScreenUpdating = True
End Sub


text:
Q: grid columns not displaying correctly I am using Bourbon Neat. I set some breakpoints in grid settings and for the mobile version I set 4 like this:
$mobile: new-breakpoint(max-width 480px 4);

I set the left and right containers like 3 for left and 1 for right; like this:
.demo
{

  @include outer-container;

  .leftContainer
  {
    @include span-columns( 6 );
    background-color:crimson;
    @include media($mobile) {
      @include span-columns( 3 of 4);
    }
  }

  .rightContainer
  {
    @include span-columns( 6 );
    background-color:blue;
  }

  @include media($mobile) {
    @include span-columns( 1 of 4 );
  }
}

But somehow the containers stack on each other instead of spanning 3 and 1 columns. What am I doing wrong?

A: It's hard to tell without seeing the HTML too, but looks like the .rightContainer code is what's breaking. The second @include media($mobile) {} is outside of the .rightContainer {}
Try this:
.demo{

  @include outer-container;

  .leftContainer {
    @include span-columns( 6 );
    background-color:crimson;

    @include media($mobile) {
        @include span-columns( 3 of 4);
    }
  }

  .rightContainer{
    @include span-columns( 6 );
    background-color:blue;

    @include media($mobile) {
        @include span-columns( 1 of 4 );
    }
  }
}

A: You are using @include span-columns(3 of 4) but the .leftContainer and .rightContainer aren´t nested inside another div with span-columns(), so you should not pass the columns of the parent as an argument.
Try this:
.demo{

  @include outer-container;

  .leftContainer {
    @include span-columns( 6 );
    background-color:crimson;

    @include media($mobile) {
        @include span-columns(3); /*Change this line*/
    }
  }

  .rightContainer{
    @include span-columns( 6 );
    background-color:blue;

    @include media($mobile) {
        @include span-columns(1); /*and this one*/
    }
  }
}

Maybe you can check this documentation for more help.


text:
Q: Laravel 4 - JSON data and an Undefined Method I am trying to select the last element from some JSON data but am getting an "Undefined Method" return.
My code is to get the $order_serialized data from a specific Order and then to pick the $last_item in that JSON data and plug it into a dd() just for testing right now. If anyone could point out or explain where I went wrong it would be very much appreciated! Thank you so very much!
Controller:
public function getEdit($id){
    $order = Order::where('id', '=', $id);

    if($order->count()) {
        $order          = $order->first();
        $order_serialized   = json_decode($order->order_serialized);
        $last_item          = $order_serialized->last();

                    dd($last_item);

        foreach($order->order_serialized as $key => $value){
            $order->$key = $value;
        }
        return View::make('orders.edit')
                ->with('order', $order);
                /*->with('last_item', $last_item);*/
    }   else {
        return App::abort(404);
    }
}

A: json_decode is going to return a stdClass object which does not have any methods, so calling $order_serialized->last() is giving you the "undefined method" error. In order to call the last method on some class, you're going to have to instantiate that class. I don't know of a way to decode JSON to a specific class in PHP.

A: When you do
$order_serialized   = json_decode($order->order_serialized);
You get back a standard class object, so it doesn't have any last() method.
I would do this instead:
$order_serialized   = json_decode($order->order_serialized, true);
$last_item = array_pop($order_serialized);

Sending true as the second param to json_decode will give you an array instead of an object.


text:
Q: Running java file in cmd - error given I recently moved a project from one machine to another but I am now given an error when attempting to run java files on the new machine. I'm trying to run a java file from part of an Android project in command prompt but I am given an error. The file compiles okay but fails to run. Here is the error I am given;
Exception in thread "main" java.lang.NoClassDefFoundError: ChatServer (
e: edu/UTEP/android/ChatServer)
        at java.lang.ClassLoader.defineClass1(Native Method)
        at java.lang.ClassLoader.defineClass(Unknown Source)
        at java.security.SecureClassLoader.defineClass(Unknown Source)
        at java.net.URLClassLoader.defineClass(Unknown Source)
        at java.net.URLClassLoader.access$100(Unknown Source)
        at java.net.URLClassLoader$1.run(Unknown Source)
        at java.net.URLClassLoader$1.run(Unknown Source)
        at java.security.AccessController.doPrivileged(Native Method)
        at java.net.URLClassLoader.findClass(Unknown Source)
        at java.lang.ClassLoader.loadClass(Unknown Source)
        at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
        at java.lang.ClassLoader.loadClass(Unknown Source)
        at sun.launcher.LauncherHelper.checkAndLoadMain(Unknown Source)

Any ideas why I am receiving this error?

A: Your ChatServer is having a package declaration of edu.UTEP.android in the top. So either you need to remove that package declaration recompile your java file again and run it
(or)
you need to create folder structure like this
CurrentDir/edu/UTEP/android/

Keep your java file in android folder and invoke java ChatServer from CurrentDir. Any of these two will solve the issue :-)
For more info on packages, you can refer to my previous answer on a similar issue here

A: Make sure that the .jar that provides ChatServer is in your runtime Classpath.

A: This issue rise when jvm don't file class path.
check where u have placed your jar file or lib folder.
Move to that directory then run javac and then java .
Issue will be resolved.


text:
Q: print photo from javascript I am retrieving same data with photos from a database with a query in PHP. i am sending this photos to Javascript as json. i get the encoded json string in javascript and i parse it
data = JSON.parse(request.responseText);
now i am printing the data in html. everything works okay. Except photos.
This is how i print data and photos:
tab.innerHTML += "
"+data[h].product_name+"
";
tab.innerHTML += "

";

I get this error
Not allowed to load local resource: file:///E:/xampp
localhost/:1 GET http://localhost/images/ 404 (Not Found)
alt='sorry:1 GET http://localhost/gamo9/css3_tabbed_nav/alt='sorry 404 (Not Found)
null:1 GET http://localhost/gamo9/css3_tabbed_nav/null 404 (Not Found)

What should I do?

A: What does data[h].product_photo have?
It should either be an URL of image loaded somewhere.
Or it can be base64 encoded image that you can display using something like:
`src="data:image/png;base64,...........


text:
Q: Echoing a number? For a file in sysfs, I tried using
echo 45>target_size

to set the value to 45. This failed, with an invalid entry. However, if I do:
x=45;echo $x>target_size

it works fine. Further, if I use a very big number, it gives me an error about having an invalid file number. So apparently when you echo a straight number, the terminal is interpreting that as a file descriptor, rather than a literal number. What is the proper way to  echo a number?

A: @steeldriver's answer is correct - the space between number and redirection operator matters. It seems to be an inconsistent behavior, as in my tests echo 45>output.txt writes 45 to file on ksh93 and dash shells.
As alternative you could always use tee command with here-string operator <<<.
tee  output_file.txt <<< "45"

Or with those shells that don't have <<< operator, echo 45 | tee output_file.txt

A: It's a matter of how the shell parses your command, I think. When you do
echo 45>target_size

the shell redirects file descriptor 45 to filetarget_size and then executes echo with no arguments.
If instead you do
echo 45 >target_size

it redirects the standard output descriptor to file target_size and then executes echo 45.
TL;DR add whitespace before the redirection operator.


text:
Q: Using pattern matching for Ordered.compare in Scala I have the following Scala class:
case class Person(firstName: String, lastName: String, age: Int)
    extends Ordered[Person] {
  def compare(that: Person): Int = {
    if (this.lastName < that.lastName) -1
    else if (this.lastName > that.lastName) 1
    else if (this.firstName < that.firstName) -1
    else if (this.firstName > that.firstName) 1
    else this.age compare that.age
  }
}

to allow sorting by lastName, firstName, and age.
How can I write this using pattern matching? I've come up with the following, but is there a better way?
case class Person(firstName: String, lastName: String, age: Int)
    extends Ordered[Person] {
  def compare(that: Person): Int = {
    that match {
      case Person(_, thatLastName, _) if this.lastName < thatFile => -1
      case Person(_, thatLastName, _) if this.lastName > thatFile => 1

      case Person(thatFirstName, _, _) if this.firstName < thatFirstName => -1
      case Person(thatFirstName, _, _) if this.firstName > thatFirstName => 1

      case Person(_, _, thatAge) => this.age compare thatAge
    }
  }
}

UPDATE: Changed to use Ordering[A] as per Landei's answer:
implicit val personOrdering = new Ordering[Person] {
  def compare(first: Person, second:Person): Int = {
    second match {
      case Person(_, thatLastName, _) if first.lastName < thatLastName => -1
      case Person(_, thatLastName, _) if first.lastName > thatLastName => 1

      case Person(thatFirstName, _, _) if first.firstName < thatFirstName => -1
      case Person(thatFirstName, _, _) if first.firstName > thatFirstName => 1

      case Person(_, _, thatAge) => first.age compare thatAge
    }
  }
}

case class Person(firstName: String, lastName: String, age: Int)

but it seems awkward that I only match second. How can I make it more "elegant"?

A: The preferred way in Scala is to provide an implicit Ordering instead of Ordered, which is much more flexible and doesn't give a headache concerning inheritance.
Concerning the pattern matching I see no better way, because the result of the compare methods are Ints, which are not guaranteed to be -1, 0, 1. Haskell's solution to give back "enum" objects (LT, EQ, GT) is much cleaner and pattern matchable, but it seems Scala followed the C++/Java tradition here for compatibility reasons.
Of course you could roll out your own comparision "framework":
abstract sealed class CompResult(val toInt:Int) {
  def andThen(next: => CompResult): CompResult
}
case object LT extends CompResult(-1) {
 def andThen(next: => CompResult) = LT
}
case object EQ extends CompResult(0) {
  def andThen(next: => CompResult) = next
}
case object GT extends CompResult(1) {
  def andThen(next: => CompResult) = GT
}

implicit def int2Comp(n:Int) =
   if (n == 0) EQ else if (n < 0) LT else GT

(("sdkfhs" compareTo "fldgkjdfl"):CompResult) match {
  case LT => println("less")
  case EQ => println("same")
  case GT => println("more")
}

In your case you could write:
case class Person(firstName: String, lastName: String, age: Int)
  extends Ordered[Person] {
  def compare(that: Person): Int = {
    (this.lastName compareTo that.lastName).
    andThen (this.firstName compareTo that.firstName).
    andThen (this.age compare that.age).toInt
  }
}


text:
Q: Open graph doesn't publish on the wall feed I've made an app with open graph.
Once I publish an action, it doesn't publish on my wall.
It publishes on  the activity feed instead.
Here is my code for publishing
function postCook()
{
  FB.api(
    '/me/[my app namespace]:cook?'
    ,
    'post',
    { recipe: 'http://www.xxx.com/Sample.html'
        ,access_token : 'MY TOKEN'},
    function(response) {
       if (!response || response.error) {
          alert( response.error.message );
       } else {
          alert('Cook was successful! Action ID: ' + response.id);
       }
    });
}

I also tried to follow the instruction here Tutorial
According to this tutorial, I've seen that Open Graph can publish to News Feed.
But I cannot make my app publish to News Feed.
Do I have to set any parameters to force it to publish on News feed (on my wall)?
Which permission I have to request?
publish_actions or publish_stream?
Thanks,

A: You cannot force Open Graph actions to be published to the news feed. Facebook keep tight control over the feed and by default, your OG actions always get published to the activity feed. And sometime only do they reach the News Feed (of your friends - never seen mine in my own feed).
So that's it, you cannot force it. Although, don't worry too much about this, OG actions actually get published often enough to allow "virality" of your app, and good reach of new user. It's definitly better than a share action, even if this one get published to the News Feed instantly.


text:
Q: How to pass multiple characters as single character to input value? When you do something like <input type="submit" value="Submit"> the button will be named Submit (because that's its value).
But what if I'm using font that doesn't have "A" letter attached to "A" position etc.? Instead it uses its own space for characters and uses for instance \f002 (this is single character). It is vector icons font and I'd like to use one icon as value of submit input.
Using <input type="submit" value="\f002"> is going to just print \f002 and not that single icon. How can I convert this?
PS
It works excellent when I use content: "\f002"; in style.css. It converts this full string to an icon.
PPS
Icons set: http://fortawesome.github.com/Font-Awesome/

A: Okay, I made it work. The answer:  but I don't have explanation - I just remember that some time ago I was struggling with similar issue and adding x helped.

A: Maybe you'd try to add a class attribute to the input button?
i.e.: <input type="submit" value="Submit" class="myClass">
Take a look at this article: http://www.webreference.com/programming/css_stylish/index.html


text:
Q: How to get data from multiple tables using SQL query I have three Tables Administration with relation one-to-many with Telephone, Fax Tables:
Administration : Id_Administration, Lib_Administration
Telephone: Id_Phone, Phone_Number, Id_Administration
Fax: Id_Fax, Fax_Number, Id_Administration
Administration table contains:
Id_Administration Lib_Administration
1                 adminstration1
2                 adminstration2

Telephone table contains:
Id_Phone Phone_Number Id_Administration
1        0313131      1
2        0212121      1
3        0353535      2
4        0343434      2

Fax table contains:
Id_Fax  Fax_Number  Id_Administration
1       0323232     1
2       0363636     2
3       0373737     2

I want to make a query to show this result:
Id_Administration Lib_Administration Phone_Number Fax_Number
1                 adminstration1     0313131      0323232
                                     0212121
2                 adminstration2     0353535      0363636
                                     0343434      0373737

I used this query
SELECT   Administration.Id_Administration, Administration.Lib_Administration,Telephone.Phone_Number, Fax.Fax_Number
FROM     ((Administration INNER JOIN
         Telephone ON Administration.Id_Administration = Telephone.Id_Administration) INNER JOIN
         Fax ON Administration.Id_Administration = Fax.Id_Administration)

But the result was iterated like this:
Id_Administration Lib_Administration Phone_Number Fax_Number
    1                 adminstration1     0313131      0323232
                                         0212121      0323232
    2                 adminstration2     0353535      0363636
                                         0343434      0363636
                                         0353535      0373737
                                         0343434      0373737

I used left join but i didn't get the right result, so where is the problem in my query?

A: Everything is possible, but sometimes hard work to achieve our goal is not worth it. Are you trying to prepare a recordset for your form?
In this scenario I would have 2 subforms, for phone and fax numbers. No need to load all in one recordset.

A: I don't think the original table structure works.  In the posted DDL you have administration-level granularity.  What you want to do is pair a phone number with a fax number- I would call this the office-level granularity.  What you can do is add another level of granularity by creating an Office table.  In the inserts, link each phone and fax number also to this office ID.  For the Select, join the phone and fax tables also to this Id_Office.  This should pair the phones by both Organization and Office to give the expected output.
For example if you include an Office table similar to below:
CREATE TABLE Administration (Id_Administration int, Lib_Administration varchar(100))
INSERT INTO Administration (Id_Administration, Lib_Administration) VALUES
 (1, 'adminstration1'), (2, 'adminstration2')

CREATE TABLE Office(Id_Administration int, Id_Office int, Lib_Office varchar(100))
INSERT INTO Office (Id_Administration, Id_Office, Lib_Office) VALUES
 (1, 1, 'A1 Office 1'), (1, 2, 'A1 Office 2')
,(2, 1, 'A2 Office 2'), (2, 2, 'A2 Office 2')

CREATE TABLE Fax (Id_Fax int, Fax_Number char(7), Id_Administration int, Id_Office int)
INSERT INTO Fax (Id_Fax, Fax_Number, Id_Administration, Id_Office) VALUES
 (1, '0323232', 1, 1), (2, '0363636', 2, 1)
,(3, '0373737', 2, 2)

CREATE TABLE Telephone (Id_Phone int, Phone_Number char(7), Id_Administration int, Id_Office int)
INSERT INTO Telephone (Id_Phone, Phone_Number, Id_Administration, Id_Office) VALUES
 (1, '0313131', 1, 1)
,(2, '0212121', 1, 2)
,(3, '0353535', 2, 1)
,(4, '0343434', 2, 2)

SELECT A.Id_Administration, A.Lib_Administration, T.Phone_Number, COALESCE(F.Fax_Number, '') AS Fax_Number
  FROM Administration A LEFT JOIN Office O ON A.Id_Administration = O.Id_Administration
                         LEFT JOIN Fax F ON F.Id_Administration = A.Id_Administration AND F.Id_Office = O.Id_Office
                         LEFT JOIN Telephone T ON T.Id_Administration = A.Id_Administration AND T.Id_Office = O.Id_Office

This produces output:
Id_Administration   Lib_Administration  Phone_Number    Fax_Number
                1       adminstration1       0313131       0323232
                1       adminstration1       0212121
                2       adminstration2       0353535       0363636
                2       adminstration2       0343434       0373737

http://sqlfiddle.com/#!18/27964/3/0


text:
Q: Impact of variance on the characterization of random variables Suppose I have two discrete random variables $X$ and $Y$, and all I know is  that they take values from the same set of non-negative integers, their expectations are the same $\mathbb{E}[X]=\mathbb{E}[Y]=\mu$, and their variances $\operatorname{Var}[X]=\mathbb{E}[(X-\mu)^2]=\sigma^2_X$ and $\operatorname{Var}[Y]=\mathbb{E}[(Y-\mu)^2]= \sigma^2_Y$ are different.
Let's take $\sigma^2_X<\sigma^2_Y$.  It's clear that $Y$ is more "dispersed" than $X$, but can anything quantitative be said about the distribution of $X$ relative to $Y$ given $\mu$, $\sigma^2_X$, and $\sigma^2_Y$?  Say, for instance, something like $f[P(X\leq x),P(X\leq x)]\leq g(\sigma^2_X,\sigma^2_Y)$ where less-than-or-equals is used as an example (it could be some other relationship), $f[\cdot,\cdot]$ relates the distributions and $g(\cdot,\cdot)$ the variances.

A: The only comparisons this can yield must be based on integrals since each variance results from the compound effect of all the distribution. An example is as follows. For every random variable $Z$ with mean $\mu$ and every $z\gt0$, let
$$\delta_Z(z)=P[|Z-\mu|\gt z].$$
The function $\delta_Z$ measures the decrease of the mass the distribution of $Z$ puts on the (symmetrical) deviations from the mean. Also, $\delta_Z(z)$ is the probability that, Bienaymé-Chebyshev inequality tells us, is bounded by $\sigma_Z^2/z^2$ for every $z$. Then,
$$\sigma_X^2\lt\sigma_Y^2\iff
\int_0^\infty z\,\delta_X(z)\,\mathrm dz\lt\int_0^\infty z\,\delta_Y(z)\,\mathrm dz,
$$
for example because
$$
\sigma_Y^2-\sigma_X^2=2\int_0^\infty z\,(\delta_Y(z)-\delta_X(z))\,\mathrm dz.
$$


text:
Q: unable to get the result of query I have data of 4 semesters in the db name,reg_no,sem,backlog,and department.
student will be eligible only if has no backlogs in 1st,2nd semester and the sum of 3rd and 4th semester backlogs are less the 4.
I want to fetch the records of students those are not eligible.
example:-data in the format of
name|reg_no|sem|backlog|department|
s1  |01    |1  |0      |cs        |
s2  |02    |1  |1      |cs        |
s3  |03    |1  |0      |cs        |

s1  |01    |2  |0      |cs        |
s2  |02    |2  |0      |cs        |
s3  |03    |2  |0      |cs        |

s1  |01    |3  |0      |cs        |
s2  |02    |3  |0      |cs        |
s3  |03    |3  |3      |cs        |

s1  |01    |4  |0      |cs        |
s2  |02    |4  |0      |cs        |
s3  |03    |4  |3      |cs        |

I need the result in this format
the output should be in this form as s2 has backlog in semester 1
and s3 has the more the 4 backlogs.
name|reg_no|sum(blacklog)|department|
s2  |02    |1            |cs        |
s3  |03    |6            |cs        |

I am using this query.
SELECT reg_no
FROM exam
where sem<3 and reg_no In(
                          SELECT reg_no
                          FROM exam
                          where sem<5
                          and department='dpt'
                          and year='2018-2019'
                          group by reg_no
                          having sum(backlog)>=0
                          order by reg_no)
group by reg_no
having sum(backlog)!=0

which gives me only the 3rd and 4th semester sum(blg) result only if it has the sum(blg)!=0 it does not give the result.
please help me out i apologize i am unable to describe my query.


text:
Q: Link opens page with modal active I have searched without much success, I have a "clients" page with ~60 clients listen. Each one has a unique modal that opens up with more information and details. What I would like is to reference some of the top clients on the home page with a link to open the clients page with modal already open. This was a project I took over so the js file is a bit of a rat's nest to dig through. Hoping there's a simpler answer.
Link Div

      <a href="#champion2" data-toggle="modal" data-target="#champion2" class="item-img-overlay">

Modal Id

      <div class="modal fade" id="champion2" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">

Please help with any js or way I should link the separate URL to have these open when lined.

A: I was able to get this working with some help. I had another hash filter so needed to work around that.  code is
  $(document).ready(function () {
    var hash = window.location.hash;
    var isClientModalRequest = hash.indexOf('client') > -1;

    if (!isClientModalRequest)
        return;

    var client = hash.split('=')[1];
    var element = $('#' + client);

    element.modal('show');
    element.css('display', 'block');
    element.addClass('in');
});


text:
Q: Flask - How to change the directory of the templates folder? I am trying to change the directory of my Flask Templates folder. I have tried this:
template_dir = os.path.abspath('../website/endpoint')
app = Flask(__name__, template_folder=template_dir)
@app.route("/api/t-tycoon/sotd")
def tt_sotd():
return render_template("sotd.html")

This code, however, creates the following error:
return render_template("sotd.html")

Another handy thing to have is the directories, so here you have it.
main.py
website
   endpoint
      sotd.html
   jsons

I have no clue what is wrong, and how this works. I read some things online about changing the Flask directory but it does not work.
If more information is needed, please let me know. I hope someone can help me figure this, as I have no clue myself.
Error: jinja2.exceptions.TemplateNotFound: sotd.html

A: You need to create your templates subdirectory next to the python module (the module where you create your Flask app- main.py in your example):
main.py
templates_subdirectory
    sotd.html

Move your template (sotd.html) to 'website' directory and configure it to be your templates subdirectory, that should solve your problem.

A: The path you are using is wrong. As @NavaneethaKrishnan said it should be os.path.abspath('website/endpoint').
However this solution is not perfect either. website/endpoint is still a relative path and it is relative to your current working directory. As a result it will only work if your current working directory is the one main.py lives in.
A better solution is:
dir_path = os.path.dirname(os.path.realpath(__file__))
template_dir = os.path.join(dir_path, "website/endpoint")

Here dir_path is the absolute path of the directory under which main.py lives in. By concatenating dir_path and website/endpoint, your template directory is guaranteed to be the one you've created and it will be irrelevant with your current working directory.


text:
Q: GLM on compile breeds a ton of errors I include some GLM files into my code, and I receive a ton of errors (at least 90 of them). Why this is happening, I have no idea. I am using the latest GLM (0.9.3.3 at the time of this writing). I am also using Qt Creator on Windows, with a QMake file you'll see.
I should also note that I ended up copying the glm folder to my include directory reciding in my mingw folder.
What can I do to fix this?
QMake
CONFIG += console

HEADERS += \
    util.hpp \
    ShaderComparable.hpp \
    SearchTree.hpp \
    FileUtility.hpp \
    Debug.hpp \
    ShaderHandler.hpp \
    Shader.hpp \
    Testing.hpp \
    Sphere.hpp \
    Shape.hpp \
    Circle.hpp \
    Maths.hpp

SOURCES += \
    util.cpp \
    ShaderComparable.cpp \
    SearchTree.inl \
    Main.cpp \
    FileUtility.cpp \
    Debug.cpp \
    ShaderHandler.cpp \
    Testing.cpp \
    Sphere.cpp \
    Shape.cpp \
    Circle.cpp

win32:LIBS += -llibEGL -llibGLESv2
unix: LIBS += -lEGL -lGLESv2

QMAKE_CXXFLAGS += -std=c++0x -U__STRICT_ANSI__

Errors
c:\qtsdk\mingw\bin\../lib/gcc/mingw32/4.4.0/../../../../include/glm/glm/./core/type_vec4.hpp: In instantiation of 'glm::detail::tvec4<glm::detail::half>::<anonymous union>':
c:\qtsdk\mingw\bin\../lib/gcc/mingw32/4.4.0/../../../../include/glm/glm/./core/type_vec4.hpp:82:   instantiated from 'glm::detail::tvec4<glm::detail::half>'
c:\qtsdk\mingw\bin\../lib/gcc/mingw32/4.4.0/../../../../include/glm/glm/./gtc/swizzle.hpp:114:   instantiated from here
c:\qtsdk\mingw\bin\../lib/gcc/mingw32/4.4.0/../../../../include/glm/glm/./core/type_vec4.hpp:79: error: member 'glm::detail::half glm::detail::tvec4<glm::detail::half>::<anonymous union>::<anonymous struct>::r' with constructor not allowed in union
c:\qtsdk\mingw\bin\../lib/gcc/mingw32/4.4.0/../../../../include/glm/glm/./core/type_vec4.hpp:79: error: member 'glm::detail::half glm::detail::tvec4<glm::detail::half>::<anonymous union>::<anonymous struct>::r' with copy assignment operator not allowed in union
c:\qtsdk\mingw\bin\../lib/gcc/mingw32/4.4.0/../../../../include/glm/glm/./core/type_vec4.hpp:79: error: member 'glm::detail::half glm::detail::tvec4<glm::detail::half>::<anonymous union>::<anonymous struct>::g' with constructor not allowed in union
c:\qtsdk\mingw\bin\../lib/gcc/mingw32/4.4.0/../../../../include/glm/glm/./core/type_vec4.hpp:79: error: member 'glm::detail::half glm::detail::tvec4<glm::detail::half>::<anonymous union>::<anonymous struct>::g' with copy assignment operator not allowed in union
c:\qtsdk\mingw\bin\../lib/gcc/mingw32/4.4.0/../../../../include/glm/glm/./core/type_vec4.hpp:79: error: member 'glm::detail::half glm::detail::tvec4<glm::detail::half>::<anonymous union>::<anonymous struct>::b' with constructor not allowed in union
c:\qtsdk\mingw\bin\../lib/gcc/mingw32/4.4.0/../../../../include/glm/glm/./core/type_vec4.hpp:79: error: member 'glm::detail::half glm::detail::tvec4<glm::detail::half>::<anonymous union>::<anonymous struct>::b' with copy assignment operator not allowed in union
c:\qtsdk\mingw\bin\../lib/gcc/mingw32/4.4.0/../../../../include/glm/glm/./core/type_vec4.hpp:79: error: member 'glm::detail::half glm::detail::tvec4<glm::detail::half>::<anonymous union>::<anonymous struct>::a' with constructor not allowed in union
c:\qtsdk\mingw\bin\../lib/gcc/mingw32/4.4.0/../../../../include/glm/glm/./core/type_vec4.hpp:79: error: member 'glm::detail::half glm::detail::tvec4<glm::detail::half>::<anonymous union>::<anonymous struct>::a' with copy assignment operator not allowed in union
c:\qtsdk\mingw\bin\../lib/gcc/mingw32/4.4.0/../../../../include/glm/glm/./core/type_vec4.hpp:80: error: member 'glm::detail::half glm::detail::tvec4<glm::detail::half>::<anonymous union>::<anonymous struct>::s' with constructor not allowed in union
c:\qtsdk\mingw\bin\../lib/gcc/mingw32/4.4.0/../../../../include/glm/glm/./core/type_vec4.hpp:80: error: member 'glm::detail::half glm::detail::tvec4<glm::detail::half>::<anonymous union>::<anonymous struct>::s' with copy assignment operator not allowed in union
c:\qtsdk\mingw\bin\../lib/gcc/mingw32/4.4.0/../../../../include/glm/glm/./core/type_vec4.hpp:80: error: member 'glm::detail::half glm::detail::tvec4<glm::detail::half>::<anonymous union>::<anonymous struct>::t' with constructor not allowed in union
c:\qtsdk\mingw\bin\../lib/gcc/mingw32/4.4.0/../../../../include/glm/glm/./core/type_vec4.hpp:80: error: member 'glm::detail::half glm::detail::tvec4<glm::detail::half>::<anonymous union>::<anonymous struct>::t' with copy assignment operator not allowed in union
c:\qtsdk\mingw\bin\../lib/gcc/mingw32/4.4.0/../../../../include/glm/glm/./core/type_vec4.hpp:80: error: member 'glm::detail::half glm::detail::tvec4<glm::detail::half>::<anonymous union>::<anonymous struct>::p' with constructor not allowed in union
c:\qtsdk\mingw\bin\../lib/gcc/mingw32/4.4.0/../../../../include/glm/glm/./core/type_vec4.hpp:80: error: member 'glm::detail::half glm::detail::tvec4<glm::detail::half>::<anonymous union>::<anonymous struct>::p' with copy assignment operator not allowed in union
c:\qtsdk\mingw\bin\../lib/gcc/mingw32/4.4.0/../../../../include/glm/glm/./core/type_vec4.hpp:80: error: member 'glm::detail::half glm::detail::tvec4<glm::detail::half>::<anonymous union>::<anonymous struct>::q' with constructor not allowed in union
c:\qtsdk\mingw\bin\../lib/gcc/mingw32/4.4.0/../../../../include/glm/glm/./core/type_vec4.hpp:80: error: member 'glm::detail::half glm::detail::tvec4<glm::detail::half>::<anonymous union>::<anonymous struct>::q' with copy assignment operator not allowed in union
c:\qtsdk\mingw\bin\../lib/gcc/mingw32/4.4.0/../../../../include/glm/glm/./core/type_vec4.hpp:81: error: member 'glm::detail::half glm::detail::tvec4<glm::detail::half>::<anonymous union>::<anonymous struct>::x' with constructor not allowed in union
c:\qtsdk\mingw\bin\../lib/gcc/mingw32/4.4.0/../../../../include/glm/glm/./core/type_vec4.hpp:81: error: member 'glm::detail::half glm::detail::tvec4<glm::detail::half>::<anonymous union>::<anonymous struct>::x' with copy assignment operator not allowed in union
c:\qtsdk\mingw\bin\../lib/gcc/mingw32/4.4.0/../../../../include/glm/glm/./core/type_vec4.hpp:81: error: member 'glm::detail::half glm::detail::tvec4<glm::detail::half>::<anonymous union>::<anonymous struct>::y' with constructor not allowed in union
c:\qtsdk\mingw\bin\../lib/gcc/mingw32/4.4.0/../../../../include/glm/glm/./core/type_vec4.hpp:81: error: member 'glm::detail::half glm::detail::tvec4<glm::detail::half>::<anonymous union>::<anonymous struct>::y' with copy assignment operator not allowed in union
c:\qtsdk\mingw\bin\../lib/gcc/mingw32/4.4.0/../../../../include/glm/glm/./core/type_vec4.hpp:81: error: member 'glm::detail::half glm::detail::tvec4<glm::detail::half>::<anonymous union>::<anonymous struct>::z' with constructor not allowed in union
c:\qtsdk\mingw\bin\../lib/gcc/mingw32/4.4.0/../../../../include/glm/glm/./core/type_vec4.hpp:81: error: member 'glm::detail::half glm::detail::tvec4<glm::detail::half>::<anonymous union>::<anonymous struct>::z' with copy assignment operator not allowed in union
c:\qtsdk\mingw\bin\../lib/gcc/mingw32/4.4.0/../../../../include/glm/glm/./core/type_vec4.hpp:81: error: member 'glm::detail::half glm::detail::tvec4<glm::detail::half>::<anonymous union>::<anonymous struct>::w' with constructor not allowed in union
c:\qtsdk\mingw\bin\../lib/gcc/mingw32/4.4.0/../../../../include/glm/glm/./core/type_vec4.hpp:81: error: member 'glm::detail::half glm::detail::tvec4<glm::detail::half>::<anonymous union>::<anonymous struct>::w' with copy assignment operator not allowed in union
mingw32-make.exe[1]: Leaving directory `C:/Programming/C++/Qt/qtesc/esc/Debug'
In file included from c:\qtsdk\mingw\bin\../lib/gcc/mingw32/4.4.0/../../../../include/glm/glm/./core/type.hpp:40,
                 from c:\qtsdk\mingw\bin\../lib/gcc/mingw32/4.4.0/../../../../include/glm/glm/glm.hpp:97,
                 from ../esc/Maths.hpp:3,
                 from ../esc/Sphere.hpp:5,
                 from ../esc/Sphere.cpp:1:
c:\qtsdk\mingw\bin\../lib/gcc/mingw32/4.4.0/../../../../include/glm/glm/./core/type_vec3.hpp: In instantiation of 'glm::detail::tvec3<std::basic_ostream<char, std::char_traits<char> > >::<anonymous union>':
c:\qtsdk\mingw\bin\../lib/gcc/mingw32/4.4.0/../../../../include/glm/glm/./core/type_vec3.hpp:82:   instantiated from 'glm::detail::tvec3<std::basic_ostream<char, std::char_traits<char> > >'
c:\qtsdk\mingw\bin\../lib/gcc/mingw32/4.4.0/../../../../include/glm/glm/./virtrev/xstream.hpp:92:   instantiated from here
c:\qtsdk\mingw\bin\../lib/gcc/mingw32/4.4.0/../../../../include/glm/glm/./core/type_vec3.hpp:79: error: member 'std::basic_ostream<char, std::char_traits<char> > glm::detail::tvec3<std::basic_ostream<char, std::char_traits<char> > >::<anonymous union>::<anonymous struct>::r' with constructor not allowed in union
c:\qtsdk\mingw\bin\../lib/gcc/mingw32/4.4.0/../../../../include/glm/glm/./core/type_vec3.hpp:79: error: member 'std::basic_ostream<char, std::char_traits<char> > glm::detail::tvec3<std::basic_ostream<char, std::char_traits<char> > >::<anonymous union>::<anonymous struct>::r' with destructor not allowed in union
c:\qtsdk\mingw\bin\../lib/gcc/mingw32/4.4.0/../../../../include/glm/glm/./core/type_vec3.hpp:79: error: member 'std::basic_ostream<char, std::char_traits<char> > glm::detail::tvec3<std::basic_ostream<char, std::char_traits<char> > >::<anonymous union>::<anonymous struct>::r' with copy assignment operator not allowed in union
c:\qtsdk\mingw\bin\../lib/gcc/mingw32/4.4.0/../../../../include/glm/glm/./core/type_vec3.hpp:79: error: member 'std::basic_ostream<char, std::char_traits<char> > glm::detail::tvec3<std::basic_ostream<char, std::char_traits<char> > >::<anonymous union>::<anonymous struct>::g' with constructor not allowed in union
c:\qtsdk\mingw\bin\../lib/gcc/mingw32/4.4.0/../../../../include/glm/glm/./core/type_vec3.hpp:79: error: member 'std::basic_ostream<char, std::char_traits<char> > glm::detail::tvec3<std::basic_ostream<char, std::char_traits<char> > >::<anonymous union>::<anonymous struct>::g' with destructor not allowed in union
c:\qtsdk\mingw\bin\../lib/gcc/mingw32/4.4.0/../../../../include/glm/glm/./core/type_vec3.hpp:79: error: member 'std::basic_ostream<char, std::char_traits<char> > glm::detail::tvec3<std::basic_ostream<char, std::char_traits<char> > >::<anonymous union>::<anonymous struct>::g' with copy assignment operator not allowed in union
c:\qtsdk\mingw\bin\../lib/gcc/mingw32/4.4.0/../../../../include/glm/glm/./core/type_vec3.hpp:79: error: member 'std::basic_ostream<char, std::char_traits<char> > glm::detail::tvec3<std::basic_ostream<char, std::char_traits<char> > >::<anonymous union>::<anonymous struct>::b' with constructor not allowed in union
c:\qtsdk\mingw\bin\../lib/gcc/mingw32/4.4.0/../../../../include/glm/glm/./core/type_vec3.hpp:79: error: member 'std::basic_ostream<char, std::char_traits<char> > glm::detail::tvec3<std::basic_ostream<char, std::char_traits<char> > >::<anonymous union>::<anonymous struct>::b' with destructor not allowed in union
c:\qtsdk\mingw\bin\../lib/gcc/mingw32/4.4.0/../../../../include/glm/glm/./core/type_vec3.hpp:79: error: member 'std::basic_ostream<char, std::char_traits<char> > glm::detail::tvec3<std::basic_ostream<char, std::char_traits<char> > >::<anonymous union>::<anonymous struct>::b' with copy assignment operator not allowed in union
c:\qtsdk\mingw\bin\../lib/gcc/mingw32/4.4.0/../../../../include/glm/glm/./core/type_vec3.hpp:80: error: member 'std::basic_ostream<char, std::char_traits<char> > glm::detail::tvec3<std::basic_ostream<char, std::char_traits<char> > >::<anonymous union>::<anonymous struct>::s' with constructor not allowed in union
c:\qtsdk\mingw\bin\../lib/gcc/mingw32/4.4.0/../../../../include/glm/glm/./core/type_vec3.hpp:80: error: member 'std::basic_ostream<char, std::char_traits<char> > glm::detail::tvec3<std::basic_ostream<char, std::char_traits<char> > >::<anonymous union>::<anonymous struct>::s' with destructor not allowed in union
c:\qtsdk\mingw\bin\../lib/gcc/mingw32/4.4.0/../../../../include/glm/glm/./core/type_vec3.hpp:80: error: member 'std::basic_ostream<char, std::char_traits<char> > glm::detail::tvec3<std::basic_ostream<char, std::char_traits<char> > >::<anonymous union>::<anonymous struct>::s' with copy assignment operator not allowed in union
c:\qtsdk\mingw\bin\../lib/gcc/mingw32/4.4.0/../../../../include/glm/glm/./core/type_vec3.hpp:80: error: member 'std::basic_ostream<char, std::char_traits<char> > glm::detail::tvec3<std::basic_ostream<char, std::char_traits<char> > >::<anonymous union>::<anonymous struct>::t' with constructor not allowed in union
c:\qtsdk\mingw\bin\../lib/gcc/mingw32/4.4.0/../../../../include/glm/glm/./core/type_vec3.hpp:80: error: member 'std::basic_ostream<char, std::char_traits<char> > glm::detail::tvec3<std::basic_ostream<char, std::char_traits<char> > >::<anonymous union>::<anonymous struct>::t' with destructor not allowed in union
c:\qtsdk\mingw\bin\../lib/gcc/mingw32/4.4.0/../../../../include/glm/glm/./core/type_vec3.hpp:80: error: member 'std::basic_ostream<char, std::char_traits<char> > glm::detail::tvec3<std::basic_ostream<char, std::char_traits<char> > >::<anonymous union>::<anonymous struct>::t' with copy assignment operator not allowed in union
c:\qtsdk\mingw\bin\../lib/gcc/mingw32/4.4.0/../../../../include/glm/glm/./core/type_vec3.hpp:80: error: member 'std::basic_ostream<char, std::char_traits<char> > glm::detail::tvec3<std::basic_ostream<char, std::char_traits<char> > >::<anonymous union>::<anonymous struct>::p' with constructor not allowed in union
c:\qtsdk\mingw\bin\../lib/gcc/mingw32/4.4.0/../../../../include/glm/glm/./core/type_vec3.hpp:80: error: member 'std::basic_ostream<char, std::char_traits<char> > glm::detail::tvec3<std::basic_ostream<char, std::char_traits<char> > >::<anonymous union>::<anonymous struct>::p' with destructor not allowed in union
c:\qtsdk\mingw\bin\../lib/gcc/mingw32/4.4.0/../../../../include/glm/glm/./core/type_vec3.hpp:80: error: member 'std::basic_ostream<char, std::char_traits<char> > glm::detail::tvec3<std::basic_ostream<char, std::char_traits<char> > >::<anonymous union>::<anonymous struct>::p' with copy assignment operator not allowed in union
c:\qtsdk\mingw\bin\../lib/gcc/mingw32/4.4.0/../../../../include/glm/glm/./core/type_vec3.hpp:81: error: member 'std::basic_ostream<char, std::char_traits<char> > glm::detail::tvec3<std::basic_ostream<char, std::char_traits<char> > >::<anonymous union>::<anonymous struct>::x' with constructor not allowed in union
c:\qtsdk\mingw\bin\../lib/gcc/mingw32/4.4.0/../../../../include/glm/glm/./core/type_vec3.hpp:81: error: member 'std::basic_ostream<char, std::char_traits<char> > glm::detail::tvec3<std::basic_ostream<char, std::char_traits<char> > >::<anonymous union>::<anonymous struct>::x' with destructor not allowed in union
c:\qtsdk\mingw\bin\../lib/gcc/mingw32/4.4.0/../../../../include/glm/glm/./core/type_vec3.hpp:81: error: member 'std::basic_ostream<char, std::char_traits<char> > glm::detail::tvec3<std::basic_ostream<char, std::char_traits<char> > >::<anonymous union>::<anonymous struct>::x' with copy assignment operator not allowed in union
c:\qtsdk\mingw\bin\../lib/gcc/mingw32/4.4.0/../../../../include/glm/glm/./core/type_vec3.hpp:81: error: member 'std::basic_ostream<char, std::char_traits<char> > glm::detail::tvec3<std::basic_ostream<char, std::char_traits<char> > >::<anonymous union>::<anonymous struct>::y' with constructor not allowed in union
c:\qtsdk\mingw\bin\../lib/gcc/mingw32/4.4.0/../../../../include/glm/glm/./core/type_vec3.hpp:81: error: member 'std::basic_ostream<char, std::char_traits<char> > glm::detail::tvec3<std::basic_ostream<char, std::char_traits<char> > >::<anonymous union>::<anonymous struct>::y' with destructor not allowed in union
c:\qtsdk\mingw\bin\../lib/gcc/mingw32/4.4.0/../../../../include/glm/glm/./core/type_vec3.hpp:81: error: member 'std::basic_ostream<char, std::char_traits<char> > glm::detail::tvec3<std::basic_ostream<char, std::char_traits<char> > >::<anonymous union>::<anonymous struct>::y' with copy assignment operator not allowed in union
c:\qtsdk\mingw\bin\../lib/gcc/mingw32/4.4.0/../../../../include/glm/glm/./core/type_vec3.hpp:81: error: member 'std::basic_ostream<char, std::char_traits<char> > glm::detail::tvec3<std::basic_ostream<char, std::char_traits<char> > >::<anonymous union>::<anonymous struct>::z' with constructor not allowed in union
c:\qtsdk\mingw\bin\../lib/gcc/mingw32/4.4.0/../../../../include/glm/glm/./core/type_vec3.hpp:81: error: member 'std::basic_ostream<char, std::char_traits<char> > glm::detail::tvec3<std::basic_ostream<char, std::char_traits<char> > >::<anonymous union>::<anonymous struct>::z' with destructor not allowed in union
c:\qtsdk\mingw\bin\../lib/gcc/mingw32/4.4.0/../../../../include/glm/glm/./core/type_vec3.hpp:81: error: member 'std::basic_ostream<char, std::char_traits<char> > glm::detail::tvec3<std::basic_ostream<char, std::char_traits<char> > >::<anonymous union>::<anonymous struct>::z' with copy assignment operator not allowed in union
In file included from c:\qtsdk\mingw\bin\../lib/gcc/mingw32/4.4.0/../../../../include/glm/glm/./core/type.hpp:39,
                 from c:\qtsdk\mingw\bin\../lib/gcc/mingw32/4.4.0/../../../../include/glm/glm/glm.hpp:97,
                 from ../esc/Maths.hpp:3,
                 from ../esc/Sphere.hpp:5,
                 from ../esc/Sphere.cpp:1:
c:\qtsdk\mingw\bin\../lib/gcc/mingw32/4.4.0/../../../../include/glm/glm/./core/type_vec2.hpp: In instantiation of 'glm::detail::tvec2<std::basic_ostream<char, std::char_traits<char> > >::<anonymous union>':
c:\qtsdk\mingw\bin\../lib/gcc/mingw32/4.4.0/../../../../include/glm/glm/./core/type_vec2.hpp:82:   instantiated from 'glm::detail::tvec2<std::basic_ostream<char, std::char_traits<char> > >'
c:\qtsdk\mingw\bin\../lib/gcc/mingw32/4.4.0/../../../../include/glm/glm/./virtrev/xstream.hpp:92:   instantiated from here
c:\qtsdk\mingw\bin\../lib/gcc/mingw32/4.4.0/../../../../include/glm/glm/./core/type_vec2.hpp:79: error: member 'std::basic_ostream<char, std::char_traits<char> > glm::detail::tvec2<std::basic_ostream<char, std::char_traits<char> > >::<anonymous union>::<anonymous struct>::r' with constructor not allowed in union
c:\qtsdk\mingw\bin\../lib/gcc/mingw32/4.4.0/../../../../include/glm/glm/./core/type_vec2.hpp:79: error: member 'std::basic_ostream<char, std::char_traits<char> > glm::detail::tvec2<std::basic_ostream<char, std::char_traits<char> > >::<anonymous union>::<anonymous struct>::r' with destructor not allowed in union
c:\qtsdk\mingw\bin\../lib/gcc/mingw32/4.4.0/../../../../include/glm/glm/./core/type_vec2.hpp:79: error: member 'std::basic_ostream<char, std::char_traits<char> > glm::detail::tvec2<std::basic_ostream<char, std::char_traits<char> > >::<anonymous union>::<anonymous struct>::r' with copy assignment operator not allowed in union
c:\qtsdk\mingw\bin\../lib/gcc/mingw32/4.4.0/../../../../include/glm/glm/./core/type_vec2.hpp:79: error: member 'std::basic_ostream<char, std::char_traits<char> > glm::detail::tvec2<std::basic_ostream<char, std::char_traits<char> > >::<anonymous union>::<anonymous struct>::g' with constructor not allowed in union
c:\qtsdk\mingw\bin\../lib/gcc/mingw32/4.4.0/../../../../include/glm/glm/./core/type_vec2.hpp:79: error: member 'std::basic_ostream<char, std::char_traits<char> > glm::detail::tvec2<std::basic_ostream<char, std::char_traits<char> > >::<anonymous union>::<anonymous struct>::g' with destructor not allowed in union
c:\qtsdk\mingw\bin\../lib/gcc/mingw32/4.4.0/../../../../include/glm/glm/./core/type_vec2.hpp:79: error: member 'std::basic_ostream<char, std::char_traits<char> > glm::detail::tvec2<std::basic_ostream<char, std::char_traits<char> > >::<anonymous union>::<anonymous struct>::g' with copy assignment operator not allowed in union
c:\qtsdk\mingw\bin\../lib/gcc/mingw32/4.4.0/../../../../include/glm/glm/./core/type_vec2.hpp:80: error: member 'std::basic_ostream<char, std::char_traits<char> > glm::detail::tvec2<std::basic_ostream<char, std::char_traits<char> > >::<anonymous union>::<anonymous struct>::s' with constructor not allowed in union
c:\qtsdk\mingw\bin\../lib/gcc/mingw32/4.4.0/../../../../include/glm/glm/./core/type_vec2.hpp:80: error: member 'std::basic_ostream<char, std::char_traits<char> > glm::detail::tvec2<std::basic_ostream<char, std::char_traits<char> > >::<anonymous union>::<anonymous struct>::s' with destructor not allowed in union
c:\qtsdk\mingw\bin\../lib/gcc/mingw32/4.4.0/../../../../include/glm/glm/./core/type_vec2.hpp:80: error: member 'std::basic_ostream<char, std::char_traits<char> > glm::detail::tvec2<std::basic_ostream<char, std::char_traits<char> > >::<anonymous union>::<anonymous struct>::s' with copy assignment operator not allowed in union
c:\qtsdk\mingw\bin\../lib/gcc/mingw32/4.4.0/../../../../include/glm/glm/./core/type_vec2.hpp:80: error: member 'std::basic_ostream<char, std::char_traits<char> > glm::detail::tvec2<std::basic_ostream<char, std::char_traits<char> > >::<anonymous union>::<anonymous struct>::t' with constructor not allowed in union
c:\qtsdk\mingw\bin\../lib/gcc/mingw32/4.4.0/../../../../include/glm/glm/./core/type_vec2.hpp:80: error: member 'std::basic_ostream<char, std::char_traits<char> > glm::detail::tvec2<std::basic_ostream<char, std::char_traits<char> > >::<anonymous union>::<anonymous struct>::t' with destructor not allowed in union
c:\qtsdk\mingw\bin\../lib/gcc/mingw32/4.4.0/../../../../include/glm/glm/./core/type_vec2.hpp:80: error: member 'std::basic_ostream<char, std::char_traits<char> > glm::detail::tvec2<std::basic_ostream<char, std::char_traits<char> > >::<anonymous union>::<anonymous struct>::t' with copy assignment operator not allowed in union
c:\qtsdk\mingw\bin\../lib/gcc/mingw32/4.4.0/../../../../include/glm/glm/./core/type_vec2.hpp:81: error: member 'std::basic_ostream<char, std::char_traits<char> > glm::detail::tvec2<std::basic_ostream<char, std::char_traits<char> > >::<anonymous union>::<anonymous struct>::x' with constructor not allowed in union
c:\qtsdk\mingw\bin\../lib/gcc/mingw32/4.4.0/../../../../include/glm/glm/./core/type_vec2.hpp:81: error: member 'std::basic_ostream<char, std::char_traits<char> > glm::detail::tvec2<std::basic_ostream<char, std::char_traits<char> > >::<anonymous union>::<anonymous struct>::x' with destructor not allowed in union
c:\qtsdk\mingw\bin\../lib/gcc/mingw32/4.4.0/../../../../include/glm/glm/./core/type_vec2.hpp:81: error: member 'std::basic_ostream<char, std::char_traits<char> > glm::detail::tvec2<std::basic_ostream<char, std::char_traits<char> > >::<anonymous union>::<anonymous struct>::x' with copy assignment operator not allowed in union
c:\qtsdk\mingw\bin\../lib/gcc/mingw32/4.4.0/../../../../include/glm/glm/./core/type_vec2.hpp:81: error: member 'std::basic_ostream<char, std::char_traits<char> > glm::detail::tvec2<std::basic_ostream<char, std::char_traits<char> > >::<anonymous union>::<anonymous struct>::y' with constructor not allowed in union
c:\qtsdk\mingw\bin\../lib/gcc/mingw32/4.4.0/../../../../include/glm/glm/./core/type_vec2.hpp:81: error: member 'std::basic_ostream<char, std::char_traits<char> > glm::detail::tvec2<std::basic_ostream<char, std::char_traits<char> > >::<anonymous union>::<anonymous struct>::y' with destructor not allowed in union
c:\qtsdk\mingw\bin\../lib/gcc/mingw32/4.4.0/../../../../include/glm/glm/./core/type_vec2.hpp:81: error: member 'std::basic_ostream<char, std::char_traits<char> > glm::detail::tvec2<std::basic_ostream<char, std::char_traits<char> > >::<anonymous union>::<anonymous struct>::y' with copy assignment operator not allowed in union

A: I had this issue. It's because glm doesn't work with -std=c++0x. You have to use c++98.

A: I fixed most of the errors by not including glm/ext.hpp, as that appeared to be what was doing the damage. If anyone knows anything about why this is happening, it would be cool to hear from you on this.


text:
Q: Can't override AppCompat PopupMenu I am just trying to use an overriding style for the PopupMenu.
I am attaching it to my overall style like this
<style name="MyTheme" parent="Theme.AppCompat.Light">
  <item name="colorAccent">@color/red</item>
  <item name="colorPrimary">@color/red</item>
  <item name="colorPrimaryDark">@color/red</item>
  <item name="android:colorBackground">@color/red</item>
  <item name="android:windowBackground">?android:attr/colorBackground</item>
  <item name="android:textColorPrimary">@color/black</item>
  <item name="android:alertDialogTheme">@style/AlertDialogStyle</item>
  <item name="android:popupMenuStyle">@style/PopupMenuStyle</item>
  <item name="android:spinnerDropDownItemStyle">@style/Widget.AppCompat.DropDownItem.Spinner</item>
</style>

This is the style
<style name="PopupMenuStyle" parent="Theme.AppCompat.Light.PopupMenu">
  <item name="android:background">@color/white</item>
</style>

The parent can't be found. Which parent do I need here?


text:
Q: Javascript - Regex rule, find XX but not in span tag Text
message = 'Hello, my name ist Peter!';

My Tags
tags = {};
tags.tagsOne = {};
tags.tagsOne['t1'] = 'hello|is|there|g';
tags.tagsOne['t2'] = 'bub';
tags.tagsOne['t3'] = 'dog|house';
tags.tagsTwo = {};
tags.tagsTwo['t1'] = 'blub|man';
tags.tagsTwo['t2'] = 'word';
tags.tagsTwo['t3'] = 'sorry|high';

Regex
regexT1 = new RegExp('('+tags.tagsOne['t1']+'|'tags.tagsTwo['t1']+')','gi');
regexT2 = new RegExp('('+tags.tagsOne['t2']+'|'tags.tagsTwo['t2']+')','gi');
regexT3 = new RegExp('('+tags.tagsOne['t3']+'|'tags.tagsTwo['t3']+')','gi');

Replace
message = message.replace(regexT1,'$1');
message = message.replace(regexT2,'$1');
message = message.replace(regexT3,'$1');

He finds and replaces the $1 too.
Is it possible in regex to say, but not this -> $1
Example
-> http://jsfiddle.net/tVmTe/3/
UPDATE:
Working example
-> http://jsfiddle.net/tVmTe/9/

A: Split the message on space and consider each word individually.
var words = message.split(' '),
   var i = 0;
for(i; i < words.length; ++i){
   if(regexT1.test(words[i])){
      words[i] = words[i].replace(regexT1,'$1');
      continue;
   }
   //...
}
message = words.join(' ');


text:
Q: Live audio streaming from Java server to browser (Flash,HTML5) For a project, I need to be able to stream live audio from a Java server to the browser on the client. My first guess was to use RTMP with a Flash player, my second guess to make use of the HTML5 audio tag. But so far, I've failed to find anything useful (like a library), so does anyone have any pointers on how to do this?
Here's the setup: The sound comes in from a VoIP server as a bunch of PCM samples. From there, it has to go to get to the client, while usually only one client listens to one stream. So I need to be able to send many VoIP streams to several clients, a simple form of authentication would also be nice (like a token or a secret URL where the stream is located at).
So far, I've looked at Red5 (looks to me like one-to-many streaming only) and searched for Java-based RTMP libraries. Any help is gladly appreciated!


text:
Q: Spring JDBC : Inconsistent results when performing Order By Any help would be greatly appreciated. I am working on a project using Spring JDBC for data access and am performing a simple query with an order by column expression, I am currently getting inconsistent results meaning the order by doesn't seem to be working. I have tried more than one database still no avail.
String sql = "select * from account where upper(name) like upper(:query) order by name asc";
MapSqlParameterSource params = new MapSqlParameterSource().addValue("query", "%" + query + "%");

List<Account> accountsSearched = namedParameterJdbcTemplate.query(sql, params, new BeanPropertyRowMapper<Account>(Account.class));

Any ideas what could be the issue?

A: So the problem is not within your SQL code, but problem exist in search method implementation
Existing Code
public List<Account> search(String uncleanedQuery, int offset) {
    String query = uncleanedQuery.replaceAll("([-+.^:,])","");
    String sql = "select * from account where upper(name) like upper(:query) order by name asc";
    MapSqlParameterSource params = new MapSqlParameterSource().addValue("query", "%" + query + "%");
    List<Account> accountsSearched = namedParameterJdbcTemplate.query(sql, params, new BeanPropertyRowMapper<Account>(Account.class));
    Set<Account> accountSearchSet = new HashSet<Account>(accountsSearched);
    List<Account> accounts = new ArrayList<Account>(accountSearchSet);
    return accounts;
}

In the above code, we are fetching data correctly but assigning it to HashSet. HashSet does not respect ordering by name and generates random order for Account, due to which you are getting random order every time.
Solution 1:
There is no reason, you actually need Set. Using set just making your program slow.  If you want to get DISTINCT data then modify SQL query.
public List<Account> search(String uncleanedQuery, int offset) {
    String query = uncleanedQuery.replaceAll("([-+.^:,])","");
    String sql = "select * from account where upper(name) like upper(:query) order by name asc";
    MapSqlParameterSource params = new MapSqlParameterSource().addValue("query", "%" + query + "%");
    List<Account> accountsSearched = namedParameterJdbcTemplate.query(sql, params, new BeanPropertyRowMapper<Account>(Account.class));
    return accountsSearched;
}

Solution 2:
Still, you want to go with your approach then change code to use TreeSet and order based on the name
public List<Account> search(String uncleanedQuery, int offset) {
    String query = uncleanedQuery.replaceAll("([-+.^:,])", "");
    System.out.println("Search Query Called");
    String sql = "select * from account where upper(name) like upper(:query) order by name";

    MapSqlParameterSource params = new MapSqlParameterSource().addValue("query", "%" + query + "%");

    List<Account> accountsSearched = namedParameterJdbcTemplate.query(sql, params,
            new BeanPropertyRowMapper<Account>(Account.class));

    Comparator<Account> comp = new Comparator<Account>() {

        @Override
        public int compare(Account a1, Account a2) {
            return a1.getName().compareTo(a2.getName());
        }
    };

    SortedSet<Account> accountSearchSet = new TreeSet<Account>(comp);
    accountSearchSet.addAll(accountsSearched);

    List<Account> accounts = new ArrayList<Account>(accountSearchSet);

    return accounts;
}


text:
Q: Simplifying tr[A^-1(B.A)] Can anyone help me simplify the following equation:
$\text{tr} \left [ \mathbf{A}^{-1} \left ( \mathbf{B} \circ \mathbf{A} \right ) \right ] = \text{tr} \left [ \mathbf{A}^{-1}\mathbf{C}\mathbf{A}^{-1}\left ( \mathbf{B} \circ \mathbf{A} \right ) \right ]$
The matrix $\mathbf{A}$ is parameterized  as $A_{xy} = \text{exp}(d_{xy}/\ell)$ and I ultimately want to solve for $\ell$. My naive idea of simplifying using the invariance under circular permutations e.g. $\text{tr} \left [ \mathbf{A}^{-1} \left ( \mathbf{B} \circ \mathbf{A} \right ) \right ] = \text{tr} \left [ \left ( \mathbf{B} \circ \mathbf{A} \right ) \mathbf{A}^{-1} \right ] = \text{tr} \left [ \mathbf{B} \right ]$ does not hold since $\mathbf{A}\left(\mathbf{B} \circ \mathbf{C}\right) \neq \left(\mathbf{A}\mathbf{B}\right) \circ \mathbf{C}$.
The matrices $\mathbf{A}$, $\mathbf{B}$, $\mathbf{C}$ are all symmetric, which seems like it might help!
Any advice greatly appreciated!


text:
Q: Possibly offensive usernames I flagged this user as having a possibly offensive name (another example):

I said "possibly offensive" because it's possible it's a genuine surname I wasn't aware of, but googleing didn't show any evidence and urban dictionary pretty much matched my definition of it which seems offensive.

*

*Is this really a genuine name?

*If not how is it possibly not offensive and thus a bad flag?

(I flagged in good faith so even if it is a genuine name declining seems harsh)

A: I won't get into whether this particular name is offensive or not, but both Shadow Wizard and Rosinante seem to be of the opinion that this is 2012 and not the Victorian era, and so such words should be overlooked. While that stance can be justified in chat/speech/private lives, etc., I believe that if you're asking and answering questions or leaving comments around with your name attached to it, then it is better (and I would go far as to say make it a policy) to not have any objectionable/vulgar content as your display name.
Let's be sensible here. Your display name is also used by others to refer to you and your content. As such, even if the whole "It's just a word, what's the big deal? Get over it" argument holds in isolation, by forcing others to use the same, you are offending them.  For example, you can set your display name to cunt face, and it doesn't have a target and hence, is not offensive by Shadow Wizard's reasoning. But everyone is forced to refer to you as @cunt face or @cunt or write things like "blappity blah and you can also foo the bar like in cunt face's answer...".
Although you can change your display name later to something more reasonable, it won't change the text in the comments or in the answers. As such, any and all context to any of those statements is lost and this makes SO/SE look less like a civil and polite society and more like a teenager's chat history.
There is a place for reasonably vulgar words used in a non-offensive, targetless manner. That's in your profile in the "About  me" section. You can write "I hate this fu*king job" or "This has been a s*itty month" or "I'd rather be eating s*itburgers than answering n00b questions", and I don't think anyone could care less about it. Welbog's profile is a good example of that.

A: Why offensive? Who exactly is the target of the offense?
For example, name like "white_people_are_dumb" is indeed offensive, as it targets specific group of people with direct offence.
I don't think those living in Fitchburg are really offended by that name you reported, so I guess the moderator reviewing your flag thought the same.
As far as I know, moderator has only two options for flag he/she is reviewing: approve or decline so flagging is a risk: either it's approved and you gain flag weight, or it's declined and you lose points.


text:
Q: Finding the magnitude a matrices I need some help. I have a list of 3 x 3  matrices of real numbers.I want to find how close each of these matrices are to a {{0,0,0},{0,0,0},{0,0,0}} matrix. Any suggestions to a method algorithm or code?

A: The answer depends on how you characterise the matrix. Let say you can define it in terms of sum of absolute values of the element.
norm1[m_List] := Total@Flatten@Abs[m]

Or you can define it as Norm of diagonal elements
norm2[m_List] := Norm@Diagonal[m]

Given a matrix m
m = RandomReal[{-5, 5}, {3, 3}]

{{-2.72364, 2.26668, 4.07867}, {-1.8835, 0.968504, 1.47028}, {4.15286,
     2.12865, 3.64299}}

This would be its 'length'
norm1[m]

23.3158

norm2[m]

4.65055

There can be a better answer if you can specify your exact problem.


text:
Q: DRF how to open media url using django storage(sftp)? I'm using storage SFTP module for saving media now i'm facing issues to open image url path as we know there is no media is project directory because i am using sftp.
Please suggest me the best way to render back end images using django rest.
Detailed info:  models, view and setting