Very special rational points on curves over number fields

Question: For some reason, I'm convinced  the answer to the following question should be (obviously) negative, but I can't come up with a good reason.
Does there exist a number field $K$, a smooth projective geometrically connected curve $X/K$ of genus $g\geq 2$ with a $K$-rational point $x$ such that, for any number field $L/K$, $x$ does not intersect $ X(L)$?
Let me make the last part of the question more precise. Firstly, let $\mathcal X$ be the minimal regular model of  $X$ over $O_K$. When I say that $x$ does not intersect $X(L)$ I mean that the intersection product  $(x,y)_{\mathcal X}$ on $\mathcal X$ equals zero for all $y\in X(L)-\{x\}$. (Here $x$ and $y$ also denote their Zariski closures in $\mathcal X$.)
I think it could happen that some $K$-rational point does not intersect any other $K$-rational point. Take for example  a curve with $X(K) = \{pt\}$. For some reason I do think that there should always be some (other) $L$-rational point which intersects this $K$-rational point.
Comment: What do you mean by intersection product of two horizontal curves on $\mathcal X$ ?
Comment: Let $D$ and $E$ be  horizontal divisors on $\mathcal X$ over $S=\mathrm{Spec} O_K$. Then $(D,E)$ is defined to be $\sum_{s\in \vert S\vert} i_s(D,E) \log \# k(s)$, where the sum runs over the closed points of $S$ and $i_s(D,E)$ is the local intersection multiplicity of $D$ and $E$ over $s$.
Answer: The answer is no (for any genus). Fix a closed point $s\in \mathrm{Spec}(O_K)$ such that $\mathcal X_s$ is smooth. Let $x_s$ be the intersection point of $\overline{\{ x\}}$ with the fiber $\mathcal X_s$. Look (Zariski) locally at $\mathcal X$ around $x_s$. Lift a generator of the maximal ideal of $O_{\mathcal{X}_s, x_s}$ to $O_{\mathcal X, x_s}$, then you get a horizontal curve in $\mathcal X\otimes O_{S,s}$ passing through $x_s$. Taking the Zariski closure of the horizontal curve in $\mathcal X$ then gives you a horizontal curve in $\mathcal X$ passing through $x_s$. Its intersection with $\overline{\{ x\}}$ is positive, and its generic fiber is a point of $X(\bar{K})$ hence of $X(L)$ for some finite extension $L/K$.
Finally, there are infinitely many local liftings of a given generator (just perturb a lifting by adding a multiple of the uniformizing element of $O_{S,s}$), so at least one of them will gives a horizontal curve different from $\overline{\{ x\}}$.
Comment: A "system of generators" of $m_{X_s,x_s}$ is just a "generator" in this case, right? I thought the local ring of $X_s$ at $x_s$ would be a dvr as $x_s$ is smooth on $\mathcal X_s$. As a not very important side question, I just starting  wondering whether this lifting could be done in some "almost uniform" sense for all curves $X$ over $K$ of fixed genus $g$ (and maybe some "extra fixed data"). For example, could one control the degree of the extension $L/K$ in terms of this data? Do different local liftings give rise to bigger and bigger extensions?
Comment: @Harry, yes I will correct the answer. For the second part of your question, it is easy to have extension $L/K$ of big degree. I don't know how to get small extensions except for local henselian DVR.
Comment: Yeah, I also soon realized it is easy to obtain $L/K$ of arbitrary big degree. This is already clear with the zero section of $\mathbf{P}^1_{\mathbf{Z}}$. But, I'm actually very interested in knowing how to choose a rational point with "controlled" degree even in the henselian case. Naive question: if we can control $[L:K]$ for henselian local dvr's, then wouldn't we be able to also do it for local dvr's by taking their henseliazation?
Comment: @Harry, in the henselian case, one can take $L=K$. Indeed, $\mathcal X$ is Zariski locally around $x_s$ étale over $\mathbb A^1_{O_K}$. Pull-back any section of $\mathbb A^1_{O_K}$ passing through the origin of the special fiber will give a section of $\mathcal X$ passing through $x_s$ (because $O_K$ is henselian). But this will not give control in the general case because in the henseliazation, there may be algebraic extensions of big degrees.


Putting the dir_id using boxr package in R

Question: I am trying to setup the working directory-using the url-"https:\..."
Code:
<code>box_setwd(url)

Error:-
Error in box_id(dir_id) :
box.com API ids must be (coercible to) 64-bit integers.
</code>
I am exploring bit64 package meanwhile it will be great to have a workaround.
I hope the details are enough.
Comment: I could solve the problem from the box_ls() documentation- let me know the next step
Answer: the dir and other ids pertaining to the boxr commands are the numeric extensions in  the url- it's available in the documentation


Two methods of bootstrap significance tests

Question: Using bootstrap I calculate p values of significance tests using two methods:

resampling under the null hypothesis and counting the outcomes at least as extreme as the outcome coming from the original data
resampling under the alternative hypothesis and counting the outcomes at least as distant from the original outcome as the value corresponding to the null hypothesis

I believe that the 1st approach is entirely correct as it follows the definition of a p value. I'm less sure about the second, but it usually gives very similar results and reminds me a Wald test.
Am I right? Are both methods correct? Are they identical (for large samples)?

Examples for the two methods (edits after DWin's questions and Erik's answer):

Example 1. Let's construct a bootstrap test similar to the two sample T test.
Method 1 will resample from one sample (obtained by pooling the original two).
Method 2 will resample from both samples independently.
Example 2. Let's construct a bootstrap test of correlation between x₁…xₐ and y₁…yₐ. Method 1 will assume no correlation and resample allowing for (xₑ,yₔ) pairs where e≠ə.
Method 2 will compile a bootstrap sample of the original (x,y) pairs.
Example 3. Let's construct a bootstrap test to check if a coin is fair.
Method 1 will create random samples setting Pr(head)=Pr(tail)=½.
Method 2 will resample the sample of experimental head/tail values and compare the proportions to ½.
Comment: Which "alternative hypothesis"? In traditional Fisherian nomenclature there would not be just one alternative but an infinite family of alternatives. And how do you "sample under a hypothesis" for that matter? Sampling is done on the data. the hypothesis is about a parameter.
Comment: @DWin: Thanks, please see my example added to my question.
Answer: The first approach is classical and trustworthy but can not always be used. To get bootstrap samples assuming the null hypothesis you must either be willing to assume a theoretical distribution to hold (this is your first option) or to assume that your statistic of interest has the same distributionally shape when shifted to the null hypothesis (your second option). For example, under the usual assumption the t-distribution has the same shape when shifted to another mean. However, when changing the null frequency of 0.5 of a binomial distribution to 0.025 will also change the shape.
In my experience, otherwise in the case that you are willing to make these assumptions you often also have other options. In your example 1) where you seem to assume that both samples could have come from the same base population a permutation test would be better in my opinion.
There is another option (which you seems to be your 2nd choice) which is based on bootstrap confidence intervals. Basically, this assumes that if your stated coverage holds that significance at a level of $\alpha$ is equivalent to the null hypothesis not being included in the $(1-\alpha)$-confidence interval. See for example, this question: What is the difference between confidence intervals and hypothesis testing?
This is a very flexible method and applicable for many tests. However, it is very critical to construct good bootstrap confidence intervals and not simply to use Wald-approximations or the percentile method. Some info is here: Bootstrap-based confidence interval
Comment: Nice answer. So the second option requires symmetricity too right? Assume the mean of your confidence interval is larger than 0 and you are considering H not to be that it is 0. Then, looking at where 0 is in your confidence interval is different from looking at how extreme is the mean value assuming H not (these are in two different directions, if you assume you are shifting the confidence interval).
Comment: @erik just started a bounty on a similar question - which is basically a long a windy version of the above comment - when can option 2 be used and under what conditions ? https://stats.stackexchange.com/questions/175659/non-parametric-bootstrap-p-values-vs-confidence-intervals


Multiple Developers, One Apache (with mod_perl)

Question: I have multiple developers on one server, each with their own copy of the same perl codebase checked out of SVN.
I want each developer to have their own subdomain pointing to their own copy of the codebase.
I tried putting PerlSwitches inside , but that didn't seem to work. e.g.

<VirtualHost dev1.devserver.com>
    PerlSwitches -I/home/dev1/www -w -T
    <Location /webapp/>
        SetHandler  perl-script
        PerlHandler WebApp::Handler
    </Location>
</VirtualHost>

<VirtualHost dev2.devserver.com>
    PerlSwitches -I/home/dev2/www -w -T
    <Location /webapp/>
        SetHandler  perl-script
        PerlHandler WebApp::Handler
    </Location>
</VirtualHost>

