What is the easiest way to print a DateTime using an hour adjustment instead of a locale?

Question: I am working on a system where each user can specify a setting of their adjustment from UTC in hours.
So when a date/time is input from this user, the value is adjusted by their setting and saved as UTC. Similarly, on the way out, the date/time is retrieved from the database, adjusted per their setting and displayed.
I might be thinking about this too much, but does this mean to show the correct date/time for each person, I have to effectively adjust the hours and tell the instance of my SimpleDateFormat that this is "UTC"? Right now I am in the UK where the current time zone is UTC+1 and if I don't specify to print in UTC then the time is off by one hour!
DateTime dateWithOffset = statusDate.plusMinutes(currentTimezoneOffsetInMinutes);

SimpleDateFormat sdf = new SimpleDateFormat("dd MMM yyyy HH:mm");
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
return sdf.format(dateTime.toDate());

Am I thinking about this correctly? Or is there an easier way to print a date in a format given that I just want an hours adjustment from UTC?
Comment: Would the `setRawOffset` method of the `TimeZone` class  work for you?
Comment: Minor inconsistency; Your first sentence says hours but your code says minutes.
Comment: @BasilBourque Thanks! I tried to simplify the question as much as possible! We save the offset in minutes so it would be 60, 120, etc. Thank you for your detailed answer, I will read and understand it properly on Monday, right now it's the weekend!
Comment: @DavidSpence What did you mean by `locale` in the title? No mention in the rest of the Question.
Comment: Probably not the correct term. I meant that the user does not choose their country etc. I'm not sure how common the approach is, choosing the number of hours offset from UTC as a user setting!
Answer: You are working too hard. Never do manual adjustments for offsets and time zones, never be adding or subtracting minutes to a date-time value for that purpose. Let a decent date-time library do that work.
java.time
The Joda-Time team advises us to migrate to the java.time framework built into Java 8 and later.
The ZoneOffset class represents an offset-from-UTC. Keep in mind that in some areas an offset may involve not only a number of hours but also minutes and even seconds.
The OffsetDateTime class represents a a moment in the timeline with an assigned offset.
int hours = 3;  // input by user

ZoneOffset offset = ZoneOffset.ofHours( hours );
OffsetDateTime odt = OffsetDateTime.now( offset );

The standard ISO 8601 formats are used by the toString methods in java.time.
String output = odt.toString();

Generally the best practice is to do your business logic and data storage in UTC. Convert to/from an offset or zoned value only for interaction with user.
In java.time a moment on the timeline in UTC is represented by the Instant class. You can extract an Instant object from the OffsetDateTime.
Instant instant = odt.toString();

Both this Instant and this OffsetDateTime represent the same simultaneous moment on the timeline. They present different wall-clock times.
It may be more clear to skip the use of the OffsetDateTime.now convenience method and start with Instant.
Instant instant = Instant.now();  // Always in UTC, by definition.
ZoneOffset offset = ZoneOffset.ofHours( hours );
OffsetDateTime odt = OffsetDateTime.ofInstant( instant , offset );  // Same moment but presenting alternate wall-clock time.

