Finding the tension in a 3D circular motion problem with little information

Question:
I've been stuck on this for some time now; to find the tension I would resolve both vertically and horizontally towards the centre of the circle that P travels on - but for this, I require $\sin$/$\cos$ of the angle the rod makes, which in turn requires the radius of P's motion and one other side. I can't deduce this from the text. Is there some other way in which I should be approaching this? I just can't find a way to solve it using alternative methods. Thanks in advance.
Answer: Since the radius is perpendicular to the tangent (rod), the angle $\theta$ between the rod and the vertical is given by $$\sin\theta=\frac{r}{2r}=\frac12$$
I hope this helps.


User profile tabs only for current user

Question: On my user profile I have various tabs (view, my bookmarks, translate, ...). the problem ist, those tabs should only be visible for profile owner and not if I visit another profile.
Some of those tabs (bookmarks, submissions) are set via view: user/%/submissions with a menu tab - the permissions here are set. But how do I set permission for those tabs only to the current user?
Answer: Alter menu and set 'access callback' => 'user_access'
Or if you have custom profile tpl then render tabs like this:
global $user;
if (arg(0) == 'user' && $user->uid == arg(1)){
  //*******render tabs here*********/
}

Comment: if I set  `$items['user/%/view']['access callback'] = 'user_access'` I can't the see tab, even if I am on my own profile. Also do I have to set this for every single tab?
Comment: /**
     * Implementing hook_menu_alter
     * Restrict MENU TABS access
     */
 global $user;
    function MODULE_NAME_menu_alter(&$items) {
        if(isset($user) || $user->uid !=0) {
            $items['user/%user/yourtabname1']['access callback'] = FALSE;
             $items['user/%user/yourtabname2']['access callback'] = FALSE;
                   //Change the MENU PATH as per your requirement.
        }
    }
Yes ,you have to set permission for each tab.

User profile tabs only for current user


XML results are overridden when multiple suites are executed

Question: I'm running my TestNG tests Programatically. I'm Injecting multiple suites and executing. But when I execute the following, testng-results.xml doesn't contain all the results from each suite. I only get results of the last suite. Has anyone faced the same issue before?
            TestNG tng = new TestNG();
            List<XmlSuite> suites = new ArrayList<>();

            for (Deployment deployment : deploymentList) {

            tcList = tlsite.getTestCaseClassList();

                XmlSuite suite = new XmlSuite();
                suite.setName(deployment.getName());
                XmlTest test = new XmlTest(suite);
                test.setName("AutomationTests");
                List<XmlClass> classes = new ArrayList<>();

                for (Object className : tcList){
                    try {
                        classes.add(new XmlClass((String) className));
                    } catch (TestNGException e){
                        log.error("Error occurred while adding the class : " +e.toString());
                    }
                }
                test.setXmlClasses(classes) ;
                suites.add(suite);
            }
            tng.setXmlSuites(suites);
            tng.setOutputDirectory("my-out");
            tng.run();

Update : If I run this in the following way it works. But I want o dynamically generate the suite. What am I doing wrong?
            TestNG testng = new TestNG();
            List<String> suites = new ArrayList<>();
            suites.add("../src/test/resources/testng.xml");
            testng.setTestSuites(suites);
            testng.run();

testng.xml
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd" >
<suite name="suite of suites">
    <suite-files>
        <suite-file path="testng_pattern1.xml" />
        <suite-file path="testng_pattern2.xml" />
    </suite-files>
</suite>

Answer: I have provided example which is working as you are expecting, I hope, see GitHub. You need to set parent suite for your suites using childSuite.setParentSuite(parentSuite) for all your nested suites.
Comment: I want the results in a single file.
Comment: You mean single file or single report?
Comment: I need all the results in a single testng-result.xml. As i mentioned when I use the second method it works as expected.
Comment: Thanks for the answer.


For $m \in \mathbb{Z}$, sow the Maclaurin series for $(1+x)^m$

