Unit Testing framework for Embedded platform in C++?

Question: I am working on an embedded systems project using ACE Framework and all the development is done using eclipse IDE. I am looking for a good testing framework.
Basically the project involves parsing of incoming data and I am searching for a unit testing framework which suits my project. What are my options here?
Comment: Welcome to SO! When you place a question try to add a minimum content: input sample, expected output sample, what did you try, research and where are you stuck.
So leave a question, show us your code, what did you try and your research:  https://stackoverflow.com/help/how-to-ask
You can also add a bounty to draw more attention to this question once you have enough reputation: https://stackoverflow.com/help/privileges/set-bounties
Answer: I recommend you try out Catch or doctest, which are quite similar.
Comment: My team has Cath2 working on a STM32 discovery (Cortex M-4), so this is a possible choice indeed.
Comment: Testing doctest for STM32 (m4)
Comment: @Bktero I checked the feature list for Catch, and it doesn't mention mock support or embedded support. How does it work with STM32 in your experience -- compiling for Linux and running there, or compiling to run on the STM32 device?
Comment: @CivFan that was a long time ago, I'm sure if I remember all this! Indeed, Catch2 doesn't have support for mock objects. It doesn't need anything special for "embedded support". From what I recall, you can do something like this: ```#define CATCH_CONFIG_RUNNER
Catch::Session session;
session.configData().testsOrTags.emplace_back("[some tag]");
session.run();
```
The test results will be printed to stdout.
Answer: Try ceedling: It is UT framework from throw the switch,
from http://www.throwtheswitch.org/ceedling
Comment: According to its website, ceedling doesn't support C++
Comment: More general thing.
Comment: @volpato, yes, it supports C.
Answer: I recommend using this light-weight unit testing framework designed for embedded software use with C++ that I created:
https://github.com/Novodes/SimpleTest-EmbeddedSafety/
It was tested with ARM Compiler version 6.6.4 and 6.6.
There are just two files: simpletest.cpp and simpletest.h
This is based on the SimpleTest repository I forked and adapted for embedded software. It is super easy to use and integrate into your code.


How do I know if this acoustic electric guitar works?

Question: I was given an acoustic electric guitar, but I've never used one before. After changing the battery I tried plugging it into a portable speaker and a consumer stereo/receiver just to see if it gave any output. Nothing — the frequency histogram on the display of the external amplifier doesn't even twitch when playing. I don't have the proper equipment or cables, just what's at hand at home, i.e. consumer electronics and cables.
I've tried all combinations on the dials, and although I don't know what half of them do, I think I can rule them out as the problem at this point. It's by a manufacturer that no longer exists, and I've not found any instruction manuals online.

There's no power switch, so I've worked under the assumption that it conserves power by only being active when there's a plug in the jack. I don't know know whether that's true, but the low battery LED blinks momentarily when plugging it in/out, so I guess that's right.
I've disassembled the preamp (if that's what it's called) and reseated all connectors (7 in total — 3 pin headers and 4 cables) but apparently bad connections weren't the problem either. Visual inspection didn't reveal any defects in the components.
Still, I can't say at this point whether it's working or broken. Did I misunderstand something about this thing?
Comment: Plugging in to a receiver may well not give the guitar signal a good impedance match. Needs trying with a proper guitar amp, using a proper jack-jack lead. Any music shop should oblige. The pickup system is well thought of, so persevere!
Comment: Because many guitars use exactly this short between the shaft and ring as the "power switch". When you plug in a stereo plug then it would only briefly power the circuit as the tip slides across the contacts (which could explain the blinking of the LED at the start) but then simply biases the right stereo channel to -9V without any significant current flowing to keep the power on.
Comment: @leftaroundabout Thank you for the explanation, that's good news to me. I was hoping you'd say that, which means I might not have any repairs to do. I'll test this with a manual short later. Now that you mention it, I should have figured this out when reseating the *three wire* connector for the jack... ♀♂
Comment: @Tim Thank you for your suggestion! I am not interested in "good" though — any quality will do as long as it gives a life sign. If opportunity arises I will try to seek out a music shop, but it might be a while.
Comment: What cable did you plug into the guitar? A ¼" stereo one probably won't work, it must be mono.
Comment: @leftaroundabout Yes, I thought about the fact that I use stereo plugs, but ultimately disregarded it as an issue. The mono plug should just be the equivalent of a stereo plug with GND and right audio shorted together. Unless the contact happens only hit the insulator between the ring and the sleeve (unlikely) I assume it should still produce some output. Why shouldn't it work, according to you?
Comment: Short the ring to the sleeve, and you have a standard 1/4" mono jack.
Comment: @leftaroundabout Yep, some aluminium foil later and it turned on. Thank you for providing me with the missing on switch.
Answer: If you can find a plug in guitar tuner - not the sort that clips on - that may show signs that the guitar output is o.k.
Obviously the volume needs to be turned up. The AST and UST are the two 'pickups'. AST stand for acoustic soundboard transducer, and UST is under saddle transducer. If they're not switched on, no signal is forthcoming. So check they're on, and the balance is central.
Other than that, trying it through an amp designed for the purpose is the best test. Good luck.
Comment: Thanks for explaining the labels. How would I check that AST and UST are switched on? Judging by the picture, I can't see a state in which they're not. Except maybe using the two holes in the bottom left, which expose two trimpots to a screwdriver.
Comment: Basically, there's a 50:50 with the pups! Put the switches in opposite states, and one is bound to be on.
Answer: [Turning my earlier comment into an answer]
As you've correctly assumed, active guitars generally switch on their power whenever a cable is plugged in. But though there are jacks that have a proper, isolated auto-switch built in for this purpose, many guitars don't have such sockets but instead use a simple hack to get the power switch functionality out of an ordinary stereo jack: if you plug a mono plug into a stereo socket, the shaft will connect to both the "ring" and "shaft" contacts. Thus, if the battery's + pole is fixed but the − pole connected to the ring contact, having a mono plug plugged in will cause − to be connected to ground, thus closing the power circuit.
That however does not work when using a stereo plug instead: then the ring will simply dangle at -9V, and not enough current flows to power the preamp.
Answer: A portable speaker won't work if it is passive. But if you have (or can easily borrow) one of those external speakers for PC, anything with an external power supply, then you should be able to hear it. In that case the only other thing you'll need is an adapter from 1/2" plug (guitar) to 3.5mm (typical speakers/headphones jacks).
Comment: Thanks for confirming that it should produce some sound. The speaker has an amp — it's a Bluetooth speaker. The stereo receiver also does, naturally. I have loads of those adapters (stereo) as well but haven't had any luck so far.
Answer: Here's how I ended up testing it, based on the missing piece provided in the comments of how these things turn on:

A simple short of the right channel with some random RCA adapter.
Comment: @leftaroundabout An adaption of a larger piece in alu minor
Comment: What an, erm, _beautiful piece of precision engineering_...
Comment: So how did the test results go?
Comment: @Dekkadeci I got audible/visible static out of it for one thing, which is enough to know it actually turns on. It also picked up the strings and played it back, so there seem to be no problems. Time to put it back together and make myself a cable.


Monit - monitor tinc VPN

Question: Is there any way to monitor a tinc VPN with a monit network check?
The following check does not see if the vpn connection is actually established (means if there is a connection to one of the vpn servers)
CHECK NETWORK vpn with INTERFACE mynetwork
IF FAILED LINK
THEN RESTART

What I do now is checking for one host in my vpn:
CHECK HOST myhost with ADDRESS 10.8.1.111
    IF FAILED ICMP TYPE ECHO
    THEN restart

Which is fine so far but does not cover the situation that this specific host is down while others are up.
Answer: I have same problem, and my solution was this:
cat /etc/monit/conf.d/tinc

# monitor tinc daemon
check process tinc with pidfile /var/run/tinc.net.pid
  group system
  start program = "/usr/sbin/service tinc start"
  stop program  = "/usr/sbin/service tinc stop"
  if failed host 127.0.0.1 port 655 type udp then restart

Monit - monitor tinc VPN


Drupal differential db restore

Question: I have several Drupal sites hosted on my shared hosting server. Each site has a dev, test and production instances, with separate Docroots and Apache Vhosts and separate mysql db instances. Not using features module.
Production db has real live data in it. dev and test dbs have dummy data. But as per the development workflow, if a new module has to be installed the developers do it in dev and test instances. That creates a new table and some records in the dev/test db instances.
Now that if they want to have the same module installed in the production site, I want them to able to run an operation via web which takes that particular table/data to the production instance from dev/test.
To explain bit more: This is what I need.
A ==> Test Site
B ==> Production Site ==> Real Data
A new module is installed in A. This creates a table and some records in A. We should be able to take that particular table/data from A and import into B keeping all the B's data consistent. And we dont really know what table is created in A. This is all done by the developers.
In a nut shell. B = (A U B) i.e. B should become A Union B
I tried mysqldiff but that works only for schema but not data.
Ideas please.
Comment: You say "Not using features module" -> question tagged with `features` ?
Comment: To highlight the same I have done so. Should i remove the tag?
Answer: This is a huge question.
I just can share my experience
First i export mysql data from live site with Backup and Migrate module.
I do restore it in my dev site. In this dev site, i beware to not send infortunetly emails, so i install Reroute email module. (great because the settings are not in database but in settings.php file)
Then i make my own dev on localhost with real datas
Depends if your have the abilities to do that, and if the datas are not so confidential to do so.
But to stick with your question, db diff is impossible is guess. And you have to upload the new module files and enabled them manually (or with drush). Settigs in drupal are totally encapsulated in db
Answer: You may want to look into Percona Toolkit.
There are two particular tools you may want to use

pt-table-checksum : This tool can be used to determine which tables have a different checksum between a Master and Slave.
pt-table-sync : This tool will actually find the row and column differences in data based on PRIMARY KEY values. I would suggest using the --print and --sync-to-master options to output the generated SQL to a text file.

CAVEAT
I can see from the question that you do not have MySQL Replication set up. Therefore, I would suggest the following:

STEP 01) Get two DB Servers

Server MDB : A copy of Test DB
Server SDB : A copy of Prod DB

STEP 02) Setup Master/Slave Replication

MDB as Master
SDB as Slave

STEP 03) Execute pt-table-checksum against the Master. The program should autodetect connected Slaves.
STEP 04) Use pt-table-chekcksum output to see which table on the Master (Test) has a different checksum on the Slave (Prod)
STEP 05) For every table that have mismatched checksum values, run pt-table-sync and send output to a text file.
STEP 06) Take the generated SQL and execute it on the Slave.

When you are done with STEP 05, the Slave's data content should be the B = (A U B) you are looking for.
WARNING : Thoroughly backup all your data on Test and Prod before doing this !!!
Give it a Try !!!

Drupal differential db restore


The method or operation is not implemented error

Question: Quando vou fazer a adição de um registro na minha tela Incluir, me aparece esse erro.
O que pode ser?
Service
public void AddItem(Test item)
        {

            var codigos = this.context.Tests.SingleOrDefault(x => x.Codigo == item.Codigo);
            if (codigos != null)
            {
                this.context.Testes.Any(x =>
                x.Id == codigos.Id
                && x.Codigo != item.Codigo);
                throw new ValidationException("Codigo", Resources.TestesResources.ErroUniqueKeyCodigo);
            }
            else
            {
                base.context.Tests.Add(item);
                base.Save();

            }

        }

Controller
[HttpPost]
 public ActionResult Incluir([ModelBinder(typeof(CollectionModelBinder))]Testitem)
        {
            if (this.ModelState.IsValid)
            {
                item.Id = this.Id;
                item.Value = DateTime.Now;
                item.Use = User;
                try
                {
                    this.Service.AddItem(item);
                    return this.SuccessView(true);
                }
                catch (ValidationException exception)
                {
                    base.AddValidationErrors(exception);
                    return base.PartialView(item);
                }
            }
            else
                return base.PartialView(item);
        }

Erro
Comment: Nesse screenshot, deixas-te a parte mais importante de fora: a stack trace. Põe a stack trace aqui, e coloca o código relevante, onde a excepção foi lançada.
Comment: Você consegue debugar e dizer exatamente em que linha dá o erro ?
Comment: Coloquei alguns breakpoints no código ele nem cai nos metódos, quando debuga.
Comment: Posta o código de ValidationException, por favor
Answer: Muito provavelmente você utilizou geradores de código onde geram métodos no seguinte formato:
void MeuNovoMetodo () {
    throw new NotImplementedException ();
}

Eles fazem isso para que seu código possa compilar mas que você não se esqueça de implementar ele depois. Você só vai descobrir qual método esqueceu de implementar olhando a stack trace, ou pesquisando nos arquivos pela NotImplementedException exception.


Is data on a 1 to 4 scale interval or ordinal?

Question: I have data on 26 participants (13 from computing and remaining 13 from non computing) who have participated in my research. Each participant is treated with a lab module (Hands on Robotics Session). Now each participant will be evaluated using a rubric on scale of 1 to 4. This experiment has both pre and post test.
Is  data on a 1 to 4 scale interval or ordinal?
Comment: It doesn't matter. You should first be thinking about the scientific questions you would like to answer with these data and what the numbers mean about those questions.  For additional guidance, search our site for [related threads](http://stats.stackexchange.com/search?q=%2Binterval+%2Bordinal). That might help you to ask an improved question whose answers may be more relevant and useful for your research.
Comment: When you say 1 to 4 scale, do you mean a single item with four response option or do you mean the average of many items on a 1 to 4 scale or do you mean something else?
Answer: It is probably ordinal. If this is similar to a Likert scale the data have a natural order but the difference between 1 and 2 may not be the same as the difference between 2 and 3. If 1 unit on the scale is not the same for 3 to 2 as for 2 to 1 the scale is not interval.


How do I prevent data conflicts in integration test using JUnit, Spring Boot and TestContainers?

Question: I'm Using Junit in Spring Boot, along with TestContainers (Docker, MySQL 8.0.29) to develop integration tests.
When I execute my tests individually, they all succeed. However when I run them all at once (i.e. in CI/CD), they fail. This is because the tests are not executed in order, and an item might already be deleted before the test to find the item is executed.
To fix this I want to give the entities a unique ID. However, the ID is already automaticly set in my Hibernate entity:
@Entity
public class Assignment {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Integer id;

I've tried to delete all items before each test is executed, however this does not work:
    @Autowired
    private JdbcTemplate jdbcTemplate;

    @BeforeEach
    void tearDown() {
        JdbcTestUtils.deleteFromTables(jdbcTemplate, "assignment");
    }

Example integration test:
    @Test
    void When_getById_Verify_Fields() {
        AssignmentDTO assignmentDTO = new AssignmentDTO();
        assignmentDTO.setTitle("test");
        assignmentDTO.setDescription("test");
        assignmentDTO.setUserId("1");
        assignmentDTO.setCreator("1");

        assignmentService.addAssignment(assignmentDTO);

        AssignmentDTO expectedAssignment = assignmentService.getById(1);

        assertEquals(assignmentDTO.getTitle(), expectedAssignment.getTitle());
        assertEquals(assignmentDTO.getDescription(), expectedAssignment.getDescription());
        assertEquals(assignmentDTO.getUserId(), expectedAssignment.getUserId());
        assertEquals(assignmentDTO.getCreator(), expectedAssignment.getCreator());
    }

Answer: Each test method should generally remove the data it creates to prevent this problem.
What you can do that the data is not committed to the database you can add the @Transactional annotation to the test method or the test class if you want it for all test methods..
This will do a rollback after the test method.
Comment: Simon is very right here. Just solve the issue of test pollution as you would when running against a regular database. While you can solve test pollution on the infrastructure level (container per test), this is not recommended, since it will slow down the suite considerably. Solve test pollution on the logical level instead.
Answer: If you want to execute SQL script before or after each test, you can use annotations from org.springframework.test.context.jdbc.
And an example of how to use it in a test :
@SqlGroup({
        @Sql(executionPhase = Sql.ExecutionPhase.BEFORE_TEST_METHOD, scripts = {
                "classpath:datasets/integration/integration_test_before.sql"}),
        @Sql(executionPhase = Sql.ExecutionPhase.AFTER_TEST_METHOD, scripts = {
                "classpath:datasets/integration/integration_test_after.sql"})})

These annotations need to be added to the class test. With this annotation, you will execute a script before the test and after to initialize data and delete data.
The SQL files need to be in src/test/resources/datasets/integration.
You can find the link to a guide to use it: https://www.baeldung.com/spring-boot-data-sql-and-schema-sql
Answer: You can easily fix this by returning the object saved at addAssignment or the id. See my suggestion below
AssignmentDTO assignment = assignmentService.addAssignment(assignmentDTO);

AssignmentDTO expectedAssignment = assignmentService.getById(assignment.getId());

The reason why is failing besides you delete all data is because the auto-increment still persist. See this in order to reset the auto-increment.


What framework and compiler directive to use for portable class libary in ASP.NET5?

Question: What framework and compiler directive to use for portable class library in ASP.NET5?
For framwwork, that "pcl" ?
<code>"pcl": {
    "frameworkAssemblies": {
        // ...
    },
    "dependencies": {
        // ...
    }
}
</code>
And as compiler directive, is that "PORTABLE" ?
<code>#if PORTABLE
//
#else
//
#endif
</code>
Answer: Sorry, there is no support for PCL.
Comment: Is this by design (please share a link) or is it a bug/missing feature?


diffrent default and selected value in html select

Question: I need different default and selected value for HTML <select> tag. It means that I need my <form> load with a selected <option>, then after pressing <button type="reset"> button another option set to select tag, but how?
<select size="1" name="select1" >
    <option  value='1'> default value </option>
    <option selected="true" value="2">selected value</option>
</select>

onclick event for button doesn't works:
<button onclick="resetSearchPanel();" type="reset"> ...

java script function:
 function resetSearchPanel() {

  document.forms['submitSearch'].elements['select1'].value = "1";

}

above snippet works when the button type property setted as 'button' but it doesn't work when type set to reset!
Answer: Onclick of reset, just make the required value in the select tag as selected.
on Onclick() method of reset button, make sure that you write a function which does whatever you want to.
If you set the button type as reset, it will reset the whole of form data, so youe select tag will not be having the value you set it to. Remove reset tag, and it should be fine.
If its must for you to use type as "reset" then you have to use work arounds to make sure that  your code is executed after the form is reset, but that approach is strongly discouraged.
Comment: whats the function that you have written?
Comment: http://stackoverflow.com/questions/78932/how-do-i-programatically-set-the-value-of-a-select-box-element-using-javascript Please refer to this link
Comment: What is submitSearch here? Have you verified that document.forms['submitSearch'].elements['select1'] is able to get your exact select tag?
Comment: YES! it is snippet, not full code. It works when type is button.
Comment: Whats the problem if you don't use reset type and just use button type?
Comment: I need reset button, it resets all inputs, it is my only input!
Comment: No other than setting a delay, there is no way to do that.
Answer: The reset button will reset all values back to default. Its onclick happens before the actual reset taking place, so any change you make there will be lost.
Since there is no "onafterclick" even, only way around if you must use reset button is using a timer:
function resetSearchPanel() {
    window.setTimeout(function() {
        document.forms['submitSearch'].elements['select1'].value = "1";
    }, 100);
}

This will change the selected value 0.1 seconds after clicking the button.
Comment: Thanks, It works. But is there any better solution? It seems dirty coding!!  I can't vote up because of my low reputation, thank You.
Comment: Clean coding would be using custom reset button but I understand you can't change the HTML.. ??
Answer: You have given button type='reset' dont know why because type reset will clear the form data. So for your problem you need to give the button type='button'
<button onclick="resetSearchPanel();" type="button">

Hope this will work for you.
Comment: I need reset button. I have several input in my form and I need reset all to default value after clicking reset.
Answer: Select option you need on page load with JavaScript.
Comment: @MohsenKashi - If there are limitations that restrict what solutions are acceptable to you, you should add them to the question.
Comment: Because of our company framework limits, this solution can't implemented
Comment: @HottDogg it is our coding conversation


shell_exec chmod on directories

Question: I'm calling a PHP file from the browser which is searching for some sub-directories and changing their permissions to 777 using chmod. The process runs under user 'www-data'
I've (temporarily!!) allowed the 'www-data' to have the correct rights in the /etc/sudoers file, but still can't get the permissions to change.
<?php
shell_exec("find /home/path -type d -name Directory_name_to_search_for -print0 | xargs -0 sudo chmod 777");
?>

Is this something to do with where I'm calling sudo?
Comment: did you check if `find` is actually finding anything?
Comment: Yes - From the command line it prints out a long list of the directory names, but with no spaces inbetween.
Comment: to be expected, `print0` forces `find` to use null (`\0`) as the inter-filename separator, which xargs uses in `-0` mode, so that spaces in filenames don't get treated as filename separators. since find is working, then something' wonky with your sudo setup.
Comment: OK - sudo setup was indeed incorrect - thank you very much all fixed now.
Answer: a line break at the beginning of the output seemed to prevent shell_exec printing anything else. Hope this saves someone else an hour or two.
<?php
shell_exec("find /home/path -type d -name Directory_name_to_search_for -print0 | xargs -0 sudo chmod 777 2>&1");
?>

2>&1
Comment: OK - the logs give me this; `COMMAND=/bin/chmod 777 /home/dropbox/home/path/match_1/Directory_name_to_search_for /home/path/match_2/Directory_name_to_search_for` etc etc. All of the directories exist, so the find bit works, but the output is broken up only by spaces.
Comment: Working now - Youssef got me there and Marc B thank you.

shell_exec chmod on directories


Infinite product of measurable spaces

Question:
Suppose there is a family (can be
infinite) of measurable spaces. What
are the usual ways to define a sigma
algebra on their Cartesian product?

There is one way in the context of
defining product measure on
planetmath. Let $(E_i, B_i)$ be
measurable spaces, where $i \in I$
is an index set, possibly infinite.
We define their product as follows:

let $E= \prod_{i \in I} E_i$  , the    Cartesian product of $E_i$,

let $B=\sigma((B_i)i \in I)$ , the    smallest sigma algebra
containing    subsets of $E$ of the
form $\prod_{i    \in I}B_i$  where
$B_i=E_i$ for all    but a finite
number of $i \in I$ .

I was wondering why it is required
that "$B_i=E_i$ for all but a finite
number of $i \in I$"?

Thanks and regards!

ADDED:
I was wondering if the product sigma algebra defined in 2 is the smallest sigma algebra such that any tuple composed of one measurable set from each individual sigma algebra is measurable?
Comment: A sensible $\sigma$-algebra on the product should be such that all projections $p_i:E\to E_i$ are measurable. This implies that any sensible $\sigma$-algebra contains the one you give in 2 and, therefore, the one you give in 2 is the smallest sensible $\sigma$-algebra.
Comment: Well, in 2 you give the usual way to define the product $\sigma$-algebra you ask for in 1...
Comment: Is 2 the only way? or the only useful way?
Comment: Thanks! Can you explain why the projections $p_i$ being measurable requires that condition?
Comment: @Tim: if you write down exactly what it means for the projections to be measurable, you'll see it yourself :)
Comment: @Tim: have you taken a topology course? This is exactly analogous to the construction of the product topology and happens for the same reason.
Comment: @Qiaochu Yuan: I haven't, but I learned about topology myself, and I try to understand what you guys wrote here, with some references and the internet to fall on when any problem comes. It is nice to know there is similarity between these two.
Answer: This is a good question.  I haven't yet worked out a complete answer myself, but Mariano's comment above is definitely part of it: the given product $\sigma$-algebra has the property which is analogous to that of the product topology (which it resembles and is surely modelled on): it is the smallest $\sigma$-algebra which makes all of the projections measurable.
Because of this, I believe that if you make a category out of all measurable spaces and measurable functions in the obvious way, the product $\sigma$-algebra you have defined turns out to be the categorical product: i.e., it satisfies the requisite universal mapping property.  Again, this is the situation for the product topology.
But I think the rest of the explanation has to do with the fact that this $\sigma$-algebra gives you the theorems you want, just as the product topology -- and not the "box topology" for instance -- has nice properties, especially Tychonoff's theorem.  (The product topology was introduced for the first time in Tychonoff's paper, and his theorem played a large role in convincing mathematicians that it was the "right" topology on an infinite Cartesian product.)
I'm not sure exactly what the analogous result to Tychonoff's theorem is here, but I do know that this "coarsest" product $\sigma$-algebra enables one to define arbitrary products of probability spaces: see this lovely paper of S. Saeki1 for an incredibly short proof of that.  I hope it is at least clear where the "coarseness" of the chosen product $\sigma$-algebra comes in handy: if (say in the case of a countably infinite index set, to fix ideas) (added: Michael Greinecker's answer shows that countable products actually behave rather well, so let's instead think about uncountable products) we allowed arbitrary products $Y = \prod_{i} Y_i$ of
measurable subsets $Y_i \subset X_i$ to be measurable, then what should the measure of
$Y$ be?  If the set of indices for which $\mu(Y_i) < 1$ is uncountable, the product (taking the net of finite subsets of $I$) must approach zero.  By requiring $Y_i = X_i$ for almost every $i$, we get that $\mu_i(Y_i) = 1$ for almost every $i$ and the infinite
product is really a finite product.
Is there more to the story than this?  Is the above construction of the product probability measure the "right" analogue of Tychonoff's theorem in this context (is there even a "right" analogue of Tychonoff's theorem in this context?)?  I'm not sure, and I would be interested to hear more from others.
1 Saeki, Sadahiro, A proof of the existence of infinite product probability measures, Am. Math. Mon. 103, No. 8, 682-683 (1996). ZBL0882.28005, MR1413587. Link to a snapshot in the Wayback Machine.
Comment: @Pete: You would probably notice anyway, since you visit this site a lot. But since another answer was posted as an _extensive comment to the answer by Pete L. Clark_ I thought it might be good to ping you.
Comment: Essentially, the surprise boils down to the ancient observation (Hausdorff, von Neumann, Rokhlin) that every sufficiently nice probability space can be identified with part of the unit interval and at most countably many atoms.
Comment: I am not so sure about the universal property. Wasn't there a question on MO about how this fails?
Comment: @Qiaochu: I believe you are thinking of this question: http://mathoverflow.net/questions/49426.  As it says (and as I said) the universal mapping property is in the category of measurable spaces, not the category of measure spaces.  So I'm pretty sure what I said is true.
Comment: The issue is the following: The categorical product exists in the category of *measurable spaces* and the construction you give works. The product of probability spaces from measure theory is *not* a product in the category of measure spaces (whatever the morphisms you try). Dmitri Pavlov's answer to the question on MO gets around this by identifying two measure spaces if they have the same $L^{\infty}$-von Neumann algebra, and then expresses that in the (essentially) dual category of complete locales with distinguished $\sigma$-ideal. There are not many distinct objects left...
Comment: Thanks for bringing up my question to another level! Nice to know there are other things with common feature, which can be unified under category theory.
I was wondering if the product sigma algebra is the smallest sigma algebra such that any tuple composed of one measurable set from each individual sigma algebra is measurable?
Comment: @Martin: Well, even I slow down a bit over the holidays.  Your "ping" was helpful -- thanks very much.
Comment: That Saeki paper is amazing.
Answer: This is essentially an extensive comment on the post by Pete L. Clark.
We can define a product of a function with real values $(a_i)_{i\in I}$ in the following way (an elaboration on the definition by Pete): Let $\mathcal{F}$ be the set of finite subsets of $I$. It is a directed set under set inclusion. We define a net $\pi:\mathcal{F}\to\mathbb{R}$ by $\pi(F)=\times_{i\in F}a_i$. We let $\times_i a_i$ be the limit of the net $\pi$ if it exists. It is worth pointing out that this notion of convergence differs from the usual infinite product of a sequence of numbers in which convergence to zero is ruled out, so that convergence becomes equivalent to convergence of the series of logarithms of the factors. Essentially, the limit is then defined to be undefined when it would be zero otherwise. This makes little sense in probability theory, where we often want to show that a sequence of independent events has probability $0$. Also, the product defined here is "absolute", it does not depend on any order on the index set $I$.
Fact: If $(a_i)\in [0,1]^I$, then $\times_i a_i$ exists. If, moreover, $\times_i a_i>0$, then there exists a countable subset $C\subseteq I$ with $a_i=1$ for all $i\in I\backslash C$.
Proof: From the obvious fact that if $P\geq 0$ and $0\leq a_i\leq 1$ one has $Pa_i\leq P$, it follows that the net $\pi$ is nonincreasing. It is also obviously bounded below by $0$, so $\times_i a_i$ exists as the limit of a nonincreasing net that is bounded below. Assume now that $\times_i a_i>0$. For each positive natural number $n$, let $F_n=\{ i\in I:a_i<1-1/n \}$. For every $n$, $F_n$ is finite, so $\{i\in I:a_i<1\}=\bigcup_n F_n$ is countable.
Fact: If $I$ is countable and for every $i\in I$, $Y_i$ is a measurable subset of $X_i$, then $\prod_i Y_i$ is in the product $\sigma$-algebra.
Proof: W.l.o.g., let $I=\mathbb{N}$. For every $n$, the set $S_n=X_1\times\ldots X_{n-1}\times Y_n\times X_{n+1}\times\ldots=\pi_n^{-1}(Y_n)$ is by definition in the product $\sigma$-algebra. Now $\prod_{n\in\mathbb{N}}Y_n=\bigcap_{n=1}^\infty S_n$ which is in the $\sigma$-algebra as the countable intersection of measurable sets.
By a similar argument, one can show that for a general index set $I$, every measurable set can be written (subject to the usual labeling issues) as $\prod_{i\in C}Y_i\times\prod_{i\in I\backslash{C}}X_i$ with $C$ being a countable subset of $I$ and $Y_i$ an arbitrary measurable subset of $X_i$. So every measurable set in the product $\sigma$-algebra is determined by countably many coordinates. A useful Lemma for thinking about this and related issues is the following:
Lemma: Let $X$ be a set and $\mathcal{Y}$ be a family of subsets of $X$ and let $B\in\sigma(\mathcal{Y})$. Then there exists a countable family $\mathcal{C}\subseteq\mathcal{Y}$ such that $B\in\sigma(\mathcal{C})$.
Proof: Just verify that the family of all sets constructed by countable subfamilies forms a $\sigma$-algebra.
As a last remark: Tychonoff's theorem has a direct application in studying probabilities on infinite product spaces. The crucial step in proving the Daniell-Kolmogorov Extension Theorem is showing that the resulting probability measure is not just finitely additive but countably additive on the product algebra. For this one uses regularity with respect to the compact sets in the product topology (see here1 for a general approach). This is also the reason why the theorem does not hold for arbitrary product spaces (so the independent product of probability spaces is quite special).
1Expository Notes on the Kolmogorov Extension Problem
from the website of Kim C. Border. Here are also Wayback Machine links to this text and the website with various notes.
Comment: ...But it's clearly as a matter of taste.  As for (2) -- i.e., that arbitrary *countable* products are automatically measurable because they are countable intersections of cylindrical sets...point taken!  Thanks for making this explicit.
Comment: $@$Michael: if you can be a bit more explicit about the "two misleading mistakes" in my answer, I will try to address them.
Comment: $@$Michael: about the infinite product: not everyone agrees that an infinite product of positive numbers which approaches zero is "convergent".  Restricting the sets as I did remedies this.
Comment: If you do probability theory, you have to allow convergence of a product to 0. How else are you going to calculate the probability of infinitely many independent coin-flips to be head in every case?
Comment: The other issue is that countable products of measurable sets are measurable. The countable product of (Y_n) is defined as the set of sequences $(y_n)$ with $y_n\in Y_n$ for all $n$. Each such condition defines a cylinder set and their intersection gives the product. In the paper by Saeki, he essentially works with the algebra generated to verify the conditions and makes the extension theorem do the work for the sigma-algebra. This does not mean that the latter does not contain countable products.
Comment: $@$Michael: As you've explained, it is not necessary to think of a single coin flip as an infinite product to calculate its probability: rather one sees that any given element $x$ of the sample space lies in cylindrical sets with arbitrarily small measure, so the measure of $\{x\}$ must be zero.  In general, when the index set is countable, you can think in terms of infinite products or also in terms of countable intersections; to me the latter seems simpler (and one doesn't have to speak of products "converging to zero", which number theorists like me are trained against)...
Comment: I'm not sure what you think is misleading about what I said.  You write "all we can con[c]lude is that if the product is positive, at most countably many coordinates were smaller than 1", which is the contrapositive of what I said, so of course I agree.  (By the way, these conventions about infinite products originate in complex analysis, where many important functions are defined by convergent "Euler products" in a half plane $\Re z > a$, and thus one knows they have no zeros in that region.)
Comment: I actually mean the sentence afterwards. It is true that is we let all but finitely many sets have measure $1$, the product becomes really a finite product. But it also becomes really a countable product if we let all but countably many indices have measure $1$ and have no index with measure $0$. And thank you for filling my knowledge gaps in complex analysis.
Comment: @MichaelGreinecker my question was closed as a duplicate of this, so could you point out what I'm missing in this post?  I don't think I really understand it given that it's supposed to contain the answers to my questions in it.  http://math.stackexchange.com/questions/211910/what-is-a-product-measure-space-for-the-infinite-case
Answer: Details of $\textbf{lemma}$ mencionated by Michael Greinecker : Let
$L=\{E \subseteq X; E\in \sigma(C)\,\mbox{for some} \, C\subseteq \mathcal{Y},\,\mbox{with C countable}\}$
See that the following hold:
$\bullet$ X, $\emptyset \in L$ (Obvious);
$\bullet$ If, $E\in L$, then $E^{c}\in\sigma(C_E)$ for $C_E\subseteq \mathcal{Y}$ (countable) such that $E\in\sigma(C_E)$;
$\bullet$ if $\{E_n\}_{n\in\mathbb{N}} \subseteq L$, we can take $\displaystyle C=\bigcup_{n=1}^{\infty}C_{E_n}$ with $C_{E_n}$ in the same sense of above item. Then C is countable and $\displaystyle\bigcup_{n=1}^{\infty}E_n \in \sigma(C)$.
This proof that L is an $\sigma$-algebra. Finnaly observes that
$\bullet$ $\mathcal{Y}\subseteq L$ (Using $\sigma$-algebra generating by each element of $\mathcal{Y}$);
$\bullet$ For all countable $C\subseteq \mathcal{Y}$ see that $\sigma(C)\subseteq \sigma(\mathcal{Y})$, and this implies that $L\subseteq \sigma(\mathcal{Y})$.
Because $\sigma(\mathcal{Y})$ is the smallest $\sigma$ -algebra containg $\mathcal{Y}$, we have $L=\sigma(\mathcal{Y})$.
This proof that each event just depend of a countable many sets of generators.
$\textbf{More about}:$
In the case of product, by the notes from Michael we have that the product $\sigma$-algebra is generated by the sets $\displaystyle \prod_{n\in C}Y_n \times \prod_{n\in I\setminus C}X_n$ with $C\subseteq I$ countable, this implies that for every $E\subseteq X$ exist an at most countable $C\subseteq I$ and $E_C$ in product sigma algebra of $(X_i, B_i)_{i\in C}$ satisfying $$E=\pi_{C}^{-1}(E_C)\hspace{3cm}(1)$$ for $\pi_C : \prod_{i\in I} X_{i} \to  \prod_{i\in C} X_{i}$ the natural projection. This results says that, the product sigma algebra is not generated by the sets $\prod_{i\in I} Y_{i}$ with $Y_i \in B_i$ for all $i\in I(uncontable)$, indeed if every $Y_i\neq X_i$, for uncontable many of index $i\in I$, not exist an countable $C\subset I$ and $E_C$ such that (1) holds.

Infinite product of measurable spaces


User should not be allowed to edit language

Question: I have a question regarding this.
I have a Multilingual site in drupal 8 and i want to disable the edit language for user, so they can´t change the language, if they have chosen one or redirect them, if they are trying.
Of course if you are administrator, you should be able to change their languages and my own.
Any modules, which can do this or configuration somewhere in the i18 module? Or does this require a custom made module?
Thank you for your time.
Answer: There are options under Configuration » Regional and language » Languages » Detection and selection where you can set the User Detection method to be the first one, or maybe the only one, that determines which language to display the site in.
This way the logged in users would only be able to see the site in the language chosen in their profiles.
To prevent them from changing it try Language access.
Comment: Thanks. It helped, so when i have created an account with english i could not go to another language in the URL.


O que é o novo objeto Temporal do JavaScript?

Question: Descobri uma proposta do TC39 que está em estágio 3 de um novo objeto para se trabalhar com datas. Este se chama Temporal.
Analisei um código de exemplo que usa esta nova API:
console.log(
  "Initialization",
  Temporal.now.instant()
);

// Initialization 2021-01-13T20:57:01.500944804Z

Ele funciona como um método static (semelhante aos statics do objeto Math), e no exemplo acima ele retorna "quase" uma string na mesma forma que new Date().toISOString():

console.log(new Date().toISOString());

Sobre o assunto, foi dito que Temporal seria uma solução mais simples para desenvolvedores JavaScript/TypeScript que precisam trabalhar e manipular datas. Esta solução poderia até dispensar o uso de bibliotecas externas como date-fns e momentjs. Na hora me despertou interesse e gostaria de saber mais sobre esta nova implementação.

Esta é uma implementação nova que veio pra substituir o objeto Date? Sei que o Date não vai a lugar algum, mas a API Temporal veio pra resolver alguns problemas?

Se sim, quais?

Sei que está em estágio 3, mas é possível usá-lo no Node.js em alguma versão através de uma flag?

Alguma versão do TypeScript suporta, mesmo que experimentalmente, esta nova API?

As dores de cabeça que eu tenho ao trabalhar com datas vão finalmente ser resolvidas com um "objeto salvador"? (sei que bala de prata não existe)
Comment: _(Off-topic)_ Só para constar, "bala de prata" se refere a uma solução ou tecnologia capaz de aumentar substancialmente a produtividade dos projetos, não tem sido encontrada num nível mais "macro" (como a troca do paradigma de programação) porém ganhos significativos em nível mais "micro" existem, por exemplo adotar a tecnologia certa para o problema em questão (em oposição a adotar uma menos adequada) ou usar uma biblioteca que melhora a produtividade para resolver certo problema. Aí entraria também uma API mais moderna para lidar com datas (que não sei se uma classe só dá conta de melhorar).
Answer: A API Temporal é, no momento em que escrevo esta resposta, uma proposta de adição ao ECMAScript que se encontra no estágio 3 do processo de incorporação à especificação (o famigerado TC39 process). Repositório referente à proposta.
Mediante estandardização, a API Temporal consistirá de um objeto global Temporal (similar aos já existentes Math, Date, JSON etc) que irá aglutinar classes, funções e utilitários para a manipulação de datas e horas no JavaScript. Embora a API desta proposta não deva ser alterada, os implementadores desta proposta NÃO DEVEM enviar implementações Temporal não sinalizadas até que a IETF padronize os formatos de serialização de sequência de fuso horário / calendário.
Sobre a API podemos citar:

Construtores notáveis do objeto Temporal:

Temporal.Instant
Temporal.PlainDateTime
Temporal.PlainDate
Temporal.PlainTime
Temporal.PlainYearMonth
Temporal.PlainMonthDay
Temporal.TimeZone
Temporal.Duration

Outras propriedades do objeto Temporal:

Temporal.now

Já quero deixar uma vontade: cada um dos construtores acima tem uma funcionalidade específica e seus próprios métodos. :-) Para detalhes individuais, consultar a especificação e documentação da proposta.
Até então, o único meio "nativo do JavaScript" para lidar com datas e horas no JavaScript é utilizar o objeto Date e suas respectivas funções e métodos. No entanto, essa API é extremamente antiga e possui vários problemas de design.
Como é de conhecimento comum, o JavaScript foi implementado num prazo extremamente curto por Brendan Eich, que baseou o funcionamento do Date na API (hoje majoritariamente depreciada) java.Util.Date. Apesar de, com atualizações futuras, o Java ter ganhado novos meios de lidar com datas e horas, o JavaScript permaneceu com a infame API Date. A Temporal API é a "evolução" do gerenciamento de datas e horas no JavaScript, sem os problemas da API antiga.
A nova API Temporal visa à resolução desses problemas, uma vez que:

Fornece APIs simples e fáceis de usar para executar computações relacionadas à datas e horas.
Suporte de primeira classe para todas as time zones, o que inclui suporte a horários de verão (cálculos DST-safe)
Lida somente com objetos imutáveis (ao contrário da maioria das APIs Date, que são mutáveis).
Analisa somente formatos de string estritamente especificadas.
Suporta outros calendários, além do Gregoriano.

Desse modo, como vimos acima, o novo objeto Temporal fornecerá uma grande variedade de construtores e objetos para:

Representar propriamente informações relativas à datas e horas.
Possibilitar computações apropriadas baseadas em cada tipo.

Não acho que vale a pena alongar mais que isso, uma vez que a documentação da proposta é bem completa e expressiva, além de que, como vimos, pode estar sujeita à mudanças. Quando a API for estabilizada, comprometo-me a atualizar esta resposta com informações mais detalhadas.

FAQ da pergunta

Esta é uma implementação nova que veio pra substituir o objeto Date? Sei que o Date não vai a lugar algum, mas o Temporal veio pra resolver alguns problemas?

Não. O Date realmente não vai a lugar nenhum, até porque isso quebraria a web, o que iria contra um dos principais princípios do processo TC39, que é não quebrar APIs antigas do JavaScript.
A API Temporal veio para tornar o trabalho com datas e horas mais simples. É bem provável que torne a API Date menos comum em novos projetos e aplicações, mas Date jamais deixará de existir no JavaScript.

Sei que está em estágio 2, mas é possível usá-lo no Node.js em alguma versão através de uma flag?

Editado ao dia 11 de março de 2021: Acabou de passar para o estágio 3, o que significa que as engine poderão começar implementações iniciais – ainda sem estabilidade garantida.
O Node.js (baseado no motor V8) ainda não possui suporte nativo à API Temporal, mas existe polyfill que pode ser utilizado.
No entanto, não acho sábio fazer uso dessa API neste momento para projetos "reais", uma vez que ainda não está totalmente estabilizado.

Alguma versão do TypeScript suporta, mesmo que experimentalmente, esta nova API?

Não. O TypeScript ainda não fornece definições de tipos "nativas" para a API Temporal.

As dores de cabeça que eu tenho ao trabalhar com datas vão finalmente ser resolvidas com um "objeto salvador"? (sei que bala de prata não existe)

Todas, provavelmente, não. :-) Mas como vimos acima, a API Temporal resolverá diversos problemas históricos da API Date, o que decerto facilitará o trabalho com datas e horas.
No entanto, é um campo complicado e repleto de edge-cases. Apesar de facilitar, a API Temporal não faz com que eles sumam.
Comment: Pois é, o `Date` sempre vai existir por causa da retrocompatibilidade, que é um dos "pilares" da web moderna. Mas não se preocupe! Assim que `Temporal` for estandardizada (e o suporte se disseminar), `Date` raramente será usada em novos projetos — pelo menos eu espero. :P
Comment: @CmteCardeal, pode editar, se quiser, estou meio sem tempo para ver isso em detalhes agora. Ainda planejo rescrever essa resposta do zero quando avançar ao estágio 4. O pior mesmo é achar o tempo... :D
Answer: A outra resposta já deu uma visão geral, só gostaria de complementar alguns pontos.

Obs: como a API ainda está sujeita a mudanças, não me aprofundei muito nos exemplos. Coloquei apenas alguns que usam a versão atual do polyfill (que pode ou não ter mudado quando você estiver lendo esta resposta), para dar uma noção do que a API é capaz.

Podemos começar com a principal motivação desta proposta, segundo seus próprios criadores:

Date has been a long-standing pain point in ECMAScript. This proposes Temporal ... that brings a modern date/time API to the ECMAScript language.

Em tradução livre, seria: "Date tem sido há muito tempo um ponto problemático em ECMAScript. Propomos Temporal... que traz uma API de datas moderna para a linguagem".
A ideia da proposta, portanto, é criar uma nova API de datas, para corrigir alguns pontos que eles consideram problemáticos em Date.
Uma curiosidade é que alguns dos responsáveis pela proposta são os criadores do Moment.js.

Um dos problemas é o fato de Date, apesar do nome, não ser exatamente uma data (no sentido de representar um único valor de dia, mês, ano, hora, minuto e segundo). Conforme já explicado aqui e aqui, o Date na verdade representa um timestamp: a quantidade de milissegundos decorrida desde o Unix Epoch (que por sua vez equivale a 1970-01-01T00:00Z - 1 de janeiro de 1970 à meia-noite, em UTC).
Ou seja, o Date representa um instante único, um ponto na linha do tempo. Pense no "agora": neste exato momento, que dia é hoje e que horas são? Em cada parte do mundo, a resposta será diferente (em algumas partes do mundo, é 14 de fevereiro, em outras pode ser dia 13 ou 15, e o horário também será diferente). Apesar da data e hora serem diferentes, o instante (o valor do timestamp) é o mesmo para todos. E o Date, segundo a especificação da linguagem, só guarda a informação do timestamp.
Quando você imprime a data (via alert ou console.log) ou quando obtém informações dela (seja via os getters ou toString()), este timestamp é convertido para o fuso horário que está configurado no ambiente onde o código está rodando (browser, Node, etc). Ou seja, o Date usa a configuração do fuso horário para converter o timestamp para os valores corretos de data e hora (ou converte para UTC, quando você usa métodos como toISOString() ou os "getters UTC", como getUTCHours, getUTCMonth, etc).
Essa abordagem one-size-fits-all (um tipo para a todos governar todas as situações) pode até "simplificar" as coisas (pois assim temos um único tipo de propósito geral), mas também acaba gerando várias situações - na minha opinião - inconvenientes.
Por exemplo, se você só quer uma data de aniversário (somente dia, mês e ano), sem se importar com o horário ou timezone, bastaria fazer algo como new Date(ano, mes, dia). Porém, na verdade internamente o horário será ajustado para meia-noite no fuso horário do ambiente no qual o código roda (seja o browser, ou o Node, etc). Isso porque somente o dia, mês e ano não é o suficiente para obter o timestamp (por exemplo, uma data como o dia 14/02/2021 não representa um instante único, você precisa saber qual o horário e em qual fuso horário ele se refere, para ter um valor de timestamp). Então com Date você sempre está lidando com timestamps e fusos horários, mesmo quando não quer ou não precisa.
Um exemplo (rodando no Node - lembrando que ajustar o process.env.TZ não funciona no Windows, e ajustá-lo no meio do script só funciona a partir do Node 13):
let d = new Date(2021, 1, 14); // em Date, fevereiro é mês 1 :-(
let t = Temporal.PlainDate.from({ year: 2021, month: 2, day: 14 }); // fevereiro é mês 2 \o/
console.log(d.toString(), t);

// mudar para o timezone da Califórnia
process.env.TZ = 'America/Los_Angeles';
console.log(d.toString(), t);

Eu crio um Date e um Temporal.PlainDate que correspondem a 14 de fevereiro de 2021 - aliás, outro bônus incrível desta API: os meses não são indexados em zero - janeiro é 1 e não zero!
O timezone configurado no meu ambiente é America/Sao_Paulo (vulgo "Horário de Brasília"). Então o Date terá o horário ajustado para meia-noite no Horário de Brasília, e este é o timezone usado para imprimir a data.
Mas quando eu mudo o timezone do ambiente, isso afeta a saída de toString() (o timestamp do Date ainda é o mesmo, mas este será convertido para o novo timezone ao ser impresso). Já PlainDate não é afetado por esta configuração, pois ele só guarda o dia, mês e ano, sem se importar com o horário ou o timezone. A saída é:
Sun Feb 14 2021 00:00:00 GMT-0300 (Brasilia Standard Time) Temporal.PlainDate <2021-02-14>
Sat Feb 13 2021 19:00:00 GMT-0800 (Pacific Standard Time) Temporal.PlainDate <2021-02-14>

Lembrando que o resultado pode variar de acordo com o timezone que estiver configurado no seu ambiente.
Repare que Date.toString() mostra um valor diferente de acordo com o timezone que está configurado (aliás, o mesmo ocorre com os getters: d.getDate() retornaria 14 ou 13, dependendo do timezone configurado). Já PlainDate, por não ter nenhuma informação sobre horários ou timezones, não é afetado por nenhuma configuração e mantém seu valor constante.
Creio que isso evitará muitos erros que costumam ocorrer até hoje ("Criei um Date mas ele mostra o dia/horário errado").
Além disso, a nova API define vários tipos diferentes, um para cada situação (indo no caminho oposto do one-size-fits-all): tem um tipo para data (somente dia, mês e ano), outro para horário (somente hora, minuto, segundo), outro para data e hora, mas sem fuso horário, outro para data/hora e fuso, outro para timestamp, etc.
Esta imagem (retirada da documentação) nos dá um bom resumo dos tipos disponíveis:

E esta mostra a relação entre estes tipos:

Conversão entre timezones
Uma coisa que o JavaScript não tem é conversão entre diferentes timezones.
O mais próximo que temos é algo como d.toLocaleString('pt-BR', { timeZone: 'Europe/Berlin' }), que de fato retorna os valores de data e hora convertidos para o timezone indicado. Mas o problema é que o formato depende do locale, e não temos controle sobre isso. E se quisermos a data/hora em um timezone específico, mas em outro formato? Eu teria que ir trocando o locale até encontrar um, mas e se nenhum tiver o formato específico que eu quero? Ou se eu simplesmente não quiser um formato, e sim um objeto contendo os valores de data e hora convertidos para outro timezone?
Com Date, não dá. Já o Temporal prevê várias formas de converter:

mantendo o horário local: tenho um objeto que representa 14/02/2021 às 10h no Horário de Brasília, quero mudar somente o timezone (ou seja, converter para 14/02/2021 às 10h no fuso do Japão, por exemplo)
mantendo o instante: quando é 14/02/2021 às 10h no Horário de Brasília, que dia e hora é no Japão? (R: 22h do mesmo dia)

A API ainda trata casos mais complexos que só os timezones trazem para você, como as transições de horário de verão: permite que você trate os vários corner cases que ocorrem (quando uma hora é pulada, ou quando ela ocorre 2 vezes - nos casos em que o relógio é atrasado em uma hora quando termina o horário de verão, por exemplo), além de permitir consultar o histórico de mudanças de cada timezone.

Aritmética de datas
Atualmente o JavaScript não possui um bom suporte para aritmética de datas. Na prática, o melhor que dá para fazer para calcular a diferença entre duas datas é subtrair os valores dos timestamps e depois fazer os cálculos na mão.
Mas nem sempre isso é suficiente. Só para ficar em um caso, a diferença em meses não é algo tão trivial quanto parece: por exemplo, entre 01/01/2019 e 01/02/2019 há 31 dias. Dividindo por 30 e arredondando, dá 1 mês.
Mas entre 01/02/2019 e 01/03/2019 há 28 dias. Dividindo por 30, dá 0,93: se arredondar pra baixo, dá zero meses. Mas entre 1 de fevereiro e 1 de março a diferença não é de um mês? Então devemos arredondar pra cima nesse caso?
Mas e se fosse entre 01/01/2019 e 29/01/2019, a diferença também é de 28 dias. Só que entre 1 de janeiro e 29 de janeiro ainda não se passou 1 mês, então eu não posso arredondar pra cima nesse caso. "Ah, então eu só arredondo pra cima se não estiver no mesmo mês".
Aí você vê que entre 01/01/2019 e 27/02/2019 a diferença é de 57 dias, que dividido por 30 dá 1,9. Se arredondar pra cima dá 2, mas entre 1 de janeiro e 27 de fevereiro ainda não se passaram dois meses. E agora?
Com Temporal, bastaria fazer algo do tipo:
const today = Temporal.PlainDate.from('2019-01-01');
const futureDate = Temporal.PlainDate.from('2019-02-27');
const until = today.until(futureDate, { largestUnit: 'months' });
console.log(until); // 1 mês e 26 dias

// ou, se quiser apenas a quantidade de meses, use until.months

Aliás, está previsto um tipo específico para durações: Temporal.Duration. Com isso ficará mais simples fazer operações como "somar dias/meses/anos/qualquer-outra-quantidade-de-tempo a uma data".
Claro, isso poderá mudar o comportamento de alguns corner cases. Por exemplo, se você somar 1 mês à 31 de janeiro:

let d = new Date(2021, 0, 31); // 31 de janeiro de 2021
// somar 1 mês
d.setMonth(d.getMonth() + 1);
console.log(d.toString()); // 3 de março!

Na verdade a "soma" é feita ajustando-se o valor do mês e mantendo os demais campos. No caso acima, mudamos o mês para fevereiro, e o dia mantém-se em 31, mas como fevereiro não tem 31 dias, é feito um ajuste para 3 de março (os dias "excedentes" acabam "dando overflow" e "invadindo" o mês seguinte).
Mas aí entra uma questão semântica: se tenho uma data em janeiro e somo 1 mês, por que o resultado é uma data em março? Não deveria ser em fevereiro? Tudo bem que isso é discutível, já que não existe uma regra "oficial" para aritmética de datas (tal como existe na matemática) e cada API implementa de um jeito. Mas o Temporal (usando a implementação atual do polyfill) ajusta a data para o último dia de fevereiro, caso o valor do dia exceda a quantidade de dias do mês:
let d = Temporal.PlainDate.from('2021-01-31'); // 31 de janeiro de 2021
d = d.add(Temporal.Duration.from({ months: 1 }));
console.log(d); // Temporal.PlainDate <2021-02-28> (28 de fevereiro de 2021)

Enfim, um bom resumo das possibilidades está na própria documentação.

Resumindo, os problemas de se trabalhar com datas vão continuar existindo (como tratar corretamente, converter entre timezones, fazer cálculos, etc). O que pode ficar mais fácil - assim espero - é resolver esses problemas :-)
E lembrando que Date não vai sumir, inclusive a nova API prevê a conversão de Date para Temporal.Instant.
Comment: @CmteCardeal Adicionei mais algumas coisas na resposta. Mas acho que não vou mais adicionar muita coisa pois a API ainda está sujeita à mudanças (inclusive, eu cheguei a testar algumas semanas atrás e realmente a versão atual mudou bastante, até os nomes de algumas classes e métodos inclusive), então acho que vou esperar ela ser oficialmente lançada para poder atualizar a resposta com mais exemplos...
Comment: Tivemos essa atualização no Github da proposta: _""NOTA: Embora a API desta proposta não deva ser alterada, os implementadores desta proposta NÃO DEVEM enviar implementações Temporal não sinalizadas até que a IETF padronize os formatos de serialização de sequência de fuso horário / calendário.""_ Acho que a API em si não vai mais mudar. O que falta agora é só questões de implementações. Não cheguei a verificar completamente, mas pode ser que a API siga esse padrão agora, logo mudanças no estágio 3 já são bom difíceis de acontecer.
Comment: @CmteCardeal Bom, mesmo assim, acho que vou esperar mais um pouco pra atualizar a resposta. Ainda nem terminei de ler toda a documentação...


Help with a modal Hilbert-style proof of (□(a>b)&◊(a&c))>◊(b&c)

Question: Can't grasp how it can be proved. To proof just propositional calculus formula (without modal operators) at first seems rather natural to me. Tried the law of importation scheme but it didn't work out.
There are a lot of axiom schemata allowed (link below) + K + Necessitation + MP + Substituition
It does not really matter what Hilbert-style calculus to use. The only two requirements:
a) no assumptions
b) no premises
set of axioms is on a p.13
http://books.google.ru/books?id=XNzzliL2cBgC&pg=PA23&lpg=PA23&dq=a+new+introduction+to+modal+logic+axioms&source=bl&ots=hOuN2jTOra&sig=dMGzFI6ZFf2RJa7GLLDNio9aM2E&hl=ru&sa=X&ei=-2y2U7n_KNOO4gSlmoGACA&ved=0CE0Q6AEwBQ#v=onepage&q=a%20new%20introduction%20to%20modal%20logic%20axioms&f=true
Comment: It is not clear to me the statement : "any usage of valid sentences would work"; **if** we are considering the *propositional formula* : $((a \rightarrow b) \land (a \land c)) \rightarrow (b \land c)$, it is a *tautology*. Thus, by *Completeness* for *propositional calculus*, it is provable. If it can help, the formula is equivalent to : $(a \rightarrow b) \rightarrow ((a \land c) \rightarrow (b \land c))$ which again is a *tautology*.
Comment: [Here's a MathJax tutorial](http://meta.math.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference) :)
Comment: What the axioms for propositional calculus that you're using?  What the axioms for modal logic that you're using?  What rules can get used?
Comment: Mauro, yep it is not very clear. What I meant is that you may use any valid sentences (it will help me) excluding the given one.
Comment: Doug, there are abou 15 axioms allowed. As I have said it will be sufficient to use any valid sentences (excluding the presented one) since I need a hint. If your proof will include theorems apart from my allowed-axiom_schemata-and-theorems list I'll do necessary changes. My problem is that I cannot solve it even using any (!) theorems.
Comment: Mauro, you are right. p 13 [http://books.google.ru/books?id=XNzzliL2cBgC&pg=PA23&lpg=PA23&dq=a+new+introduction+to+modal+logic+axioms&source=bl&ots=hOuN2jTOra&sig=dMGzFI6ZFf2RJa7GLLDNio9aM2E&hl=ru&sa=X&ei=-2y2U7n_KNOO4gSlmoGACA&ved=0CE0Q6AEwBQ#v=onepage&q=a%20new%20introduction%20to%20modal%20logic%20axioms&f=false]
Comment: Thanks for the reference. I assume that your problem is Ex.2.1(c), page 48. The proof is relative to **system K**. At pages 24-25 the system is "specified" as : modal axiom K + Rule of Uniform Subst + Rule of Modus Ponens + Rule of Necessitation + the "propositional" axiom schema **PC** : is $\alpha$ is a valid wff of PC, then $\alpha$ is an axiom. The formula (see my comment above) : $((a→b)∧(a∧c))→(b∧c)$ is a *valid* wff of PC; thus, you can us "as is" in your proof.
Comment: @Mauro, yep, now I see. But now I've got kind of a sport interest to solve the problem(:
Answer: $\renewcommand{\lif}{\supset}$
First, it's important to understand the intuition behind the theorem.  That will help guide you in constructing an axiomatic proof.
$$
\renewcommand{\land}{\wedge}
(\Box (a \lif b) \land \Diamond(a \land c)) \lif \Diamond (b \land c)
$$
With the Kripke semantics, this says "if $a \lif b$ is true in every accessible world and $a \land c$ is true in some accessible world, then $b \land c$ must be true in some accessible world."  An intuition behind proof might be:

Consider the accessible world $w$ in which $a \land c$ is true.  Because $a \lif b$ is true in every accessible world, it must be true in $w$ as well. Since $a$ is true (from $a \land c$), then $b$ follows by modus ponens.  Since $c$ is also true (from $a \land c$), then $b \land c$ is true.  Then $b\land c$ is true in some accessible world, and thus $\Diamond(b \land c)$.

Constructing axiomatic proofs from scratch is kind of a pain, and it might be easier to start with a natural deduction style proof, and then map that back to an axiomatic proof.  A natural deduction style proof would be something like

0.

1. Assume $\Box(a \lif b) \land \Diamond(a \land c)$.
2. $\Box(a \lif b)$ by conjunction elimination.
3. $\Diamond(a \land c)$ by conjunction elimination.

4. Possibility introduction subproof with $a \land c$.
5. $a \lif b$ by K-reiteration.
6. $a$ by conjunction elimination.
7. $b$ by conditional elimination (modus ponens).
8. $c$ by conjunction elimination.
9. $b \land c$ by conjunction introduction.

10. $\Diamond(b \land c)$ by $\Diamond$ introduction with 3, and 4–9.

11. $(\Box(a \lif b) \land \Diamond(a \land c)) \lif \Diamond(b\land c)$ by conditional introduction 1–10.

What can we do on the axiomatic side?  Well, if we take propositional reasoning for granted, we do, to begin:

$\Box(a\lif b) \land \Diamond(a \land c)$ (hyp)
$\Box(a \lif b)$ (taut. consequence)
$(a \lif b) \lif ((a \land c) \lif (b \land c))$ (tautology)
$\Box((a \lif b) \lif ((a \land c) \lif (b \land c)))$ (necessitation)
$\Box(a \lif b) \lif \Box((a \land c) \lif (b \land c))$ (distribution)
$\Box((a \land c) \lif (b \land c))$ (modus ponens)

At this point, you need to figure out what rules you've got available for handling possibility.  Ideally you'd have a possibility distribution axiom like
$$
\Box(\phi \lif \psi) \lif (\Diamond\phi \lif \Diamond\psi) \tag{Possibilitation}
$$
if you have that, or can derive it, then you can continue:

$\Diamond(a \land c) \lif \Diamond(b \land c)$ (possibilitation)
$\Diamond(a \land c)$ (taut. consequence)
$\Diamond(b \land c)$ (modus ponens)

That's still not quite what you need, because you'd need a deduction theorem to get the conditional.  That means you'll need to go back a bit and figure out how to do all of this "one-layer removed".  This should be a good starting point, though.
Comment: @MauroALLEGRANZA I've updated my answer.  In $K$ you can't derive $\Diamond\phi$ from $\Box\phi$.  You need the axiom M (aka T) for that.  In Kripke semantics, $\Box\phi$ is true if $\phi$ is true in *every* accessible world, and $\Diamond\phi$ is true if $\phi$ is true in *some* accessible world.  $\Box\phi$ can be true when $\Diamond\phi$ if there are no accessible worlds.  Compare with $\forall$ and $\exists$: $\forall x.Rx \lif Px$ can be true even if $\exists x. Rx\land Px$ is false.  It just means that there aren't any $x$ such that $Rx$.
Comment: Thank you Joshua for this invaluable insight in the modal semantics. ND-style proof is very clear and straightforward, but I cannot elicit the Hilbert-proof without using hypotheses. All that I have at hand are axiom schemata and the substituition rule.
Comment: @CharlesBronson I very much hope that you also have the necessitation rule ($\vdash \phi / \vdash \Box\phi$), and modus ponens ($p \lif q, p / q$), or else I don't think you're going to be able to do this.  But as I did in my answer, we'll have to guess at what axioms are available unless you show them in the question.  Add them to the question please so that we can provide better, more applicable answers.
Comment: thank you for advice. Updated the question. The modal part itself is very easy, but I didn't expect such a failure on the propositional part):
Answer: This answer address the "unsolved" problem regarding the proof of the "propositional part" of the question, using an Hilbert-style proof system (with Natural Deduction, the proof is quite easy, and has been already provided).

The list at page 13 of M.J.Cresswell & G.E.Hughes, A New Introduction to Modal Logic (1966) is significantly called a "list [of] valid PC wff"; we are not sure that they form a complete axiom system for PC (i.e. that they are enough to prove all tautologies).
In order to prove the formula :

$((a→b)∧(a∧c))→(b∧c)$

we need a complete Hilbert-style axiom system; I'll use that of Elliott Mendelson, Introduction to Mathematical Logic (4th ed - 1997), based on the following three axioms :

(A1)  $\mathcal{B} \rightarrow ( \mathcal{C} \rightarrow \mathcal{B})$
(A2)  $(\mathcal{B} \rightarrow ( \mathcal{C} \rightarrow \mathcal{D})) \rightarrow ((\mathcal{B} \rightarrow \mathcal{C}) \rightarrow (\mathcal{B} \rightarrow \mathcal{D}))$
(A3)  $(\lnot \mathcal{C} \rightarrow \lnot \mathcal{B}) \rightarrow ((\lnot \mathcal{C} \rightarrow \mathcal{B}) \rightarrow \mathcal{C})$

and modus ponens as only rule of inference.
The symbol $\land$ for conjunction is not primitive; it is defined as :

$\mathcal{B} \land \mathcal{C} =_{def} \lnot (\mathcal{B} \rightarrow \lnot \mathcal{C})$.

In order to prove our formula, we need some preliminary Lemmas; you can find the proof in Mendelson's book [for some of them, see this post].
Lemma 1.8 [page 36] :

$\vdash \mathcal{B} \rightarrow \mathcal{B}$.

We need only (A1) and (A2) to prove it.
With Lemma 1.8 and using only (A1) and (A2) it is possible to prove the Deduction Theorem [Prop 1.9, page 37]:

if $\Gamma, \mathcal{B} \vdash \mathcal{C}$, then $\Gamma \vdash \mathcal{B} \rightarrow \mathcal{C}$.

With the Deduction Th it is easy to prove :
Corollary 1.10(a) [page 38] :

$\mathcal{B} \rightarrow \mathcal{C}, \mathcal{C} \rightarrow \mathcal{D}  \vdash \mathcal{B} \rightarrow \mathcal{D}$.

Then Mendelson proves Lemma 1.11.(a)-(e)

$\vdash \lnot \lnot \mathcal B \rightarrow \mathcal B$
$\vdash \mathcal B \rightarrow \lnot \lnot \mathcal B$
$\vdash \lnot \mathcal B \rightarrow (\mathcal B \rightarrow \mathcal C)$
$\vdash (\lnot \mathcal C \rightarrow \lnot \mathcal B) \rightarrow (\mathcal B \rightarrow \mathcal C)$
$\vdash (\mathcal B \rightarrow \mathcal C) \rightarrow (\lnot \mathcal C \rightarrow \lnot \mathcal B)$.

We can easily derive from Lemma 1.11.(e) :

Lemma A : $\vdash (\mathcal B \rightarrow \lnot \mathcal C) \rightarrow (\mathcal C \rightarrow \lnot \mathcal B)$.

Proof
(i) $\mathcal B \rightarrow \lnot \mathcal C \vdash \lnot \lnot \mathcal C \rightarrow \lnot \mathcal B$ --- from Lemma 1.11.(e) with $\lnot \mathcal C$ in place of $\mathcal C$, by mp
(ii) $\mathcal B \rightarrow \lnot \mathcal C \vdash \mathcal C \rightarrow \lnot \mathcal B$ --- from (i) and Lemma 1.11(b) with Coroll.1.10(a)
(iii) $\vdash (\mathcal B \rightarrow \lnot \mathcal C) \rightarrow (\mathcal C \rightarrow \lnot \mathcal B)$ --- from (ii) by DT.
Now we need the equivalent of $\land$-introduction and -elimination rules; we have to derive them using the abbreviation for $\land$.

Lemma B : $\vdash (\mathcal B \land \mathcal C) \rightarrow \mathcal B$.

Proof
(i) $\vdash \lnot \mathcal B \rightarrow (\mathcal B \rightarrow \lnot \mathcal C)$ --- Lemma 1:11(c)
(ii) $\vdash \lnot (\mathcal B \rightarrow \mathcal \lnot C) \rightarrow \lnot \lnot \mathcal B $ --- from (i) and Lemma 1.11(e) by mp
(iii) $\vdash \lnot (\mathcal B \rightarrow \mathcal \lnot C) \rightarrow \mathcal B $ --- from (ii) and Lemma 1.11(a) by Coroll.1.10(a)
(iv) $\vdash (\mathcal B \land \mathcal C) \rightarrow \mathcal B $ --- from (iii) by def of $\land$.

Lemma C : $\vdash (\mathcal B \land \mathcal C) \rightarrow \mathcal C$.

Proof
(i) $\vdash \lnot \mathcal C \rightarrow (\mathcal B \rightarrow \lnot C)$ --- (A1)
(ii) $\vdash \lnot (\mathcal B \rightarrow \lnot C) \rightarrow \lnot \lnot C$ --- from (i) and Lemma 1.11(e) by mp
(iii) $\vdash \lnot (\mathcal B \rightarrow \lnot C) \rightarrow C$ --- from (ii) and Lemma 1.11(a) by Coroll.1.10(a)
iv) $\vdash (\mathcal B \land C) \rightarrow C$ --- from (iii) by def of $\land$.
Now we prove :

Lemma D : $\vdash \mathcal B \rightarrow ( \mathcal C \rightarrow (\mathcal B \land \mathcal C))$.

Proof
(i) $\mathcal B, \mathcal B \rightarrow \lnot \mathcal C \vdash \mathcal \lnot C$ --- by mp
(ii) $\mathcal B \vdash (\mathcal B \rightarrow \lnot \mathcal C) \rightarrow \mathcal \lnot C$ --- from (i) by DT
(iii) $\mathcal B \vdash \mathcal C \rightarrow \lnot (\mathcal B \rightarrow \lnot \mathcal C)$ --- from (ii) and Lemma A by mp
(iv) $\vdash \mathcal B \rightarrow (\mathcal C \rightarrow \lnot (\mathcal B \rightarrow \lnot \mathcal C))$ --- from (iii) by DT
(v) $\vdash \mathcal B \rightarrow ( \mathcal C \rightarrow (\mathcal B \land \mathcal C))$ --- from (iv) def of $\land$.
We prove :

Lemma E : $\mathcal B \rightarrow ( \mathcal C \rightarrow \mathcal D) \vdash (\mathcal B \land \mathcal C) \rightarrow \mathcal D$.

Proof
(i) $\mathcal B \rightarrow ( \mathcal C \rightarrow \mathcal D)$ --- assumed
(ii) $\mathcal B \land \mathcal C$ --- assumed
(iii) $\mathcal B$ --- from (ii) by Lemma B
(iv) $\mathcal C \rightarrow \mathcal D$ --- from (i) and (iii) by mp
(v) $\mathcal C$ --- from (ii) by Lemma C
(vi) $\mathcal D$ --- from (iv) and (v) by mp
(vii) $\mathcal B \rightarrow ( \mathcal C \rightarrow \mathcal D) \vdash (\mathcal B \land \mathcal C) \rightarrow \mathcal D$ --- from (i) and (vi) by DT.
Now our last preliminary Lemma:

Lemma F : $\vdash (\mathcal B \land \mathcal C) \rightarrow (\mathcal C \land \mathcal B)$.

Proof
(i) $\mathcal B \land C$ --- assumed
(ii) $\mathcal B$ --- from (i) by Lemma B
(iii) $\mathcal C$ --- from (i) by Lemma C
(iv) $\vdash \mathcal C \rightarrow ( \mathcal B \rightarrow (\mathcal C \land \mathcal B))$ --- Lemma D
(v) $\mathcal C \land \mathcal B$ --- from (iii), (ii) and (iv) by mp twice
(vi) $\vdash (\mathcal B \land \mathcal C) \rightarrow (\mathcal C \land \mathcal B)$ --- from (i) and (v) by DT.

Now that we have in place all needed "tools", we can proceed with the proof of our theorem.
Main proof
(i) $\mathcal A \rightarrow \mathcal B, \mathcal B \rightarrow \mathcal \lnot C  \vdash \mathcal A \rightarrow \mathcal \lnot C$ --- from Coroll.1.10(a)
(ii) $\mathcal A \rightarrow \mathcal B, \mathcal C \rightarrow \mathcal \lnot B  \vdash \mathcal C \rightarrow \lnot \mathcal A$ --- from (i) by Lemma A and Coroll.1.10(a) twice
(iii) $\mathcal A \rightarrow \mathcal B \vdash (\mathcal C \rightarrow \mathcal \lnot B)  \rightarrow (\mathcal C \rightarrow \lnot \mathcal A)$ --- from (ii) by DT
(iv) $\mathcal A \rightarrow \mathcal B \vdash \lnot (\mathcal C \rightarrow \lnot \mathcal A) \rightarrow \lnot (\mathcal C \rightarrow \mathcal \lnot B)$ --- from (iii) and Lemma 1.11(e) by mp
(v) $\mathcal A \rightarrow \mathcal B \vdash (\mathcal C \land \mathcal A) \rightarrow (\mathcal C \land \mathcal B)$ --- from (iv) by def of $\land$
(vi) $\vdash (\mathcal A \rightarrow \mathcal B) \rightarrow ((\mathcal C \land \mathcal A) \rightarrow (\mathcal C \land \mathcal B))$ --- from (v) by DT
(vii) $\vdash (\mathcal A \rightarrow \mathcal B) \rightarrow ((\mathcal A \land \mathcal C) \rightarrow (\mathcal B \land \mathcal C))$ --- from (vi) and Lemma F by Coroll 1.10(a) twice

(viii) $\vdash ((\mathcal A \rightarrow \mathcal B) \land (\mathcal A \land \mathcal C)) \rightarrow (\mathcal B \land \mathcal C)$ --- from (vii) by Lemma E.

Comment
It is of interest to compare the above system with J.Barkley Rosser, Logic for Mathematicians (1953 - Dover reprint).
The system has $\lnot$ and $\land$ as primitive and $\supset$ is defined through [see page 15] :

$P \supset Q =_{def}\lnot (P \land \lnot Q)$.

The axioms are [see page 56 - using the abbreviation] :

1) $\quad P \supset (P \land P)$
2) $\quad (P \land Q) \supset P$
3) $\quad (P \supset Q) \supset (\lnot (Q \land R) \supset \lnot (R \land P) )$

while modus ponens is the only rule of inference.
In a manner similar to Mendelson's book, Rosser proves [pages 61-62] :

Theorem IV.4.1 : $P \supset Q, Q \supset R \vdash \lnot (\lnot R \land P)$
Theorem IV.4.2 : $\vdash \lnot (\lnot P \land P)$
Theorem IV.4.3 : $\vdash \lnot \lnot P \supset P$

Then he proves [page 63] :

Theorem IV.4.7 : $\lnot P \supset \lnot Q \vdash Q \supset P$.

Finally, we have :

Theorem IV.4.8 : $P \supset Q \vdash (R \land P ) \supset (Q \land R)$

Proof
(i) $P \supset Q \vdash \lnot (Q \land R) \supset \lnot (R \land P)$ --- axiom 3
(ii) $\lnot (Q \land R) \supset \lnot (R \land P) \vdash (R \land P) \supset (Q \land R)$ --- from Th.IV.4.7 with $Q \land R$ for $P$ and $R \land P$ for $Q$
(iii) $P \supset Q \vdash (R \land P ) \supset (Q \land R)$ from (i) and (ii) by transitivity of $\vdash$.
To complete the proof of the formula in the OP's question, we need some more work :

to prove the commutativity of $\land$ [see Theorem IV.4.13, page 64],
to prove the Deduction Theorem [see Theorem IV.6.1, page 65].
Comment: Thank you, Mauro! You're the MVP!


Do tag synonyms show up somewhere?

Question: I suggested a tag synonym. I wonder if this shows up somewhere (other than in the linked page)? As far as I can tell, this does not appear in the review menu:

Not that we have too many of them, but I am interested to know.
Answer: The answer seems to be that is shows up on the tag synonym page, where people are supposed to go and vote on proposals. This means proposals aren't very visible (who sits staring at the tag synonym page?) This "feature" of the site is subject to various debates over on meta.stackexchange.com (e.g. here, or here, or here), but we can't do much here other than participate in that debate because these kinds of design things are set as network-level policy rather than at the site-level.
For now I have exercised moderator privilege and approved the synonym you proposed. If you see any other synonyms that are needed then you can propose them and post about them on meta.
Comment: Great, thanks!!

Do tag synonyms show up somewhere?


Does TMG Reporting hate the month of July?

Question: We have a ForeFront TMG 2010 SP1 installation. Reporting in the past has worked great.
However, I now need to find out why we've ripped through half our monthly quota in the first 6 days of the billing cycle, and TMG is failing me. The reports are generating OK, but there's just no data in them.
I can report just fine right up until the 1st of July. Any reports from the 1st of July just come back with no data.
I checked the logs inside MSDE and as far as I can tell the SQL data is all intact, but I know that TMG compiles these statistics nightly and stores them somewhere, but I can't find where to verify if they are working correctly.
Any ideas how to troubleshoot reporting in TMG 2010?
Comment: You Aussies and your quotas...I guess this is the type of fun we have to look forward to in the states... :-(
Comment: The pricing for the new FTTP services they're rolling out contry-wide over the next 10 years have just been released as well. Anyone feel like paying [$140/month for their internet](http://www.internode.on.net/residential/fibre_to_the_home/nbn_plans/)? Thought not.
Comment: I would gladly pay $140 for a 100/40 connection...if only it weren't for that pesky 200GB quota...Netflix alone would bankrupt me
Answer: So, it turns out the event log was filled with hundreds of SQL Server Reporting errors about invalid credentials and bad linked servers. I went through every troubleshooting step on several MSDN articles to reset permissions, reset passwords, match GUIDs for reporting services, and nothing fixed it.
I ended up having to export all the TMG firewall rules and restore a backup from a few weeks ago. It all works OK now, but obviously all the logs are gone. No idea what caused it.


problema com margem de div

Question: olá, estou fazendo um kanban e estou com dificuldade de deixar as divs alinhadas. A div que tem mais atividades fica certa, mas as demais ficam lá em baixo.
foto da tela
segue o código:
<!DOCTYPE html>

        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <link rel="stylesheet" href="../static/css/kanban.css">
        <title>Kanban</title>

Segunda

Terça

Quarta

Quinta

Sexta

Bloqueio

Concluído

                            {% for tarefa in tarefas_list_col_1 %}

{{ tarefa.titulo }}

                                            {{ tarefa.tempo_previsto }}

                                            ...........................................

                                            {% for obs in tarefa.label %}

                                                        {{ obs }}

                                            {% endfor %}

                            {% endfor %}

                            {% for tarefa in tarefas_list_col_2 %}

{{ tarefa.titulo }}

                                            {{ tarefa.tempo_previsto }}

                                            ...........................................

                                            {% for obs in tarefa.label %}

                                                        {{ obs }}

                                            {% endfor %}

                            {% endfor %}

                            {% for tarefa in tarefas_list_col_3 %}

{{ tarefa.titulo }}

                                            {{ tarefa.tempo_previsto }}

                                            ...........................................

                                            {% for obs in tarefa.label %}

                                                        {{ obs }}

                                            {% endfor %}

                            {% endfor %}

                            {% for tarefa in tarefas_list_col_4 %}

{{ tarefa.titulo }}

                                            {{ tarefa.tempo_previsto }}

                                            ...........................................

                                            {% for obs in tarefa.label %}

                                                        {{ obs }}

                                            {% endfor %}

                            {% endfor %}

                            {% for tarefa in tarefas_list_col_5 %}

{{ tarefa.titulo }}

                                            {{ tarefa.tempo_previsto }}

                                            ...........................................

                                            {% for obs in tarefa.label %}

                                                        {{ obs }}

                                            {% endfor %}

                            {% endfor %}

                            {% for tarefa in tarefas_list_col_6 %}

{{ tarefa.titulo }}

                                            {{ tarefa.tempo_previsto }}

                                            ...........................................

                                            {% for obs in tarefa.label %}

                                                        {{ obs }}

                                            {% endfor %}

                            {% endfor %}

                            {% for tarefa in tarefas_list_col_7 %}

{{ tarefa.titulo }}

                                            {{ tarefa.tempo_previsto }}

                                            ...........................................

                                            {% for obs in tarefa.label %}

                                                        {{ obs }}

                                            {% endfor %}

                            {% endfor %}

segue o código do css:

div.container {
    height: 100%;
}
div.topo1 {
    width: 14%;
    display: inline-block;
    font-size: 20px;
    text-align: center;
    min-width:14%;
}
div.topo2 {
    width: 14%;
    display: inline-block;
    margin-right: 0vw;
    font-size: 20px;
    text-align: center;
    min-width:14%;
}
div.topo3 {
    width: 14%;
    display: inline-block;
    margin-right: 0vw;
    font-size: 20px;
    text-align: center;
    min-width:14%;
}
div.topo4 {
    width: 14%;
    display: inline-block;
    margin-right: 0vw;
    font-size: 20px;
    text-align: center;
    min-width:14%;
}
div.topo5 {
    width: 14%;
    display: inline-block;
    margin-right: 0vw;
    font-size: 20px;
    text-align: center;
    min-width:14%;
}
div.topo6 {
    width: 14%;
    display: inline-block;
    margin-right: 0vw;
    font-size: 20px;
    text-align: center;
    min-width:14%;
}
div.topo7 {
    width: 14%;
    display: inline-block;
    margin-right: 0vw;
    font-size: 20px;
    text-align: center;
    min-width:14%;
}
div.col1 {
    width: 14%;
    display: inline-block;
    min-width:14%;

}
div.col2 {
    width: 14%;
    display: inline-block;
    min-width:14%;

}
div.col3 {
    width: 14%;
    display: inline-block;
    min-width:14%;
}
div.col4 {
    width: 14%;
    display: inline-block;
    min-width:14%;
}
div.col5 {
    width: 14%;
    display: inline-block;
    min-width:14%;
}
div.col6 {
    width: 14%;
    display: inline-block;
    min-width:14%;
}
div.col7 {
    width: 14%;
    display: inline-block;
    min-width:14%;
}

Answer: Tens que adicionar a regra vertical-align para top.
vertical-align: top;

problema com margem de div


How to show that the condition of one hand predicts the condition of the other hand

Question: I have this kind of data:
subject    hand    condition
s01        left    1
s01        right   0
s02        left    2
s02        right   2
..         ..      ..

The condition is a variable that gets values between $0$ and $5$ and indicates severity of a certain medical diagnosis.
I would like to show that if there is a problem with the left hand then there is likely a problem with the right hand, too. In other words, I want to show that there is some kind of dependence between the conditions of the different hands.
What kind of statistical test can I use here? I guess it is some kind of paired test I am looking for?
Comment: Do you really want to predict the *right* hand as a function of the *left* hand, or do you just want to see if the two hands are correlated?
Comment: Just to see if the hands are correlated
Answer: I would simply reorganize your data so that each subject is in their own row (so-called 'wide-form') with the first column indicating the severity rating for their left hand and the second column indicating their right hand.  For example:
           left    right
s01        1       0
s02        2       2
..         ..      ..

Then you can simply correlate the two columns / variables.  Since your data are ordinal ratings, you could use the Spearman rank correlation.  (There are several other rank correlations you could use, but that is probably the simplest and most conventional.)  Your observed Spearman's rho can be tested against $\rho=0$ (no association).  In fact, standard statistical software should output the test automatically.
Comment: The Spearman rank correlation coefficient came out to be about $0.8$ for my data :) The sample size is near 20,000, so I can make a strong conclusion. Thank you sir!
Comment: You're welcome, @med. .8 is a strong association & would be significant even w/ fairly small N.
Answer: A way to measure this may be the intraclass correlation, which is the proportion of the total variance of the outcome that is explained by the common identifier (here, subject). In your problem, things are complicated by the condition being a categorical rather than a continuous variable. So what I would do is to fit a multilevel/mixed model with an ordinal probit link, say, and compute ICC as variance of the random effects / (variance of the random effects + variance of the residuals) where the latter variance is one for the probit link.
More discussion can probably be found in this post.
Comment: I can't judge how this answer stands compared to what was suggested by @gung but it sounds too difficult for my level. Hence, I accepted the other answer.
Comment: No problem. I think @gung's answer points to the same idea, basically, although differently executed.


Tirar screenshot no meio do vídeo ffmpeg / ffprobe?

Question: Eu gostaria que o tempo em que a thumb fosse gerada correspondesse a 50% do tempo do episódio com ffmpeg estou usando esse código
<code>$ffmpeg -ss 00:00:18 -i $video -vf scale=800:-1 -vframes 1 $output
</code>
Como faço para no lugar de 00:00:18, ser o tempo exato no meio do video?
Answer: Para pegar um frame no segundo 18:
<code>ffmpeg -ss 18 -i video.mp4 -vframes 1 -f image2 frame.jpg
</code>
Comment: Se precisar salvar em um tamanho diferente adicione o parâmetro -s com a resolução desejada:

`ffmpeg -ss 18 -i video.mp4 -vframes 1 -s 320x240 -f image2 frame.jpg`


Triangle inequality for distance between parts

Question: Let $(X,d)$ be a metric space, $A,B$ be arbitrary non empty subsets of $X$. Define $d(A,B)=\inf_{x\in{A},y\in{B}}{d(x,y)}$. Does this new function on$[2^X\setminus\emptyset]^2$ satisfy the triangle inequality? (Obviously it is not a distance, since for any proper subset $A\subset X$, $d(X,X\setminus A)=0$, but $X\neq X \setminus A$).
It seems to me that since $\forall a \in A, \forall b \in B, \forall c \in C, d(a,c) \leq d(a,b)+d(b,c)$ by the triangle inequality, $$\inf_{a\in A, b\in B,c\in C}{d(a,b)+d(b,c)}\geq \inf_{a\in A, b \in B}{d(a,c)}$$ and so $d(A,C)\leq d(A,B)+d(B,C)$, but I am not sure I am not missing something.
EDIT: I have a counterexample, so my reasoning must be wrong, but what step is illegitemate here?(Consider the boundary of a square in $\mathbb{R}^2$, let $A$ be the left edge, $B$ the bottom and $C$ the right. Then $d(A,C)>0$ but $d(A,B)+d(B,C)=0$.)
Comment: Often distances like this are defined on compact subsets instead of all subsets.  It makes certain things cleaner.
Comment: Why can you use the same $b$ in both distances?
Answer: In your proof, you use the same $b\in B$ for both distances on the LHS.  This is not necessarily what happens.
Observe that
$$
d(A,B)+d(B,C)=\inf_{a\in A,b\in B}d(a,b)+\inf_{b'\in B,c\in C}d(b',c)\leq \inf_{a\in A,b\in B,c\in C}d(a,b)+d(b,c).
$$
The inequality shows up because the condition that $b=b'$ is more restrictive.  Therefore, the inequality doesn't work as stated.
In fact, suppose that $A$ and $C$ are disjoint sets whose distance between them is positive and $B=X\setminus (A\cup C)$.  Then $d(A,C)>0$, $d(A,B)=0$, and $d(B,C)=0$.  This describes a counterexample.


My app has successfully been installed on Android, but crashes as soon as it loads

Question: My apk is successfully pushed onto my Android device which is a Huawei Y6. My ant build is successful, as is my ndk-build. When i press my apps icon a black screen is loaded onto the phone. This lasts a few seconds before crashing. Here is a copy of my AndroidManifest.xml
<code>  <?xml version="1.0" encoding="utf-8"?>

  <manifest xmlns:android="http://schemas.android.com/apk/res/android"
            package="com.tutorial.game"
            android:versionCode="1"
            android:versionName="1.0"
            android:installLocation="auto">

  <!-- Android 2.3.3 -->
  <uses-sdk android:minSdkVersion="19" android:targetSdkVersion="25" />

  <!-- OpenGL ES 3.0 -->
  <uses-feature android:glEsVersion="0x00030000" />

  <!-- Allow writing to external storage -->
  <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

<application android:label="@string/app_name"
             android:icon="@drawable/ic_launcher"
             android:allowBackup="true"
             android:theme="@android:style/Theme.NoTitleBar.Fullscreen"
             android:debuggable="true"
             android:hardwareAccelerated="true" >
    <activity android:name="HelloSDL2Activity"
              android:theme="@android:style/Theme.NoTitleBar.Fullscreen"
                    android:configChanges="orientation|keyboard|keyboardHidden|screenLayout"
              android:screenOrientation="sensorLandscape"
              android:launchMode="singleTask" android:hardwareAccelerated="true" android:enabled="true">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>

     </activity>
  </application>

</manifest>
</code>
I ran this from the command line to create a logfile:
<code>adb logcat -V long *:W *:E *:F > log.txt
</code>
and here is a snippet of what was logged:
<code>  [ 03-31 20:32:36.129   820:28542 W/ActivityManager ]

  Force finishing activity 1 com.tutorial.game/.HelloSDL2Activity

  [ 03-31 20:32:36.239   820:28542 W/ActivityManager ]

  Exception thrown during pause

  android.os.TransactionTooLargeException

at android.os.BinderProxy.transactNative(Native Method)

at android.os.BinderProxy.transact(Binder.java:496)

at android.app.ApplicationThreadProxy.schedulePauseActivity(ApplicationThreadNative.java:715)

at com.android.server.am.ActivityStack.startPausingLocked(ActivityStack.java:1012)

at com.android.server.am.ActivityStack.finishActivityLocked(ActivityStack.java:3393)

at com.android.server.am.ActivityStack.finishTopRunningActivityLocked(ActivityStack.java:3223)

at com.android.server.am.ActivityStackSupervisor.finishTopRunningActivityLocked(ActivityStackSupervisor.java:3026)

at com.android.server.am.ActivityManagerService.handleAppCrashLocked(ActivityManagerService.java:12440)

at com.android.server.am.ActivityManagerService.makeAppCrashingLocked(ActivityManagerService.java:12337)

at com.android.server.am.ActivityManagerService.crashApplication(ActivityManagerService.java:13066)

at com.android.server.am.ActivityManagerService.handleApplicationCrashInner(ActivityManagerService.java:12547)

at com.android.server.am.NativeCrashListener$NativeCrashReporter.run(NativeCrashListener.java:86)
</code>
Can anyone make sense of any of this. I've been searching Google for how to understand the logfile messages, but with little success.
Here is another snippet from the logfile:
<code> [ 03-31 20:37:05.049   820:29426 W/ActivityManager ]

 Exception thrown during pause

android.os.DeadObjectException

at android.os.BinderProxy.transactNative(Native Method)

at android.os.BinderProxy.transact(Binder.java:496)

at android.app.ApplicationThreadProxy.schedulePauseActivity(ApplicationThreadNative.java:715)

at com.android.server.am.ActivityStack.startPausingLocked(ActivityStack.java:1012)

at com.android.server.am.ActivityStack.finishActivityLocked(ActivityStack.java:3393)

at com.android.server.am.ActivityStack.finishTopRunningActivityLocked(ActivityStack.java:3223)

at com.android.server.am.ActivityStackSupervisor.finishTopRunningActivityLocked(ActivityStackSupervisor.java:3026)

at com.android.server.am.ActivityManagerService.handleAppCrashLocked(ActivityManagerService.java:12440)

at com.android.server.am.ActivityManagerService.makeAppCrashingLocked(ActivityManagerService.java:12337)

at com.android.server.am.ActivityManagerService.crashApplication(ActivityManagerService.java:13066)

at com.android.server.am.ActivityManagerService.handleApplicationCrashInner(ActivityManagerService.java:12547)

at com.android.server.am.NativeCrashListener$NativeCrashReporter.run(NativeCrashListener.java:86)
</code>
Comment: Have you tested the logic out on a PC where it will be easier to debug?
Comment: Transaction too large means you stuffed too much data into an Intent's Bundle.  But this looks more like a secondary crash log than the primary cause, are you sure there isn't more?
Comment: here is the link containing the rest of the log file http://www.filehosting.org/file/details/653849/game18.txt
Comment: I've debugged the application on the PC and everything runs fine. The only real problem is that the load time using Visual Studio is very slow. I'm attempting to optimize this. But even when i modify the program so that only one texture is loaded, it still crashes when I port it over to Android.
Comment: My texture file is 5.25mb and at the start of my program all textures are loaded and initialised. Could this be the problem?
Answer: You are getting TransactionTooLargeException which could be because you are trying to load 5.25mb of data.
Sharing data via intents/bundles uses binder whose maximum limit at an instance is 1mb.
You screen is getting black because you may be trying to do heavy tasks while application is getting created.
Comment: Ok. Is there a different way I could share this data, or would it be better if I used lazy_initialization to lessen the time and work needed to load my program?
Comment: The size of my apk that is pushed onto my android device is 12.87 mb. Could be the data that the binder is unable to cope with?
Answer: So the first bug that I've managed to solve is to do with the icon. icon.png is located in the drawable file which is in the jni folder. I inserted an icon that had dimensions 500 x 726 into this file. Now even though you get your image displayed as the icon on your Android device, this actually causes the app to crash - hence the black page being displayed. There are actually five sizes of launcher icon,
48 × 48 (mdpi)
72 × 72 (hdpi)
96 × 96 (xhdpi)
144 × 144 (xxhdpi)
192 × 192 (xxxhdpi)
512 × 512 (Google Play store)
Notice that both width and height have to be the same size. Anway having placed an icon with the correct dimensions in the drawable file causes my app to no longer crash out after a few seconds. It hasn't solved the entire problem however! More debugging to do.