Thanks.
Comment: You need some other config command, ask in mod_perl mailing list
Answer: Try adding PerlOptions +Parent above the PerlSwitches directive...Should force it to allocate a new interpreter pool.
Link to mod_perl PerlOptions directive
Answer: Although this post is pretty old, I though to point out of few things in case someone comes across it while searching.  I'd consider mod_perl a production target (although I'd personally prefer fastcgi) NOT a good development environment for reasons pointed out above.  If you are starting a new Perl project you should consider building on top of Plack (http://plackperl.org/) or a modern framework such as Catalyst (http://www.catalystframework.org/) which is designed from the start to be developer friendly.
Good luck!
Answer: I don't think it can be done. mod_perl is an integral part of the apache process. You will probably need to setup two separate httpds.
It may be best to separate them for development purposes anyways.
Answer: You may need separate Apache installs as noted. You could use ip aliases, hostnames to give each dev an ip with an apache answering on default ports, or just bind the apaches to non-standard ports as best suits you.
You may be able to get somewhere using su exec, but I think that only works with CGI mode so it won't help you if you need mod_perl.


How do I access the Cognito UserPoolClient Secret in Lambda function?

Question: I have created Cognito UserPool and UserpoolClient via Resources in serverless.yml file like this -
CognitoUserPool:
  Type: AWS::Cognito::UserPool
  Properties:
    AccountRecoverySetting:
      RecoveryMechanisms:
        - Name: verified_email
          Priority: 2
    UserPoolName: ${self:provider.stage}-user-pool
    UsernameAttributes:
      - email
    MfaConfiguration: OFF
    Policies:
      PasswordPolicy:
        MinimumLength: 8
        RequireLowercase: True
        RequireNumbers: True
        RequireSymbols: True
        RequireUppercase: True

CognitoUserPoolClient:
  Type: AWS::Cognito::UserPoolClient
  Properties:
    ClientName: ${self:provider.stage}-user-pool-client
    UserPoolId:
      Ref: CognitoUserPool
    ExplicitAuthFlows:
      - ALLOW_USER_PASSWORD_AUTH
      - ALLOW_REFRESH_TOKEN_AUTH
    GenerateSecret: true

Now I can pass the Userpool and UserpoolClient as environment variables to the lambda functions like this -
my_function:
  package: {}
  handler:
  events:
    - http:
      path:<path>
      method: post
      cors: true
  environment:
    USER_POOL_ID: !Ref CognitoUserPool
    USER_POOL_CLIENT_ID: !Ref CognitoUserPoolClient

I can access these IDs in my code as -
USER_POOL_ID = os.environ['USER_POOL_ID']
USER_POOL_CLIENT_ID = os.environ['USER_POOL_CLIENT_ID']

I have printed the values and they are being printed correctly. However, UserpoolClient also generates one AppClient secret which I need to use while generating secret hash. How shall I access app client secret (UserpoolClient's secret) in my lambda?
Answer: Probably now what you hoped for, but you cannot export client secret in CloudFormation explicitly. Take a look at the return values from AWS::Cognito::UserPoolClient. There you can only get the client ID.
What you could do is to create the client in another CF template and either create there a custom resource to read the secret and output it, or have an intermediate step where you get this value with CLI and then pass it into serverless.
There is currently no other option.


Input não acompanha o tamanho da col-md-8

Question: Estou treinando na criação de forms, e estou fazendo uso de bootstrap nele, principalmente das
 e
. Porém, quando fui colocar apenas dois elementos na mesma linha, respectivamente e` o campo de input do primeiro item não acompanhou o tamanho da coluna, deixando assim um espaço em branco entre os dois campos. Como faço pra que ele aumente? tentei aplicar css somente no id do campo e não resultou em alteração.
Abaixo o código que estou usando na row:

        Nome Completo

        <input id="fullname" type="text">

        Idade

        <input id="age" type="number">

E links adicionados externamente:
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">

<link href='https://fonts.googleapis.com/css?family=Lato:300,400,700' rel='stylesheet' type='text/css'>

<link href='custom.css' rel='stylesheet' type='text/css'>

Comment: Natã, talvez você possa aumentar o 'padding' ou a 'margin' da sua div. De qualquer forma seria melhor você expor um exemplo mais sólido do seu código para que as respostas sejam melhores.
Comment: Otávio, adicionei a parte de código que estou usando na row, acha que seria o bastante ou coloco o form por completo?
Answer: Você não precisa adicionar um estilo customizado, como o @hugo indicou, basta adicionar a classe form-control e o próprio Bootstrap vai aplicar.

<link rel="stylesheet" type="text/css" media="screen" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" />

                Nome Completo

                <input id="fullname" class="form-control" type="text">

                Idade

                <input id="age" class="form-control" type="number">

Comment: Só lembrando que o form-control vem com diversas outras classes que talvez não seja interessantes para o form que eles está construindo, principalmente se for um form customizado dentro do BS... Acho que talvez o melhor seja usar a classe w-100 nesse caso como coloquei no edite.
Comment: Mas levando em conta que o AP especificou que está treinando forms com BS, acho que é mais provável que `.form-control` seja a resposta mais sensata neste caso.
Answer: Vc pode simplesmente colocar 100% de largura nos inputs, assim eles ocupam o tamanho inteiro da coluna. (eu coloquei o css direto para todos os inputs, vc vc pode criar uma classe mais específica para isso, aqui foi só um exemplo)
Ou usar a classe w-100 que é uma classe original do Bootstrap 4 e deixa o elemento com width: 100% (usei essa classe no segundo input como exemplo)
Exiba em "Página toda" para ver como fica a resposividade

    input:first-of-type {
        width: 100%;
    }
<link rel="stylesheet" type="text/css" media="screen" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" />

                Nome Completo

                <input id="fullname" type="text">

                Idade

                <input id="age" class="w-100" type="number">


.flac file with google cloud speech API fails

Question: I've successfully run this nodejs demo from my local machine with the supplied .raw file. Now I would like to use my own file, which started as a .wav file which I converted using the following sox command (as per step 3 of the google speech troubleshoot page):
sox resources/my-audio.wav --channels=1 --bits=16 --rate=16000 --endian=little resources/my-audio.flac

However I am still getting an empty response from google (no transcript, no error) when I try with my-audio.flac. I can play the flac file just fine on my machine.
Any suggestions?
Answer: Figured it out... turns out the sox command to convert the wav on the support page isn't quite right. Here is the command that worked for me:
sox resources/my-audio.wav \
--channels=1 \
--bits=16 \
--rate=16000 \
--encoding=signed-integer \
--endian=little resources/my-audio.raw

The two key differences with my original command were (1) add the --encoding=signed-integer (thanks to this) and (2) use the .raw extension on the output filename.


Como eu posso pegar o SerialNumber da BIOS

Question: Estou pesquisando e não consigo encontrar uma função em VB6 para buscar o SerialNumber da BIOS da maquina rodando o sistema.
Alguém pode me ajudar?
Answer: <code>Option Explicit

Private m_mainWmi As Object
Private m_deviceLists As Collection

Private Function GetMainWMIObject() As Object
  On Error GoTo eh
  If m_mainWmi Is Nothing Then
    Set m_mainWmi = GetObject("WinMgmts:")
  End If
  Set GetMainWMIObject = m_mainWmi
  Exit Function
eh:
  Set GetMainWMIObject = Nothing
End Function

Public Function WmiIsAvailable() As Boolean
  WmiIsAvailable = CBool(Not GetMainWMIObject Is Nothing)
End Function

Public Function GetWmiDeviceSingleValue(ByVal WmiClass As String, ByVal WmiProperty As String) As String
  On Error GoTo done
  Dim result As String

  Dim wmiclassObjList As Object
  Set wmiclassObjList = GetWmiDeviceList(WmiClass)
  Dim wmiclassObj As Object
  For Each wmiclassObj In wmiclassObjList
    result = CallByName(wmiclassObj, WmiProperty, VbGet)
    Exit For
  Next

done:
  GetWmiDeviceSingleValue = Trim(result)
End Function

Public Function GetWmiDeviceList(ByVal WmiClass As String) As Object
  If m_deviceLists Is Nothing Then
    Set m_deviceLists = New Collection
  End If

  On Error GoTo fetchNew

  Set GetWmiDeviceList = m_deviceLists.Item(WmiClass)
  Exit Function

fetchNew:
  Dim devList As Object
  Set devList = GetWmiDeviceListInternal(WmiClass)
  If Not devList Is Nothing Then
    Call m_deviceLists.Add(devList, WmiClass)
  End If
  Set GetWmiDeviceList = devList
End Function

Private Function GetWmiDeviceListInternal(ByVal WmiClass As String) As Object
  On Error GoTo eh
  Set GetWmiDeviceListInternal = GetMainWMIObject.Instancesof(WmiClass)
  Exit Function
eh:
  Set GetWmiDeviceListInternal = Nothing
End Function

Private Sub Form_Load()

  Dim CPU As String
  CPU = GetWmiDeviceSingleValue("Win32_Processor", "ProcessorID")
  Text1.Text = CPU

  Dim BIOS As String
  BIOS = GetWmiDeviceSingleValue("Win32_BIOS", "SerialNumber")
  Text2.Text = BIOS

End Sub
</code>
Comment: Na resposta anterior eu coloquei pra capturar o drive. Falha nossa. Agora esse é pra bios mesmo.
Comment: Ok. vlw obrigado.


Message could not be send to a azure cloud message queue

Question: I currently trying to send message to a azure message queue from a company server, but seem to have issues with confirming that the message is received on azure.
Nobody is consuming the message, so it should be placed in the "dead message queue".
Messages that I send from the server does not increment that counter. Message send from a VM does increment the counter?
What could be blocking this? Any way to debug the issue.
None of my exceptions are being triggered..
Beisdes this, I noticed my messages are being received in the dead letter queue and not active message queue.
Nothings is consuming the message, but all azure queue examples I have seen so far mentions that the active message queue should be incremented?
The server does have a proxy for web access, but shoudl that be used aswell for this type of connection?
what is the difference between those two?
I added the stacktrace message:
The process failed: Microsoft.Azure.ServiceBus.ServiceBusCommunicationException: No connection could be made because the target machine actively refused it ErrorCode: ConnectionRefused ---> System.Net.Sockets.SocketException: No connection could be made because the target machine actively refused it

but my check for whether the connection isclosed, always returns false.
Comment: Have you checked that your on prem server can actually reach the queue and is not blocked by your firewall?
Comment: How do I do that..
In the code

I check whether !program.Azureclient.IsClosed

Which returns true.
Answer: From what I've read, I think Sam Cogan in the comments is right.  I think you need to open the appropriate ports to allow Service Bus to communicate.
The article below lists Open Port Requirements:
https://blogs.msdn.microsoft.com/servicebus/2017/11/07/open-port-requirements-and-ip-address-whitelisting/

Azure Service Bus requires the use of TLS at all times.
It supports connections over TCP port 5671 and over TCP port 5672. The server immediately offers a mandatory upgrade to TLS using the AMQP-prescribed model. The AMQP WebSockets binding creates a tunnel over TCP port 443 that is then equivalent to AMQP 5671 connections.
Both modern (.Net Standard and Java) clients use AMQP, hence the above guidance applies.
The older .NET library has a custom, WCF based protocol that used TCP and port 9354 (called SBMP, Service Bus Messaging Protocol).
If you solely use our rest API you may be able to open only port 443.

TL;DR
Try opening outbound TCP ports 5671, 5672 on your firewall, if that doesn't work, try to open port 9354 instead.
P.S.
Here are links as to how you can open ports on your firewalls:

Linux: https://www.codero.com/knowledge-base/content/24/431/en/how-to-open-_-close-ports-in-your-firewall-on-linux-iptables-firewalld-ufw.html
Windows server (pick outbound instead of inbound like this link says):https://www.vultr.com/docs/how-to-open-a-port-in-windows-firewall-on-windows-server-2012

And also here's a link to reasons why messages might be automatically sent to the dead letter queue:
https://docs.microsoft.com/en-us/azure/service-bus-messaging/service-bus-dead-letter-queues#moving-messages-to-the-dlq

HeaderSizeExceeded
exception.GetType().Name
TTLExpiredException
Session id is null.
MaxTransferHopCountExceeded
Specified by application


change value in react with different files

Question: So I have this react file structure
app/
  |- assets/
  |   |-pages/
  |   |   |-desktop.jsx
  |   |   |-mobile.jsx
  |   |-components.jsx
  |-index.jsx

In the index.jsx I require desktop.jsx in desktop.jsx I require components.jsx but there is a part in components.jsx that needs to change the state in a index.jsx class.
so its like this:
index.jsx -> desktop.jsx -> components.jsx
so how do I change the state of a class in index.jsx with a function that is in components.jsx
thanks for helping!
Comment: The easiest way would be to pass down a function from `index.jsx` to `desktop.jsx` then to `components.jsx` via the props. Call that in `components.jsx` and then the function can change the state which will propagate down.
Comment: Read [Thinking in React](https://reactjs.org/docs/thinking-in-react.html) and [Lifting State Up](https://reactjs.org/docs/lifting-state-up.html) in the React documentation.
Comment: Yes @Joe I understand that but how does that part work that i can communicate from components.jsx to index.jsx?
Comment: @JoeClay yeah I understand those basics but the problem is over multiple files
Answer: With React, the thing to remember is props down, events up. This means to pass values from a parent component to a child, do it via props; to pass values from a child back to a parent, use an event.
In your case, you have multiple "layers" of components, so you'll have to do it in multiple steps. For example:
<Index val="the value to pass" />

Somewhere in the Index component render method, you have the following line:
<Desktop val={this.props.val} />

Thus, the original value is now accessible in the Desktop component. And like the Index component, the Desktop component render method includes:
<Components val={this.props.val} />

To pass the value back up the chain of components requires events and event handlers. For example:
Imagine that the Index component has a method onValChange which handles a change to the value. Then we render the child components like this:
// in the index component, a change will call the index component
// onValChange method
<Desktop val={this.props.val} onValChange={this.onValChange} />

// in the desktop component, a change will call the props.onValChange
// method (which is the same one passed in the line above)
<Component val={this.props.val} onValChange={this.props.onValChange} />


Finding event handlers in source trees

Question: So, I'm trying to implement a looping mode in the totem movie player. I would like to do this by adding a checkbox under "Edit" that turns looping on.
I'm trying to figure out what code gets called when "Edit" and the "Shuffle Mode" option under it is clicked. Is there any easy way to find where the appropriate event handler is?
My usual method of code reading (stepping through it with the debugger) didn't work because this is a GUI program, and as soon as you get to the main loop it doesn't stop until there's a breakpoint, and where to put the breakpoints is basically what I'm trying to find out.
I've been using Netbeans for this, and I should note that I can't use Eclipse.
Thank you.
Answer: The UI for Totem and the callback names for each element defined in the GtkBuilder file, data/totem.ui.
http://git.gnome.org/browse/totem/tree/data/totem.ui
This file says that the handler for the "Shuffle Mode" action is shuffle_mode_action_callback. Then you can use grep:
grep -r shuffle_mode_action_callback totem-git/src
The result of this command indicates that this function is defined in src/totem-menu.c.

Finding event handlers in source trees


Show that $\lim_n \int_A f(nx)dx =\lambda(A) \frac1T \int_0^T f(t) dt$ for a measurable, bounded, T-periodic function.

Question: I found this exercice :
Let $f : \mathbb{R} \to \mathbb{R}$ a measurable bounded and T-periodic function. Show that for every bounded borel set A, $$\lim_n \int_A f(nx)dx =\lambda(A) \frac1T \int_0^T f(t) dt$$
I can prove it when A is an bounded interval of $\mathbb{R}$. But, I can't prove the general result.
My first idea was to use that the borel set is generated by open intervals. I proved that the null set satifies the property, if $A$ and $B$ satifies the property then $A\setminus B$ also, if $(A_n)$ satifies the property and $A_n\subset A_{n+1}$ then $\cup A_n$ also. But, I wasn't able to prove that is $A_1, ..., A_N$ satisfies the property then $\cap_{i=1}^N A_n$ also.
My second idea was to use the definition of the Lebesgue measure as the infimum of lenght of covering by open intervals. But I obtained only one inequality.
Answer: Hint: Given $\epsilon >0$ there exists a set $B$ which is  a finite disjoint union of intervals of the type $(a,b]$ with $\int |\chi_a-\chi_b| <\epsilon$. Ref: Theorem D, p. 56 of Measure Theory by P R Halmos.


Working up to Andy Mckee's "Blue Liquid"

Question: Recently I discovered "Blue Liquid" by Andy Mckee while listening to music on Spotify. For whatever reason, I instantly loved the song and decided that I wanted to be able to play it before I died.
I have been playing guitar for over six years, but have only recently (over the past year) developed an interest in fingerstyle playing and percussive techniques and have always felt overwhelmed and unsure of where to start and where to look when it comes to finding resources on advanced guitar playing.
So I'd kind of been putting it off. When I heard "Blue Liquid", however, I decided it was time to get going and move forward in my journey as a guitar player.

What are the exact names of some of the techniques or types of techniques used in the song?
What are some good, well-written, and thorough method books or method book series that cover those skills?

I took private lessons for a while many years ago, then stopped due to high school time demands. Now that I am going to college, I'd love to find a teacher and start lessons again, but I can't afford them.
Answer: I don't think there is a any "technical" terms that is used for percussive fingerstyle as they usually end up being nothing more than descriptors of what the guitarist doing (from my knowledge). Case in point, this individual points out the following techniques:

String Slap, Thump and thumb, Thump and nails, Nail Knocks, Drum and Strum, the Tap and Slap.

However, someone else might call the "slap and tap" polyphonic tapping that includes a rhythmic component.
That being said, my experience playing percussive guitar has been a lot of "monkey see monkey do" logic so perhaps I am overlooking terms.
As for book I have never used any for this particular style of guitar, but apparently according to one of my friends this book was quite useful for her.
Beyond this if your looking for a place to start and assuming your quite good with a more "regular" finger picking techniques,  I would look at polyphonic tapping as that can be quite difficult learn especially if you never played piano if you did you'll probably find this somewhat easier.
Lastly, this should go without saying, but play slow as learning this style of guitar requires a lot of coordination.


Cannot make seleniumbase load with an existed chromium profile

Question: Using the code below:
    try:
        with SB(headed=True,uc=True,user_data_dir='path/to/Profile 1',browser='chrome') as sb:
           sb.open('hocalhost:1111')
           sb.sleep(2)
    except:
        print('Some error occur!!')

Expecting to see seleniumbase do the test on the profile i just speciffed. But it just create a new profile under the directory i passed. Info from chrome://version

Profile Path   path/to/Profile 1/Default

and do the test there.
I've tried to use chromium_arg='--profile-directory='Profile 1' and also not working.
What can i do to solve the problem? Thanks
Answer: There are a few things I'm seeing. Looks like you misspelled localhost in your open() line. When using user_data_dir with uc=True, there may be an issue if your user_data_dir contains spaces in the file path (this is especially true if running with PyInstaller). If that didn't help, use either uc or user_data_dir, but not both together, as undetected-chromedriver has multiple open issues with setting the user_data_dir, as seen here: https://github.com/search?q=repo%3Aultrafunkamsterdam%2Fundetected-chromedriver+user_data_dir&type=issues, which includes the issue with the profile directory getting overwritten when setting a custom one: https://github.com/ultrafunkamsterdam/undetected-chromedriver/issues/1232


Facebook URL schemes on a mobile website, open app if its installed, otherwise go to the webpage

Question: I am creating a hybrid desktop/mobile website that all share the same pages, aka I do not have two separate URLs for desktop and mobile.  I am trying to get Facebook links to open in the native Facebook app, if possible, otherwise go to the regular URL.  Is there something out there in the Facebook schemes that handles that automatically?
Basically, if mobile app is not installed or if the user is on a desktop, go here:  https://www.facebook.com/pages/[pageid]
If mobile app is installed, then go here:
fb://page/[pageid]
Comment: iOS or Android or both?
Comment: Both.  It's not an "app" I'm developing, it's an HTML website (still figuring out whether the person I'm doing it for supports JDK or PHP).I've tested fb://page/[pageid] as a regular href hyperlink on both iOS and Android browsers, they all open the Facebook app if it is installed.  The problem is desktop browsers or if they don't have the app installed.
Comment: Is there any difference between the Fans Page and Personal Page?
Answer: A Simple way would be CSS Media Queries.
Show the fb:// link for small device widths. and a regular http:// link for larger screen sizes.
EDIT
Clicky
Clicky

Then using CSS Media queries hide one of the links depending on the size of the screen.
UPDATE
Instead of using CSS a more satisfying user experience can be created with javascript by attempting to open the deep link URL directly after opening the HTTP URL after X seconds in a timeout.
setTimeout(function () { window.location = "https://www.facebook.com"; }, 25);
window.location = "fb://";

The HTTP URL will always load, but in the case that deep links are not available,  attempting to open one will silently fail, falling back to the web version.
Source: https://www.quora.com/How-does-Bitlys-Deep-Linking-detect-if-the-user-already-has-the-app-installed
Comment: How can a CSS media query change the href of a hyperlink?  I've never seen that done before.
Comment: Is it possible to use the "fb:" syntax to open specific post? I have been unable to make it work
Comment: @Niko Please see the update that I posted, it should help you out. Not sure about linking to specific posts.
Comment: @ConnorFinnMcKelvey, this code works very well, but can you please elaborate how this works. As I tried this for my application named 'test' which is already installed on mobile. So how can I open my 'test'. I don't have any kinda knowledge about this, plz help.
Comment: @ConnorFinnMcKelvey I tried your solution but facebook official app got crashed with this code snipeet. any clue ?
Comment: In June 2020, Safari does not work with the updated method. It throws a "Safari cannot open the page because the address is invalid" and does not fallback properly to the browser URL.
Answer: You can use navigation to check if the mobile has app installed if not you can simply use a link
 onShare() {
    const title = 'Title';
    const url = 'https://www.facebook.com/';
    const text = "Share";
    if (navigator.share) {
      navigator
        .share({ title: `${title}`, url: `${url}`,text: `${text}`})
        .then(() => {
          console.log('Shared');
        })
        .catch(console.error);
    } else {
      window.location.replace(
        `https://www.facebook.com/sharer.php?u=${url.trim()}&quote=${text}`
      );
    }
  } //onShare ends here