Question: For $m \in \mathbb{Z}$, sow the Maclaurin series for $(1+x)^m$ is
$\sum_{n=0}^{m} \frac{m!}{n!(m-n)!}x^n$
I think i followed the correct procedure but I don't know how to account for the M values in the denominator or how to see the pattern need to write the expansion in sigma notation.It feels like i skipped steps in the end which would reveal (m-n) for each part of the expansion.
Comment: What you have there is correct.  I wouldn't bother to multiply out (m)(m-1)(m-2) etc. as you have done as it actually takes you away from showing that that equals $\frac{m!}{(m-k)!}$ as you hope to show.
Comment: LATEX !!! and note that by definition of the [binomial coefficients](https://en.wikipedia.org/wiki/Binomial_coefficient) : $(1+x)^m = \sum_{n=0}^m {m \choose n} x^n$. what needs a proof is that $ {m \choose n} = \frac{m!}{n!(m-n)!}$. $\quad$ [the Taylor series theorem that if $f$ is real-analytic and if the series converges then](https://en.wikipedia.org/wiki/Taylor_series#Approximation_and_convergence) $f(x) = \sum_{k=0}^\infty \frac{f^{(k)}(0)}{k!} x^k$ applied to $f(x) = (1+x)^m$ being one possible (but complicated) proof.
Answer: What you have there is mostly correct.  There is one error.
First, not an error, but I wouldn't bother to multiply out $(m)(m-1)(m-2)$ etc. as you have done as it actually takes you away from showing that that equals $\frac{m!}{(m-n)!}$ as you hope to show.
The error:
$\frac{x^0}{0!(m-0)} + \frac{m x^1}{1!(m-1)} + \frac{m(m-1) x^2}{2!(m-2)}+ \frac{m(m-1)(m-2) x^3}{3!(m-3)}...$ is incorrect.
It should be:
$\frac{x^0}{0!} + \frac{m x^1}{1!} + \frac{m(m-1) x^2}{2!}+\frac{m(m-1)(m-2) x^2}{3!}...$
and
$m(m-1)(m-2)\cdots(m-(n-1)) = \frac{m!}{(m-n)!}$
And your conclusion.


Laravel join on returned query with get()

Question: I'm working with a Laravel 5 project whereby I'm using a trait to create reusable logic and generic functions that are easy to read and consume.
One of these functions, getDevices simply returns a collection of all of my devices, however, my function getCalls needs to run a join on the returned collection of my getDevices and without duplicating my getDevices function or moving the model into the getCall I'm not sure what I'm missing and how I can achieve such result.
I'm getting an error in my view saying that the join method does not exist.

Method Illuminate\Database\Eloquent\Collection::join does not exist.

<?php

namespace App\Traits;

use App\Models\Device;
use App\Models\DeviceGroupsCalls;
use Carbon\Carbon;
use DB;

trait Calls {

  /*
  * Get all devices
  */
  protected function getDevices()
  {
    return Device::get();
  }

  /*
  * Get all enabled devices
  */
  protected function getEnabledDevices()
  {
    return Device::where('enabled', true)->get();
  }

  /*
  * Get all disabled devices
  */
  protected function getDisabledDevices()
  {
    return Device::where('enabled', false)->get();
  }

  /*
  * get all calls by devices
  */
  protected function getCalls()
  {
    $query = $this->getDevices();
    $devices = $query->join('devicegroupscalls', 'devicegroupscalls.device_groups_id', '=', 'devices.device_groups_id')
                     ->where('devices.enabled', true)
                     ->where('devicegroupscalls.enabled', true)
                     ->first();

    return $devices;
  }

}

Comment: `get()` returns the results and is no longer a query builder object.
Comment: Get is terminating call and will return a collection instead of a query builder, you should do Device::all->join etc.

Also ->first() will only return the first device, if you want to get all the devices you should use ->get();
Answer: You have already get result then you are joining record which is not proper. Please see updated file.
<?php

namespace App\Traits;

use App\Models\Device;
use App\Models\DeviceGroupsCalls;
use Carbon\Carbon;
use DB;

trait Calls {

  /*
  * Get all devices
  */
  protected function getDevices()
  {
    return new Device;
  }

  /*
  * Get all enabled devices
  */
  protected function getEnabledDevices()
  {
    return Device::where('enabled', true);
  }

  /*
  * Get all disabled devices
  */
  protected function getDisabledDevices()
  {
    return Device::where('enabled', false);
  }

  /*
  * get all calls by devices
  */
  protected function getCalls()
  {
    $query = $this->getDevices();
    $devices = $query->join('devicegroupscalls', 'devicegroupscalls.device_groups_id', '=', 'devices.device_groups_id')
                     ->where('devices.enabled', true)
                     ->where('devicegroupscalls.enabled', true)
                     ->first();

    return $devices;
  }

}

Answer: As the error says (Method Illuminate\Database\Eloquent\Collection::join does not exist.) you try to use a Laravel query method on Collection.
You have to use this method (join) before you execute methods like get(), first() (these methods execute query to database).
In method getDevices() instead using get() try to use query(). This will create query builder instance instead of getting data from database (and returns Laravel collection)


API design pattern for specifying different response models

Question: I'm trying to rough out an api for returning article content.  It seems valuable to be able to specify whether we want the entire article, a summary, or possibly some other variation on that content.
My instinct is to add a query parameter to a GET request like dataModel (feel free to suggest better names).  For instance, the default may be the entire article, but summary may just be id, title, & description, and list might return id, title, author, & lastModifiedDate.

/v0/articles/{id}
/v0/articles/{id}?dataModel=summary
/v0/articles/{id}?dataModel=list

However we are using Swagger for documentation and Swagger doesn't appear to support returning different objects based on query parameters (see this).  So I'm wondering if there are other established patterns that would be equally acceptable?
Answer: The right solution with Swagger is to create a return type that contains common properties across all the data models.  Then you can model a discriminator and use the allOf constructs for creating the proper response type.
If you take a look at the sample definition here:
https://swaggerhub.com/api/swagger-tutorials/modeling-samples/1.0.0
You'll see how it can be done with an Animal return type, and Cat and Dog concrete types.
Answer: One workaround is to use path variables instead of URL query string for dataModel and use the following route instead

/v0/articles/{id}
/v0/articles/{id}/summary (returns a model with id, title & description)
/v0/articles/{id}/list (returns a model with id, title, author, & lastModifiedDate)
Comment: This had occurred to me, but 'summary' and 'list' are just different rendering of the resource 'articles' so I'd prefer not to create new path structure for them...


Multiple calls to CryptHashData

Question: I gather that this is creating an md5 hash, but confused about exactly what is being hashed.
char val1[4] = {...};
DWORD val2 = ...;

CryptCreateHash(hCryptProv, CALG_MD5, 0, 0, &hHash)  // Creates hash object
CryptHashData(hHash, reinterpret_cast<const PBYTE>(val1), sizeof(val1), 0) // perform hash #1
CryptHashData(hHash, reinterpret_cast<const PBYTE>(val2), sizeof(val2), 0) // perform hash #2

How is hash #1 being combined with hash #2?
Is it performing an md5( md5(val1) + val2 )?  or an md5( val1 + val2 )?  Or something I'm not considering at all?
Answer: CryptHashData adds your data to the hash object. If you call CryptGetHashParam later you are going to get the hash of val1+val2.
Comment: So if val2 is 0, for example, then I should be able to remove the second hash call without any effect to the final hash value?  that doesn't seem to be the case
Comment: @LemonBeagle It is not the case because if you add a DWORD with the value 0 to the hash object the length of the data changed. A value of zero does not mean that no data is added to the hash object. It means that sizeof(DWORD) data with value 0 is added to the hash object.
Comment: Aha.. I was simply adding, not concatenating... thanks so much
Comment: I will vote you up when I get 15 rep... I wish I could now, this really helped, thanks

Multiple calls to CryptHashData


How to read line by line from Spring Webflux FilePart DataBuffer

Question: I am using Spring Webflux to upload files. In my case i have to upload a CSV file.
From what i can collect with the searches i have done is this code:
public Flux<String> getLines(Flux<FilePart> filePartFlux) {
    return filePartFlux.flatMap(filePart ->
            filePart.content().map(dataBuffer -> {
                byte[] bytes = new byte[dataBuffer.readableByteCount()];
                dataBuffer.read(bytes);
                DataBufferUtils.release(dataBuffer);
                return new String(bytes, StandardCharsets.UTF_8);
            })
            .map(this::processAndGetLinesAsList)
            .flatMapIterable(Function.identity());
}

But during this process ,if the dataBuffer reaches its capacity , it will read the last line partially, and hence an incorrect csv will be processed if i pass the half value.
Is there any method by which i can be certail that the filw is read line by line instead of the Flux.
Example :
Databuffer 1 emitted from flux contains:
<name,title,address
joe,engineer,straight way california,
mike,doc >

Databuffer 2 from Flux contains :
<tor,hatlway street,
jeremy,plumber,newyork>

The solution that i have in my mind currently is to maintain a stack where i will push incomplete records by comparing the CSV splitted header length with splitted current record length, and in case if its less , then pop emelemt from stack and join the two strings.
I am hoping that there is an efficient way to do all this.
Answer: filePartFlux is Flux<FilePart>

val buffer = DataBufferUtils.join(filePartFlux).block()
val reader =  buffer.asInputStream(true).bufferedReader()
while(reader.ready()) {
    val line = reader.readLine()
    println("$line")
}

@Vishal jotshi, or this is better:
DataBufferUtils.join(filePartFlux).subscribe {
 buffer -> buffer.asInputStream(true).bufferedReader().use {
 reader -> while(reader.ready()) {
    val line = reader.readLine()
    println("$line")
}

}
Comment: The community [encourages](https://meta.stackoverflow.com/questions/392712) adding explanations alongside code, rather than purely code-based answers. As explained [here](https://meta.stackoverflow.com/questions/300837): "While this code may answer the question, providing additional context regarding *why* and/or *how* this code answers the question improves its long-term value."
Comment: Blocking and joining filePartFlux will load all of file data into memory which is what i am trying to avoid.So i would not suggest doing this.
Comment: Using .join will read everything into memory.


CaseInsensitive search in HashMap

Question: I have a map:
static Map<String, String> = getMap(); //getting a map from a config file.

Now in this Map I need to perform a caseInsensitive search, using KEYS. I am NOT putting the values in map, not through put function, but you can think it as a values stored in data base in a key value format, and retrieving it as a Map. I need to do a caseInsentive search.
After researching, using a TreeMap would solve the problem, but not efficient --> O(log n)
or overring the get() method of HashMap, creating my own HashMap. but this would include overrding many methods, and I dont want this much, it not a part of very important code.
Right now I am im storing the values, in lowercase in database, and checking. But it makes it error prone, and not readble, in database.
Can there be a simpler method to do it?
Comment: Have you looked at [CaseInsensitiveMap](https://commons.apache.org/proper/commons-collections/javadocs/api-3.2.1/org/apache/commons/collections/map/CaseInsensitiveMap.html)?
Comment: What exactly are you searching for (in the key or the value)? Are you looking for a complete match or a partial match? Could you provide some examples in your question?
Comment: Are you searching keys or values?
Comment: I am searching for a complete match, just to be case-insensitive. I am searching for keys. CaseInsensitive map is not generic, how can I use it?
Comment: The database is basically, a file, which stores it in that format.
Comment: It is generic in 4.0: [generic CaseInsensitiveMap](https://commons.apache.org/proper/commons-collections/apidocs/org/apache/commons/collections4/map/CaseInsensitiveMap.html)
Comment: @Keppil, I am using JDK 1.7, when I try to import the generic version, it dosent allow me. I think its not there in JDK 1.7
Comment: It should work with 1.5 and above. Did you use the right import? [Maven link](http://mvnrepository.com/artifact/org.apache.commons/commons-collections4/4.0)
Comment: @Keppil How can I add dependecy for collection file in Config file? Where I add dependency for java version like: JDK = 1.7
Answer: 1.) TreeMap extends Map can be an option, but time complexity is O(log n)
final Map<String, Object> map = new TreeMap<String, Object>(String.CASE_INSENSITIVE_ORDER);

2.) You could use CaseInsensitiveMap from Apache's Commons Collections as suggested above.
3.) Creating your own HashMap Class and overriding methods.
public class MyCaseInsensitiveMap extends HashMap<String, String> {
    ...
    put(String key, String value) {
       super.put(key.toLowerCase(), value);
    }

    get(String key) {
       super.get(key.toLowercase());
    }
}

4.) You need a wrapper class for your String key with a case-insensitive equals() and hashCode() implementation. Use that instead of the String for the Map's key.
example here
** There does not seems to be straight forward library available except for apache commons.
PS: Consolidated from other links available in SO also.
Comment: 1 -> No. 2-> Not generic. 3-> I am not putting the keys in the map through put function, but its stored in config file. 4-> I tried it but didnt work. I did something like : static Map = getMap();
Comment: I think it didnt work because, not adding to map using put function, so values added are String format only, not StringWrapper.
Answer: If you are fine with O(1) but utilizing more space, this may help:
class CaseInsensitiveLookupMap {

private Map<String,String> keysMap = new HashMap<String,String>();
private Map<String,String> dataMap;

public CaseInsensitiveLookupMap(Map<String,String> dataMap){
  this.dataMap=dataMap;
  for(String key: dataMap.keySet()){
     keysMap.put(key.toLowerCase(),key);
  }
}

public String get(String keyToSearch){
  String _key = keysMap.get(keyToSearch.toLowerCase());
  if(_key!=null) {
    return dataMap.get(_key);
  }
  return null;
}

}

CaseInsensitive search in HashMap


How to make visual studio auto-save changes after delay like vscode?

Question: I recently started to work with visual studio 2017. I am looking for making visual studio 2017 to auto-save after delay as what vscode does. Is there any way to achieve that?
Answer: Not exactly what you ask for, but Visual Studio has AutoRecover feature that can restore unsaved changes in case of a crash.
You can also auto save files when Visual Studio loses focus.


Estemating trends for extreme weather using Poisson/NegativeBinomial Regression

Question: I have a large set of weather data containing historic information on how many days a month a certain threshholf of daily rainfall  at one location is reached. My goal is to investigate if a statistcally significant trend is present in my data (not to forecast future extreme weather events ) and if it is positive or negative. Since my dataset consists of the number of events in a month (i.e. 0 = no events, 1 = 1 event a month etc.), and the month as a date (i.e "1900-01-01" for January of 1900), I believe a Poisson- or Negative Binomial Model to be appropriate.
I have used both to try and find a trend and was pretty happy with my results, but plotting the residuals left me with some questions.
Since I want to find out if the number of events increases or decreases with time, I am using the number of events per month (data) as the dependent variable and a vector representing the number of months since the first month (time <-(c(1:length(data))) as the independent variable.
Here is my code with my data sample at the bottom of this post:
library(MASS)

hist(data)
time<-c(1:length(data))
poisreg<-glm(data~time,family = poisson(link = "log")) # Trying Poisson Model to calculate Trend
cd1<-cooks.distance(poisreg)
which(cd1>=1)           # No outliers
summary(poisreg)
dispersiontest(poisreg) # Test reveals that model is overdispersed. Dispersion = 1.717436

nbreg<-glm.nb(data~time) # Switching to Negative Binomial Model, to see if Dispersion is improved
cd2<-cooks.distance(nbreg)
which(cd2>=1)          # No outliers
summary(nbreg)        # Dispersion is a lot better than it was

plot(data~time,type="h", xlab= "Months since Start", ylab = "Number of occurences per month")
abline(h=mean(data),lwd=3,col="green") # Mean of data set
lines(fitted(nbreg),lwd=2,col="red")   # Plotting Trend of nbreg with fitted values. Trend of both models is basically the same.

This gets me a significant, positive Trend
Call:
glm.nb(formula = data ~ time, init.theta = 2.780757975, link = log)
Deviance Residuals:
    Min       1Q   Median       3Q      Max
-1.8847  -0.7779  -0.1715   0.4344   2.6846
Coefficients:
             Estimate Std. Error z value Pr(>|z|)
(Intercept) 0.5035181  0.0778014   6.472 9.68e-11 ***
time        0.0006797  0.0002180   3.118  0.00182 **
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
(Dispersion parameter for Negative Binomial(2.7808) family taken to be 1)
    Null deviance: 684.01  on 599  degrees of freedom
Residual deviance: 674.41  on 598  degrees of freedom
AIC: 2244
Number of Fisher Scoring iterations: 1
              Theta:  2.781
          Std. Err.:  0.412
 2 x log-likelihood:  -2238.008

with a plausible graph (red line is the trend, green line is the mean):

The residuals however are pretty bad, with clear trends present when there shouldnt be any:

Ive tried to remedy this by  introducing  quadratic terms to  my model using poly(), which didnt help. I am guessing the problem lies somewhere with the big number of months where data=0 (since the threshold was never reached). What can I do to improve the residual plots? Is it even necessary if im only trying to find a trend in historic data (and dont want to forecast)?
Are there any models that would be more appriopriate to use for finding trends in this dataset?
Is my approach here generally ok or are there any big mistakes Ive made or things Ive missed?
Thank you!
Here is the data for the number of extreme weather events per month:
data<-c(0, 5, 1, 4, 1, 0, 1, 0, 0, 4, 0, 0, 6, 1, 0, 3, 1, 1, 2, 1,
1, 3, 2, 1, 1, 2, 2, 2, 1, 0, 1, 0, 4, 1, 1, 0, 2, 1, 0, 2, 1,
2, 4, 0, 3, 2, 2, 2, 1, 3, 1, 0, 2, 0, 2, 0, 2, 0, 2, 4, 0, 2,
1, 5, 1, 4, 3, 0, 3, 3, 1, 2, 3, 2, 0, 0, 1, 1, 3, 0, 1, 0, 3,
1, 0, 1, 2, 3, 2, 3, 1, 0, 4, 1, 2, 0, 5, 3, 2, 0, 0, 0, 1, 2,
1, 1, 2, 0, 2, 1, 2, 0, 1, 0, 2, 3, 1, 6, 2, 1, 1, 3, 2, 4, 1,
0, 1, 1, 4, 0, 1, 5, 0, 2, 4, 0, 2, 2, 2, 2, 2, 2, 0, 1, 1, 2,
4, 1, 1, 0, 5, 1, 0, 2, 1, 2, 0, 1, 0, 1, 0, 2, 1, 3, 2, 2, 3,
0, 3, 1, 2, 6, 5, 4, 3, 2, 6, 1, 2, 2, 4, 1, 4, 1, 2, 0, 6, 2,
2, 0, 9, 2, 1, 2, 4, 2, 5, 0, 1, 2, 6, 0, 2, 2, 1, 1, 2, 1, 1,
1, 4, 9, 3, 4, 0, 5, 0, 1, 2, 2, 1, 1, 2, 4, 1, 0, 1, 2, 2, 2,
2, 4, 2, 6, 3, 0, 2, 2, 0, 0, 0, 1, 2, 1, 4, 1, 1, 9, 1, 0, 3,
3, 0, 3, 3, 0, 0, 2, 6, 9, 6, 2, 0, 1, 2, 0, 4, 0, 5, 0, 1, 1,
4, 0, 0, 0, 3, 2, 0, 2, 1, 0, 2, 2, 4, 4, 1, 4, 1, 2, 3, 1, 3,
1, 6, 5, 1, 3, 1, 1, 1, 2, 1, 1, 3, 6, 3, 5, 2, 1, 1, 4, 7, 1,
6, 4, 5, 4, 2, 1, 1, 0, 0, 3, 1, 0, 1, 1, 1, 1, 2, 5, 1, 2, 2,
0, 2, 3, 2, 0, 0, 4, 0, 2, 3, 1, 1, 6, 0, 1, 2, 5, 3, 1, 2, 0,
1, 3, 0, 1, 0, 2, 0, 0, 1, 2, 6, 2, 0, 0, 0, 2, 2, 4, 0, 1, 1,
2, 0, 4, 0, 0, 2, 0, 6, 0, 5, 2, 0, 8, 4, 0, 3, 3, 0, 3, 5, 2,
4, 5, 2, 2, 1, 3, 4, 0, 1, 1, 3, 1, 2, 1, 0, 5, 3, 0, 0, 2, 4,
1, 4, 4, 1, 1, 0, 2, 2, 0, 3, 0, 1, 0, 0, 2, 3, 2, 1, 3, 0, 3,
2, 11, 2, 8, 1, 1, 0, 3, 5, 3, 2, 2, 4, 1, 0, 2, 0, 2, 2, 2,
6, 5, 2, 4, 3, 9, 0, 7, 0, 0, 2, 0, 1, 0, 0, 0, 5, 2, 1, 0, 0,
1, 4, 5, 2, 1, 0, 2, 6, 0, 7, 2, 1, 3, 1, 1, 2, 6, 6, 1, 1, 1,
4, 3, 0, 3, 3, 4, 5, 1, 5, 6, 5, 1, 3, 0, 1, 3, 1, 3, 1, 5, 1,
4, 4, 0, 2, 2, 1, 1, 5, 0, 2, 3, 1, 2, 6, 0, 1, 2, 1, 5, 4, 2,
1, 0, 3, 3, 7, 5, 1, 0, 1, 2, 4, 4, 4, 3, 9, 1, 2, 2, 5, 2, 1,
2, 1, 0, 1, 0, 6, 6, 6, 3, 2, 2, 0, 3, 5, 2, 0, 0, 1, 1, 2, 3,
2, 1, 1, 1, 0, 1, 1, 0, 2, 3, 3, 7, 0, 2)

EDIT:
Afte applying various DHARMa residual diagnostics, the neg-binom model seems to be ok. Ive added them here if anyone has a similiar problem:
Comment: Welcome to CV. I can't comment on your analysis as a whole, but you really can't expect GLM residual plots to look like (general) LM ones. For one, the band's in the plots are because only discrete response levels are possible in these models. I'd recommend you have a look at [DHARMa](https://cran.r-project.org/web/packages/DHARMa/vignettes/DHARMa.html) for GL(M)M residual diagnostics. If that still shows problems you could consider a zero-inflated model.
Comment: @PBulls Thank you for the DHARMa Tip! If I understand these residual diagnostics correctly, there shouldnt be any major problems with my nb-model.
Answer: Well, my first thought while reading this was "what about the month of the year?" and the plots reinforce that, as there are 12 bands. You note that this is all at one location, and, while you don't say which location, at most places in the world there are rainy seasons and dry seasons. So, I'd add "month" to the model, and maybe change "time" to "year".
The other idea I had was to use time series methods that allow you to disaggregate a time series into trend, cyclical, and random components. There is an R package tempdisagg and I think there are other packages that do this, as well. tempdisagg has a vignette and an article associated with it (see the package documentation).
Comment: Thank you for your answer! While your suggestion of adding months to my independent variables doesnt seem to br necessary to fix the issue at hand, i will still to do so as they offer valuable insight into seasonal data trends.
Comment: The bands are due to the outcome ranging from 0-11 occurrences (by chance, and there's no 10 observed so only 11 distinct bands) rather than that being the number of months in a year, but it's still a good suggestion to check if there are any cyclical patterns.


Why do lower pitched string instruments have a larger body?

Question: I know that increasing the length of the string will decrease the pitch, but that doesn't explain why the body of a cello is larger than a violin, only longer.
What would be the "problem" with having a violin with a really long neck so it's the length of cello, and putting cello strings on it.
Is there some physical issue with trying to achieve a low pitch in a small resonating body (or visa versa)?
Comment: related: https://physics.stackexchange.com/questions/466877/why-are-large-speaker-cones-required-to-to-produce-loud-low-frequency-sounds
Answer: The lower the sound the instrument is producing, the larger the vibrating plate needs to be to produce that sound. The vibrations from the strings are being transferred to to the face of the instrument by the bridge, and the face of the instrument vibrates in response, making the air move, producing the waves that we hear as sound.
The larger face plate also increases the volume of the lower sound. If you had a cello with a violin sized body, you wouldn't hear the instrument very well, and the low notes would sound very "weak" and "thin".
EDIT:
Scott's comment has enough votes to stay visible, but I'm quoting it in the answer to make sure:
QUOTE: "Yep. I'd just add that as a rule of thumb, to most efficiently get air moving for a particular frequency, the vibrating plate should be at least 1/4 of the wavelength of sound to be produced long. That makes a cello plate about right for viola c = 128 Hz, but only half the desired length for the bottom C at 64 Hz. A violin is way too short to get air moving efficiently at 64 Hz. – Scott Wallace " :QUOTE
As another example, an imperfect analogy would be the game of skip-rope, where two people swing a rope between them so someone may jump the rope. A very long rope requires more energy to swing and makes a slower and larger rotation, where a short rope can be swung more quickly.
The depth of the instrument body also helps reinforce the reproduction of lower frequencies due to resonance. Low frequency resonance occurs with the coupled motion of the top plate, the back plate and the enclosed air, so for good low frequency resonance, the cello body needs to be deep as well as large.
Comment: Yep.  I'd just add that as a rule of thumb, to most efficiently get air moving for a particular frequency, the vibrating plate should be at least 1/4 of the wavelength of sound to be produced long.  That makes a cello plate about right for viola c = 128 Hz, but only half the desired length for the bottom C at 64 Hz.  A violin is way too short to get air moving efficiently at 64 Hz.
Comment: You should incorporate @ScottWallace comment into your answer.  As it stands, you have pretty much written a tautology.   The whole point is that you can't produce a note of X wavelength with a body less than (at best)  X/2 dimension.
Comment: @CarlWitthoft  Yes, this was my late-at-night-just-before-bed answer, and I was looking for a good link to the physics of vibrating plates. I'll edit to include more info.
Answer: Just to complement Alphonso's answer: the lower the pitch, the lower the frequency. The lower the frequency, the larger the wavelength. Surfaces respond better to waves, when their wavelength is close to the size of the surface.
Imagine you try to shake a sheet of paper, by holding it vertically. There is a minimum frequency you need to apply to make it undulate. Now, if you try to apply this same frequency to a post-it, it won't shake, just move along with your hand. To make it undulate you would need to shake it much faster (higher frequency, smaller wavelength), because the post-it is smaller then a sheet of paper. Also, if you take a meter long sheet of paper and shake it that fast, it won't undulate a lot too. You would probably see the waves fading out through the paper, while it's other end barely moves. There is of course a lower frequency that would make it undulate entirely.
Instruments function in a similar way. The string has to shake the body, to produce a louder sound, and therefore the body size must minimally match the wavelength of the sound waves you want to produce.
Answer: Some of the answers seem to be saying that you want the body to resonate at the frequency of the sound so as to produce the maximum amplitude of sound. That's not quite right. The graph below shows a measurement of the resonance curve of a 1713 Stradivarius violin (redrawn by me from a figure by Carleen Hutchins). There are a number of different resonance peaks, some strong and some weak; the ones near 200 and 400 Hz are vibrations of the wood, and the one near 300 Hz is a resonance of the air moving in and out through the f-holes. The white lines show the fundamental frequencies of the four strings.

So you can see that there certainly are peaks, which indicate resonances, but they're rather narrow and there are a lot of them. From what little I understand of violin acoustics, the effect on the sound is complicated, and has to do with the way the different harmonics coincide with the many different resonances. When you play with vibrato, you're sliding the harmonics back and forth over these resonance peaks. In any case, this is definitely not a situation where the fundamental frequency of the note simply matches the resonance frequency of the body and/or air cavity.
The OP specifically asks:

Why do lower pitched string instruments have a larger body?

In other words, why can't we have a double bass with a soundboard the size of a violin? The answer really has less to do with resonance of the body than with the size of the body in relation to the size of the sound waves. Each of the resonance peaks in the graph above corresponds to some pattern of vibration of the soundboard. Below are some diagrams from WP of the patterns of vibration of a guitar's soundboard.

The crucial point here is that in all of these patterns, there are some areas that are rising while others are falling. That is, different parts of the soundboard have different phases. Now the lowest note you can play on a double bass is 41 Hz, which corresponds to a wavelength of 800 cm. Suppose you tried to produce this sound using a soundboard the size of a violin, where the different vibrating patches were only 5-10 cm in size. Then for any patch that was vibrating outward, trying to produce an overpressure in the air, there would be another patch right nearby that was simultaneously vibrating inward, trying to produce an underpressure. They not cooperating. They will come very close to canceling out.
Let's refer to the patch that's trying to produce an overpressure as +, and the other as -. Ideally you would like the the + patch and the - patch to be 400 cm apart. This would be half a wavelength, and then the + and - would actually be cooperating on producing the same 800 cm sine wave: one would be producing the crest, while the other produced the trough.
In reality, the size of a double bass's soundboard is somewhere in between these two extremes. Because it's pretty small compared to most of the wavelengths it plays, there is a lot of cancellation going on, and not much cooperation. However, the cancellation is not perfect, so you do get some sound. The instrument could be made louder by making it bigger, but that would be impractical.
Comment: "The crucial point here is that in all of these patterns, there are some areas that are rising while others are falling" – I'd agree for a guitar, but in the bowed string instruments, the lowest body mode is indeed when most of the top moves consistently _in phase_ with the side of the bridge under which the bass bar sits. What moves with the opposite phase is the _bottom_ of the body, because it's coupled to the other side of the bridge via the sound post. The figures you're showing, whilst interesting, are at any rate not very relevant (though the basic principle you're discussing is).
Comment: @leftaroundabout: Interesting, thanks. It's clear that you know a lot more about violin acoustics than I do. I'm not totally succeeding in visualizing what you're describing, but if you think you could improve this answer with some edits, that would be great.
Comment: This answer is correct as far as it goes, but there is the additional effect, as I mentioned elsewhere here, that even if (say) the belly of a guitar were vibrating as a whole in and out at 60 Hz, this will still not excite the air to vibrate as well as a larger plate, simply because small plates don't make big waves very well.
Comment: @ScottWallace: That's true, but it's an effect that doesn't depend on frequency. It's just true over all that a larger surface area is always more efficient at creating sound waves, simply because it displaces more air.
Comment: @BenCrowell - that's not quite true. Once a plate is about the size of a given wavelength, any increase in area will not increase efficiency at creating sound waves for a given energy input.  Plates that are much smaller than about a 1/4 wavelength are much less efficient than larger ones, because they are trying to start a wave that's much larger than they are.  This is why tiny loudspeakers simply can't produce good bass efficiently, but they do fine with high frequencies.
Answer: You are only partly correct.  For a given tension a string's fundamental resonant frequency scales with length.   However, to within mechanical and material limits, you can increase or decrease tension on a fixed-length string to achieve any resonant frequency desired.
The string on a musical instrument is analogous to the oscillator in an electronic audio generator: it produces the source frequency(ies).  The bridge and body of the instrument are analogous to the amplifier, transferring the energy from the string to the atmosphere with (one hopes!) minimal impedance mismatch (and yes, there is such a thing as acoustic impedance in air) so as to maximize the sound volume.
Comment: It may be good to amplify "within mechanical and material limits" to note that for a cello-length string to reach the pitch of a violin's (high) E string would require that it be thinner and/or tighter than practical, and for a violin-length string to reach the pitch of a cello's (low) C string would require that it be thicker and/or looser than practical.
Comment: @supercat  I'm a physicist.  I make my strings out of unobtanium.
Answer: While each answer explains the physical properties and their relationship to the pitches being produced by the instrument, I'm inclined to add the aspect of the volume of air contained inside the instrument that resonates to amplify the sound the strings are producing. Larger volumes of air will resonate at lower pitches and increase the level of the sound being produced by the strings. The notes on a violin only require a sound box internal volume to resonate at a relatively high pitch, whereas a cello or bass needs a considerably larger sound box that will resonate at lower pitches in order to effectively amplify the sound being produced.


Determination of complex logarithm

Question: Good day everyone. I was reading more advanced lecture notes on complex analysis and encountered a lot of questions, concerning the determination of complex logarithm. So far I don't even understand the concept of it, but I'll provide you with several practical questions concerning the topic.
First of all, the determination of the complex logarithm on an open set  $\Omega \subset \mathbb{C}$ is continuous $f(w)$ such that:
$$\forall w \in \Omega \text{ }\exp(f(w))=w$$
So then it starts. Maybe someone could explain what presumptions the following statement contradicts.
There is no continuous determination for complex logarithm in $\mathbb{C}$ \ ${0}$.
The second part is more practical.
We say that determination of the complex logarithm is called principal if it given as a complement of $\mathbb{C}$ and semi axis of negative or zero real numbers $\Omega_{\pi}=\mathbb{C}$ \  $\{z\in \mathbb{C} : \Re(z) \leq 0\}$. Such as
$$ f(z) = \log(|z|)+ i\begin{cases} \arcsin{(y/|z|)} & x \geq 0, \\ \pi - \arcsin{(y/|z|)} & x \leq 0,\, y \geq 0, \\ -\pi - \arcsin{(y/|z|)}  & x \leq 0,\, y \leq 0. \end{cases}$$
We can see that the argument belongs to $(-\pi,\pi]$, but I neither understand why a set without negative real numbers defines such an argument nor how it happens. After this there is an example stating that if we take $\Omega_0=\mathbb{C}$ \ $\{z \in \mathbb{C} : \Re \geq 0\}$ then the argument will be $(0,2\pi]$ but I also didn't get how this happens. What will happen if we remove the non positive imaginary part? What kind of argument will we have then?
The wiki lacks an entry on this topic, so maybe a detailed answer will help others who encountered the same problem.
Comment: The statement is correct. It seems that what you mean is not where the statement goes wrong but where an attempt at constructing a continuous logarithm on $\mathbb C\setminus\{0\}$ goes wrong?
Comment: "Maybe someone would explain what presumptions does the following statement contradicts" is unclear -- could you perhaps rephrase that? (Also the singular of mathematical "axes" is "axis"; the singular is "axe" only when "axes" refers to the instruments used to chop down trees.)
Comment: "Maybe someone would explain what presumptions does the following statement contradicts" I meant at what point do we found our statement to be incorrect or simply where does it goes wrong. I am sorry for grammatical mistakes it's the problem of multiple translations.
Answer: I think your first question is, why is there no continuous logarithm function defined in the complex plane, omitting $0$. The answer is, trace out a circle of radius $1$ centered at the origin, starting at $1$, and evaluate the logarithm function as you go around. Go ahead, do it! You will find that you either make a discontinuity somewhere along the way, or else when you get back to $z=1$ you are off by $2\pi i$ from the value you started with.
Now the same thing happens with the argument function. Start it with, say, the value $0$ at $z=1$, go around that circle (counterclockwise, just to be specific), and when you come back to $z=1$ the argument will be $2\pi$; discontinuity! The cure for the discontinuity is to make it impossible to go all the way around the circle. The easiest way to do that is to remove some ray that starts at the origin and goes to infinity. If the ray you remove is the non-positive reals, then the argument, starting with the value $0$ at $z=1$, will increase almost but not quite to $\pi$ as you go around counterclockwise (not reaching the excised ray), and will decrease almost but not quite to $-\pi$ as you go around the other way.
The non-positive imaginary part ray has argument $3\pi/2$ as you approach it counterclockwise from $z=1$, and argument $-\pi/2$ as you approach it the other way, so if you omit that ray then the argument can be taken to be between $-\pi/2$ and $3\pi/2$.
If I have missed the point of your question, please try again.
Answer: By inverting Euler's formula $e^{ix} = \cos{x} + i \sin{x}$, you get
$\log(r(\cos{\theta} + i \sin{\theta}))$
$ = \log{r} + \log(\cos{\theta} + i \sin{\theta})$
$ = \log{r} + i \theta$
The problem here is that $\theta$, the argument or phase angle of a complex number, is not unique, due to sin and cos being periodic.  For example, the following are all valid polar representations of $-1-i$:

$\sqrt{2} \text{ cis } \frac{-3\pi}{4}$
$\sqrt{2} \text{ cis } \frac{5\pi}{4}$
$\sqrt{2} \text{ cis } \frac{-11\pi}{4}$

So, how do you decide whether $\log (-1-i)$ is $\frac{\log{2}}{2} - \frac{3\pi}{4} i$, $\frac{\log{2}}{2} + \frac{5\pi}{4} i$, or $\frac{\log{2}}{2} - \frac{11\pi}{4} i$?  By arbitrary picking a $2\pi$-wide interval to which $\theta$ is restricted.

If you choose $\theta \in (-\pi, \pi]$, then $\log (-1-i) = \frac{\log{2}}{2} - \frac{3\pi}{4} i$.
If you choose $\theta \in [0, 2\pi)$, then $\log (-1-i) = \frac{\log{2}}{2} + \frac{5\pi}{4} i$.

Whichever "branch cut" you choose, there will be a discontinuity across it.  For example, using $\theta \in (-\pi, \pi]$, then if $x$ is a negative real number,

$\lim_{y \rightarrow 0^+} (x + yi) = \log{|x|} + \pi i$
$\lim_{y \rightarrow 0^-} (x + yi) = \log{|x|} - \pi i$

Determination of complex logarithm


bring spefic record from query to form in MS ACCESS

Question: I have a form of table of people.
I Have another form of tests and the people who tested.
I have a query that give me the names of all the people and if the average grade of some people is over 55, it gives me PASSED OR NO PASSED.
Now , i made a form of the table of people,
And I want to bring the Grade (PASSED OR NOT) from the query to the form.
I have no idea how to do that.
I tried to the some text box with "=[qry]![Grade]"
but it gives me "#NAME?" Error.
Anyone has an idea ? Thanks.
I Use Microsoft access 2016.
STUDENTS table fields -
Name
Age
Class
TESTS table fields -
Name of student,
Name of test,
Grade
Query fields - comes from tests table --
Name of student,
PASSED/ NOT PASSED
FORM fields-
All the fields of students table, passed or not from the query
Comment: Does the recordset for this form have the grade field?
Comment: just the qurey has the grade field And i want to bring it to my form
Comment: Have you tried in properties of the form change the data source to this query
Comment: Data source of the field or the form ?
Comment: The form first, then the Textbox relating to Grade
Comment: But all the fields of the forms come from the table, just the grade field comes from the query
Comment: Can you post the table fields and the fields of the query in your question?
Comment: Which table does the query come from?
Comment: I just edited my original post with the fields
Comment: What is the name of the query?
Comment: Is there any relationship between test table and students?
Comment: Yes , the name of the student
Comment: This relationship is 1-1 or 1-many?
Comment: 1 to many .. Every student has a couple of tests
Comment: I just post a possible answer, see if it works
Answer:
If the table Students and Tests are in Relationship and you want display their fields in a Single form:

First, edit your query: the tables for this query should be both Students and Tests.
Select the fields from Students and Tests to this query.
Open the form in design mode and change the data source of the form to the referred query.
The textbox data source you want display the field Grade from Table Tests should be set Grade

If the data you need is only on Tests Table:

Open the form in design mode and change the data source of the form to the Tests table.

If you want a Form with subform, as the main form shows the data from Students and the subform shows their Tests data

As you mentioned, the form is already set the data source with Students Table. don't change it.
Create a subform inside the Form with the subform data source = Tests, then show the relationship each Tests have to each Students

Above are the possibilities you have, you can try the one is more easy to you or suitable what you want.
If you want a Relationship between Students and Tests, it is recommendable, set in Students a primary key and in Tests one Field that can relate to Students' primary key.
In Ms access, Tables are designed to store data, but with queries is more powerful, they can Select data from more than on Table, for example (since it has a Relationship between them)
Comment: What do you mean that the tables for the query should be both students and tests ?
I have all the details in tests table, what do i need students table also ?
Comment: @Noam If you need the fields Age and Class from Students, include this table in Query along Tests. But if you need only Tests, change the form Data Source to Tests


Survival data simulation based on confidence interval of Hazard ratio

Question: I got a published hazard ratio (HR) of 0.464 with 95%CI as (0.337, 0.639) from a paper.
My question is

How can I get the distribution of the HR, so that I can check the different quantiles?
is that possible to reconstruct patient level data via simulation if we know the median survival time of each group is 6.9 vs 4.3 (4.3/6.9 is not exactly 0.464) but the model adjusted HR is still consistent with 0.464 with 95%CI as (0.337, 0.639)?

thank you
Answer:
If HR distribution is unknown, then its reconstruction is impossible solely based on maximum likelihood and confidence interval. If model is known and simple enough (e.g. binomial distribution) AND number of samples is known, one can reconstruct the model (e.g. in case of binomial, MLE is directly an estimate of the model parameter).
You cannot reconstruct patient level data out of anything other than patient level data :D. You can run a simulation to generate data similar to that of the true patient data based on the model parameters. If you know the true model, you can answer your own question: if the parameters you provide are enough to run a simulation unambiguously, then yes it is possible, otherwise no. If you don't know the model, we don't know it either :D


Default Value da Role numa dropdown

Question: Tenho no meu index os utilizadores, cada utilizador tem uma Dropdown com as Roles, quando faz o Get não mostrar o valor que está por default na Dropdown
Controller:
 public ActionResult IndexGestor(string roles)
        {

            //query entre 2 bases de dados
            var IDsCatequese = db.Catequese.ToList();
            var nomeCatequese = db2.Users.ToList();

            var result = (from o in IDsCatequese
                         join t in nomeCatequese on o.CatequeseID equals t.CatequeseID
                         //where t.Roles.Any(r => r.RoleId == t.Id)
                         select new CatequeseUsersViewModel
                         {
                             UserID = t.Id,
                             Nome = t.Nome,
                             UserName = t.UserName,
                             NomeCatequese = o.NomeCatequese,
                             CatequeseID = o.CatequeseID,
                             //Roles = t.Roles

        }).ToList();

            var userManager = HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>();
            foreach (var user in result)
            {
                user.Roles = userManager.GetRoles(user.UserID);
                ViewBag.Roles = new SelectList(db2.Roles, "id", "Name", user.Roles);
            };

            return View(result.ToList());
        }

View:
@foreach (var item in Model)
{

    @Html.DisplayFor(modelItem => item.Nome)

    @Html.DisplayFor(modelItem => item.UserName)

     @Html.DisplayFor(modelItem => item.NomeCatequese)

    @Html.DropDownListFor(modelItem => item.Roles,(IEnumerable<SelectListItem>)ViewBag.Roles, new { @class = "form-control" })
                                                    @Html.DisplayFor(modelItem => item.Roles)

                                            }
ViewModel:
  public class CatequeseUsersViewModel
    {
        public String UserID { get; set; }
        public String NomeCatequese { get; set; }
        public int CatequeseID { get; set; }
        public String UserName { get; set; }
        public String Paroquia { get; set; }
        public String Nome { get; set; }
        public ICollection<String> Roles { get; set; }
    }

Answer: De fato não vai funcionar. Você está escrevendo ViewBag.Roles N vezes: uma para cada execução do foreach:
        foreach (var user in result)
        {
            user.Roles = userManager.GetRoles(user.UserID);
            ViewBag.Roles = new SelectList(db2.Roles, "id", "Name", user.Roles);
        };

O correto é você escrever a ViewBag uma única vez e definir cada DropDownList em View:
@foreach (var item in Model)
{

            @Html.DisplayFor(modelItem => item.Nome)

            @Html.DisplayFor(modelItem => item.UserName)

            @Html.DisplayFor(modelItem => item.NomeCatequese)

            @Html.DisplayFor(modelItem => item.RoleId)
            @Html.DropDownListFor(modelItem => item.Roles,((IEnumerable<Role>)ViewBag.Roles).Select(option => new SelectListItem {
                Text = option.Name,
                Value = option.Id,
                Selected = (item != null) && (item.RoleId == option.Id)
            }), new { @class = "form-control" })

}

Comment: O meu Mvc não conhece o argumento "Role" dentro de um IEnumerable. Porque será?
Comment: Alguma coisa está errada aí. Eu não colocaria `public ICollection Roles { get; set; }` dentro do `ViewModel`. Colocaria `public String RoleId { get; set; }`.
Comment: As Roles é uma "ICollection" dos Users, ou se eu modificar as tabelas da minha identity, para ficar um utilizador ser correspondente a uma Role.
Comment: Bom, então a modelagem da *View* está inteira errada mesmo. [Veja os artigos sobre BeginCollectionItem](http://pt.stackoverflow.com/search?q=begincollectionitem) para fazer esta parte.

Default Value da Role numa dropdown


How can I set up my application to ONLY return messages for ResponseStatusException?

Question: By default, Spring Boot does not return messages for any exceptions, including ResponseStatusException, meaning that the message about bar below will not be returned to the client:
    @GetMapping("/foo")
    @ResponseBody
    public Foo getFoo(@RequestParam(name = "bar", defaultValue = "0") int bar) {
        if (bar <= 0) {
            throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "bar must always be positive");
        }
        return example.getFoo(bar);
    }

This can be changed by setting server.error.include-message=always in the application.properties, however this causes ALL exception messages to be returned to the client, including this one:
    @GetMapping("/baz")
    @ResponseBody
    public Baz getBaz() {
        if (!security.checkSecurity()) {
            throw new RuntimeException("Security breach! Hope no one finds out!");
        }
        return example.getBaz();
    }

I know this is a trivial example and the solution would be just "don't throw server exceptions from your controller", but the exception might actually come from some other code buried deep in the application, it could even be a NullPointerException or whatever.
How can I get the application to show messages only from ResponseStatusException and not other types of exception? (I guess other than adding try-catch clauses to every single controller method.)
Comment: Then define your exception which will be handled as you wish. Check one of my previous answers today https://stackoverflow.com/a/67090661/7237884
Comment: @Boug this is similar to Akif's answer. Here you are generating the `ResponseEntity` manually... I want Spring to generate the `ResponseEntity` from my `ResponseStatusException`, otherwise I feel there is no point in using `ResponseStatusException`. Is there a way to just tell Spring to handle `ResponseStatusException` in the default way in your `handleXYZ` methods?
Answer: You can add extra (@ExceptionHandler) methods to any controller to specifically handle exceptions thrown by request handling (@RequestMapping) methods in the same controller. Such methods can:

Handle exceptions without the @ResponseStatus annotation (typically predefined exceptions that you didn't write)
Redirect the user to a dedicated error view
Build a totally custom error response

Controller advice allows you to use exactly the same exception handling techniques but apply them across the whole application, not just to an individual controller. You can think of them as an annotation-driven interceptor.
Any class annotated with @ControllerAdvice becomes a controller-advice and three types of method are supported:

Exception handling methods annotated with @ExceptionHandler.
Model enhancement methods (for adding additional data to the model) annotated with @ModelAttribute. Note that these attributes are not available to the exception handling views.
Binder initialization methods (used for configuring form-handling) annotated with
@InitBinder.

Solution:
@ControllerAdvice
public class RestControllerAdvice {

  @ExceptionHandler(ResponseStatusException.class)
  public ResponseEntity<String> handleStatusException(ResponseStatusException exception) {
    throw exception;
  }

  @ExceptionHandler(Exception.class)
  public ResponseEntity<String> handleException(Exception exception) {
    return new ResponseEntity<>("Exception", HttpStatus.INTERNAL_SERVER_ERROR);
  }
}

Comment: I found a possible solution: `(new DefaultErrorAttributes()).resolveException(request, response, this, new ResponseStatusException(...));` However this returns a message `500 INTERNAL_SERVER_ERROR "Unknown error occurred"` rather than just `Unknown error occurred`
Comment: Here you are generating the `ResponseEntity` manually... I want Spring to generate the `ResponseEntity` from my `ResponseStatusException`, otherwise I feel there is no point in using `ResponseStatusException`. Is there a way to just tell Spring to handle `ResponseStatusException` in the default way in your `handleStatusException` method?
Comment: Update answer. Yes, just throw a status exception and you will have default behavior.
Comment: Hmm, that worked, which I was quite surprised about as I always thought exceptions thrown from exception handlers wouldn't get handled. However, is there a way to do it for the default exceptions? I tried `throw new ResponseStatusException(HttpStatus.INTERNAL_SERVER_ERROR, "Unknown error occurred")` but it didn't work, the original exception's message got returned to the client rather than "Unknown error occurred". The problem with `ResponseEntity` is it requires you to create the error object yourself. For `ResponseStatusException`, Spring automatically creates the error object with 5 fields
Comment: PS: I also found that if ANY exception gets thrown from the exception handler, it will just process the original exception as normal. You don't have to re-throw the exception that was passed in as you did. In other words, Spring ignores the exception thrown from the exception handler, and serializes the originally thrown exception. But in the case of normal exceptions, I want Spring to serialize a new `ResponseStatusException` I'm creating, and NOT the original exception.
Comment: Also, with this last way, it returns the status code as 400, even if you tell it 500
Answer: Catch all the exceptions and in the catch block throw ResponseStatusException like in:
@GetMapping("/actor/{id}")
public String getActorName(@PathVariable("id") int id) {
    try {
        return actorService.getActor(id);
    } catch (ActorNotFoundException ex) {
        throw new ResponseStatusException(
          HttpStatus.NOT_FOUND, "Actor Not Found", ex);
    }
}

Comment: I think that's what I was saying in my original post when I said "(I guess other than adding try-catch clauses to every single controller method.)" I'd rather avoid doing this if possible for Runtime Exceptions, as it will cause every controller method to be somewhat polluted with error handling code. For checked exceptions it's fine, as you would have to catch those anyway and it's bad practice to have throws clause in controller methods.


Find the value of $\alpha$ given values $\sin(\alpha + \frac{\pi}{6})$ and $\tan(\alpha)$

Question: Find $\alpha$, given:

$\sin(\alpha + \frac{\pi}{6})$
$\tan(\alpha)=-5$
And terminal side is in Quadrant II

I only got as far as figuring out that the coordinate for the point in QII is $(-1,5)$ and the length of that segment is $\sqrt{26}$. But I'm stuck in getting $\alpha$.
Comment: ...what value is the sine of alpha plus a sixth of pi (the first one)?
Comment: that is the only information given.
Comment: Isn't $\alpha$ simply $\tan^{-1}(-5)$?
Comment: That's what I was thinking. I'll ask my professor. Thanks!
Answer: Unfortunately, it's not quite as simple as taking the arctangent of $\tan(\alpha)$. Were your point in Quadrant I, it would be that simple, but that's not the case. On the bright side, it's not a whole lot more complicated than that.
Well, maybe a little more complicated.

The answer you're looking for is $$\alpha=\arctan(-5)+\pi$$ I could just leave it at that and say that the $+\hspace{1mm}\pi$ comes from some magical property of the arctangent function, but that's no fun. The fun part is why we need to add some integer multiple of $\pi$ to the output of the arctangent function to get the correct answer, and why that integer changes depending on what quadrant the angle you want to find happens to be in.
Call that integer $n$. In Quadrant I, $n=0$. In Quadrants II and III, $n=1$, and in Quadrant IV, $n=2$ (or $0$). To get a feeling for why this is, let's look at the graph of $y=\arctan(\tan(x))$. I've added dashed lines at odd integer multiples of $\frac{\pi}{2}$, and the regions between them correspond to $n=-2$, $n=-1$, $n=0$, $n=1$, and $n=2$, respectively, from left to right.
$\hspace{2.25cm}$
Seeing as $\arctan$ and $\tan$ are inverse functions, we would expect the graph of $y=\arctan(\tan(x))$ to look like the graph of $y=x$. That's clearly not the case; instead, it looks like the graph of $y=x$ has been split up into $\frac{\pi}{2}\times\frac{\pi}{2}$ chunks that are then all lined up on the $x$-axis.
The reason why the above graph looks the way it does has to do with how we define the arctangent function. The tangent function isn't inherently one-to-one, so in order to define its inverse, we need to restrict its domain to $\left(-\frac{\pi}{2},\frac{\pi}{2}\right)$, which means that the range of the arctangent function is also $\left(-\frac{\pi}{2},\frac{\pi}{2}\right)$. Unfortunately, angles greater in magnitude than $\frac{\pi}{2}$ do exist. So what's going to happen when you want the arctangent function to produce one of those angles? It'll produce some number in its range that is an integer multiple of $\pi$ away from the angle you're looking for.
For example, $\arctan(\tan(2\pi))$ should obviously return $2\pi$, right? Instead, the result is $0$, which, by some stroke of sheer mathematical luck, happens to be an integer multiple of $\pi$ away from $2\pi$ (joking a little here). For a more interesting example, $\arctan\left(\tan\left(\frac{7\pi}{4}\right)\right)$ returns $-\frac{\pi}{4}$. Since $\frac{7\pi}{4}$ and $-\frac{\pi}{4}$ are equivalent on the unit circle, this might be fine in some settings, but in others, all you need to do is add $2\pi$ to get back to $\frac{7\pi}{4}$.
Finally, notice that the act of adding integer multiples of $\pi$ to your answers here is like moving the line segments in the graph I included up or down by integer multiples of $\pi$ to reconstruct the graph of $y=x$.


For What Kinds Of Problems is Quantile Regression Useful?

Question: I am trying to learn more about Quantile Regression.
As I understand, Quantile Regression is  used to estimate the conditional quantile of a response variable (given predictor variables).
Mathematically, let $Y$ be the response variable and $X$ be a vector of predictor variables. The $\tau$-th quantile regression model can be written as:
$$
Q_{Y|X}(\tau) = X\beta(\tau)
$$
where $Q_{Y|X}(\tau)$ is the conditional quantile function of $Y$ given $X$, and $\beta(\tau)$ is a vector of unknown parameters that depend on the quantile $\tau$. The goal of quantile regression is to estimate the parameters $\beta(\tau)$ for a given value of $\tau$.
I am trying to understand: For what kinds of problems is Quantile Regression better suited?
When I asked my teacher in school, my teacher indicated that Quantile Regression is intended for applications where you might be specifically interested in modelling the effect of the predictors on some quantile of the response (e.g. median response) instead of the mean response.
But I am trying to understand - in what types of situations would you specifically be interested in modelling a Quantile of the Response Variable instead of the Mean Response? Are there some industries/domains where this requirement naturally arises?
The closest thing which comes to mind is situations where the conditional distribution of the response given the predictor variables might be heavily skewed , partly violating the assumptions of standard regression. In such a case, I think it might somehow be more useful to model some quantile of the response (via Quantile Regression) instead of the mean response. Is this reasoning correct?
Comment: "Prof, when do we want to model quantiles?" "When we're interested in the quantiles." Just phenomenal teaching. $//$ You have an academic affiliation, so you should be able to access journal articles. Koenker is the original developer of quantile regression. You might be interested in the motivation given in his work.
Comment: (A) When the median gives a better summary than the mean. (B) When you are interested in the full conditional distribution of the response. (C) When you need a simple way to calculate 80% prediction intervals (slightly optimistic).
Comment: QR generates much more useful predictions wrt extreme-valued information insofar as one can specify quantiles widely diverging from the mean or median.
Comment: @MichaelM the problem with linear QR and your point (B) is that it does not guarantee proper conditional distributions (e.g. crossing quantiles)
Comment: @Firebug, good point. Perhaps composite quantile regression (a collection of QRs for different quantiles with a restriction that the slopes are common across quantiles) could fix that problem.
Comment: @Dave, Koenker's original paper has an interesting story behind itself. The original motivation of the first draft is hardly visible in the published version where a different motivation is used to be able to "sell" the paper based on the fads of the time...
Answer: One example from tech is p90 of website load speed or service response time. This analysis also comes up in logistics. Here you care about just how bad the worst experience is. Typically this is something you monitor as you make changes, with alerts that fire when that quantile rises above some threshold. Even if, on average, the website loads quickly or purchases arrive the next day, you want to know about the worst scenarios.
In education research, you often care about how an intervention like an AI tutor affects different types of students. Does it move up the left tail (low test scores) or the right tail (helping highest-scoring students)?
The common theme in many such applications is that you are not interested in the conditional mean or how it changes, but in other parts of the distribution.
Answer: Quantile regression is used for modeling growth curves of children.  A pediatrician is not surprised if a child is below the median height as a function of age but starts to worry if the child's height is below the 10th percentile of height given age.  Quantile regression allows estimation of quantiles without assuming a distribution.
But there are two catches.  Quantile regression needs the response variable to be very continuous (i.e., few ties), and the efficiency of the estimates is not great.  In the simplest case with no predictors and one predicts the median, quantile regression gives exactly the sample median, which has efficiency $\frac{2}{\pi}$ compared to using the mean, which also estimates the median if the distribution happened to be symmetric.  So one could say that quantile regression is for larger sample sizes.
Semiparametric ordinal regression models can also estimate quantiles without assuming a distribution, they allow for arbitrarily heavy ties in the data, and they can also estimate the mean and the entire cumulative distribution of Y.  See here for resources.  Semiparametric models are very efficient as compared to parametric models.
Comment: Please re-read the text.  It says that only `R rms::orm` and `JMP` have programmed a sparse matrix solution that efficiently computes the needed quantities when there are thousands of intercepts.  The two software implementations use similar sparse matrix methods.
Comment: In the link, what do you mean in that last comment about JMP, that JMP can handle a case that `rms::orm` cannot?
Comment: This example acutally goes further: If a child is at the 67. percentile of body height at their birth, they will stay on that percentile at least for their first two years. This even be used to predict their clothes size. A calculator is here (German only, unfortunately): https://www.btelligent.com/baby-kleidergroessenrechner/
Answer: Mentioned in dimitriy's answer, but deserving of a little more detail: if you want to find a target inventory or capacity, you will typically not only want to satisfy average demand, but achieve a higher service level. (Note that there are different definitions of "service level" in inventory theory, not all of which make sense in any given situation.)
For instance, you might run a quantile regression in order to forecast what the conditional 95th percentile of total demand in a supermarket is, where you condition on predictors like day of week, day of year, price or promotional activity. This quantile prediction then becomes your target inventory. (Whether the 95th percentile is actually the one to maximize your profit, or maybe you had better aim for a 90th or 98th percentile, is a difficult question that depends on your logistics and on the behavior of your customers. The question is easy to answer in a newsvendor situation, which is not always what you are facing.)
This is why the recent M5 forecasting competition, which explicitly focused on retail forecasting and used Walmart data, required submitting quantile forecasts in its "uncertainty" track.
Answer: Another answer, straight from a real-life project: Imagine you're an e-commerce seller on a large platform (think Amazon, Rakuten, or whatever is popular in your area). Now you want a data-driven solution for telling your customer for each of your products how long it will take to deliver. You could just do a regression on past delivery times for this kind of item, right?
But there's a catch: These platforms usually require their sellers to sign service level agreements, and one of the things they usually have to commit to is that at least 90% of their shipments (or some other share, this is highly country-specific) arrive on time, i.e. the actual delivery time is smaller or equal to what was promised. So if you want a result that complies with the contract you've signed, you want to use a 90%-quantile regression.
Comment: @dimitriy The on-time-or-sooner-rate can only be calculated in retrospective. If you want a prediction, you need regression. If you want a prediction that leads to at least 90% of shipments arriving at the predicted time or earlier, you need quantile regression.
Comment: What does the p90 regression give you compared with calculating the on-time-or-sooner delivery rates for each seller?
Answer: Some practical examples where I have used quantile reg:
Neonatologists and obstetricians are interested in predicting the birth weight of babies. But they are especially interested in very small and very large babies, as this is where problems are most common (e.g. the baby needing emergency care, or problems in labor).  I ran quantile reg. on low and high quantiles and found that the predictors were quite different from what I got for OLS regression.
Epidemiologists are interested in the spread of disease. I worked for a long time at a place that did research into the spread of HIV/AIDS. One way that these spread is through sex, so, we were interested in people who had sex with a lot of partners. Trying to predict this turned out to be quite different from predicting the mean number of partners. (This is also a case where the errors are not remotely normal).


How to build a field list in a node?

Question: I have two content types: 'artist' and 'venue'.
When an artist node is viewed, it needs to display a list of venues and dates. Venue name will link to the venue node eg:
<code>Artist
--------------------
Venue1 | 1-Jan 20:00
Venue2 | 2-Jan 17:00
Venue3 | 4-Jan 20:00
</code>
The possible solutions are:

Create a 'performance' content type that links (using the References module) to artist and venue, and has a date field. Then attach the list using Views. This seems like a lot of extra work for the editor.
Add two unlimited value fields to artist node: reference to venue and date field. It is difficult to keep them in sync and clunky.
Would this be a good use of the entity API? I don't know enough about entities yet, but have a feeling that would be overkill for something so simple?
Answer: Are you looking for Field Collection?
You can create collection with Node Reference field and Date field. Then Field Collection Table will help you with outputting.
This exactly works with Entity API.

How to build a field list in a node?


Probability Coupons

Question: https://i.stack.imgur.com/RoDb7.jpg I don't understand why you alternate between adding and subtracting the probability. So you have the probability of the first coupon then you subtract the probability of the second coupon but add the third.
Answer: We are looking for the probability of any of the events $P\left(\cup_{j=1}^N A_j\right)$.
At first you might say this is the sum of all probabilities for each event $p_1 = \sum_j P(A_j)$, but then you have counted the case where more than one event happens double, so we need to subtract those events.
The probability of more than one of the events $A_j$ can be viewed as $p_2 = \sum_{j_1 < j_2} P(A_{j_1}A_{j_2})$. But in this computation we are counting double all the terms where three events occur, so we must subtract that probability ($p_3$) from this one. As we were  already subtracting $p_2$ from $p_1$, when we subtract $p_3$ from $p_2$, this becomes an addition in the final sum.
Hope this helps.
Comment: good answer, this is called inclusion exclusion principle.
Answer: This is about the Principle of Inclusion and Exclusion (http://en.wikipedia.org/wiki/Inclusion%E2%80%93exclusion_principle)
You add some possibilities, but some 'regions' in the Venn-diagrams (see link) are counted double, so you substract them. But then, you substract some regions to often, so you add them again...
Comment: Okay got it. Thanks. You you add the sum of the finite sets then subtract the double overlay then add in where they appear in three sets.

Probability Coupons


Why is $scope.someArray.push not a valid function to pass to .then on $q.promise

Question: Relevant fiddle:  https://jsfiddle.net/tqf4zea7/1/
I'm using $q in an angular controller.  To test some scenarios, I created an array on the scope to push messages to:
$scope.messages = [];

I have set up a function that returns a $q function as so:
function returnAPromise(valToReturn){
    return $q(function(resolve, reject){
        $timeout(function(){
            resolve(valToReturn);
        }, 500);
    });
}

I then have a .then() call on the result that looks like this:
returnAPromise('third').then($scope.messages.push);

Since I only want to push the value that the promise was resolved with to the array, I figured I could just pass in the push method of the messages array, but when I do that, I get the following error:
VM289 angular.js:12520 TypeError: Array.prototype.push called on null or undefined
    at processQueue (VM289 angular.js:14792)
    at VM289 angular.js:14808
    at Scope.$eval (VM289 angular.js:16052)
    at Scope.$digest (VM289 angular.js:15870)
    at Scope.$apply (VM289 angular.js:16160)
    at VM289 angular.js:17927
    at completeOutstandingRequest (VM289 angular.js:5552)
    at VM289 angular.js:5829

If I enclose push in a function, it works fine:
returnAPromise('third').then(function(message){
     $scope.messages.push(message)
});

Is this a closure issue I don't understand?
Answer: You need to bind push since it uses this
returnAPromise('third').then($scope.messages.push.bind($scope.messages));

Comment: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind Examples section describes the issue and why .bind() resolves it.  Unfortunately, it includes the line "A common mistake for new JavaScript programmers".  =[  I've been demoted.
Answer: I know there is an accepted answer, but i will explain this more clearly here
Example
lets start with an example
var scope = {
  scopeFn: function() {
    console.log('this', this)
  }
}

function callFn(fn) {
  fn();
}

callFn(obj.scopeFn) // will log window object
callFn(function() {
  obj.scopeFn();
});// will log scope object

as you can see, wrapping the function will give the called object the value of this, but calling it directly without wrapping it will call the window object.
why?
this will bind to the object its called from.
In the first example callFn(obj.scopeFn) you are passing the function as a parameter, hence when the function is called, its called directly not from the scope object. (scope object is lost, only the function reference is sent).
in the second example you are calling the function scopeFn from the object, hence the this will bind to its object. (scope object is not lost, as the whole thing is there when its called)
Solution
To solve this issue you need to bind the function you are passing as a parameter for the resolve, so it will always be called as if it is called from its parent object.
var scopeMessage = $scope.messages;
returnAPromise('third').then(scopeMessage.push.bind(scopeMessage));


Formatação de gráficos no Excel

Question: Como fazer para que quando eu pegue a informação de um servidor usando mysql, essa informação apareça na planilha com gráfico já formatado no excel?
Answer: 1º Você precisa definir uma área no excel para os dados que serão utilizados como fonte para o gráfico;
2º Você precisa criar um Módulo no VBA que conecta com o banco MySQL, faz o select dos dados que você quer no gráfico e plota o resultado deste select na área de dados do gráfico reservada no excel.
3º Sempre que você executar a macro que faz o select no MySQL, os dados serão atualizados no excel.
Exemplo: você cria um gráfico no excel e define que a área de dados do gráfico será da célula A1 até D1000, depois quando você popular essas células com os dados que você vai trazer do banco de dados, o gráfico será atualizado também.
Comment: Mas tem que ser na mesma planilha?
Comment: Normalmente sim, pode colocar em outra aba, se não quiser que fique na mesma aba do gráfico.

Formatação de gráficos no Excel


Best way to load a notification image?

Question: What is the best way to load a notification image?
Here's my current way: As you can see the image loads synchronously and thus the notification can be delayed. This is a bad way.
public Bitmap getBitmapFromURL(String strURL) {
    try {
        URL url = new URL(strURL);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setDoInput(true);
        connection.connect();
        InputStream input = connection.getInputStream();
        Bitmap myBitmap = BitmapFactory.decodeStream(input);
        return myBitmap;
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    }
}

Bitmap bitmap = getBitmapFromURL("https://graph.facebook.com/YOUR_USER_ID/picture?type=large");

// CONSTRUCT THE NOTIFICATION DETAILS
builder.setAutoCancel(true);
builder.setSmallIcon(R.drawable.ic_launcher);
builder.setContentTitle("Some Title");
builder.setContentText("Some Content Text");
builder.setLargeIcon(bitmap);
builder.setContentIntent(pendingIntent);

I really need an answer to continue working on my project.
Comment: Stack Overflow is not a programming competition. We require questions to have one, specific, verifiable answer. Asking for "the best" will not work. You need to narrow down precisely what you mean by "best". What are your requirements? What constraints do you have? Describe the solution you are looking for, and then someone can provide it.
Answer: You should first notify your Notification with no image or place holder, then load your bitmap with an AsyncTask, or use Picasso and Target callback.
Give to your task the builder that you used for the first notify, when bitmap is loaded, add it to the builder, and then re-notify your Notification.
If there's a risk that content had changed before complete image loading, store a variable that identify your current content to show, that you can check before renotify.
You can follow that exemple of MediaNotificationManager provide by google UniversalMusicPlayer project.
In your case :
// CONSTRUCT THE NOTIFICATION DETAILS
builder.setAutoCancel(true);
builder.setSmallIcon(R.drawable.ic_launcher);
builder.setContentTitle("Some Title");
builder.setContentText("Some Content Text");
//builder.setLargeIcon(bitmap); // replace this line with place holder drawable from resources
builder.setContentIntent(pendingIntent);

manager.notify(NOTIFICATION_ID, builder.build());

currentLoadImageTask = new LoadImageTask(manager, builder);
currentLoadImageTask.execute("https://graph.facebook.com/YOUR_USER_ID/picture?type=large");

// ...

static class LoadImageTask extends AsyncTask<String, Void, Bitmap> {

    final NotificationManager manager;
    final NotificationCompat.Builder builder;

    public LoadImageTask(final NotificationManager manager, final NotificationCompat.Builder builder) {
        this.manager = manager;
        this.builder = builder;
    }

    @Override
    protected Bitmap doInBackground(final String... strings) {
        if (strings == null || strings.length == 0) {
            return null;
        }
        try {
            final URL url = new URL(strings[0]);
            final HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setDoInput(true);
            connection.connect();
            final InputStream input = connection.getInputStream();
            return BitmapFactory.decodeStream(input);
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    @Override
    protected void onPostExecute(final Bitmap bitmap) {
        if (bitmap == null || manager == null || builder == null) {
            return;
        }
        builder.setLargeIcon(bitmap);
        manager.notify(NOTIFICATION_ID, builder.build());
    }
}

With picasso :
// CONSTRUCT THE NOTIFICATION DETAILS
builder.setAutoCancel(true);
builder.setSmallIcon(R.drawable.ic_launcher);
builder.setContentTitle("Some Title");
builder.setContentText("Some Content Text");
//builder.setLargeIcon(bitmap); // replace this line with place holder drawable from resources
builder.setContentIntent(pendingIntent);

manager.notify(NOTIFICATION_ID, builder.build());

// ...

Picasso.with(context)
    .load("https://graph.facebook.com/YOUR_USER_ID/picture?type=large")
    .resize(250, 250)
    .into(new Target() {
        @Override
        public void onBitmapLoaded(final Bitmap bitmap, final Picasso.LoadedFrom from) {
            builder.setLargeIcon(bitmap);
            manager.notify(NOTIFICATION_ID, builder.build());
        }

        @Override
        public void onBitmapFailed(final Drawable errorDrawable) {
             // Do nothing
        }

        @Override
        public void onPrepareLoad(final Drawable placeHolderDrawable) {
             // Do nothing
        }
    });

If not in UiThread you can create a Runnable and execute it in Looper
 final Handler uiHandler = new Handler(Looper.getMainLooper());
 uiHandler.post(new Runnable() {
      @Override
      public void run() {
           // Call from here
      }
 });

Picasso is much better simply because using cache.
And I highly recommend you to resize every bitmap you set in notification because it can easily provoc OutOfMemoryException if you dont.
Comment: This is the kind of answer I've been looking for. But, are you sure this is the correct way to use Picasso?
Comment: That's not the "classic" way where your reference directly your imageView through into() method, but in your case you have to get the Bitmap result of loading because notification manager not let you access to the imageview. And using Target is how you can get async bitmap load result with picasso. http://square.github.io/picasso/2.x/picasso/com/squareup/picasso/RequestCreator.html#into-com.squareup.picasso.Target-
Comment: I get error `java.lang.IllegalStateException: Method call should happen from the main thread.`  at this line `.into(new Target() {`
Comment: yes it have to, or you can specify an executor.
Comment: How can I fix this error?
Comment: I'm trying to load the image from inside `OnMessageReceived`. See method here: https://github.com/firebase/quickstart-android/blob/master/messaging/app/src/main/java/com/google/firebase/quickstart/fcm/MyFirebaseMessagingService.java
Comment: There's many ways, I add one of them in my answer.
Answer: Remember,if you are loading something using the web, you have to wait a bit.
There are several solutions:

Load an image from the web like in your example and show.
Show a stub image and show downloaded image later by updating the notification
Use a little that helps top cache web inches. For instance, picaso

http://square.github.io/picasso/
Answer: use Picasso lib to load image from url like
 Picasso.with(this.load(imageUri).into(imageview_id);

Best way to load a notification image?


App crashes after Monotouch update to 5.2.13

Question: After I have updated monotouch to Version 5.2.13 my App crashes when I touched inside a UIButton.
About my Code: (it's a question of a LoginView):
I have a UIViewController which includes a ScrollView.
For each User the ScrollView provides a UIView (the UserImageView).
This UserImageView contains a UserImage, Username and so on. Over the UserImage lays a UIButton which should catches the Touch-Events to selected a User.
This Button causes the Exception below more precisely the HitTest method from the UIView.
I get the following Stacktrace:
Stacktrace:
  at (wrapper managed-to-native) MonoTouch.UIKit.UIApplication.UIApplicationMain (int,string[],intptr,intptr) <IL 0x0009f, 0xffffffff>
  at MonoTouch.UIKit.UIApplication.Main (string[],string,string) [0x00042] in /Developer/MonoTouch/Source/monotouch/src/UIKit/UIApplication.cs:29
  at MF.Stationaer.iPad.Application.Main (string[]) <IL 0x00028, 0x00073>
  at (wrapper runtime-invoke) <Module>.runtime_invoke_void_object (object,intptr,intptr,intptr) <IL 0x00050, 0xffffffff>

Native stacktrace:
0   MFiPad_MD            0x0009061c mono_handle_native_sigsegv + 284
1   MFiPad_MD            0x000059a8 mono_sigsegv_signal_handler + 248
2   libsystem_c.dylib                   0x92cd259b _sigtramp + 43
3   ???                                 0xffffffff 0x0 + 4294967295
4   UIKit                               0x0228c741 __38-[UIView(Geometry) hitTest:withEvent:]_block_invoke_0 + 96
5   CoreFoundation                      0x0116cf1a __NSArrayChunkIterate + 362
6   CoreFoundation                      0x01138635 __NSArrayEnumerate + 997
7   CoreFoundation                      0x01138026 -[NSArray enumerateObjectsWithOptions:usingBlock:] + 102
8   UIKit                               0x0228c66b -[UIView(Geometry) hitTest:withEvent:] + 646
9   UIKit                               0x0228c765 __38-[UIView(Geometry) hitTest:withEvent:]_block_invoke_0 + 132
10  CoreFoundation                      0x0116cf1a __NSArrayChunkIterate + 362
11  CoreFoundation                      0x01138635 __NSArrayEnumerate + 997
12  CoreFoundation                      0x01138026 -[NSArray enumerateObjectsWithOptions:usingBlock:] + 102
13  UIKit                               0x0228c66b -[UIView(Geometry) hitTest:withEvent:] + 646
14  UIKit                               0x022a1157 -[UIScrollView hitTest:withEvent:] + 79
15  UIKit                               0x0228c765 __38-[UIView(Geometry) hitTest:withEvent:]_block_invoke_0 + 132
16  CoreFoundation                      0x0116cf1a __NSArrayChunkIterate + 362
17  CoreFoundation                      0x01138635 __NSArrayEnumerate + 997
18  CoreFoundation                      0x01138026 -[NSArray enumerateObjectsWithOptions:usingBlock:] + 102
19  UIKit                               0x0228c66b -[UIView(Geometry) hitTest:withEvent:] + 646
20  UIKit                               0x0228c765 __38-[UIView(Geometry) hitTest:withEvent:]_block_invoke_0 + 132
21  CoreFoundation                      0x0116cf1a __NSArrayChunkIterate + 362
22  CoreFoundation                      0x01138635 __NSArrayEnumerate + 997
23  CoreFoundation                      0x01138026 -[NSArray enumerateObjectsWithOptions:usingBlock:] + 102
24  UIKit                               0x0228c66b -[UIView(Geometry) hitTest:withEvent:] + 646
25  UIKit                               0x0228c765 __38-[UIView(Geometry) hitTest:withEvent:]_block_invoke_0 + 132
26  CoreFoundation                      0x0116cf1a __NSArrayChunkIterate + 362
27  CoreFoundation                      0x01138635 __NSArrayEnumerate + 997
28  CoreFoundation                      0x01138026 -[NSArray enumerateObjectsWithOptions:usingBlock:] + 102
29  UIKit                               0x0228c66b -[UIView(Geometry) hitTest:withEvent:] + 646
30  UIKit                               0x02286dbd +[UIWindow _hitTestToPoint:pathIndex:forEvent:] + 378
31  UIKit                               0x02258ca0 _UIApplicationHandleEvent + 1648
32  GraphicsServices                    0x047c5ef5 PurpleEventCallback + 1274
33  CoreFoundation                      0x011a9195 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE1_PERFORM_FUNCTION__ + 53
34  CoreFoundation                      0x0110dff2 __CFRunLoopDoSource1 + 146
35  CoreFoundation                      0x0110c8da __CFRunLoopRun + 2218
36  CoreFoundation                      0x0110bd84 CFRunLoopRunSpecific + 212
37  CoreFoundation                      0x0110bc9b CFRunLoopRunInMode + 123
38  GraphicsServices                    0x047c47d8 GSEventRunModal + 190
39  GraphicsServices                    0x047c488a GSEventRun + 103
40  UIKit                               0x02258626 UIApplicationMain + 1163
41  ???                                 0x0b96e514 0x0 + 194438420
42  ???                                 0x0b96d6c0 0x0 + 194434752
43  ???                                 0x0b96d33c 0x0 + 194433852
44  ???                                 0x0b96d42f 0x0 + 194434095
45  MFiPad_MD            0x00009d12 mono_jit_runtime_invoke + 722
46  MFiPad_MD            0x00169e4e mono_runtime_invoke + 126
47  MFiPad_MD            0x0016df34 mono_runtime_exec_main + 420
48  MFiPad_MD            0x001732e5 mono_runtime_run_main + 725
49  MFiPad_MD            0x00066f15 mono_jit_exec + 149
50  MFiPad_MD            0x002115d5 main + 2837
51  MFiPad_MD            0x00002d65 start + 53

Got a SIGSEGV while executing native code. This usually indicates
a fatal error in the mono runtime or one of the native libraries
used by your application.
Here is the important Part of my Code:
public class LoginViewController : UIViewController
{
    ...
    public override void ViewDidLoad()
    {
        ...

        BuildUserUI();

        ...
    }

    private void BuildUserUI()
    {
        currentIconLocation = new PointF(50, 10);

        for (var i = 0; i < UserList.List.Count; i++)
            CreateUserInGrid(UserList.GetUserByIndex(i));
    }

    private void CreateUserInGrid(LoginUser user)
    {
        var imgFrame = new RectangleF(currentIconLocation.X, currentIconLocation.Y, 140, 170);

        var loginImg = new UILoginImage(imgFrame);
        loginImg.Image = user.Image ?? defaultUserImage.CGImage;
        loginImg.Name = user.Nachname;

        if (!string.IsNullOrEmpty(user.Vorname))
            loginImg.Name += ", " + user.Vorname;

        loginImg.Tag = user.UserIndex;
        loginImg.AddTarget(this, new Selector("ShowNumberPad:"), UIControlEvent.TouchUpInside);
        loginImg.LoginUser = user;
        scrollView.AddSubview(loginImg);
        loginImages.Add(loginImg);

        limitedScrollView.UserInteractionEnabled = false;

        var newSize = new SizeF(scrollView.Frame.Size.Width, currentIconLocation.Y + imgFrame.Size.Height + 20);
        scrollView.ContentSize = newSize;
        limitedScrollView.ContentSize = new SizeF(limitedScrollView.Frame.Size.Width, limitedScrollView.Frame.Size.Height);

        currentIconLocation.X += imgFrame.Size.Width;

        if (currentIconLocation.X + imgFrame.Size.Width > scrollView.Frame.Size.Width)
        {
            currentIconLocation.Y += imgFrame.Size.Height;
            currentIconLocation.X = 50;
        }
    }

    [Export("ShowNumberPad:")]
    private void ShowNumberPad(NSObject sender)
    {
        ...
    }
}

public class UILoginImage : UIView
{
    [Export("initWithFrame:")]
    public UILoginImage(RectangleF frame)
        : base(frame)
    {
        var shadowFrame = new RectangleF(0, 0, 117, 148);

        wrapperControl = new UIControl(shadowFrame);
        AddSubview(wrapperControl);

        shadowImage = new UIImageView(shadowFrame);
        shadowImage.Image = ImageCache.GetResourceImage("Images/Login/LoginSchatten.png");
        wrapperControl.AddSubview(shadowImage);

        var mainBackFrame = new RectangleF(8, 9, 98, 128);
        whiteBackgroundImage = new UIImageView(mainBackFrame);
        whiteBackgroundImage.Image = ImageCache.GetResourceImage("Images/Login/Singlewhite.png");
        wrapperControl.AddSubview(whiteBackgroundImage);

        var imageFrame = new RectangleF(13, 15, 87, 116);

        clickHelper = UIButton.FromType(UIButtonType.Custom);
        clickHelper.Frame = imageFrame;
        wrapperControl.AddSubview(clickHelper);

        userImage = new UIImageView(imageFrame);
        AddSubview(userImage);

        var mitarbeiterlabelFrame = new RectangleF(-12, 137, 140, 25);
        mitarbeiterNameLabel = new FontSizeLabel(mitarbeiterlabelFrame);
        mitarbeiterNameLabel.TextAlignment = UITextAlignment.Center;
        mitarbeiterNameLabel.Font = UIFont.SystemFontOfSize(12);
        mitarbeiterNameLabel.Opaque = false;
        mitarbeiterNameLabel.BackgroundColor = UIColor.Clear;
        AddSubview(mitarbeiterNameLabel);

        var benutzerlabelFrame = new RectangleF(mitarbeiterlabelFrame.X, mitarbeiterlabelFrame.Y + 13, 140, 25);
        benutzerNameLabel = new FontSizeLabel(benutzerlabelFrame);
        benutzerNameLabel.TextAlignment = UITextAlignment.Center;
        benutzerNameLabel.Font = UIFont.SystemFontOfSize(10);
        benutzerNameLabel.Opaque = false;
        benutzerNameLabel.BackgroundColor = UIColor.Clear;
        benutzerNameLabel.TextColor = UIColor.DarkGray;
        AddSubview(benutzerNameLabel);
    }

    public void AddTarget(NSObject target, Selector action, UIControlEvent controlEvents)
    {
        clickHelper.AddTarget(target, action, controlEvents);
    }

    public void RemoveTarget(NSObject target, Selector action, UIControlEvent controlEvents)
    {
        clickHelper.RemoveTarget(target, action, controlEvents);
    }
}

Comment: This can occurs when an instance (e.g. of your `UIButton`) is no more referenced and the GC collects it. However without seeing the source code it's not possible to confirm it.
Answer: I'm not sure your use of AddTarget is a good way to hook up a UIButton's click.
You should be using clickHelper.TouchUpInside to wire up click events.  This is a standard C# event.
Another option would be to wire up an action to this event inside your XIB file in XCode.


Ativar o GPS do smartphone

Question: Estou desenvolvendo um app que utiliza as funções de geolocalização. O mesmo já está pegando as localizações do smartphone, e consigo verificar se a conexão do GPS ou não.
Até ai tranquilo, o que não estou conseguindo é que se o GPS estiver desligado, peça para o usuário ligar o mesmo, levando-o direto a tela de configurações do GPS, ou apenas com um clique de um turn on no GPS e não deixe o mesmo utilizar o app até que seja ligado.
Answer: Atualmente não é possível ativar/desativar o GPS diretamente do aplicativo, porém, você pode sim levar o usuário para a configuração do dispositivo que faz isso.
Para isso, após fazer essa verificação do GPS e constatar que está desligado, o usuário pode tocar um botão que terá esta ação simples para abrir a Activity de configuração:
startActivity(new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS));

Agora, fazer com que o aplicativo não seja utilizado até que o GPS esteja pronto, você mesmo já possui a solução, já que faz a verificação de disponibilidade dele, certo?
Comment: Ótimo! Considere marcar esta resposta como aceita caso tenha respondido sua dúvida. Assim irá ajudar outros com a mesma dúvida.
Comment: Valeu @Paulo, funcionou sim, exatamente isso que queria, agora só basta fazer uma janela com um para ir para a startActivity.

Ativar o GPS do smartphone


How Rapidminer handle same distance for KNN Algorithm

Question: Actually I already asked in rapidminer forum, but no one has given an answer yet..
https://community.rapidminer.com/discussion/55963/how-k-nn-algorithms-work-with-same-distance-in-rapidminer#latest
I can't find a satisfying answer for KNN-algorithm with same euclidean distance in rapidminer..
I found a similar question, but it's not explain how rapidminer work for this case.
Dealing with ties, weights and voting in kNN
say k=5. Now I try to classify an unknown object by getting its 5 nearest neighbours. What to do, if distance is a lot of the same distance.. if after determining the 4 nearest neighbors, the next 2 (or more) nearest objects have the same distance and diferent label? Which object of these 2 or more rapidminer chosen as the 5th nearest neighbor?
I confused.. I try in excel, and the result is diferent with rapidminer for some data. in excel the result label is "LU":

but the result in rapidminer is "LT" :

result rapidminer weighted vote is checked is "LU" :

How rapidminer work with case like that... how rapidminer sorting the distance ?... something wrong with my data ?, or rapidminer sorting random for same distance?
thanks you in advance for your help
Answer: I answered your original question on StackOverflow this way:
In these cases, where distances are the same, RapidMiner kNN uses the internal sorting of the ExampleSet that was used at training time. So internally it picks the examples that it "saw first".
Try to change the sorting before building the kNN model, it should give different results.
You can verify it with the official source code on github: https://github.com/rapidminer/rapidminer-studio/blob/master/src/main/java/com/rapidminer/operator/learner/lazy/KNNClassificationModel.java
Answer: A solution if you are concerned with ties and worried about what kind of tie breaking method a particular algorithm might use is to add a very small random value to one of your predictors (if possible). This way ties will be broken randomly, and won't depend on the order of your input set