Handling input
If the user is inputting date-time values as strings, we need to parse. In java.time that means the DateTimeFormatter class. The formatting codes are similar to the outmoded java.text.SimpleDateFormat but not exactly identical, so be sure to study the doc.
DateTimeFormatter formatter = DateTimeFormatter.ofPattern( "dd MMM uuuu HH:mm";

Since the offset-from-UTC is given separately, we parse this input string as a LocalDateTime devoid of time zone information.
LocalDateTime ldt = LocalDateTime.parse( inputString , formatter );

To view, create a String object formatted in ISO 8601 format by calling ldt.toString().

2016-01-02T12:34:45

Apply the pre-determined ZoneOffset object to yield a OffsetDateTime object.
OffsetDateTime odt = ldt.atOffset( offset );

2016-01-12T12:34:45+03:00

Think in UTC
Handling date-time values is a headache. UTC is your aspirin.
When a programmer arrives at the office, she should take off her "UK citizen / London resident" hat, and put on her "UTC" hat. Forget all about your own local time zone. Learn to think in UTC (and 24-hour clock). Add another clock to your desk or computer, set to UTC (or Reykjavík Iceland), or at least bookmark a page like time.is/UTC. Do all your logging, business logic, data serialization, data-exchange, and debugging in UTC.
Make Instant your first-thought, your go-to class. It's value is always in UTC by definition.
Instant instant = Instant.now();

Look at the Instant extracted from the OffsetDateTime value we saw above whose String representation was 2016-01-12T12:34:45+03:00. Being in UTC means 9 AM rather than noon, same moment but three hours difference in wall-clock time. The Z is short for Zulu and means UTC.
String output = odt.toInstant().toString();

2016-01-12T09:34:45Z

Adjust into an offset or time zone only as needed, when expected by a user or data sink. FYI, a time zone is an offset-from-UTC plus a set of rules for handling anomalies such as Daylight Saving Time (DST). Use a time zone in preference to a mere offset wherever possible.
The Europe/London time zone is the same as UTC in the summer, but in winter uses Daylight Saving Time nonsense, and is one hour ahead of UTC. So using the same Instant seen just above, the London wall-clock time is 10 AM rather than 9 AM in UTC, and different from the noon we saw with an offset of +03:00.
ZoneId zoneId = ZoneId.of( "Europe/London" );
ZonedDateTime zdt = ZonedDateTime.ofInstant( instant , zoneId );

2016-01-12T10:34:45+01:00[Europe/London]

Always specify the desired/required offset or time zone; never rely on the implicit current default by omitting this optional argument. (Ditto for Locale by the way.) Note how in all the code of this answer the fact that your JVM has a current default time zone (ZoneId.systemDefault) of Europe/London and the fact that my JVM has a current default time zone of America/Los_Angeles is completely irrelevant. The code runs the same, gets the same results, regardless of whatever machine you use to develop, test, and deploy.
Locale
Specify a Locale object when generating a textual representation of a date-time value that involves a name of month or day, commas or periods and so on. The Locale determines (a) the human language to use when translating such names, and (b) the cultural norms to follow in deciding issues such as punctuation marks.
The Locale has nothing to do with time zones and offset-from-UTC. For example, you could use Locale.CANADA_FRENCH with a date-time zoned for Asia/Kolkata if you had a Québécois user in India.
Comment: Thank you for putting the time into writing such a detailed answer.


Illogical Improper integral with parameter?

Question: $\displaystyle \int_b^c \frac{e^{-ax}*(\sin(bx)-\sin(cx))}{x}\, dx$, $a>0$ and $b,c \in \Bbb R$
I have this improper integral with parameter and I do not understand how to solve it.I have found an answer in my pdf college textbook but the answer is not logical.
Here is what it says:
 $φ(x)= \displaystyle \int_b^c {e^{-ax}*\cos(yx)} \, dy$,  $\;x \in (0,+\infty)$
How did this $\cos(yx)$ term appeared from $\sin bx-\sin cx$?
Answer: Simply because
$$\frac{\mathrm e^{-ax}(\sin cx-\sin bx)}x =\int_b^c {e^{-ax}\cos(yx)} \,\mathrm dy. $$
Comment: Bernard What is your proof?
Comment: That still doesn't explain anything!


Shortest proof of Kuratowski's lemma

Question: I want a short proof of Kuratowski's lemma (about maximal chains).
Does proving Kuratowski's lemma need first prove Zorn lemma?
I am writing a book in which I claim that the reader needs to know only basic set theory in order to understand it. For this reason I need a short proof of Kuratowski's lemma, for the readers of my book.
Comment: Zorn's lemma *is* basic set theory.
Comment: There are easy, elementary proofs of (KL implies ZL) and (ZL implies KL). Thus, proving KL can't be significantly easier than proving ZL.
Comment: Well, the proof using ZL seems to be straightforward, see [PlanetMath](http://planetmath.org/?op=getobj&id=11512).
Comment: There are elementary proofs, but they all provide little insight. The best proof is IMHO by transfinite recursion: Add elements until you cannot add elements anymore without the set not being a chain..
Answer: The answer depends entirely on what you consider elementary set theory. Kuratowski's lemma is equivalent to the axiom of choice, which is independent of the usual ZF axioms of set theory. Thus, you can't prove it in ZF; you can either assume it as an axiom, or assume one of the other equivalents of the axiom of choice and derive it from that.
If you intend to assume the axiom of choice and derive Kuratowski's lemma from that, you will need to use transfinite recursion at some point. If you take this approach, your proof will be intuitively nice, as Michael Greinecker noted in the comments, but it will be technically a bit difficult if you mean to do it very rigorously.
If, on the other hand, you intend to assume Zorn's lemma as a basic axiom, you can prove Kuratowski's lemma almost trivially, but at the cost of assuming a much less intuitively satisfying equivalent of the axiom of choice. An intermediate alternative is to take the well-ordering principle as an axiom.
If you're going to want more than one of the various equivalent statements later, you might as well spend a little extra time introducing them. As I said elsewhere, brevity is not always a good thing when you're trying to explain something.

Shortest proof of Kuratowski's lemma


Why `it1++` works, but `it1=it1+1` does not, where it1 is iterator of list container

Question: Given a std::list iterator called it, it1++ is equivalent to it1=it1+1. So why then does it1++ work fine, but it1=it1+1 is giving an error in the below code?
Code
#include <iostream>
#include <list>

int main()
{
    std::list<int> l1{19, 2, 3, 21, 5, 19, 7, 11};
    std::list<int>::iterator it1;

    std::cout << "1st\n";
    it1 = l1.begin();
    it1++;
    it1 = it1 + 1; // This giving error
}

Output
Invalid operands to binary expression
 ('std::list<int>::iterator' (aka '_List_iterator<int>') and 'int')

Comment: @Bathsheba At a guess, some of the downvoting might be because the question started with code (I've now rectified that.), which typically is a bad sign indicating that the asker has not thought through the question.
Answer: Re: "it1++ is equivalent to it1=it1+1" -- that's not the case. It's true for built-in numeric types, but once overloaded operators come into play, there's no inherent connection between the two operators. Iterators for std::list are forward iterators; they do not have an operator+, but they do have an operator++.
Edit, elaboration:
A forward iterator let's you move forward in a sequence. To do that, it provides two overloads of operator++, so that you can write it++ and ++it. std::forward_list provides forward iterators.
A bidirectional iterator let's you move forward and backward in a sequence. In addition to the operations provided by forward iterators, it provides two overloads of operator--, so that you can write it-- and --it. std::list provides bidirectional iterators.
A random access iterator let's you move to arbitrary places in the sequence. In addition to this operations provided by bidirectional iterators, it provides an overload of operator+ so that you can write it + 3. It also provides an overload of operator[] so that it[n] is equivalent to *(it + n). std::vector provides random access iterators.
Comment: Can you please change `operator—` to `operator--`, I can't request an edit with that few changes. It might confuse.
Comment: @thomas.st -- thanks for pointing that one out. My iPad insists on making that change; I fixed it everywhere else, and missed that one. Good thing my main system isn't that smart.


Node js JSON: Access Object

Question: I parse 'body' and save it to my var jsonNew getting 'results'.
let json = JSON.parse(body);

var jsonNew = json['results'];

jsonNew gives me:
[
  {
    address_components: [
      [Object], [Object],
      [Object], [Object],
      [Object], [Object],
      [Object], [Object],
      [Object]
    ],
    formatted_address: 'Germany',
    geometry: {
      location: [Object],
      location_type: 'ROOFTOP',
      viewport: [Object]
    },
    place_id: '123',
    plus_code: {
      compound_code: '123',
      global_code: '132+86'
    },
    types: [ 'street_address' ]
  }
]

How can I access geometry.location to get 'lat' and 'lng'?
Which are the search terms I need to google to find the solution? What exactly do I have here?
"geometry" : {
            "location" : {
               "lat" : 1234,
               "lng" : 12345
            },
            "location_type" : "ROOFTOP",
            "viewport" : {
               "northeast" : {
                  "lat" : 5555,
                  "lng" : 6666
               },
               "southwest" : {
                  "lat" : 555,
                  "lng" : 666
               }
            }
         }

Answer: I was able to solve this getting [0] of the array - I am stupid!
var jsonNew = json['results'][0].geometry.location;

Node js JSON: Access Object


What is a local base for a topological vector space

Question: On Rudin there's the following definition:

A local base of a topological vector space $X$ is thus a collection
  $B$ of neighborhoods of $0$ such that every neighborhood of $0$
  contains a member of $B$

This definition makes no sense for me. For example, if we replace member of $B$ by 'neighborhood of $0$' then the above definition becomes:

A local base of a topological vector space $X$ is thus a collection
  $B$ of neighborhoods of $0$ such that every neighborhood of $0$
  contains a neighborhood of $0$
Comment: I don't no if thats part of your confusion, but note that the notion of basis for a topology and basis of a vector space are very very different. You're dealing with the former.
Comment: Are you confused with the fact that not every collection of neighborhoods fulfills that condition? When you "translated" $B$ into words, you forgot to say that every neighborhood contains a neighborhood of $0$ belonging to one particular collection of neighborhoods.
Answer: No, it's a collection $\mathcal{B}$ of neighbourhoods of $0$ such that if $O$ is any neighourhood of $0$ there exists some $B \in \mathcal{B}$ such that $B \subseteq O$.
A typical example in $\mathbb{R}$ is $\mathcal{B} = \{(-\frac{1}{n}, \frac{1}{n}): n \in \mathbb{N}^+\}$. These open intervals are all open neighbourhoods of $0$ and every neighbourhood $O$ of $0$ contains some ball of radius $r>0$ around $0$, so $(-r,r) \subseteq O$, and then finding $k$ with $\frac{1}{k} < r$, we see that we can take $(-\frac1k, \frac1k) \in \mathcal{B}$ and $(-\frac1k, \frac1k) \subseteq (-r,r) \subseteq O$.
The point is that sometimes we can take a small (here countable) set of neighbourhoods that are all we need for considering continuity at $0$, or closure properties of $0$, instead of the full set of neighbourhoods.
Comment: Doesn't every neighborhood contain neighborhoods inside? Can you give an example of a neighborhood around 0 that does not contain neighborhoods around 0?
Comment: @GuerlandoOCs The point is that we can choose a **special** neighbourhood inside any neighbourhood; this collection of special ones is a base.
Comment: There's an $O$ that should be a $0$, right?
Comment: @GuerlandoOCs yes, I corrected it.


Install SSL Certificate for a DNS redirection

Question: We have an application developped on a internal server.
A DNS redirection to the livebox IP has been done for our customers to access a service online via OVH.
The online URL is client.lexcelera.com.
We have baught a SSL certificate for client.lexcelera.com but I don't know how to install it.
We are on a CentOs 6.4 OS with an AOL server.
We are using pound to set the ports.
Any idea how to install my certificate?
Edit
Here are the result of the host command:
[root@OpenMat ~]# host client.lexcelera.com
client.lexcelera.com has address 188.8.131.52

but when I try on 184.108.40.206 I get:
22.214.171.124.in-addr.arpa domain name pointer lneuilly-657-1-25-1.w80-15.abo.wanadoo.fr.

Here is my pound.cfg:
User            "pound"
Group           "pound"
LogLevel        2

ListenHTTP
        Address 0.0.0.0
        Port    80
End

ListenHTTPS
        Address 0.0.0.0
        Port    443
        Cert    "/etc/pound/localhost.pem"
End

# By default show the "projop" production server
Service
        BackEnd
                Address 0.0.0.0
                Port    8000
                TimeOut 600
        End
End

Thanks!
Answer: Since you are using Pound, that is the application which accepts the initial HTTPS request and which must have the certificate configured or "installed". Check its man page on the commands to use (HTTPS listener).


sequence in Hilbert space

Question:
Let $(x_n)_{n=1}^{\infty}$ and $(y_n)_{n=1}^{\infty}$ be sequences in the closed unit ball in a Hilbert space. Prove that if $\langle x_n,y_n \rangle→1$ then $\lVert x_n−y_n \rVert→0$.

(From the Fundamentos de análise funcional by Botelho Pellegrino.)
Can I say from the assumption that it is an orthogonal basis within the Hilbert space? Also, how does the other assumption about the closed unit ball help me?
Comment: Hint: $2\langle x_n y_n\rangle = \|x_n\|^2 + \|y_n\|^2 - \|x_n - y_n\|^2$.
Answer: Sine you always have $(\forall n\in\Bbb N):\langle x_n,y_n\rangle\leqslant\|x_n\|\|y_n\|\leqslant1$ and since $\lim_{n\to\infty}\langle x_n,y_n\rangle=1$, you have $\lim_{n\to\infty}\|x_n\|\|y_n\|=1$. It follows from this and from the fact that you always have $\|x_n\|,\|y_n\|\leqslant1$ that$$\lim_{n\to\infty}\|x_n\|=\lim_{n\to\infty}\|y_n\|=1.$$And then\begin{align}\lim_{n\to\infty}\|x_n-y_n\|^2&=\lim_{n\to\infty}\|x_n\|^2+\|y_n\|^2-2\langle x_n,y_n\rangle\\&=1+1-2\\&=0.\end{align}
Comment: $||x_n||\leqslant 1$ and $||y_n||\leqslant 1$ it is stated that they belong to the closed unit ball, right?
Comment: Yes, that is correct.

sequence in Hilbert space


How does R's "poisson.test" function work, mathematically?

Question: I am trying to understand the mathematics underneath the poisson.test function in the stats package in R.  I am using it to compute a p-value when comparing a sample of data against another poisson rate; not another sample of data.
I've looked up the documentation around this but I cannot find anything which outlines the mathematics of the test itself, only how it is used. If anyone is able to help, or point me in the right direction I'd be greatly appreciative.
Comment: Some questions are not an ideal fit for any site. However, I believe your post is  within our scope and I have reopened it. A question involving R (or any other statistical language) is *NOT* off topic *if it requires statistical expertise to understand or answer* (which is the case here). Indeed, R is our most popular tag by some distance; a rather bizarre occurrence if all R questions were automatically off topic.
Comment: See the discussion here: https://stats.stackexchange.com/questions/350745/help-me-understand-poisson-test which included both (one and two sample) forms of the test. It may be that you need even more detail than is there though
Comment: Questions about software are off topic here, but I think you can probably rephrase your question so that it does not involve R.
Comment: Well I initially posted on Stack Overflow and they told me i couldn't post it there either and that I should post it here? I will refrain from posting in future.
Answer: When you say "another Poisson rate" ... if that other Poisson rate is derived from data then you are comparing data with data.
I'll assume you mean against some prespecified/theoretical rate (i.e. that you're performing a one-sample test).
You didn't state whether you were doing a one-tailed or two-tailed test. I'll discuss both
What it's doing is using the Poisson distribution with the specified rate you're testing against, and then computing the tail area "at least as extreme" (in the direction of the alternative) as the sample you got.
e.g. consider a one-tailed test; $H_0: \mu \leq 8.5$ vs $H_1: \mu > 8.5$ and the observed Poisson count of 14. Then we can compute that the upper tail at and above 14 has 0.0514  of the probability - e.g.:

> 1-ppois(13,8.5)
[1] 0.05141111

(I realize this is not the best way to compute this in R - we should use the lower.tail argument instead - but wanted to make it more transparent to readers less familiar with R; by comparison ppois(13,8.5,lower.tail=FALSE) looks like an off-by-one error)
This calculation agrees with poisson.test:
> poisson.test(14,r=8.5,alt="greater")

        Exact Poisson test

data:  14 time base: 1
number of events = 14, time base = 1, p-value = 0.05141
alternative hypothesis: true event rate is greater than 8.5
95 percent confidence interval:
 8.463938      Inf
sample estimates:
event rate
        14

With a two-tailed test it sums those values with equal or lower probability (i.e. as with typical Fisher-style exact tests, it uses the likelihood under the null to identify what's "more extreme"):

The probability of a 14 with Poisson mean 8.5 is about 0.024 and in the left tail the largest x-value with probability no larger occurs at 3, so the probabilities of 0,1,2 and 3 are added in:
>  1-ppois(13,8.5)+ppois(3,8.5)
[1] 0.08152019

check against the output:
> poisson.test(14,r=8.5)

        Exact Poisson test

data:  14 time base: 1
number of events = 14, time base = 1, p-value = 0.08152
alternative hypothesis: true event rate is not equal to 8.5
95 percent confidence interval:
  7.65393 23.48962
sample estimates:
event rate
        14

R code is publicly available -- you can check the code; in this case it bears out what I said above.
Answer: Glen's answer notes that you can check the code for this function, but I'm not sure if you know how to do this, so I'll augment his answer by showing you how.  To check the code, just load the relevant library and type in the function name without any arguments:
library(stats)
poisson.test

function (x, T = 1, r = 1, alternative = c("two.sided", "less",
    "greater"), conf.level = 0.95)
{
    ...some code here...

    PVAL <- ...some code...

    ...more code here...

    structure(list(statistic = x, parameter = T, p.value = PVAL,
        conf.int = CINT, estimate = ESTIMATE, null.value = r,
        alternative = alternative, method = "Exact Poisson test",
        data.name = DNAME), class = "htest")
    }
}
<bytecode: 0x0000000019efa180>
<environment: namespace:stats>

You will see from the code that the poisson.test function creates a htest object (a list that is classed as a hypothesis test) containing calculations for the test statistic, p-value, and confidence interval.  The code is quite long, but a lot of it can be ignored.  The parts of interest are the code to calculate the test statistic and p-value, which are about 12-15 lines of code each.  You might be able to walk through it and see how each of these objects is calculated, which will tell you the mathematics they are using.  This will augment Glen's answer, which confirms the output of the test in a particular case.


dispatch action on form submit to add object to array in reducer

Question: I am trying to submit a form in a modal that adds a time and event to my state. My sample data is:
  {
    date: "Sat 2nd",
    enjoyments: ['Football', 'Rugby'],
    achievements: [{'Tennis', '1100am'}, {'Football', '1200pm'],
    id: 1
  },

I have my form:
   submitForm(){
        this.props.onChange(this.props.dayId, e.label, )

    }

  render() {

    console.log(this.props)
    var options = [
      { value: 1, label: 'Play Music' },
      { value: 2, label: 'Football' }
    ];

    var hourSelect = [
      { value: 0, label: '00' },
      { value: 1, label: '01' },
      { value: 2, label: '02' },
      { value: 3, label: '03' },
      { value: 4, label: '04' },
      { value: 5, label: '05' },
      { value: 6, label: '06' },
      { value: 7, label: '07' },
      { value: 8, label: '08' },
      { value: 9, label: '09' },
      { value: 10, label: '10' },
      { value: 11, label: '11' },
      { value: 12, label: '12' },
      { value: 13, label: '13' },
      { value: 14, label: '14' },
      { value: 15, label: '15' },
      { value: 16, label: '16' },
      { value: 17, label: '17' },
      { value: 18, label: '18' },
      { value: 19, label: '19' },
      { value: 20, label: '20' },
      { value: 21, label: '21' },
      { value: 22, label: '22' },
      { value: 23, label: '23' }
    ];

    var minSelect = [
      { value: 0, label: '00' },
      { value: 15, label: '15' },
      { value: 30, label: '30' },
      { value: 45, label: '45' }
    ];

    return (

          <ModalWrapper
            onRequestClose={this.props.closeModal}
            style={this.props.customStyles}
            contentLabel="Modal" >

Add Achievement

          <Select
            name="form-field-name"
            value="one"
            options={options}
          />
          <Select
            name="form-field-name"
            value="one"
            options={hourSelect}
          />
          <Select
            name="form-field-name"
            value="one"
            options={minSelect}
          />

            Submit

          </ModalWrapper>

    )

and my action:
export const addAchievement = (id, text) => ({ type: types.ADD_ACHIEVEMENT, text, id, time})

My reducer only adds to an array of achievements at the moment, how can I change my reducer to add a time to an array of objects?
   case ADD_ACHIEVEMENT:
      return state.map(item => {
          if (item.id === action.id) {
              return Object.assign({}, item, {
                achievements: [
                ...item.achievements,
                action.text,
                ]
              });
          }

        return item;
    });

Getting error for data:
 11 |     date: "Sat 2nd",
  12 |     enjoyments: ['Football', 'Rugby'],
> 13 |     achievements: [{'Tennis', '1100am'}, {'Football', '1200pm'}],
     |                             ^
  14 |     id: 1
  15 |   },

Comment: You need to give the function for onClick within {}

Submit
Comment: Thanks how can I change my reducer to add an object to an array that contains the time?
Comment: Check the answer :)
Comment: Thanks my data has an error, can i use an object in an array like I have?
Comment: That's not an object; objects have keys and values, e.g., `{ Tennis: '1100am' }`. You're mixing object and array notation.
Comment: Also, when asking a new question, open a new question rather than adding on to an existing question.
Answer: You need to give the function for onClick within {}
Submit

Also you can change the reducer to
case ADD_ACHIEVEMENT:

  return state.map(item => {
      if (item.id === action.id) {
          return {...item,
            achievements: [
            ...item.achievements,
            action.text,
            ],
            date: action.time
          };
      }

      return item;
});

Comment: Thanks but I get an error I've added to my question, can you help?


Monty hall problem extended.

Question: I just learned about the Monty Hall problem and found it quite amazing. So I thought about extending the problem a bit to understand more about it.
In this modification of the Monty Hall Problem, instead of three doors, we have four (or maybe $n$) doors, one with a car and the other three (or $n-1$) with a goat each (I want the car).
We need to choose any one of the doors. After we have chosen the door, Monty deliberately reveals one of the doors that has a goat and asks us if we wish to change our choice.
So should we switch the door we have chosen, or does it not matter if we switch or stay with our choice?
It would be even better if we knew the probability of winning upon switching given that Monty opens $k$ doors.
Comment: As a side note, if you're trying to change the problem for the purpose of *teaching* it, (rather than just creating a fun variety,) you should have Monty reveal n-2 goats, where n=total doors at start.  That still matches the original problem (he'd open 1 of the 3,) and it makes the correct answer (not switching) really obvious as N increases. "You pick 1 of 100 doors. He opens 98, revealing goats. Do you keep the one you picked, or switch to the other?"  (See @Tony's answer below - I didn't before posting this, but it makes the same point.  +1 to him.)
Comment: OMG that is the perfect monty hall... I have a 3 in 4 chance of finally getting the goat my wife keeps telling me I cant have!
Comment: @einpoklum - The car is still the better outcome.  If nothing else, it can be sold or traded for many goats... Enough to create a self-sustaining herd given sufficient suitable land. :)
Comment: A visual explanation: [http://blog.vctr.me/monty-hall](http://blog.vctr.me/monty-hall/). Scroll down to the bottom to play with the strategy/doors/speed :)
Comment: @Jaydles I don't know, people's intuitions are different. Two years ago, I saw that exact explanation, with a million doors rather than 100 (making it even more "obvious"). I still thought switching made no difference.
Comment: Why would you want the car? It: 1. Is expensive to maintain. 2. Increases dependency on fossil fuels. 3. Undermines Mass Transit. 4. Doesn't produce tasty cheese and milk !
Comment: @sqb making a new tag for a single problem seems pretty unnecessary. There isn't a branch of mathematics called 'monty hall theory'. There are very few cases where single problems warrant a tag (usually when something is an open conjecture or a full theory has been established around the problem). Please consult meta first if you feel a new tag should be introduced.
Comment: An important note: the Monty Hall problem assumes that Monty will always open a door and ask if you want to switch, regardless of which door you picked.  Otherwise, he could tend to ask you if you wanted to switch only if you picked the right door to begin with.  Having seen episodes of the original show, he did NOT always ask, leading people to correctly suspect switching might not be the best strategy.
Comment: @JamesSnell enough to buy some goats, sure, but enough to buy a whole herd and some land and everything else (fences, slaves to tend them, etc.), I doubt it. (of course, it depends on _which_ car exactly)
Comment: Closure is wrong way round. **This ought be CLOSED as duplicate** of [this generalization with multiple cars](https://math.stackexchange.com/a/346620/1012942). First, this was posted later in December 2013. That other generalization was posted is March 2013. Second, this post presumes and is limited to 1 car. That generalization varifies the number of cars.
Comment: @Lohoris the goat doesn't come with its own land either. Nor fences, unless you choose to keep the door.
Comment: @thgaskell Beautiful. The most intuitive simulation of the monty hall problem I have ever seen. Thanks!
Comment: possible duplicate of [The Monty Hall problem](http://math.stackexchange.com/questions/96826/the-monty-hall-problem)
Comment: @Jaydles The answer by sqb includes that part of the problem too!
Comment: @user54609 I'm the same as you.  I had to reason out the reasoning of the original in my head again before Jaydles's comment made sense.
Comment: @DanielRust Agreed, but there are many [_many_](https://www.google.com/search?q=site%3Amath.stackexchange.com+%22monty+hall%22) questions about the Monty Hall problem and people often compare (or try to reduce) other probabilty question to the Monty Hall problem. I'll consult _meta_ in the future.
Answer: I decided to make an answer out of my comment, just for the heck of it.

$n$ doors, $k$ revealed
Suppose we have $n$ doors, with a car behind $1$ of them. The probability of choosing the door with the car behind it on your first pick, is $\frac{1}{n}$.
Monty then opens $k$ doors, where $0\leq k\leq n-2$ (he has to leave your original door and at least one other door closed).
The probability of picking the car if you choose a different door, is the chance of not having picked the car in the first place, which is $\frac{n-1}{n}$, times the probability of picking it now, which is $\frac{1}{n-k-1}$. This gives us a total probability of $$ \frac{n-1}{n}\cdot \frac{1}{n-k-1} = \frac{1}{n} \cdot \frac{n-1}{n-k-1} \geq \frac{1}{n} $$
No doors revealed
If Monty opens no doors, $k = 0$ and that reduces to $\frac{1}{n}$, which means your odds remain the same.
At least one door revealed
For all $k > 0$, $\frac{n-1}{n-k-1} > 1$ and so the probabilty of picking the car on your second guess is greater than $\frac{1}{n}$.
Maximum number of doors revealed
If $k$ is at its maximum value of $n-2$, the probability of picking a car after switching becomes $$\frac{1}{n}\cdot \frac{n-1}{n-(n-2)-1} = \frac{1}{n}\cdot \frac{n-1}{1} = \frac{n-1}{n}$$
For $n=3$, this is the solution to the original Monty Hall problem.
Switch.
Comment: I like the added k, seems like the best answer so far (at least for me)
Comment: If monty opens all doors except for one, then k will be n-2. Putting it in the general formula you made, the probability is $\frac{n-1}{n}$ . As n gets larger, the probability that we win increases. Infact, if number of doors is 40, a simulation on http://blog.vctr.me/monty-hall/ shows that we win 99 out of 100 times. Amazing!
Comment: +1. The addition of $k$ makes this a really nice extension of the original problem.
Comment: n-1/n solves for goats!  Removing a door is ( n-1-1)/(n-1). 1 of the 1s is the car. So we have m = doors Monty removes.  Solving for goats (getting the car by process of elimination) is ( n-1-m)/(n-m).  The original odds are not 1 in 3.  Eliminating a door leaves 1 in 2 for a goat or a car.  Solving for a car by eliminating goats *without a door removed* are: 2/3 × 1/2 = 1/3, same as directly picking the car *if a goat door is not removed*.
Answer: By not switching, you win a car if and only if you chose correctly initially. This happens with probability $\frac{1}{4}$. If you switch, you win a car if and only if you chose incorrectly initially, and then of the remaining two doors, you choose correctly. This happens with probability $\frac{3}{4}\times\frac{1}{2}=\frac{3}{8}$. So if you choose to switch, you are more likely to win a car than if you do not switch.
You never told me whether you'd prefer to win a car or a goat though, so I can't tell you what to do.
Comment: Credit to the origin of the picture http://xkcd.com/1282/
Comment: Goats are browsers; they'd prefer it if your yard was full of trees, bushes, brambles, and stuff they can reach *up* to. Although they'll graze if that's what's available they do better and stay healthier on browse.
Comment: I once lived out in the country, and it was a dream of mine to get two goats to keep the grass short. I wanted to name one of the goats Briggs, and the other one Stratton.
Comment: @mousomer: one of our funniest experiences was transporting a goat kid home in the back of a Subaru. Driving up I-77 we got a *lot* of really odd looks from people. (As one car passed us the woman in the passenger seat looked at us and I clearly saw her say, "What the f...?" :-). Don't think I ever laughed that much while driving, before or since - an' I swear, I was sober as a judge..! :-)
Comment: It's very similar to having a dog, just a little livelier.
Comment: @BobJarvis Yes indeed. A sheep is much more suitable for keeping grass short.
Answer: Let's reason in the case of $n$ windows and just $1$ car.
When Monty gives you the opportunity to modify your initial choice, it is definitely better to take it. Here's a way to see it:
The probability of finding the car with the first choice is just $\frac{1}{n}$, and this is the same probability that you have of winning if you keep your initial choice.
Of course you will win by changing your choice if the intersection of two events will happen:

You didn't choose the car with the first choice ( $P(A) = \frac{n-1}{n}$ )
You are lucky and you find the car with your second choice ( $P(B\mid A) = \frac{1}{n-2}$ )

So the probability of winning by changing your mind is the product
$$ P(A\cap B) = P(A)\cdot P( B\mid A ) = \frac{n-1}{n}\cdot \frac{1}{n-2} = \frac{n-1}{n(n-2)} > \frac{1}{n} $$
Since $ \frac{n-1}{n-2} \to 1 $ when $n\to \infty$, we notice that Monty's help is not that useful in the case of many many windows.
Comment: "The above two events are independent" - no they are not. It is obvious that if you chose the car on your first pick, you will get a goat on your second. You need to rephrase this in terms of the conditional probability that you will choose right on your second choice, given that you chose wrong on your first.
Comment: @shauryagupta This is how I finally convinced my dad about this problem. I first said, we'll play the game with cards. I'll know where the ace is, and I'll ask you to pick and if you want to swap. We did about 6 times, but you don't reach convincing results fast enough. So I said, scrap that. We'll use the whole deck. You need to pick the ace of spades. After he picked one, I took the rest of the deck away except for one card. Then asked if he wanted to swap. It was pretty obvious at this point.
Comment: We can generalize even further and have Monty opening $k$ doors (with $k <= n - 2$), for a probability of picking the right door on your second guess of $\frac{1}{n - k - 1}$.
Comment: To add to this answer a little bit, consider the case with $n$ doors where Monty opens each of the remaining doors except for 1 (another, different generalization of the original problem to OP's). Then, again, if you don't switch your probability of winning is $\frac{1}{n}$, and if you do switch, your probability of winning is exactly equal to the probability that you chose incorrectly at first (this is identical to the case with 3 doors). Then your probability of winning is $\frac{n-1}{n}\rightarrow 1$ as $n\to\infty$, so in this case, Monty's help is incredibly useful.
Comment: If monty opens only one door, the probability that we win with switching decreases with increase in number of doors. However, If monty opens all doors leaving behind 2 doors, the probability increases!
Comment: Thanks @user2357112 for pointing that out! I now corrected my exposition.
Answer: Increasing the number of doors is a common extension of the problem, and is analytically useful for giving people an intuition about why switching is optimal.  This is not, strictly speaking, the situation you're describing (since your question is about adding a single door and Monty still only opening one door), but it's a similar case.
Consider a Monty Hall Problem of 100 doors: Let's say you choose one, then Monty opens 98 other doors.  Which probability is higher: the probability that you picked the right one from the beginning (1%), or the probability that you didn't and thus the one door that Monty left unopened is the real winner (99%)?
Answer: Last time I came across a Monty Hall question I wrote my own tester in Java. Here it is - with the number of doors set to 4:
public class MontyHall {

    // How many doors.
    static final int Doors = 4;

    // Prizes.
    enum Prize {

        Goat,
        Car;
    }

    public static void main(String[] args) throws InterruptedException {
        // The number of times we would have won if we switched.
        int winWhenSwitched = 0;
        // The number of times we would have won if we didn't switch.
        int winWhenNotSwitched = 0;
        // The number of times we would have lost both ways.
        int lost = 0;

        // n doors.
        Prize doors[] = new Prize[Doors];
        // N Tests
        for (int i = 0; i < 100000; i++) {
            // Put a car behind just one door.
            pickRandomDoorForCar(doors);
            // Make my first choice.
            int firstChoice = randomDoor();
            // Open one remaining goat door.
            int goatDoorOpened = openOneGoatDoor(doors, firstChoice);
            // What would have been my second choice - if I switched?
            int secondChoice = makeSecondChoice(doors, firstChoice, goatDoorOpened);
            // Count wins/losses.
            if (doors[firstChoice] == Prize.Car) {
                // We would have won without switching!
                winWhenNotSwitched += 1;
            } else {
                // We win if we switched to the car!
                if (doors[secondChoice] == Prize.Car) {
                    // We picked right!
                    winWhenSwitched += 1;
                } else {
                    // Bad choice.
                    lost += 1;
                }
            }
        }
        System.out.println("Wins when switched = " + winWhenSwitched);
        System.out.println("Wins when not switched = " + winWhenNotSwitched);
        System.out.println("Lost = " + lost);
        System.out.println("Proportion = " + ((double) winWhenSwitched / (double) winWhenNotSwitched));
    }

    // Open one door exposing a Goat.
    private static int openOneGoatDoor(Prize doors[], int firstChoice) {
        for (int j = 0; j < Doors; j++) {
            // Not the one already picked and must contain goat.
            if (j != firstChoice && doors[j] == Prize.Goat) {
                // Can only be one of them.
                return j;
            }
        }
        // Should never get here - TODO - Throw an exception here.
        return -1;
    }

    // Make a second choice - avoid first choice and opened door.
    private static int makeSecondChoice(Prize[] doors, int firstChoice, int goatDoorOpened) {
        int secondChoice = randomDoor();
        while (secondChoice == firstChoice || secondChoice == goatDoorOpened) {
            // Try again.
            secondChoice = randomDoor();
        }
        return secondChoice;
    }

    // Pick a random door and put a Car there.
    private static void pickRandomDoorForCar(Prize[] doors) {
        // Start all goats.
        Arrays.fill(doors, Prize.Goat);
        // Pick a random for the car.
        doors[randomDoor()] = Prize.Car;
    }
    // Start my random number generator.
    static final Random random = new Random(System.currentTimeMillis());

    // Pick a random door.
    private static int randomDoor() {
        return random.nextInt(Doors);
    }
}

The results print:
Wins when switched = 37483
Wins when not switched = 24888
Proportion = 1.5060671809707489

I hope this is helpful.
Answer: Another way to explain it based on your "gut feeling".
Although this is the "psychological" way of viewing it (so no hard proof like already given above).
Imagine there were 100 doors, one prize is behind one of the doors. Now pick one door. Monty knows behind which of the doors the prize is and now opens all doors except two: your door and another one. Now you get the option to switch, your original door or the one door left closed... You see where I am going?
If you picked, say, door 15. Then all doors go open except 15 and e.g. 63. Doesn't that make 63 really suspicious for containing the prize, whereas your door remained closed only because you picked it initially?
I think this is a beautiful way to "explain" this problem without getting into the math too much. This way, you can convince people of the better option: switch, because you're getting better information. If you then explain the math behind it, then it will become an easy problem!
Comment: I like to use picking the ace of spades from a deck as an example. Pick any card. I then turn over 50 cards, none of which are the ace of spades. Do you think I have the ace of spades, or do you think you have it?
Answer: The paradox changes only slightly when you increase the number of doors. The three-door model is most popular because it's the simplest statement of the problem (and the one normally seen on "Let's Make A Deal").
Basically, the reasoning behind the MHP is that, with $N$ doors, your original choice has a $\dfrac{1}{N}$ chance of being the car, which is relatively small. That means the chance that the car is elsewhere is $\dfrac{N-1}{N}$ (or $1 - \dfrac{1}{N}$, same thing). By opening one of these doors to reveal a goat, you don't change the math in the way you expect; the chance that you didn't pick the car (and thus it's behind another unopened door) is still N-1/N, but now that probability is evenly distributed between N-2 unopened doors, so the chance of any one unopened, unchosen door having the car is $\dfrac{N-1}{N(N-2)}$, which will be greater than $\dfrac{1}{N}$ for all $N > 2$.
So, with four doors, the probability that your original pick was correct is .25 ($1/4$), meaning the probability that you didn't pick the car (and that it's behind one of the three other doors) is .75 ($3/4$). Open a door to reveal a goat, and now, there is that same 75% chance that the car is behind either of the two remaining unchosen doors, so switching to either of them gives you a 37.5% chance of choosing correctly ($3/(4(2)) = 3/8$), while staying with your original choice gives you only the same 25% chance.
As you can see, the advantage (the percentage increase in probability of winning) starts shrinking pretty quickly; in the 3-door scenario, switching from your original choice gives you double the probability of winning, but with 4 doors the advantage is only 50% (.375/.25). With five doors, the winning probability of not switching is .2 while the winning probability of choosing any other unopened door is 4/15 = .2666, for a 33% advantage. With 6 doors, you have a 16.6% chance of guessing correctly on the first try and a 20.8% chance of winning if you switch, for a 25% advantage. We can project from this that the advantage of switching versus staying is $\dfrac{1}{N-2}$ for any $N>2$.
Answer: To add a bit to this discussion, there is a good book, "The Monty Hall Problem: The Remarkable Story of Math's Most Contentious Brain Teaser" by Jason Rosenhouse (published in 2009), which covers all these variants and includes a variety of explanations for understanding them. The book also gives a nice history of the problem. Unfortunately it does not include the xkcd cartoon.
Answer: You should switch. By picking one of the doors first, the probability of getting a car is 1/4. Once Monty opens one door with the goat, the probability that the car is in one of the other 2 remaining doors is 1/2 * 3/4 = 3/8 > 1/4. So you should switch. The wikipedia article http://en.wikipedia.org/wiki/Monty_Hall_problem is a good read by the way.
Comment: There are two remaining doors after Monty has opened one door. The 1/2 represents the 1 out of 2 doors remaining, and the probability 3/4 is due to the remaining probability (1 - 1/4) after you have chosen the first door and before Monty opens one door with the goat.
Answer: Here is an example a friend of mine once told me that I think really makes the monty hall problem really clear. Suppose there are one million doors, one with a golden Bugatti and the rest with an assortment of goats from all parts of the world.
At first you chose a random door. Then Monty opens all the other doors except for the one you have and one other. Then even your intuition tells you you should change the door.(this is different from the one you asked, but it's a great border-case example that is really intuitive).
Comment: @Tanner:Then that wouldn't be the Monty Hall problem any longer.
Comment: Note that this is only true if Monty intentionally chooses doors with goats. If you pick an arbitrary door, and Monty *randomly* opens 999,998 doors, and all of them *happen* to be goats, the probability of the car being behind each door is now 1/2.
Comment: Following the reasoning behind the accepted answer, this happens to be a decent (albeit extreme) example. If you open all doors except for the one that has the car, you get (n-1)/n * 1 > 1/n. At n = 1 million, the left member is clearly much bigger than the right one.
Comment: @dunk Tanner is simply emphasising the importance of the host's knowledge. It's a crucial assumption in the formulation of the problem and should be made explicit when stating it.
Answer: The correct answer is, the problem isn't defined clearly enough to arrive at the "correct answer." Let's ignore the n doors, and k doors revealed for a moment, because they aren't essential for realizing that we don't know enough information to solve the question.

We need to choose any one of the doors. After we have chosen the door, Monty deliberately reveals one of the doors that has a goat and asks us if we wish to change our choice.
So should we switch the door we have chosen, or does it not matter if we switch or stay with our choice?

One of the problems with this question, is the motivations of the host are unknown. You specifically said that he revealed one of the doors, but not whether:

He always reveals a door.

He always reveals a losing door.

Without knowing that information, it is impossible to know if you should switch, not switch, or it doesn't matter.
Answer: The Monty Hall problem always confused me.  And so, I coded it up in Matlab (2013a) to better understand it.  In this version, the number of games played and N, the number of doors per game, are user settable parameters.  I found 100,000 games gives relatively stable win/loss distributions for N = 100.
Code:
%Monty Hall problem assuming N doors, and N-2 doors
%opened prior to the final door choice.

clear;clc
rng('shuffle');

%    USER INPUT PARAMETERS
%------------------------------------------------------------
games = 100000;     %number of Monty Hall games (experiments)
N = 100;            %number of doors in each Monty Hall game
%------------------------------------------------------------

always_losses = 0;  %number of losses for always switch strategy
always_wins = 0;    %number of wins for always switch strategy
never_losses = 0;   %number of losses for never switch strategy
never_wins = 0;     %number of wins for never switch strategy

for ii = 1:games

    prize = randi(N);
    initial_choice = randi(N);

    %(N-2 doors opened prior to final choice)
    if initial_choice == prize
        always_losses = always_losses + 1;  %always switch strategy
        never_wins = never_wins + 1;        %never switch strategy
    else
        always_wins = always_wins + 1;      %always switch strategy
        never_losses = never_losses + 1;    %never switch strategy
    end

end

fprintf('\nWin fraction -- never switch:  %4.3f',never_wins/games);
fprintf('\nWin fraction -- always switch:  %4.3f\n\n',always_wins/games);

Results (for games = 100,000 and N = 100):
Win fraction -- never switch:  0.010
Win fraction -- always switch:  0.990

The computational results support Abramo's observation, namely, that Monty's help is not all that useful as the number of doors increases:  The probability of winning approaches 1.0 for the "always switch" strategy as the number of doors approaches infinity.
Letting N = 3 reduces to the familiar Monty Hall game, and, produces the correct answer for that case.
Answer: My twist on explaining the Monty Hall problem:-
You pick one door.
Monty, instead of revealing a goat behind one of the other doors, offers you BOTH of them if you switch from your initial choice.
Of course you switch, since this will absolutely double your chances.
And of course, at least one of the two doors that you switch to must have a goat, Monty just didn't show it to you. So what if he does or doesn't show it?  We all know that it's there.
Choice wise, this is exactly the same as the original problem. The illusion is that you don't get the door that Monty opens. But effectively you do, it's just that you disregard it because it has no value.
Answer: @DwB
Your explanation would work if you chose your door AFTER you were shown a door that had a goat behind it.
Since you make your choice while there are 3 choices, the probability you choose the right door is 1/3 no matter if he shows you a goat or not.
If you choose one of the goats at first, you have a probability of 2/3 of choosing one of those right?  So the beauty of this problem is that if you choose a goat first, and switch you will always get the car.
Think about it, if you choose one of the goats first, then the other goat will always get shown.  If you switch then you will always switch to the car.
You want to choose a goat first to win this game by SWITCHING.(2/3)
You want to choose a car fiRst to win this game by NOT SWITCHING.(1/3)
4 doors...
You choose a car at first(1/4)
You choose a goat at first(3/4)
He opens 2 doors with a goat behind them, so your first choice and the last door is left.
If you chose the car first and switched now, you would lose.
If you chose any of the 3 goats initially, and now switched, you would win the car.
It just comes down to the fact you have a better chance of picking one of the goats initially, so assuming he shows all the other "bad choices" to you, it is better to switch your answer you chose originally.
The probabilities you win by switching your choice, assuming that Monty opens all the other doors accept for the original one you picked and one other one.
3 doors (2/3)
4 doors (3/4)
5 doors (4/5)
6 doors (5/6)
7 doors (6/7)
8 doors (7/8)
n doors [(n-1)/n] = 1 - 1/n
as n approaches infinity 1/n becomes 0, and the general probability = 1 - 0 = 1.
So if we were to play this game with an infinite amount of doors, and switch our choice, we would win 100% of the time!
Answer: This is an adaptation of an extremely short and simple solution to the Monty Hall problem which I posted here. I think it vastly simplifies matters in this case as well.
Of course the probability of winning if the contestant does not switch doors is $1/n$. So let's suppose the contestant does switch doors and let's break it into two cases: 1. the contenstant chooses the correct door initially, 2. he doesn't. The probability in each case respectively is $1/n$ and $\frac{n-1}{n}$. In the first case, switching doors loses. In the second case since another door is now eliminated the probability of winning by switching doors is $\frac{1}{n-2}$. Therefore the probability of winning by switching doors is $\frac{n-1}{n}\cdot\frac{1}{n-2}={\bf \frac{n-1}{n(n-2)}}$. Lastly, observe $\frac{n-1}{n(n-2)}>\frac{n}{n^2}=\frac{1}{n}$.
In the example where $n=4$, the probability of winning by switching is $\frac{4-1}{4(4-2)}=\frac{3}{8}$.

Monty hall problem extended.


Posicionar botão na parte inferior do layout

Question: Gostaria de posicionar o botão Sair no final do meu layout. Estou usando LinearLayout. Alguma dica de como posso posicionar ?
Este é o código do Linear Layout:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="com.meuprojeto.perfilloginsenha.PerfilActivity">

Este é o código do botão:
<Button
    android:id="@+id/btnLogOut"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@color/colorPrimary"
    android:text="SAIR"
    android:textColor="@color/branco"
    android:textSize="20dp"
    android:textStyle="bold" />

Answer: Ao contrário do que se possa pensar, num LinearLayout, match_parent não faz com que ele ocupe todo o parent. O nome antigo, fill_parent, nesse sentido, ainda era pior.
Coloque uma view antes do botão de forma que ela ocupe todo o espaço que resta do layout. Isso obrigará a que o botão seja posicionado na parte inferior.
Para que uma view ocupe todo o espaço restante disponível deve a ela ser atribuído um layout_weight.
Exemplo:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="wrap_content"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <EditText
        android:id="@+id/editText"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        />
    <Space
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"/>

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Botão"/>
</LinearLayout>

Uma alternativa é usar um RelativeLayout e adicionar android:layout_alignParentBottom="true" ao botão:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="wrap_content"
    android:layout_height="match_parent">

    <EditText
        android:id="@+id/editText"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Botão"
        android:layout_alignParentBottom="true"/>
</RelativeLayout>

Comment: atribui o ``  com a propriedade `android:layout_weight="1"` e nada aconteceu, porém quando alterei o `layout_height` de zero para outro valor ele desceu, porém acho que não seria o ideal, pois seria uma gambiarra e em telas menores o botão esconderia.
Comment: O *layout* da resposta foi testado, por isso funciona. Como você não colocou o seu *layout* completo não sei se haverá algo mais que necessite de ser feito.
Comment: fiz um teste com seu código realmente funciona, vou verificar no meu o que pode estar diferente


sinh/cosh of complex number on TI-89

Question: Is there another way of calculating sinh(1+j) for example instead of decomposing in sin and cos?
Comment: Do all the trig. & hyperbolic functions take purely real arguments?
Comment: The Ti-89 can compute with complex numbers, but unless you require a numerical result, it will develop this expression into $\sinh 1\cos 1+i \cosh 1\sin 1$. What would you expect?
Comment: Just in case: the imaginary $i$ is found with "2nd-catalog" (that is the blue i above the "catalog" touch).
Answer: I am curious what will show up here.
My view is that the direct definition is in terms of the exponential function:
$$
\sinh(x+iy) = \frac{e^{x+iy} - e^{-(x+iy)}}{2}
$$
so unless your exponential function is ready for complex arguments, you will at some point have to evaluate $e^{ix}$ and there use cosine and sine.

sinh/cosh of complex number on TI-89


Card probabilities with conditional probability

Question: What is the probability that two hands of 13 cards dealt from a normal shuffled pack of 52 cards contain exactly two kings and one ace? What is the probability that both contain exactly one ace given that both contain exactly two kings?
Here's my attempt:
Let K1, K2 be the events that the first hand and the second hand contain exactly two kings, respectively; A1, A2 be the events that the first hand and the second hands contain exactly one ace, respectively.
$\mathbb{P}(K1 \cap A1) = {4 \choose 2}{4 \choose 1}{44 \choose 10} \Big/{52 \choose 13}$
$\mathbb{P}(K2 \cap A2) = {2 \choose 2}{3 \choose 1}{36 \choose 10} \Big/{39 \choose 13}$
Thus $\mathbb{P}((K1 \cap A1) \cap (K2 \cap A2)) = {4 \choose 2}{4 \choose 1}{44 \choose 10}{2 \choose 2}{3 \choose 1}{36 \choose 10} \Big/\left[{52 \choose 13}{39 \choose 13}\right]$.
Second part:
$\mathbb{P}(K1) = {4 \choose 2}{48 \choose 11} \Big/ {52 \choose 13}$
$\mathbb{P}(K2) = {2 \choose 2}{37 \choose 11} \Big/ {39 \choose 13}$
$\mathbb{P}(K1 \cap K2) = {4 \choose 2}{48 \choose 11}  {2 \choose 2}{37 \choose 11} \Big/ \left[{52 \choose 13}{39 \choose 13}\right]$
\begin{align}
\mathbb{P}((A1 \cap A2) | (K1 \cap K2)) &= \frac{\mathbb{P}((A1 \cap A2) \cap (K1 \cap K2))}{\mathbb{P}(K1 \cap K2)}\\
&=\left\{{4 \choose 2}{4 \choose 1}{44 \choose 10}{2 \choose 2}{3 \choose 1}{36 \choose 10} \Big/\left[{52 \choose 13}{39 \choose 13}\right]\right\}\Big/ \left\{{4 \choose 2}{48 \choose 11}  {2 \choose 2}{37 \choose 11} \Big/ \left[{52 \choose 13}{39 \choose 13}\right] \right\}\\
&\approx 0.000198
\end{align}
Please let me know if you think it's correct or if you have an easier solution. Thanks.
Answer: The expressions for the probabilities are correct. For the conditional probability, you had basically computed the necessary ingredients in the first part, so it is natural to recycle.
One can solve the conditional probability problem without using the conditional probability machinerty. Imagine that you have given both hands two Kings. Now let us deal the rest of the cards.
The probability that the first hand gets $1$ Ace is $\dfrac{\binom{4}{1}\binom{44}{10}}{\binom{48}{11}}$.
Given that the first hand got $1$ Ace, the probability the second hand does is
$\dfrac{\binom{3}{1}\binom{34}{10}}{\binom{37}{11}}$. Now multiply.


data analysis, dissertation of thesis? help please?

Question: I'm having a problem with my dissertation.
My research is "level of satisfaction in relation to customer service: comparative study between 2 fast foods
my questionnaire consists of 19 questions. I'm using SERVERF, the 5 dimensions. 8 questions for Tangibility, 3 for Reliability, Responsiveness, Assurance and 2 questions for Empathy. Example in Tangibility, "Personnel's appearance" the respondents will choose between 1 to 5. 5 - very satiesfied to 1 very unsatisfied.
I have dissected my data, results of survey according to age, gender, year level and schools.
Example, in gender, female, I have the mean per question, example Q#1 and so on, average mean of all the dimensions, exmple tangibility (Q#1 to Q8) then other dimensions, WAM of female, overall satisfaction to fastfood 1 & 2. then male...  My respondents are students whose customer of both fastfood.
my question is, how to know if there's a significance between the two establishment according to age, gender, year level and school.
I've tried using regression analysis, dependent variable is Gender then independent variable are the overall satisfaction of my respondents in the two fast food.
SPSS gave me the sig. of gender and fastfood 1; fastfood 2 and gender.
my null hypothesis is "There is no significant difference in the overall level of customer satisfaction in relation to customer service between the 2 fastfood"
I want to know if there's a significant between the 2 fastfood when it comes to gender. is that possible? in spss?
btw, I know that my data is ordinal because I used likert scale. also checked if my data is normally distributed, it's not. so non-parametric.
I'm new to spss. been using it for a week now. can someone help me? Thanks
Comment: @Sesese also: normally distributed *data* is more or less irrelevant for multiple linear regression. normally distributed *errors* are one of the assumptions underlying OLS.
Comment: A distribution that's non-normal isn't "nonparametric"; procedures can be. If it's a Likert item it *can't* be normal, there's no need to check that.  However, if you have summed Likert items to form a scale, you already assumed interval scale when you summed the items.
Answer: First, this

my null hypothesis is to know if there's a significant difference
  between the 2 fasfoods in terms of gender, age, year level and school.

is not a null hypothesis. The null hypothesis would be something like "There is no difference between preference for fast food based on gender age etc.
Second you say

I have 5 factors, 1st factor consists of 8 variables, 2nd, 3rd and 4th
  consists of 3 variables, and 2 variables for 5th factor. Total of 19
  variables/questions.

What are these factors? How will you use them? You don't mention them again in your post
Next, the dependent variable should be the rating of the food. I hope this is on a nice simple scale like 1 to 5.  The independent variables are age, gender etc (possibly the factors go here, but it is hard to say)
The statistical method, if the rating of food is ordinal, would be ordinal logistic regression. At least, that's where to start.
Comment: sorry, my null is "There is no significant difference in the overall level of customer satisfaction in relation to customer service between the two fastfood" I'm using SERVPERF which consist of 5 dimensions. using also 5 point likert scal.e 5 very satisfied to 1 very unsatisfied
Answer: First, make sure you have clearly defined your problem of interest, and correctly formulated your null hypothesis. Given that you research is "level of satisfaction in relation to customer service: comparative study between 2 fast foods", the null hypothesis would be "there is no different in terms of satisfaction between the 2 fast foods".
Then the independent variable is the level of satisfaction. It should be a ordinal variable with different levels, which-for example-can be labelled as very satisfied, satisfied, neutral, unsatisfied, very unsatisfied. The "two fast food" is THE independent variable of interest. It can be coded as a group factor. Then other measured variables related are nested within this group factor. Last, "Gender", "Age", etc., are common covariates. Think of the ANCOVA.
You can use the Cumulative-logit model. Basically, it's the logistic regression where the dependent variable has multiple ordered categories. Moreover, a more parsimonious model is the Cumulative-logit proportional odds model. The difference between these two is that the latter assumes a constant slope across all cumulative logits. This is called Proportional Odds Assumption, and of course needs to be justified.
I don't use SPSS, thus cannot give any suggestions regarding coding. But if you use SAS, the PROC LOGISTIC does exactly what you want. You can specify the "link=Clogit" to fit a cumulative-logit proportional odds model. And SAS provides some tests for checking the assumption.
Comment: thanks! I'm now checking for SAS. but..How about if i'll only gonna compare the 2 fastfoods, no group factors like gender etc. compare the results of the 2, what will you recommend to use? thanks again :)
Comment: I am not sure I get you. But age, gender, etc, are as covariates, not group variables. They are values associated with each observation(row) in your sample, aren't they?


Quais são os tipos de dados apropriados para colunas como endereço, e-mail, telefone e celular, para base de dados SQL?

Question: Que tipo de dados são recomendados para criar os seguintes campos:

endereço
e-mail
número de celular/telefone
Comment: Yuran, bem vindo ao Stackoverflow! A sua pergunta é poco clara, pode explicar melhor o que você procura saber?
Comment: MySQL - VARCHAR(size), SQLServer - nvarchar
Comment: normalmente varchar, mesmo o campo telefone podendo conter apenas números, salvar como texto garante que você não vai perder nenhum zero no inicio do numero, por exemplo.
Answer: Para os campos endereço, e-mail e telefone/celular eu recomendo utilizar VARCHAR por ele possuir um tamanho variável e salvar corretamente os dados.
Porque VARCHAR e não CHAR?
VARCHAR possui um tamanho variável de acordo com o registro contido nele.
Exemplo: Vou inserir a palavra "Yuran" que contém 5 caracteres em uma coluna VARCHAR(20) e o mesmo registro em outra coluna que é CHAR(20)
Na coluna VARCHAR vai ser utilizado apenas 5 caracteres dos 20, o tamanho daquele registro vai ser igual ao de um CHAR(5).
Na coluna CHAR vai ser utilizado todos os 20 caracteres independente do tamanho do registro ficando com CHAR(20) e pesando mais no banco.

Nunca utilize tipo numérico para salvar dados como telefone/celular
Vamos supor que você quer salvar o número "0800 800 8000" no banco, o que vai acontecer?

Dependendo do tipo numérico vai ultrapassar o tamanho limite e com isso não vai conseguir salvar no banco os dados.

Você vai perder todos "0" a esquerda do número e com isso você perde a integridade dos dados.
Comment: +1 E só pra citar outro exemplo, telefone pode ser algo assim também: `+55 (11) 9999-9999`
Comment: +1 por ter citado números do tipo 0800. Se há chance de 0800 e 0300 ser armazenado, é mais complicado tratar de exibir ele mais tarde.
Answer: Um padrão que eu costumo usar é o listado abaixo. Ele pode ser visto no meu site.
Em alguns casos eu listei mais de um exemplo. Os tipos e os tamanhos são para MySQL/MariaDB.
No caso de valores que contém numeros e caracteres diversos, é necessário ter certo cuidado, principalmente se o padrão muda muito. Atender telefones fixos e celulares, como os de São Paulo que tem 9 digitos, é possível validar na hora de entrar no sistema e uma boa mascara poderá devolver ao formato original, porém a coisa vai ficar complicada se seu sistema tem que suportar também numeros internacionais e números regionais do Brasil. Nestes casos, se não quiser se encomodar, use VARCHAR mesmo, mas nos meus exemplos abaixo eu em algumas aplicações converti telefones nacionais para BIGINT e não tive problemas.
Valores numéricos mais padrões, como CEP e CPF, certamente recomendo armazenar como numérico. Marque na colula como 'ZEROFILL' que ele colocará zeros para preencher os valores iniciais.

Razão Social VARCHAR(255)
Nome Fantasia VARCHAR(255)
CNPJ BIGINT(14), VARCHAR(18)
Data de Fundação DATE
Email VARCHAR(100)
Website VARCHAR(100)
Telefone BIGINT(14) (Já considera números de 9 dígitos). Na dúvida, use VARCHAR
Celular BIGINT(14) (Já considera números de 9 dígitos) Na dúvida, use VARCHAR
Responsável VARCHAR(255), VARCHAR(100)
Endereço VARCHAR(150)
Endereço, número VARCHAR(20) (lembre-se: "números" podem conter outros caracteres)
Bairro VARCHAR(50)
Cidade VARCHAR(50)
UF CHAR(2), TINYINT(2) (uso de números se relacionado a outra tabela)
CEP INT(8), VARCHAR(10)
Descrição TEXT

Repare que com exceção de UF, sempre uso VARCHAR, porém limito o máximo a um valor razoável de ser encontrado. Por exemplo, não existe nenhuma cidade nem bairro no Brasil com mais de 50 caracteres, ou se tem, é alguma bem desconhecida e com uns 60.
Snippets para formatar resultado numérico de determinados campos (PHP)
A formatação do telefone e celular é mais complicada porque ela não prevê números internacionais nem números 0800 o 0300. As demais já foram testadas e funcionam bem.
Colo aqui porque quem está perguntando esse tipo de questão certamente vai acabar procurando isso mais tarde.
/**
 * QSES component helper.
 *
 * @package  Alligo.Joomla
 * @since    1.6
 */
class AlgFilter {

    /**
     * Remove valores não numericos (inclusive , e .)
     *
     * @param   string  $input  Valor de entrada
     * @return  int
     */
    public static function getNumbers($input)
    {
        return preg_replace("/[^0-9]/", "", $input);
    }

    /**
     * Formata 90050123 em 90.050-123
     *
     * @param   int    $numero  Numero a ser formatado
     * @return  string
     */
    public static function formatoCep($input)
    {
        return preg_replace('/^(\d{2})(\d{3})(\d{3})$/', '\\1.\\2-\\3', $input);
    }

    /**
     * Formata 90050123 em 90.050-123
     *
     * @param   int    $numero  Numero a ser formatado
     * @return  string
     */
    public static function formatoCpf($input)
    {
        return preg_replace('/^(\d{1,3})(\d{3})(\d{3})(\d{2})$/', '${1}.${2}.${3}-${4}', $input);
    }

    /**
     * Formata CNPJ
     *
     * @param   int    $numero  Numero a ser formatado
     * @return  string
     */
    public static function formatoCnpj($input)
    {
        return preg_replace("/^(\d{2})(\d{3})(\d{3})(\d{4})(\d{2})$/", "\\1.\\2.\\3/\\4-\\5", $input);
    }

    /**
     * Formata 1234567890 em (12) 3456-7890
     *
     * @param   int    $numero  Numero a ser formatado
     * @return  string
     */
    public static function formatoTelefone($numero)
    {
        return preg_replace('/(\d{2})(\d{4})(\d*)/', '($1) $2-$3', $numero);
    }

}

Comment: _"números" podem conter outros caracteres_ - Fatão. Em Bauru/SP os endereços, por exemplo da prefeitura, têm números como 1-59, onde 1 seria algo como o número da quadra/quarteirão.
Answer: Se você não vai fazer contas com os números (somar, multiplicar, etc), não tem muito por que usar tipos numéricos.
Use CHAR ou VARCHAR, conforme apropriado.
Answer: Qual é o objetivo dessas informações?
Informar um dado para descrever uma característica do objeto em questão na tabela, certo?
Bem, para endereço de e-mail temos a possibilidade de usar letras, números e até símbolos. Uma coluna do tipo texto se faz necessária. Fica só a dúvida se um CHAR ou VARCHAR deve ser usado. Como estes dados tem tamanho variável com ampla margem de diferença o CHAR faz pouco ou nenhum sentido, até porque no MySQL ele não é tão otimizado e pode ter desempenho ligeiramente pior. Não tem nem o que pensar.
Não se preocupe muito com o tamanho, coloque algo grande.
Não se acanhe em colocar 255 ou mais para o endereço, por exemplo, já que o espaço não usado não será desperdiçado. Pode por algo menor se tiver certeza que não poderá ser maior que determinado tamanho.
No caso de e-mail, de acordo com a RFC, o endereço básico, chamado de local, pode ter 64 caracteres, mais o @ e depois 255 para o domínio. Isso se não permitir alguma informação extra além do RFC. Se colocar algo menor que 320 caracteres poderá ter problemas no MySQL.
Tem DBs que permitem colocar mais mesmo que usar um número menor, porque estritamente o SQL não proíbe ultrapassar esse valor que é só para indicar apresentação de dados e não uma restrição do que pode ser armazenado, ou seja, se é para usar uma constraint deveria ser no CHECK. Em geral é comum deixar a aplicação cuidar disso para evitar problemas em certos cenários. Porém no MySQL ele é só descritivo em versões antigas, somente na versão 8.0.x é que passou ser respeitado.
Dependendo de como for configurado um texto que exceda o máximo colocado poderá só cortar o excesso ou dará erro (muito melhor). Veja mais na documentação.
Quando falamos de telefones, documentos numéricos, etc., já foi respondida com mais detalhes, mas em resumo é uma questão de continuar sendo dado descritivo, não é para quantificar nada, não é para fazer contas, então nunca use um tipo numérico, escolha um VARCHAR, ou até mesmo um CHAR pode ser mais adequado porque costuma ter tamanho fixo.

E a recomendação geral para esses dados é que não coloque formatação nele, ou seja, não use pontos e traços, porque o futuro pode mudar. Formatação não é informação. Claro que para tudo pode ter exceção se puder justificar a escolha de forma adequada. O que não pode em hipótese alguma é usar tipo numérico.
É uma questão mais semântica do que técnica, ainda que a técnica possa influenciar também. Mesmo que ela permita não fique tentado, use um tipo descritivo para um dado descritivo.
Inclusive casos em que precisa de algum cálculo eventual é mais interessante a conversão porque o dado ainda é descritivo. Isso vale para o CPF e outros documentos, contas bancárias, códigos e muitos outros. Esses dados possuem dígito verificador e precisará calculá-lo, então é tentador usar um tipo numérico, mas isto está equivocado. O cálculo deve ser feito em cima do dado descritivo que será convertido para numérico, só para o cálculo, em bloco ou por caractere.
Não se esqueça que telefones podem ter ramal ou até outras características e não usar só algarismos. Em alguns casos esses penduricalhos, inclusive DDD(I) deve ser um campo diferente. E celular é diferente de telefone fixo.
Coloquei no GitHub para referência futura.


Semisimplicity is equivalent to each simple left module is projective?

Question: As it is well-known, a ring with unity $R$ is semisimple if and only if each left $R$-module is projective. My question:

Is semisimplicity of $R$ equivalent to each simple left $R$-module being projective?

I think it is true for a finite dimensional algebra $R$. But, in general, I could not reach any conclusion. Any help would be thanked!
Answer: Yes.
A ring is semisimple iff it does not have an essential maximal right ideals, and making simple right modules projective causes all maximal right ideals to be summands of $R$.
The connection with essential ideals is this: given any right ideal $T$, you can find another right ideal $T'$ such that $T\oplus T'$ is an essential right ideal in $R$. So in particular a maximal right ideal must have such a complement, and that complement could be zero (if it is already essential) or it could complement it to the whole of $R$ (meaning it is a summand.)  Projectivity of simple right modules rules out the first case since the exact sequence $0\to T\to R\to R/T\to 0$ splits.
It is interesting, though, that "all simple right modules are injective" does not characterize semisimple rings. These are called "right $V$-rings," and there are examples of these which are even domains.
Simples being injective does not even characterize semisimplicity for commutative rings: the commutative $V$-rings are the von Neumann regular rings.
A nice theorem of Barbara Osofsky's is: if every cyclic right module is injective, then the ring is semisimple.


Solve linear algebra expression $- \nabla . G$

Question: Let's consider the vector $G$
\begin{equation}
G = \begin{pmatrix}
-x(\alpha + \beta) + y \beta \\
x \beta - y (\alpha + \beta)
\end{pmatrix}
\end{equation}
with constants $\alpha$ and  $\beta$. I would like to solve $$- \nabla . G$$
Answer: The vector function $G=(G_1,G_2)$ (not a matrix) has derivatives $$\frac{\partial G}{\partial x}=\begin{pmatrix}-\alpha-\beta\\\beta\end{pmatrix},\qquad\frac{\partial G}{\partial y}=\begin{pmatrix}\beta\\-\alpha-\beta\end{pmatrix}$$ Hence $$\nabla\cdot G=\frac{\partial G_1}{\partial x}+\frac{\partial G_2}{\partial y}=-2(\alpha+\beta)$$


Inequality involving trigonometric and exponential functions

Question:
Find the smallest $a > 1$ such that $$\frac{a + \sin{x}}{a + \sin{y}} \leq \exp(y-x)$$ for all $x\leq y$.

I'm finding this tricky. I got $a = \displaystyle{\frac{e^\pi +1}{e^\pi -1}}$ but it's probably incorrect. My method was to maximise the LHS by letting $\sin{x}=1$ and $\sin{y}=-1$ and then minmise the RHS by letting $y-x = \pi$, and then I solved to find $a$.
Answer: Equivalently, you want $ae^x+\sin xe^x\leq ae^y+\sin y e^y$. Therefore, the function $f(x)=ae^x+\sin xe^x$ is increasing. But, $f'(x)=ae^x+\cos x e^x+\sin x e^x$, so $$ae^x+\cos x e^x+\sin x e^x\geq 0\Rightarrow a\geq-\cos x-\sin x=-\sqrt{2}\cos\left(x-\frac{\pi}{4}\right)\Rightarrow$$$$a\geq-\sqrt{2}\cos\left(\frac{5\pi}{4}-\frac{\pi}{4}\right)=\sqrt{2}$$ Conversely, if $a=\sqrt{2}$ then $f'\geq 0$, so the function is increasing, therefore your inequality holds. So the minimum value of $a$ is $\sqrt{2}$.


Como Atualizar só Alguns Campos Put em SpringBoot

Question: Olá Pessoal Explicando rapidamento o codigo esse endpoint ai é minha rota que atualiza um aluno já cadastrado eu entro com os dados que quero cadastrar e manda pra função atualizar e la "Seta" os dados o grande problema é que isso só funciona se eu "Setar" tudo, porque se eu deixa algum campo vazio, isso registra no banco de dados como null, tentei fazer uma condicional para ver se as variaveis estão nulas ou não porém quando entra na condicional das strings, como "nome" e "senha" da execption, Enfim a pergunta é : Como alterar só alguns campos no Put sem acabar setando nulo nos outros?, sem criar outras funcões pra isso, porque ai só tem 4 atributos, imagine se tivesse 40 e tivessemos que fazer uma função cada combinação de atributos usados.
<code>@PutMapping("/{id}")
@Transactional
public ResponseEntity<AlunoDto> atualizar(@PathVariable Long id,@RequestBody AttAlunoForm form) {
        Aluno aluno = form.atualizar(id, alunosRepository);
        return ResponseEntity.ok(new AlunoDto(aluno));
}
</code>
<code>    public Aluno atualizar(Long id, AlunosRepository alunosRepository) {
        Aluno aluno = alunosRepository.getOne(id);
            aluno.setIdade(idade);
            aluno.setNome(nome);
            aluno.setSenha(senha);
            aluno.setRenda(renda);

        return aluno;
    }
</code>
Answer: No caso de atualização parcial do recurso deverá ser utilizado o método PATCH ao invés do PUT.
No caso do PUT deverá ser encaminhado a representação completa do recurso que está sendo atualizado.
Put vs Patch - Medium
Para o caso do PATCH onde há a necessidade de atualizar somente os atributos que foram encaminhados você pode utilizar um if para obter esse comportamento.
<code>    public Aluno atualizar(Long id, AlunosRepository alunosRepository) {
        Aluno aluno = alunosRepository.getOne(id);
        if(idade != null) aluno.setIdade(idade);
        if(nome != null) aluno.setNome(nome);
        if(senha != null) aluno.setSenha(senha);
        if(renda != null) aluno.setRenda(renda);

        return aluno;
    }
</code>
Comment: pow mano mas é isso que eu digo, e se fosse 40 campos, ia setar os 40 ?


Memoization Libraries for C?

Question: For a project I'm working on, there are a number of states where calculations can be relied upon to return the same results (and have no side effects).  The obvious solution would be to use memoization for all the costly functions.
I would need to have memoization that handles more than one state (so that I could invalidate one cache set without invalidating another).  Does anybody know a good C library for this sort of thing?  (Note that it can't be C++, we're talking C.)
I've worked with some good implementations in Python that use decorators to be able to flexibly memoize a bunch of different functions.  I'm kind of wondering is there's a generic library that could do similar things with C (though probably with explicit function wrapping rather than convenient syntax).  I just think it would be silly to have to add caching to each function individually when it's a common enough issue there must be some off-the-shelf solutions for it.
The characteristics I would look for are the following:

Can cache functions with various types of input and output
Manages multiple different caches (so you can have short-term and long term caching)
Has good functions for invalidating caches
Intended to be used by wrapping functions, rather than altering existing functions

Anybody know a C implementation that can handle all or most of these requisites?
Comment: It is not clear to me how such a thing would work. A memoizing wrapper like `memoize(void*func, void*returnVal, int return size, ...)`? Seems complicated and fragile. A pile of preprocessor hackery? You *can* do amazing things with that kind of stuff, but it also tends to be fragile and can become a maintenance nightmare. But, in any case, good question.
Comment: @Namey: People do memoization all the time in C, but a generic C library – "generic" in terms of how C++ has templates or how Python decorators wrap this – is painful and fraught with pitfalls.
Comment: @Fred: I guess I see it differently.  Is it less painful and fraught with pitfalls to have to re-invent the wheel every time one wants to memoize an individual function?  I'd rather have one painful thing to maintain in one place than 1000 ad-hoc implementations scattered everywhere in the code.
Comment: @Namey: I meant "painful and fraught with pitfalls" for *each use* of that library. As far as when writing, adding "internal" memoization (using knowledge of the implementation) is *very* simple compared to writing a generic library. The cost of repetition is less than the cost of alternatives, IMHO.
Comment: It would be much nicer in C++11 with perfect forwarding, but I could imagine it done in C with some perf loss by providing a dictionary of type descriptors to `memoize()`. About as fragile as printf().
Comment: Memoize by the bit pattern of the data.
Comment: So nobody has actually seen a library that supports this?  That's pretty amazing, given the massive amount of C code out there.
Comment: With that said, I do acknowledge the much higher difficulty level of a "generalizable" C approach.  Unlike python, there is no generalized equality operator for checking arguments, etc.  This means a portable memoize function might only handle by-value args and be totally unable to evaluate the contents of data pointers.  But that would still be something pretty useful.
Comment: @Fred: I guess we'll just have to agree to disagree.  I tend to think about programming as an exercise in transforming and passing information, where you want to use the DRY principle liberally.  From that standpoint, I'm not sure why using a library would be much more difficult than writing a new set of memoization aparatus each time.  With that said, I'm not proposing that anyone write such a library- I'm asking if anyone has SEEN one.  At that point, I could test drive it and see if it is indeed painful enough to want to make my own wheels from scratch.
Comment: With that said, if someone says "Hey, I just wrote a C library for this after seeing your question" and it works, I would definitely consider it as a valid answer. ;)
Answer: Okay, seeing as there were no memoization libraries for C and I was looking for a drop-in solution for memoizing existing C functions in a code base, I made my own little memoization library that I'm releasing under the APL 2.0.  Hopefully people will find this useful and it won't crash and burn on other compilers.  If it does have issues, message me here and I'll look into it whenever I have the time (which would probably be measured in increments of months).
This library is not built for speed, but it works and has been tested to make sure it is fairly straightforward to use and doesn't display any memory leaks in my testing.  Fundamentally, this lets me add memoization to functions similar to the decorator pattern that I'm used to in Python.
The library is currently on SourceForge as the C-Memo Library.  It comes with a little user manual and a couple of 3rd party permissively licensed libraries for generic hashing.  If the location changes, I'll try to update this link.  I found this helpful in working on my project, hopefully others will find it useful for their projects.
Comment: I used your library and it works! Quite well. I wrote pretty much the exact same program in python, it ran in 2m 50s native, while 7s in pypy. The C program ran in 46s.
Comment: Glad to hear it.  I've made a couple of cleanups so it will work happily with more compilers.  Also, that's an impressive time for PyPy.  They must be doing some interesting things under the hood for optimization.
Comment: Yeah, well PyPy has been in development for many years by a team of PhDs... so I'm guessing they use some pretty hardcore maths.

The program I wrote was written to solve some Project Euler problem, though it's been so long and I've forgotten which one.
Comment: Yah, I know.  It's still pretty impressive to get a 25x speedup over the original Python, however.  I had recalled the usual speedups over cPython being more on the order of 2-5x.
Answer: memoization is all but built into the haskell language. You can call this functionality from c
Update:
I'm still learning about functional programming, but I do know that memoization is fairly common in functional programming becuase the language features make it easy. I'm learning f#. I don't know haskell, but it is the only functional language I know of that will interact with c. You might be able to find another functional programming language that interfaces with c in a more suitable fashion than what haskell provides.
Comment: Certainly an interesting comment.  It seems a bit like overkill to start wrapping C in Haskell, however.  I'd also worry about the potential performance hit from extra Haskell-generated C code that isn't really needed.  There would also be the problem that I am unclear how this approach would help memoize functions implemented in C.
Comment: Hey, thanks for trying at least.  An outside-the-box answer is still at least a stab at it.
Comment: I updated my answer with a little more detail. Its not too helpful, and I wouldn't have provided this answer at all if it weren't for the fact that your question has been here for 2 days without an answer. If it ends up a dead end for you, I'm sorry and wish you luck. However if it does work out, then I'm glad to have helped.
Answer: Why, just can't be C++?
Just for a starting point look to this memoization function:
declaration:
template<typename T, typename F>
auto Memoize(T key, F function) {
  static T memory_key = key;
  static auto memory = function(memory_key);
  if (memory_key != key) {
    memory_key = key;
    memory = function(memory_key);
  }

  return memory;
}

Usage example:
auto index = Memoize(value, IndexByLetter);

Memoization Libraries for C?


How to add Live Reload when using the command cordova serve?

Question: I am using this command to open up my app in the browser: cordova serve but it does not refresh itself when I update my code. How can I do that?
I have tried to use phonegap serve instead which has a live reload but it keeps sending me alerts and crashes my browser.
So, if you can please tell me how can I solve either of the two issues that will be wonderful.
Comment: Make sure that it executed from Www folder
Answer: You could try the Cordova Browsersync plugin. Instructions to use the plugin are in the plugin's repo.
Once you add this plugin using cordova plugin add cordova-plugin-browsersync, you can simply use cordova run -- --live-reload to start live reload. Note that this also enables syncing scrolls and clicks if you have multiple devices.
Comment: This plugin is out of date and broke my app. Is there an alternative?
Comment: Can livereload also be used on an android device? I need to do `cordova run android` everytime I make a change.
Comment: Also searching for an alternative
Comment: https://stackoverflow.com/a/50786052/943646 see my answer, i successfully use live reload feature with my cordova app.
Comment: This plugin is valid for me  and I should also needed to add cordova platform browser :) command is -cordova platform add browser- .
Answer: Easiest solution is just to use phonegap serve instead of cordova serve. As long as you've got phonegap installed it'll work even if you built the app with just cordova.
phonegap serve gives you an IP address that will live reload and that you can access from the browser or the phonegap developers app. Both are very handy and actually work, which is always a plus.
Comment: This is, by far, the best solution in 2019 as browsersync is no longer maintained and archived
Comment: Cordova Browser Plugin install failed. I found this to be the easiest solution with ```npm install -g phonegap```
Comment: but then in 2020, Phonegap will be shelved by Adobe..
Answer: You can also try cordova-plugin-browsersync-gen2. It's based on old abandoned plugin, fully compatible with latest versions of npm and Cordova.
Also, this version adds missing live-reload support for the following:
cordova run (for each platform individually)
cordova serve

Comment: This plugin is taking about a minute to refresh the page.
Answer: If you are using phonegap serve and you are seeing the JavaScript prompts, you need to add a snippet to prevent the app from loading the Native-level JavaScript code.
replace
with

Note that this works for both cordova.js and phonegap.js (They should be the same file)
Answer: You can use browser-sync directly, without a cordova plugin. Follow below steps

npm install -g browser-sync
Copy contents of platform/android/platform_www to www
Add following to config.xml: <allow-navigation href="http://<YOUR-IP>:3000" />
Set base-href (if angular project) to http://<YOUR-IP>:3000/index.html
Run browser-sync -w -server inside www
Update content security policy for executing JS and assets from YOUR-IP:3000. Also allow webscokets (ws) for browser-sync
Deploy app using cordova run android

Please note that you will have to redeploy the app every time you add a new plugin, and also update the www folder with new platform_www contents.
Every time you update the www, browser-sync will automatically notify your webview, and refresh the same. If you have to restart the app and connection with browser-sync is lost, connect device to computer and refresh the app using chrome device inspector, and browser-sync will be live again.
Answer: The cordova-plugin-browsersync can be out-dated. Alternatively, you can use watch command like:

npm install watch --save-dev

Go to scripts line under the package.json file then add:
"dev": "watch 'cordova run browser' www"

npm run dev

It will automatically refresh the page when you change anything under the www folder.
Sample screenshot:
Comment: It doesn't refresh the page but re-runs the `cordova run browser` and after each change in different tab with a different port. i.e. each change opens a new port and a new tab.


JSON Decodable nested array has varying formats and types

Question: Struggling with figuring out how to treat my decodable array where it has different types and structures. Essentially it is an array of data, which leads to an array of 4 types, and each of these types consists of a further array of search results.
Can you use decodable for arrays that have varying formats? Or is it simply to use object dicts?
I will attach my JSON at the bottom
struct SearchData: Decodable  {
var success: Bool
var server_response_time: Int
var data: [SearchDataType]
}

//This is the array of 3 of the group types: "Movies", "TV-Shows", "Artists"

struct SearchDataType: Decodable   {
let group: String
let data: [SearchDataMovies]
}

// Where group = "Movies"
struct SearchDataMovies: Decodable {
    let title: String
    let year: String
}

// Where group = "TV-Shows"
struct SearchDataTV: Decodable  {
    let title: String
    let year: Int
}
// Where group = "Artists"
struct SearchDataArtists: Decodable  {
    let name: String
}

Comment: Its better to get array of data first and later differentiate the group using dictionary.
Comment: why are you creating separate decodable for television and movies, you can use one ,both using same keys in dictionary
Comment: Post your JSON in text form, not screenshot
Answer: Decodable isn't going to view the strings in your group as different groups. So having group: "group: Movies", "group: Television", and "group: Games" doesn't make sense. All groups are at the same level in your JSON.
This would be your model:
struct SearchData: Decodable  {
var success: Bool
var server_response_time: Int
var data: [SearchDataType]
}

//Group name and array of groups.
struct SearchDataType: Decodable   {
let group: String
let data: [SearchDataForGroup]
}

// Where group = Any Group ("Movies", "Television", "Games", ect.)
struct SearchDataForGroup: Decodable {
let title: String
let year: String
}

If you want to call the name of your groups using decodable:
Declare a variable at the top level:
let allGroupNames = [data] = []

Then in your function for decoding you can pull out all of your group names from the group like this:
let mygroups = try decoder.decode(SearchData.self, from: data)

for groupValue in mygroups.data{
self.all groupNames = groupValue.group
print(groupNames)

}
From there if your intention is to create a tableView with sections you can use:
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
    return allGroupNames[section].group
}

Not sure if that is your intent, but hopefully this gets you started.


About the integrability of some function under some convergence assumption

Question: Let $\Omega\subset \mathbb{R}^n$ be a bounded domain and $H:=\{x\in\Omega:x_1=0\}$ a hyperplane in $\Omega$, and $\{f_k\}$  a sequence of absolutely integrable functions on $\Omega$ with $L^1$ norm  less than  $1$. Assume that $x_1\cdot f_k \to f_0$ in $L^1$ sense. as $k\to\infty$.
Question: Is  $\frac{f_0}{x_1}$  absolutely integrable? If so, is the $L^1$ norm of it  less than $1$?
(Note that $1/x$ is not integrable near the origin in $\mathbb{R}^1$.)
Clues: Note that,
$f_k \to f_0/{x_1}$  in $L^1$ sense as $k\to\infty$ does not hold. For example, take $\Omega=(-1,1)$,  $f_k=k/2$ on $(-1/k,1/k)$ and $=0$ somewhere else. Then $||f_k||_{L^1}=1$, and $f_0=0$
Answer: The answer is YES. Convergence in $L^{1}$ implies a.e. convergence of some subsequence. If $x_1f_{k_j} \to f_0$ a.e then  Fatou's Lemma gives $\int |\frac {f_0} x| \leq \lim \inf \int |f_{k_j}| \leq 1$.


How can i create a dynamically input fields using bootstrap

Question: I have created the input fields but when i click the first two ,it does well until when i request the third which comes between the first two and also other also comes between.can some help me please.
here is my javascript code:

Comment: Why is that now,its not even adding any more field.please i need more help.
Answer:

$(document).ready(function() {
    $(".add-more").on('click', function(){
        var html = $(".copy-fields").clone();
        $(".after-add-more").after(html[0]);
    });

    $("body").on("click",".remove",function(){
        $(this).parents(".control-group").remove();
    });
});

  <button class = "add-more">ADD</button>

<input type = "text" />

Because you are trying to copy the html content of class .copy-fields, Use clone() instead html() and then use html[0] for insert after as following:
$(document).ready(function() {
    $(".add-more").click(function(){
        var html = $(".copy-fields").clone();
        $(".after-add-more").after(html[0]);
    });

    $("body").on("click",".remove",function(){
        $(this).parents(".control-group").remove();
    });
});

Comment: Why is it not even adding any more field?please i need more help
Comment: thanks for your help but i have really tried it out but it has failed to add more input fields.please i need more help
Comment: Hey can you provide your html code, your html structure might be different.
Comment: I have edited my answer and include a working snippet code please review and compare the html code with yours.
Comment: @n.ssendawula do not post *your* code in *someone else's* answer. *Your* code belongs to *your* question, not to others'.