You might see a dialog box on windows, to override that behavior we can update the "if statement" as follows
...
if (navigator.share && !navigator.userAgent.includes('Win')) {
...


Best Practice for Page Efficiency

Question: I was wondering if anyone knew which of the following is most efficient (or an alternative if applicable). The idea is to create a header containing information for a specific node. This assumes all other variables, such as caching being equal. This would be for a Drupal 7 install.
i) Create a block, restricting it to the specific node
or
ii) Create a custom tpl with the information hard-coded (I know it's a Drupal no-no)
Using a block is simpler to deal with and update for obvious reasons, but I was curious if there was any significant difference in page rendering time, or resources used, etc.
Answer: A custom template always results in better performance.
Views and blocks are stored in the database which need to be queried and rendered first.
Whereas templates require less memory and cpu because the php can be executed directly.
When using a template you also have the advantage of SCMs like git or subversion.
The performance difference between templates and blocks won't be noticeable as soon as you enable caching on your site .
So what should you use? It is completely depending on the case.
If your header will be shown on multiple pages, i'd go with a template.
If you'll show it only on seperate pages (whitelisted urls), I'd go with the block.
Comment: In terms of use case there is also where the content comes from - is it user editable and if so where will the user edit it; and if it is only on certain pages, how are those pages determined - a set list of pages or something more dynamic; and other considerations depending on the requirements. Also, git/subversion are also relevant to blocks if you make your block in a module instead of via the UI.
Comment: @rooby - this assumes static, admin defined and rarely changing data. The block would be created via UI

Best Practice for Page Efficiency


Como calcular a diferença entre valores que estão na mesma coluna?

Question: Gostaria de saber se existe alguma forma de calcular a diferença entre valores que estão na mesma coluna. Por exemplo: tenho uma tabela com 2 campos: data e saldo. Preciso adicionar um novo campo, contendo a diferença de saldo de uma data para outra.
Dia        Saldo      Variação
------------------------------
01/12 ---  10 ------- 0
02/12 ---  30 ------- 20
03/12 ---  70 ------- 40
04/12 ---  80 ------- 10

Answer: Você pode fazer da seguinte maneira:
SELECT
    m.id,
    m.data,
    m.saldo,
    IFNULL(saldo - (SELECT mt.saldo FROM movimento mt WHERE mt.id < m.id ORDER BY mt.id DESC LIMIT 0,1), 0) AS variacao
FROM movimento m

Dá uma olhada no sqlfiddle.com
Comment: Pode usar até o próprio campo data para comparação e ordenação em vez de Id (que não aparece no exemplo e pode nem ser sequencial). Bacana a solução. +1
Comment: @samuelgp Exatamente do mesmo jeito - no comando apenas troque campo `id` pelo campo `dia`.
Comment: Com certeza, desde que haja apenas um movimento por data
Comment: Neste caso é apenas um registro por data mesmo. Muito obrigado! Só não entendi como resolver fazendo apenas a comparação entre datas, sem o uso de id.
Comment: Esse limit no sql server ficaria como ?
Answer: Conheço duas opções, você traz isso em uma consulta como em Calculo entre campos
SELECT ValorBoleto + TotalJuros AS Preco FROM fotoprodutos
ou este Fórmula em SQL (inglês)
SELECT
    name,
    black,
    yellow,
    white,
    qty_job
    (SUM(black) + SUM(yellow) + SUM(white)*0.4) / qty_job AS total
FROM counter
GROUP BY name;
Outra opção é você fazer isso via linguagem de programação. Quando você for salvar, você calcula o campo antes de preenchê-lo. Mas neste caso, precisaríamos de saber a linguagem de programação para ajudá-lo melhor.
Comment: Nesse caso específico precisa-se de um cálculo "entre linhas", e não "entre campos".
Comment: Diz-se campos, pois serão todas as linhas do campo, apesar do cálculo ser realizado linha a linha.
Comment: Então teria como você postar uma exemplo aqui no http://sqlfiddle.com/ ?


Android: i'm already delete my data, but in room still exists some data

Question: I have Boolean booleanCheckAvailabilityData to check availability data in my activity to  create add/remove favorite. then i create
dataFavoriteMovieById = favoriteMovieViewModel.getAllFavoriteMovieById(idMovie);
to get data by id. so i make conditional statement to check avaiability data then put the result to boolean and i use the boolean later to add or remove the favorite.
if (dataFavoriteMovieById == null) {
    booleanCheckAvailabilityData = false;
} else {
    booleanCheckAvailabilityData = true;
}

In the first run, it work. my dataFavoriteMovieById is null

But, after i add or remove favorite. it always always contains data (RoomTrackingLiveData).

How can i solve this...
my code link : https://github.com/komangss/Submission-Menjadi-Android-Developer-Expert/blob/master/app/src/main/java/com/dicoding/submissionmade2_1/activity/DetailMovieActivity.java
Answer: From what I can see in your code - getAllFavoriteMovieById works as expected. The thing is - you are using LiveData as a return type of getAllFavoriteMovieById thus it returns not the value itself but a LiveData wrapper. But if you will try to observe this LiveData object you will(presumably since I haven't seen relevant code) receive null instead of favourite value. The only correct place to assign value to your booleanCheckAvailabilityData inside this observer(depending on your DAO code of course).
favouriteMovieViewModel.getAllFavoriteMovieById().observe(this, Observer { data ->
        if (data == null) {
            booleanCheckAvailabilityData = false;
        } else {
            booleanCheckAvailabilityData = true;
        }
})

Something like that(once again it depends on your DAO code and getAllFavoriteMovieById implementation)
Hope it helps.
Comment: im already try this, and unfortunately, it cause **NullPointerException** in my boolean. if i remove the try catch it will error :  `Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void androidx.lifecycle.LiveData.observe(androidx.lifecycle.LifecycleOwner, androidx.lifecycle.Observer)' on a null object reference`
Answer: I played with your app (thanks for providing a github link) and here are my results.
Latest app version
Your latest implementation doesn't produce an NPE anymore since you use getAllFavoriteMovieById in a more consistent way. You no longer initialize a LiveData instance in FavoriteMovieRepository by yourself but delegate it to Room to do it for you. So, you won't get an NPE since Room will always create a list to return results. If there're no items, it will return an empty list. So, you can safely remove a try/catch here:
try {
    favoriteMovieViewModel.getAllFavoriteMovieById(idMovie).observe(this, new Observer<List<FavoriteMovie>>() {
        @Override
        public void onChanged(List<FavoriteMovie> favoriteMovies) {
            booleanCheckAvailabilityData = favoriteMovies.size() != 0;
        }
    });

} catch (NullPointerException e) {
    Log.d("ini bug nya", e.getMessage());
}

Original app version
In addition to what @Paul Ost said about how favoriteMovieViewModel should be used properly (by listening to it, not using it directly), I will explain why you actually had an NPE.
In that version, you were running into a NullPointerException because you returned the favoriteMovieById LiveData before it was actually initialized in your GetFavoriteMovieByIdAsyncTask.
So, here what was happening in detail. First, once your DetailMovieActivity had been created, favoriteMovieViewModel called getAllFavoriteMovieById() as below:
DetailMovieActivity.java
...
favoriteMovieViewModel = ViewModelProviders.of(this).get(FavoriteMovieViewModel.class);
dataFavoriteMovieById = favoriteMovieViewModel.getAllFavoriteMovieById(idMovie);
...

FavoriteMovieViewModel.java
FavoriteMovieViewModel instance, in turn, delegated the call to FavoriteMovieRepository instance as below:
public LiveData<List<FavoriteMovie>> getAllFavoriteMovieById(int idMovie) {
    return repository.getFavoriteMovieById(idMovie);
}

FavoriteMovieRepository.java
Finally, getFavoriteMovieById started a GetFavoriteMovieByIdAsyncTask and returned favoriteMovieById:
public LiveData<List<FavoriteMovie>> getFavoriteMovieById(int id_movie) {
    new GetFavoriteMovieByIdAsyncTask(favoriteMovieDao).execute(id_movie);
    return favoriteMovieById;
}

But that's wrong, since your favoriteMovieById was set to null by default, and so on the first run, you were always getting it.
Your AsyncTask was eventually setting a non-null value, but it was too late:
...
private static class GetFavoriteMovieByIdAsyncTask extends AsyncTask<Integer, Void, Void> {
  ...
    @Override
    protected Void doInBackground(Integer... integers) {
        FavoriteMovieRepository.favoriteMovieById = favoriteMovieDao.getFavoriteMovieById(integers[0]);
        return null;
    }
}
...

Answer: In ROOM Try Deleting the old TABLE before inserting the new data. In that case the old data will be deleted as we are deleting the old data


Terrain streaming in unity 3d

Question: I am making an open world game and i want to know if there is a way of doing terrain streaming ( loading the terrain into mamory only if the player is close to it ) without using the LoadLevelAdditiveAsync function . i am using free version so this function is not available to me .
Answer: Don't forget as long as your terrain patches together nicely, you can always Instantiate terrain prefabs at run time.
Depending on how proficient you are at it, you can also procedurally create terrain at run time as well.
Answer: You can do it, and there are different ways to do it. I figure the easiest way to do it (but definitely not the most memory friendly) would be to define your entire level in one scene with multiple small terrains, using the TerrainStitcher tool to deal with seams. Then you could parent all objects under each terrain to a single transform, and use Instantiate to create/destroy them at runtime (in another scene). There are tools that take this approach a bit further, like this one.
But remember that in general big terrains in Unity aren't memory friendly and will reduce your performance. When using an endless terrain, where you don't care about defining the terrain before runtime you can reuse a few terrain objects and simply reposition them, but if you're designing them first, there isn't too much you can do other than lowering terrain settings like Pixel Error, and limiting details and grass.

Terrain streaming in unity 3d


In longitudinal data, what can be gained from modelling "time" as a covariate?

Question: Imagine some data set where subjects $1, ..., K$ had a response $Y$ measured repeatedly over a period of time (say, 2000-2015).
Now, in order to study effects like "does the month of the measurement matter?", or "is there a trend over the years?", or "does the day of the week matter?", we can of course use these variables (month, year, weekday) as covariates with fixed effects. For example, "month" and "weekday" could be a factor, and "year" could be a continuous covariate with some slope parameter to be estimated.
However, online, I have found many examples of people suggesting that we also include a time $t$ variable which measures the continuous change in time, i.e., "days passed since the start of the experiment".
My question is, why? What is the use of such a variable? If there are some time effects, then they are going to be captured by the aforementioned fixed effects, no?
So what would be the point of complicating things by introducing a "days"-variable, which presumably does not matter too much in the determination of the response variable $Y$, and which also is not going to be a "nice" covariate, in the sense that there are probably going to be many days which has no responses (e.g., entire months during the 15 year period where the experiment was on a break, usually during the summer period).
Comment: A monotonically increasing series with equal steps as regressor = a linear trend. In this panel data setting perhaps you can include a dummy for each time step, otherwise this would be a very parsimonous way of modelling it if the data seems to exhibit a trend
Comment: Generally I keep the most granular time period you possibly can.  It's easy to make estimates to high level time frames if your model includes a more granular time variable, but the converse is impossible without strong assumptions.
Answer: There are data sets that require/can use deterministic trends using the counting numbers perhaps having multiple trends. There are other series (more frequent in my long experience) that require differencing and one or more steady state constants to deal with multiple trends. Only the data knows for sure which approach is appropriate which is why I favor software that tries both types and assesses the dominant approach. Of course empirically identified level shifts also need to be investigated as they often occlude trend detection.
There is an indeed an argument for day of the month variables as they can capture systematic activity for different days of the month such as the 1st , the 15th etc. To continue this thought we have often found series that a week-in-the-month variable was important suggesting identifiable within-month struture.
Humans and nature often act in systematic patterns and extracting that minimally sufficient structure to decompose the observed series to signal and noise without over-fitting.
All of which I speak ( lead and lag effects around holidays etc ) require one to identify and down-weight unusual values otherwise they cloud the model identification process


Successfully Install Artifactory RPM using Salt-Stack

Question: I am working on fully automating some things using Salt Stack. I am currently working on installing Artifactory v5.3.2 using a RPM via Salt Stack. I am able to get this to install and work properly but begin getting a false-positive error from salt stack.
Currently running on CentOS Linux release 7.3.1611 (Core) with a masterless salt stack (just for testing purposes) from here. According to Artifactory documentation; they recommend using yum to install the rpm package.  Installing Artifactory OSS from an RPM disribution.
I am aware of two salt-formula's for a similar use case but, these are over complicated for our needs. I attempted to post the two urls for them but don't have enough reputation for saltstack to allow me to do so.
After Downloading the rpm and placing it in the correct directory.. using this salt stack configuration does NOT work properly on the first attempt of an install:
jfrog-artifactory-oss.noarch:
  pkg.installed:
    - source: salt://path/conf/jfrog-artifactory-oss-5.3.2.rpm

returning an error message like so:
ID: jfrog-artifactory-oss.noarch
Function: pkg.installed
  Result: False
 Comment: Error occurred installing package(s). Additional info follows:`

         errors:
              - Running scope as unit run-2994.scope.
                Loaded plugins: fastestmirror
                Loading mirror speeds from cached hostfile
                 * base: mirror.steadfast.net
                 * epel: mirror.steadfast.net
                 * extras: repo.us.bigstepcloud.com
                 * updates: mirrors.lga7.us.voxel.net
                No package jfrog-artifactory-oss available.
                Error: Nothing to do
 Started: 15:51:12.374898
Duration: 11271.36 ms
 Changes:

Using this configuration for salt:
jfrog-artifactory-oss.noarch:
  cmd.run:
    - name: yum install -y /srv/salt/prod/path/conf/jfrog-artifactory-oss-5.3.2.rpm

Works the first time but, the second time running it using this format returns an error like so:
          stderr:
              Error: Nothing to do
          stdout:
              Loaded plugins: fastestmirror
              Examining /srv/salt/prod/path/conf/jfrog-artifactory-oss-5.3.2.rpm: jfrog-artifactory-oss-5.3.2-50047.noarch
              /srv/salt/prod/path/conf/jfrog-artifactory-oss-5.3.2.rpm: does not update installed package.

Now, not to make things confusing.. if I have artifactory installed, and I then revert back to the first method of installing this using the pkg.installed method, things work as expected returning a success message saying 'All specified packages are already installed'.
Typically this false positive is caused by not using the correct name of the package in the salt state file so running yum list installed returns jfrog-artifactory-oss.noarch ensuring I am using the correct naming in the salt state.
I am looking to have this work successfully regardless of if it is updating the package or not; without needing to over complicate our set up with the salt formulas provided.
Any help/advice would be greatly appreciated.
Comment: I think you should use `- sources` (in plural) as a parameter for the `pkg.installed`. Also the package name is probably `jfrog-artifactory-oss` without `.noarch`. Last part an architecture for the package which, if I remember correctly, is not a part of the package name.
Comment: So when using the `- sources` I get an error stating: Invalidly formatted 'sources' parameter. See minion log.. Which when checking the minion log appears to give the same error. Even with changing the name to `jfrog-artifactory-oss`
Comment: It just doesn't seem to make much of any sense that after using yum to install the rpm, the pkg.installed method returns the result expected. but, when using the pkg.installed method on the first attempt to install does not work at all.
Comment: I am also having this issue with correctly installing a java jdk. Curious if possibly being caused by not having a true salt master. Might need to spin up a master and do some testing that way.
Answer: Artifactory RPMs could be installed both using yum repository and rpm directly. Personally I would suggest using yum way as it makes future updates easier.
To answer your concern regarding using masterless setup - both options are fully functional in masterless as well as master-minion setups.
And one side-note. By default pkg.installed will try to use package manager native to your OS (yum/rpm in case of RedHat/CentOS). In most cases when installing package you should use it instead of calling yum or rpm directly.
Using yum
First thing we should do is to get .repo file holing information about yum repositories. Unfortunately, the one referred to in the documentation points to the repository with pro version of Artifactory. As we are interested in OSS - we should use a different one
To set it up we will first cook the .repo file with the following content:
[bintray--jfrog-artifactory-rpms]
name=bintray--jfrog-artifactory-rpms
baseurl=http://jfrog.bintray.com/artifactory-rpms
gpgcheck=0
repo_gpgcheck=0
enabled=1

Now we should use salt to configure yum to use this .repo file and install Artifactory from this repository. Assuming that yum config file is located in salt tree under files/jfrog-artifactory.repo, Salt configuration will look as follows:
/etc/yum.repos.d/artifactory.repo:
  file.managed:
    - source: salt://files/jfrog-artifactory.repo

jfrog-artifactory-oss:
  pkg.installed:
     - require:
       - file: /etc/yum.repos.d/artifactory.repo
     - fromrepo: bintray--jfrog-artifactory-rpms

The -fromrepo option will make sure that the package is being installed using specific yum repository just in case it might be available in others.
Using RPM
It is also possible to download Artifactory RPM directly to your Salt configuration and install it from there. To do this I've used the following RPM file: https://bintray.com/jfrog/artifactory-rpms/download_file?file_path=jfrog-artifactory-oss-5.3.2.rpm . Assuming the file is downloaded into files/jfrog-artifactory-oss-5.3.2.rpm of your Salt tree, the state installing this package will look as follows:
jfrog-package:
  pkg.installed:
    - sources:
      - jfrog-artifactory-oss: salt://files/jfrog-artifactory-oss-5.3.2.rpm

Please note, that -sources part is a list of key-value pairs, where key is the name of the package and value is the path to the RPM file. Top-level jfrog-package is just a label
Comment: This, is exactly what I needed. I had mis-used the `- sources` the first time you had suggested it. Thank you for the help!


Date value changed doesn't get updated in UI

Question: In a Table Grid, The data populated on Grid is JSON which I'm receiving it from another component. It also has input fields like text box and date which can be changed. Here in this case, when a date value is changed it gets updated in console but on UI. Please refer to code below:
const [startDate, setStartDate] = useState();

{colConfig[cIndex].data_type === "date" &&
   !colConfig[cIndex].cell_click_callback && (

   <DatePickerNew
   setRequesterDate={(e) =>
   dateCallback({dateVal: e, id: rowData[0].id})}
      startDate={colData} <-- Here colData is used which comes from JSON
      setStartDate={setStartDate}
      />

)}

As you can see from above code, I have used 'colData', since, I want to make changes on that value, I know we need to make use of 'startDate', but want to change the JSON data and process it further. Here I'm mimicking the API received as JSON. What code changes can be done to set the 'colData' and reflect it in UI.

As seen from above image, record with name 'Shawns', the date has been changed which is seen in console below, but, not on UI. Any suggestions or code changes highly appreciated
Please refer to codesandbox link as well -> https://codesandbox.io/s/elated-varahamihira-xpjtdb?file=/src/Grid.js:2386-3065
Comment: Does this answer your question? [When data is changed, doesn't update on UI but seen in console](https://stackoverflow.com/questions/73811484/when-data-is-changed-doesnt-update-on-ui-but-seen-in-console)
Comment: It was the same question without any solution. Can you think for any optimal solution?
Answer: The issue is that you are not using "startDate" as a variable, but just setting the startDate of the datePicker to coldata. This means that the startDate will always be coldata, and never be changed by the state. You will have to change the startDate prop of the datepicker to be "startDate", and then set the default state from another place.
(For example you could add another prop to the datepicker receiving the coldata, and on mount of the datepicker use setStartDate to set the default state.)
Here is a working codesandbox based on your version:
https://codesandbox.io/s/sad-aj-q1ir97?file=/src/Grid.js
Comment: Thanks for the response... If you don't mind can you please update codesandbox
Comment: I have edited my answer to add a working codesandbox fork based on your Version.
As you might notice, I have also renamed the state to make it clearer what it is for.
Comment: Actually I wanted date from JSON to change here in Grid
Comment: Your solution is changing all other dates as well
Comment: I just saw what you actually want to achieve, and your current setup is not made for it. First, I would start by actually making your GridData to a state. Then you can start building the grid based on this state, and changing the state based on the input fields. This would be to much effort writing for you in codesandbox though.
Comment: Yes right... but, can we take colDate inside  Datepicker and change its state and pass new value to the callback of setEstablishDate()?


How to play on the piano, 4 notes stacked on top of each other, with both a sharp and a flat, and 4 dots to the right

Question: How do you play this note on the piano that is circled in red (lower right corner of the sheet).
1) There is both a flat and a sharp notation (wouldn't they cancel)?
2) What do the four dots mean?
Comment: To echo other posts, the b is applied to the B, while the # is applied to the C. They don't cancel because they're applied to different notes.
Comment: For a recording, this is Ludwig Van Beethoven's Für Elise.
Answer: This notation simply means that you are to play the given four pitches simultaneously. From bottom to top in the right hand: E G Bb C#.
The reason there is a separate flat and a separate sharp is because they modify different pitches: a B in the case of the flat and a C in the case of the sharp. (Notice how the flat is centered on the middle line for B while the sharp is centered on the space right above that.)
And the four dots mean that all four of those pitches (which have a stem, thus they start out as quarter notes) are actually dotted quarters, so they will last the entirety of the measure. These dots, if you don't know, add half the value of the preceding entity. So if the preceding entity is a quarter note, the dot will add half of that value (an eighth note) to that quarter note, creating a dotted quarter (worth three eighth notes in duration).
Comment: The dot *adds* half of the preceding value. Since it's a quarter note, we add an eighth note. And since this is in 3/8, the three eighth notes of that dotted quarter last the entire measure.
Comment: are you sure "they will last the entirety of the measure"?  I thought a dotted note is only half of its note value?
Comment: ah, right.  sorry I thought it was in 6/8.
Comment: Some of those rhythms do give the impression of 6/16 time but the fact that the grouping is six semi-quavers together clearly indicates 3/8
Comment: Also, it's *Für Elise*, which Beethoven wrote in 3/8 :-)
Answer: As noted above, this is a chord, E G Bb C# or bunch.  Looks like an E diminished 7th and all notes should be played simultaneously and held for a 1/4 beat plus 1/8 which equals (3/8), or a whole bar in your 3/8 example.
Comment: The A is obviously just a pedal; why include that in the chord at all?
Comment: It's not an Edim7, but one of its enharmonics: C#dim7/E. This can be seen from the intervals, since the thirds follow C#-E-G-Bb, i.e., the seventh is C#-Bb (and the chord resolves to D minor in the next bar). The A in the base is perhaps somewhat confusion, but that just keeps the tension for when the progression goes to A minor a few bars later.
Comment: More like A7b9. A bass, C#, E, G and the Bb as b9. Nearly a diminished, but with that A bass it won't be. Close to -1 for this answer.
Comment: It is a diminished chord with a Major seventh. A bit weird.


Making square-root of covariance matrix positive-definite (Matlab)

Question: Motivation: I'm writing a state estimator in MATLAB (the unscented Kalman filter), which calls for the update of the (upper-triangular) square-root of a covariance matrix $S$ at every iteration (that is, for a covariance matrix $P$, it is true that $P=SS^{T}$). In order for me to perform the requisite calculations, I need to do a Rank-1 Cholesky Update and Downdate using MATLAB's cholupdate function.
Problem: Unfortunately, during the course of the iterations, this matrix $S$ can sometimes lose positive definiteness. The Cholesky downdate fails on non-PD matrices.
My question is: are there any simple and reliable ways in MATLAB to make $S$ positive-definite?
(or more generally, is there a good way of making any given covariance $X$ matrix positive-definite?)

Notes:

$S$ is full rank
I've tried the eigendecomposition approach (which did not work). This basically involved finding $S = VDV^{T}$, setting all negative elements of $V,D = 1 \times 10^{-8}$, and reconstructing a new $S' = V' D' V'^{T}$ where $V',D'$ are matrices with only positive elements.
I am aware of the Higham approach (which is implemented in R as nearpd), but it seems to only project to the nearest PSD matrix. I need a PD matrix for the Cholesky update.
Comment: I think maybe you wanted $S = PP^\top$, where $S$ is the covariance, and $P$ is the Cholesky factor.
Comment: Actually I want $S$ (the square root, or in this case, the Cholesky factor) to be positive definite. I have clarified the question though; thanks!
Comment: I am having the same problem. I did try sqrtm(x) function but it did work just for few iterations. Did you find the solution?
Comment: I tried various methods, but ended up using the standard (non-rigorous) trick of perturbing the diagonals, i.e. $S + kI$, where $k$ is a constant sufficiently large to make $S$ positive-definite. There are perhaps better approaches, but this one was quick and easy.
Comment: A bit late, but pivoting is a helpful strategy for numerically unstable.
Answer: Here is code I've used in the past (using the SVD approach). I know you said you've tried it already, but it has always worked for me so I thought I'd post it to see if it was helpful.
function [sigma] = validateCovMatrix(sig)

% [sigma] = validateCovMatrix(sig)
%
% -- INPUT --
% sig:      sample covariance matrix
%
% -- OUTPUT --
% sigma:    positive-definite covariance matrix
%

EPS = 10^-6;
ZERO = 10^-10;

sigma = sig;
[r err] = cholcov(sigma, 0);

if (err ~= 0)
    % the covariance matrix is not positive definite!
    [v d] = eig(sigma);

    % set any of the eigenvalues that are <= 0 to some small positive value
    for n = 1:size(d,1)
        if (d(n, n) <= ZERO)
            d(n, n) = EPS;
        end
    end
    % recompose the covariance matrix, now it should be positive definite.
    sigma = v*d*v';

    [r err] = cholcov(sigma, 0);
    if (err ~= 0)
        disp('ERROR!');
    end
end

Comment: Thanks for your effort -- unfortunately, it did not work. (I was doing something very similar in my 3-line program: `[V,D] = eig(A); D(D <= 1e-10) = 1e-6; Apd = V*A*V';`). This approach is similar to the one by Rebonato and Jackel, and it seems to fail for pathological cases like mine.
Comment: Thats too bad. I'd be interested in an example matrix you've found that causes this (and other methods you've tried) to fail if you have time to post one.
This is such an aggravating problem to keep running into, I hope you find a solution.
Answer: in Matlab:
help cholupdate

I get
CHOLUPDATE Rank 1 update to Cholesky factorization.
    If R = CHOL(A) is the original Cholesky factorization of A, then
    R1 = CHOLUPDATE(R,X) returns the upper triangular Cholesky factor of A + X*X',
    where X is a column vector of appropriate length.  CHOLUPDATE uses only the
    diagonal and upper triangle of R.  The lower triangle of R is ignored.

    R1 = CHOLUPDATE(R,X,'+') is the same as R1 = CHOLUPDATE(R,X).

    R1 = CHOLUPDATE(R,X,'-') returns the Cholesky factor of A - X*X'.  An error
    message reports when R is not a valid Cholesky factor or when the downdated
    matrix is not positive definite and so does not have a Cholesky factorization.

    [R1,p] = CHOLUPDATE(R,X,'-') will not return an error message.  If p is 0
    then R1 is the Cholesky factor of A - X*X'.  If p is greater than 0, then
    R1 is the Cholesky factor of the original A.  If p is 1 then CHOLUPDATE failed
    because the downdated matrix is not positive definite.  If p is 2, CHOLUPDATE
    failed because the upper triangle of R was not a valid Cholesky factor.

    CHOLUPDATE works only for full matrices.

    See also chol.

Comment: all online algorithms of this form (update & downdate) suffer from precision issues like this. I had similar issues in 1d resulting in negative estimates of variance. My suggestion would be to keep a circular buffer of the last k vectors observed, and when `cholupdate` fails, recompute the covariance based on that circular buffer and eat the cost. If you have the memory, and can stand the occasional time hit when this happens, you will not find a better method in terms of accuracy and ease of implementation.
Comment: I am using `cholupdate` but my question is about making `R` (in this case) positive definite. I have a case where my `R` is non-pd, and `cholupdate(R,X,'-')` (a downdate) fails.
Comment: Thanks, that's something to think about. Unfortunately, my covariance matrix goes through so many transformations that it is not clear at which point I have to a recomputation from the circular buffer. Nevertheless, if all else fails, I should be able to use the last known PD covariance matrix -- with the hope it doesn't produce a bias in my estimates.
Answer: One alternative way to compute the Cholesky factorisation is by fixing the diagonal elements of S to 1, and then introducing a diagonal matrix D, with positive elements.
This avoids the need to take square roots when doing the computations, which can cause problems when dealing with "small" numbers (i.e. numbers small enough so that the rounding which occurs due to floating point operations matters).  The wikipedia page has what this adjusted algorithm looks like.
So instead of $P=SS^T$ you get $P=RDR^T$ with $S=RD^{\frac{1}{2}}$
Hope this helps!
Comment: Thanks, that's a technique I could potentially use. It seems like it's been implemented here: http://infohost.nmt.edu/~borchers/ldlt.html
Answer: Effectively the Cholesky factorization can fail when your matrix is not "really" positif definite. Two cases appears, or you have a negative eingen value, or your smallest eingen value is positive, but close to zero. The second case must theorically give a solution, but numerically difficult. If have just intuitive add a small constant to the diagonal of my matrix for solving the problem. But this way is not rigourous because it modify slightly the solution. If you must to compute a really hight accuracy solution, try some research on modified Cholesky factorization.
Answer: If you try to estimate with P not positive definite you are asking for problems and chalenging algorithms, you should avoid this situation.
If your problem is numeric : P is positive definite but the numerical eigenvalue are too small - try a new scalling for your states
If you problem is indeed non positive definite - try different set of state variables.
I hope the advis eis not too late
Regards,
Zeev


Time series when seasonality appear due to both solar and the lunar calendars

Question: I have a time series data as shown in the figure below where the X axis is the serial number of the day of the year form 1 to 365 where 1 is 1-Jan and 365 or 366 is 31-Dec. The Y axis represents the value of a quantity I am measuring on each day of the year since 2015.

The the trend in the red portion of the graph are events due to Islamic religious festivals and clearly these events shifts forward each year by about two weeks since the lunar based Islamic calendar year is shorter than the solar based Gregorian calendar. The blue portion of the trend is the part of the year where Islamic calendar has little or no impact.
Question 1: Blue portion has its own seasonality, red portion has its own seasonality and red portion shifts forward by 2 weeks every year relative to the blue portion. What kind of time series technique is best suitable for modeling this kind of observations?
Question 2: If we are to use ARIMA, what modifications do we need?
Answer: Might be useful to check out the FASSTER package in R. It has the capability of handling switching seasonality.
Another option could be to use dummy variables to denote which portion and which day of the portion you're in to capture seasonality and then ARIMA on the residuals.


ajax:success callback doesn't work in rails

Question: I have a small form on the page that looks like

    <%= form_for current_user,:remote=>true do |f| %>
        please update your <%= f.label @field %>:
        <%= f.text_field @field %>
        <%= f.submit %>
      <% end %>

This triggers the Users#update which has respond_to format.js
update.js.erb is
$("#updater").bind("ajax:success", function(xhr, data, status) {
    $("#updater").remove();
});

so the form will disappear once the the field has been updated
I see that the JS is sent on the network tab on the chrome inspect thingy and the field does update in the DB. yet the #updater doesn't disappear, not if I add alert("updater"); I don't see the alert.
Am I not catching the ajax:success correctly?
Answer: I seem to have another js file that is working on #updater.. once I removed that it started working..


java.util.Map, melhor implementação considerando apenas get(Object key)

Question: Gostaria de saber qual classe que implemente java.util.Map contém o get(Object key) mais rápido.
O intuito é fazer um mini cache de dados, o volume de informação será de aproximadamente 2 a 10 mil registros.
Map<Integer, Funcionario> mapUsuarios = new ???<>();
Answer: Muito provavelmente HashMap, cuja implementação é a mais simples dentre as  alternativas disponíveis: uma simples tabela de espalhamento não-sincronizada, não-concorrente, não-ordenada (no sentido de não haver garantia na ordem em que seu iterator retorna elementos) e não-navegável (no sentido de NavigableMap).
A documentação sugere uma otimização na hora de instanciar o HashMap:

This implementation provides constant-time performance for the basic
  operations (get and put), assuming the hash function disperses the
  elements properly among the buckets. Iteration over collection views
  requires time proportional to the "capacity" of the HashMap instance
  (the number of buckets) plus its size (the number of key-value
  mappings). Thus, it's very important not to set the initial capacity
  too high (or the load factor too low) if iteration performance is
  important.
An instance of HashMap has two parameters that affect its performance:
  initial capacity and load factor. The capacity is the number of
  buckets in the hash table, and the initial capacity is simply the
  capacity at the time the hash table is created. The load factor is a
  measure of how full the hash table is allowed to get before its
  capacity is automatically increased. When the number of entries in the
  hash table exceeds the product of the load factor and the current
  capacity, the hash table is rehashed (that is, internal data
  structures are rebuilt) so that the hash table has approximately twice
  the number of buckets.
As a general rule, the default load factor (.75) offers a good
  tradeoff between time and space costs. Higher values decrease the
  space overhead but increase the lookup cost (reflected in most of the
  operations of the HashMap class, including get and put). The expected
  number of entries in the map and its load factor should be taken into
  account when setting its initial capacity, so as to minimize the
  number of rehash operations. If the initial capacity is greater than
  the maximum number of entries divided by the load factor, no rehash
  operations will ever occur.

A ideia é que, havendo memória disponível, se evite custosos processos de rehash adotando uma capacidade inicial maior que o quociente entre o número esperado de entradas e o load factor. No seu caso que é de 2 a 10 mil elementos, portanto, seria bom instanciar o HashMap com uma capacidade inicial da ordem de 2667 a 13334, já que o load factor padrão e recomendado é 0.75.
Note que se for em Android, vale a pena conhecer a classe android.util.SparseArray, que é uma implementação mais eficiente que um HashMap para uso com chaves do tipo inteiro.
Answer: Depende da forma como você vai popular e quem vai acessar os dados os dados.
Se os dados forem pré-carregados antes do uso ou pelo menos houver somente uma thread acessando o mapa, então o HashMap resolve o problema e podemos considerar a resposta do Piovezan como "canônica".
Entretanto, se a ideia é popular o cache sob demanda, isto é, adiciona valores apenas quando ocorre o primeiro acesso aos mesmos, e o acesso é concorrente, como numa aplicação web onde mais de uma requisição pode tentar ler e gravar o cache ao mesmo tempo, então o cenário é completamente diferente.
No segundo cenário, é esperado que o HashMap cause problemas, podendo, entretanto, ser substituído por implementações concorrentes como o ConcurrentHashMap.
Se o cache pode ser pré-carregado e o seu conteúdo é relativamente imutável ao longo do tempo, considere também usar um mapa imutável. Para isso, basta usar o método estático Collections.unmodifiableMap para criar um wrapper no seu mapa original e assim evitar problemas de acesso concorrente.
Comment: Ótimo comentário, o segundo cenário se enquadra perfeitamente na situação, vou efetuar testes com os Maps comentados e mais alguns como o `TreeMap` e postar os resultados!
Answer: Para resolver o meu problema efetuei um teste com algumas implementações de Map, depois de populados de maneira idêntica com 1400 objetos executei.
speedTeste(hashMap, "hashMap");
speedTeste(treeMap, "treeMap");
speedTeste(concurrentHashMap, "concurrentHashMap");

public static void speedTeste(Map map, String type) {

System.out.println("teste velocidade mapa: " + type);
    int count = 0;
    long start = System.currentTimeMillis();
    while (count++ < 10000000) {
        map.get(1);
    }
    System.out.println("\t " + (System.currentTimeMillis() - start));

}

Resultados:

teste velocidade mapa: HashMap 144
teste velocidade mapa: TreeMap 559
teste velocidade mapa: ConcurrentHashMap 207

Ou seja, mesmo o TreeMap tendo organizado as chaves neste contexto ele é muito mais lento que o HashMap para obter o valor.


Allow CD drive in a Software Restriction policy

Question: I am rolling out a disallow all Software Restriction policy on my network. I am studiously whitelisting all programs we use as I go. One issue I have is allowing .exe to run from the CD Drive. My users receive CDs from various places and need to be able to run them but I am at a loss on how to whitelist them. Does anyone have a solution?
I cant do a hash whitelist and allow certain exes because we will get new ones on a regular basis and users cant wait for IT to allow it.
I thought about doing a path rule to allow anything on the D:\ drive but I'm worried this wont work because the cd will copy temp files to pc and those will be blocked. (I am testing that now). That also isn't the most elegant solution. I am working towards unified hardware but I can't guarantee the D:\ will always be the CD drive.
Unfortunately, Google has not been much help on this particular problem
Answer: You can just make an exception for D:\ and exe will run properly from cd. I ended up going that route with a separate software restriction gpo for users that need to run stuff off cds.


How to use nested for loops to return string "1+2+3+..1+2+3+..1+2+3+.."?

Question: So I'm trying to define a receieved a string in int form that results in list form of the addition of numbers leading to the given string
eg when n = 3 the returned string should be:
"1+2+3+..1+2+3+..1+2+3+.."

My attempt:
def nestedAdditions(n):
    string = ""
    for i in range(1,n+1):
         for j in range(1,i+1):
             string += str(j)+"+"
    string += ".."
    return(string)

Answer: You are incorrectly counting from 1 to i+1 in the inner loop while you should use n+1. You are also incorrectly appending the .. after the outer loop terminates. Try this:
def nestedAdditions(n):
    string = ""
    for i in range(1,n+1):
         for j in range(1,n+1):
             string += str(j)+"+"
         string += ".."
    return(string)

then
print(nestedAdditions(3))

should print
1+2+3+..1+2+3+..1+2+3+..

Answer: You may use another method, but with minimum changes to your code, here you are:
def nestedAdditions(n):

    string = ""

    for i in range(1,n+1):

         # change to n
         for j in range(1,n+1):

             string += str(j)+"+"

         # fix loop indentation
         string += ".."

    return(string)

Answer: Here's an itertools approach:
import itertools as it
def iterAdditions(n):
    item = list(it.accumulate([str(x) + '+' for x in range (1, n+1)]))
    temp = item.pop() + '..'
    return (temp * n)

gives for iterAdditions(3):
'1+2+3+..1+2+3+..1+2+3+..'

It does speed things up a little bit above the basic nested for loop approach (@ Selcuk & Anatoliy above), although I'm not entirely sure why:
timeit nestedAdditions(10)
20.2 µs ± 166 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)

timeit iterAddition(10)
2.74 µs ± 21.8 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

Comment: Nice solution. I did some tests and it seems like `''.join` is asymptotically faster than `itertools.accumulate` if you want to add a lot of strings together, though. That makes sense because `accumulate` has to yield all the intermediate results of the additions, so the total length of all yielded strings is O(N^2) when joining N strings. Your solution probably beats the naive nested loop because of the string multiplication at the end.
Answer: No nested loops needed for this; use '+'.join to make the string with one repetition, and multiply the string by n to repeat it. Yes, you can multiply a string by a number in Python.
def rep(n):
    parts = [ str(i) for i in range(1, n+1) ]
    parts.append('..')
    s = '+'.join(parts)
    return s * n

@neutrino_logic posted running times, so for comparison:
>>> timeit(lambda: rep(100), number=100000)
1.6885969130016747
>>> timeit(lambda: iterAdditions(100), number=100000)
2.435769292002078


How to implement a custom hook

Question: I have implemented a custom login module and I want to keep it on general purpose state.
This module have been developed because users can be authenticate against an internal LDAP Server (Sun Microsystems' LDAP directory server). So in this module I want to keep only the authentication and retrieve data from the LDAP directory. That's fine, I have it, within the PHP API (LDAPc) we have available.
There are situations where the link to log into the application comes with extra querystring parameters, and I have the thought to add a hook to my custom login module, so from other module I can implement that custom hook, retrieve these querystring and do whatever we need to do... add them in an extra table linked with the user table, for example.
I could do this inside the custom login module, but if so, my module will not be valid for other drupal sites with other needs.
My first thought, following this post: http://tylerfrankenstein.com/code/drupal-create-custom-hook-for-other-modules
has been to add the lines:
    $params = $_GET;
    drupal_alter('retrieve_login_extra_params', $params);

to my current development state
/**
 * Implements hook_menu().
 */
function psaldaplogin_menu()
{
    $items = array();
    // Login Page to authenticate against PSA Ldap directory
    $items['user/psaldaplogin'] = array(
            // Every user can access to this page
            'access callback' => TRUE,
            // Define the function where implement the generation of the page
            'page callback' => '_psaldaplogin_view',
    );
    return $items;
}

/**
 * Authentication procedure
 *
 * TODO:
 *     Allow other modules implement this process as a hook,
 *     so more complex process on login step
 *     could be implemented outside this module
 *
 */
function _psaldaplogin_view()
{
    // Clear messages queue
    drupal_get_messages();

    // Check if the user is already logged
    if (user_is_logged_in()) {
        drupal_goto('home');
    }

    // Allow other modules process the querystring parameters
    // --> DOESN'T WORK
    $params = $_GET;
    drupal_alter('retrieve_login_extra_params', $params);

    // Authorized the user
    if ($username = _getAuthorizedUser()) {
        // Get the user information from PSA Ldap directory
        $userData = _getLdapUserInformation($username);
        // Register the user into Drupal
        if (_registerExternalUser($userData)) {
            // Redirecto to home
            drupal_goto('home');
        } else {
            // If the registration failed show access denied message
            drupal_access_denied();
        }
    } else {
        // If the authentication failed show access denied message
        drupal_access_denied();
    }
}

Figuring out I will be able from other module implement something like:
function slider_retrieve_login_extra_params($params)
{
    // check $params since they are unsafe data

    // test if the querystring params could be retrieve here
    file_put_contents('/tmp/genius/genius.log',
        "\n" . print_r($params, true) . "\n",
        FILE_APPEND);
}

But this chunk of code is never executed, so it is clear I have a miss understanding on how to allow other modules to implement a custom hook.
I'll appreciate if someone could point me to the right direction to achieve this solution. Otherwise I will have the module as template since for each development the login needs could be different.
Thanks for the reading.
Regards.
Answer: Putting aside the general design of your application, you are right to use drupal_alter to provide a hook.
However, you are missing the correct hook implementation function name.
It should be:
drupal_alter('retrieve_login_extra_params', $params);
// ...
function MODULE_retrieve_login_extra_params_alter(&$params){
// ...
}

You may also be interested in:

LDAP Integration
user_external_login_register
Comment: Hi David, that's great... it works. Indeed there were a comment on the article I followed that point exactly with the same issue. My mistake. I am using user_external_login_register on my module; the LDAP Integration I analysed on the past aswell but finally I started with a first approach from other team who they have been implemented the main common functions we need for our LDAP Server that is not a standard one as openLDAP and the bind mechanism is quite different.
Comment: You're welcome, all the best with your project.

How to implement a custom hook


Proving that the subspace on 2.2.1.d exercise of Kenneth Linear algebra is a subspace

Question: The exercise says as it follows:
Is the set of vectors with the shape $S = \{(a_1,a_2,...,a_n), a_1a_2=0 \}$ a subspace?
I started developing a proof by proving if $w = u + \alpha v \in S$. For that reason I got to the conclusion that if $w_1w_2 = 0$ then $v_1u_2 + v_2u_1 = 0$, but I don't know exactly how to continue with an analytical approach.
Of course, it is easy to find a case in which 2 vectors can be found in S whose sum isn't in S, but I'm trying to find a solution that doesn't go that pace.
Comment: "Of course, it is easy to find a case in which 2 vectors can be found in S whose sum isn't in S, but I'm trying to find a solution that doesn't go that pace." That's the easiest argument, why would you not be happy with this insight?
Answer: Your subset is the union of two subspaces ("$a_1=0$",and "$a_2 = 0$") neither of them containing the other. In that case, the union is not a subspace.
Comment: Can you actually show that if you have two subspaces neither of them containing the other that the union is not a subspace without first showing that the sum of elements need not be interior in this case?
Comment: @Mathematician 42: I would just consider the sum $u_1 + u_2$, $u_i \in V_i \backslash V_{i+1}$.  The union is still closed under multiplication by scalars


$form_state->set(), $form_state->setValue() doesn't save new value

Question: Below you could find my code. It works fine until below the comment. I also tried countless combination of $form_state->saveValue(), but nothing works. Any ideas?
    function myforms_form_alter(&$form, FormStateInterface $form_state, $form_id) {
      if ($form_id == 'commerce_product_default_edit_form' || $form_id == 'commerce_product_default_add_form') {
        $form['#submit'][] = 'myforms_extra_submit_handler';
      }
    }

    function myforms_extra_submit_handler($form, FormStateInterface $form_state) {
      $events_dates = $form_state->getFormObject()->getEntity()->get('event_date')->getValue();
      $count = count($events_dates);
      if (empty($events_dates[$count-1])){
        $count = $count - 1;
      }
      if ($count > 0) {
        $start_date = date("j/n/y", strtotime($events_dates[0]['value']));
        $end_date = date("j/n/y", strtotime($events_dates[$count-1]['end_value']));
        if ($count == 1) {
          $count_suffix = "zjazd";
        } else if ($count == 2 || $count == 3) {
          $count_suffix = "zjazdy";
        } else {
          $count_suffix = "zjazdów";
        }
        $date = $start_date.' - '.$end_date.' ('.$count.' '.$count_suffix.')';

        $title = $form_state->getFormObject()->getEntity()->get('title')->getValue()[0]['value'];
        /* code above works, below is the code which doesn't */
        $form_state->set('title', $title.$date);
        $form['elements']['title']['#value'] = $title.$date;
        $form['elements']['title']['#default_value'] = $title.$date;
        $form_state->setRebuild();
      }
    }

Answer: I assume with code works you mean you get the updated title value. Then another submit handler has already transferred the values to the entity and your changes to $form_state are too late.
So you can try to position your submit handler first:
array_unshift($form['#submit'], 'myforms_extra_submit_handler');

or update the entity instead of $form_state:
$entity = $form_state->getFormObject()->getEntity();
$title = $entity->get('title')->value;
$entity->set('title', $title . $date);

Caveat: Normally submit handlers in entity forms are attached to submit buttons. So you might want to check first all submit handlers which are active in the form before you decide where to place your submit handler.

Different approach
You are asking why your submit handler is not working and there is definitely a solution for that, but there is probably a much easier solution outside of the form when the form is trying to save the entity. See  Programmatically update a field's value
Answer: It's not clear what "doesn't work" means to you - what do you expect to happen, and what actually happens? We can only guess at what you mean, so perhaps I'm guessing wrong here ...
Because $form is passed to your submit handler by a value, not by reference, the changes you make to $form after your comment are confined to the scope of the submit handler and won't affect anything outside your function. If you want to change the elements of the $form array you should do that inside your hook_form_alter(), or perhaps in an Ajax callback, not in a submit function. A submit function should only be processing the form data, not trying to alter what the form looks like to the end user. But if you really must, then you can change the form values in your submit handler by set the values in $form_state instead of changing $form.
Also confusing is your $form['elements']['title']['#value'] - most form elements have a #title to hold the value of the title, or if this were a markup #type then you would have a #markup to hold the value. I'm not sure why you're trying to set #value here. It would help if you would show at least part of the structure of the $form you're trying to alter.
Comment: Hi, what I mean is I am not able to save the updated title. I also tried that in hook_entity_presave(), but with no luck. The code until saving part works.


Can I hardcode the password if I have only 1 user for whom I can manually change code now and then

Question: I tried to find out whether folks ever hardcode their passwords for web applications that don't really have more than 1 user, but haven't found any yet.
However, this hypothetical situation could be real:  "An application which uses SSL, has one user who can change code anytime, and deploy anytime"
If the developer have the capability to change the code and deploy at-will, would there be a need to:
1. Encrypt the password, and
2. Store that password (or its hash) in some DBMS.
?
Thanks.
Answer: Generally hardcoding passwords is A Bad Idea, but it really depends what you're doing. If you're building something entirely for your own use that is only deployed to your local machine and is firewalled off from the rest of the world then that would be a reasonable time to not bother with proper authentication. Otherwise you probably want to do things right.
A few things to think about:

Who has access to the source? If anyone other than the developer can see the source then hardcoding the password will be A Bad Thing.
How much damage can an unauthorized user cause? If they can cause a lot of damage then don't hardcode the password.
Is the web application only available from a single machine? That may mitigate some security concerns.
Is your single user the one who can deploy new code? If so, you might as well not bother with authentication because that user can just deploy code that doesn't check the password.

It's usually pretty easy to put in proper password authentication. Just about every web development framework includes support for good password storage (e.g. bcrypt), so why not take advantage of it?