Example where prime spectrum suits better than the maximal spectrum

Question: in a lot of algebraic geometry books I've heard that working over $\mathrm{Spec}(A)$ is better than working over $\mathrm{Spmax}(A)$ in the case where you consider a variety over a non-agebraically closed field $k$. Of course, the prime spectrum suits better because of the functoriality, but in a lot of books dealing with arithmetic of curves (in affine charts, without sheaves) there are discussions and proofs of facts dealing with non-algebraically closed fields (even zeta functions) using only maximal ideals of reduced $k$-algebras (zero sets of polynomials).
Therefore I'm searching for a simple example where prime ideals are better than the maximal ideals. Furthermore I would like to know how should I think about non-maximal prime ideals (points that are not geometric). I think that it would be useful, too, if someone could explains what's the difference between $\mathrm{Spec}(k)$ and $\mathrm{Spec}(k')$.
Thanks in advance.
Comment: Dear user: $spec(k)$ is not just  a point but a point **plus** a sheaf of local rings on that point. In this trivial situation this sheaf is just the datum of the field $k$,  but the beauty of scheme theory is that the scheme $Spec(k)$ remembers the field $k$ in its structure.
Comment: The difference between $Spec(k)$ and $Spec(k')$ is **exactly** the same as that between $k$ and $k'$ ! But this is a tautology and proves nothing for or against the use of nonmaximal prime ideals...
Comment: What is $k'$? Is it the algebraic closure of $k$?
Comment: @Manos any extension
Comment: @GeorgesElencwajg but this is just a point
Comment: Maybe the answer should be what's a point in a scheme.
Comment: @user40276: Works better for *what*?
Comment: @MartinBrandenburg For arithmetic
Answer: If $k$ is an algebraically closed field and $A=k[T_1,...,T_n]/\mathfrak p\,$ (with $\mathfrak p$ a prime ideal) is a finitely generated domain over $k$, you should think of the affine scheme $\mathrm{Spec}(A)$ as the variety $V=V(\mathfrak p)\subset \mathbb A^n(k) $ to which you adjoin formally a point $\eta_W $ for every irreducible subvariety $W\subset V$.
If $k$ is not algebraically closed the advantage of schemes over varieties is more convincing: the schemes $\mathrm{Spec}(\mathbb R[X,Y]/(X,Y))$ and $\mathrm{Spec}(\mathbb R[X,Y]/(X^2+Y^2))$ are completely different (they don't even have the same dimension) whereas  the varieties $V(X,Y)\subset \mathbb R^2$ and $V(X^2+Y^2)\subset \mathbb R^2$ are both equal to a single point.
But the really convincing superiority of schemes over varieties is attested by the amazing results obtained through the use of scheme theory in the last half century  by geometers and arithmeticians like Grothendieck, Hironaka, Deligne, Faltings, Wiles and a good proportion of Fields medalists and Abel prize recipients in that period.
Comment: Thanks for the answer, but if a point is not generic, I cannot see the utility of adding a point that is not geometric (for instance some closed point not geometric). Anyway, why wouldn't use a stratification instead of adding such new points?
Comment: I know this is an old question, but I'm not sure the middle paragraph answers the question here, since for nonalgebraically closed fields the variety as a subset of affine space is completely different than the max spec. Max spec of $\Bbb{R}[X,Y]/(X^2+Y^2)$ has a pile of complex points that distinguish it from the single point of the max spec of $\Bbb{R}\cong \Bbb{R}[X,Y]/(X,Y)$.


Translate image instead of subimage copy

Question: Imagine you have an large picture, let's say about 10000px x 3000px and you like to translate it left on the x axis and in a very efficient way. So no AffineTransform or smth like that is wanted. If possible, the part moved out on the left side should be appended on the right side, so a kind of turn around would be very cool.
What you have on hand are: Java 7, OpenCV.
Do you have any suggestions?
Answer: Here you can see how it can be done with OpenCV in C++. You just need to translate it to Java:
<code>// C++:
Mat outImg(inputImg.size(),inputImg.type());
inputImg(Rect(0, 0, shiftX, height)).copyTo(outImg(Rect(width-shiftX, 0, shiftX, height)));
</code>
Becomes something like:
<code>Mat outImg = new Mat(inputImg.size(),inputImg.type());
inputImg.submat(new Rect(0, 0, shiftX, height)).copyTo(outImg.submat(new Rect(width-shiftX, 0, shiftX, height)));
</code>
Although this one liner is not very readable ;)


I keep getting error 0x80320002 on Windows Filtering Platform

Question: I'm trying to write a simple program to block specific ports using WFP. I can block specific apps using the following code.
#include <Windows.h>
#include <fwpmu.h>
#include <stdio.h>
#include <string>

#pragma comment(lib, "Fwpuclnt")

int main() {

    HANDLE hEngine;
    FwpmEngineOpen(nullptr, RPC_C_AUTHN_DEFAULT, nullptr, nullptr, &hEngine);

    FWPM_FILTER filter{};
    WCHAR filterName[] = L"Block Calculator's internet access";
    filter.displayData.name = filterName;

    filter.layerKey = FWPM_LAYER_ALE_AUTH_CONNECT_V4;
    filter.action.type = FWP_ACTION_BLOCK;

    WCHAR filename[] = LR"(C:\Program Files\WindowsApps\Microsoft.WindowsCalculator_11.2307.4.0_x64__8wekyb3d8bbwe\CalculatorApp.exe)";
    FWP_BYTE_BLOB* appId;
    FwpmGetAppIdFromFileName(filename, &appId);

    FWPM_FILTER_CONDITION cond;
    cond.fieldKey = FWPM_CONDITION_ALE_APP_ID;
    cond.matchType = FWP_MATCH_EQUAL;

    cond.conditionValue.type = FWP_BYTE_BLOB_TYPE;
    cond.conditionValue.byteBlob = appId;

    filter.filterCondition = &cond;
    filter.numFilterConditions = 1;

    FwpmFilterAdd(hEngine, &filter, nullptr, nullptr);

    filter.layerKey = FWPM_LAYER_ALE_AUTH_CONNECT_V6;   // IPv6
    FwpmFilterAdd(hEngine, &filter, nullptr, nullptr);

    FWPM_FILTER_CONDITION test = cond;

    FwpmEngineClose(hEngine);

}

But if I modify the condition to block a specific port, I get error 0x80320002: The filter condition does not exist.
    FWPM_FILTER_CONDITION cond;
    cond.fieldKey = FWPM_CONDITION_IP_DESTINATION_PORT;
    cond.matchType = FWP_MATCH_EQUAL;

    cond.conditionValue.type = FWP_UINT16;
    cond.conditionValue.uint16 = 443;

I feel like I'm missing something simple, but I've checked the documentation and I cannot find any reason why it won't work. Any help would be appreciated.
Comment: Please edit the question to limit it to a specific problem with enough detail to identify an adequate answer.
Answer: You want FWPM_CONDITION_IP_REMOTE_PORT.


C++ shared_ptr and reading from the class

Question: I have a problem with simple reading from the file that shares file pointer between a few objects (It works for me with just simple istream, but not when I am using shared pointer of istream pointers).
I am trying to read the whole file to the buffer (file itself is a few lines long.
The code compiles, but throws segmentation fault.
The class that uses shared_ptr:
RecordsSplitter::RecordsSplitter(char *filename):iStream( new ifstream(filename, ifstream::in|ifstream::binary))
{
}

string RecordsSplitter::buildRecord() {
       char *buffer;
        int buffer_length;
        iStream->seekg (0, ios::end)_
        buffer_length = iStream->tellg();
        cout << buffer_length;
        iStream->seekg(0, ios::beg);
        iStream->read(buffer,buffer_length);
        iStream->close();
        cout << buffer;

        return 0;
}

int main(int argc, char* argv[]) {
        RecordsSplitter *splitter;
        splitter = new RecordsSplitter(argv[2]);
        int return_num = splitter->buildRecord();
        return 0;
}

Comment: I can't see any `shared_ptr` in your code.
Comment: where do you initialize your buffer?
Comment: Do not write C++ code like this: all your pointers and uses of `new` are redundant. Use plain objects instead of pointers. Your code is error-prone and complicated.
Comment: "The code compiles, but throws segmentation fault." Could you paste the code that compiles? The code you pasted doesn't. It is both incomplete and incorrect. Please provide a minimal, complete program that demonstrates the error you see. For information about how to produce a minimal complete sample program, and why producing it is a good idea, see http://sscce.org/
Answer: You declare your buffer but you don't initialise it anywhere.
You need this in your buildRecord function or a use of malloc if you so desire.
buffer = new char[buffer_length];

Your seg fault is caused by this uninitialised pointer
Don't forget to clean up!
delete[] buffer;

Comment: Or better yet, `char buffer[buffer_length]`.
Comment: @Travis: C++ doesn't have variable-length arrays.
Comment: @Travis, I suppose you could have that if: `const int buffer_length = iStream->tellg();` was there
Comment: @interjay: True, by the standard. But every compiler I use supports them.
Comment: @tom502: Correct...other things would have to be changed, but compared to the memleak that is happening with this simple fix, I would say it is an improvement.
Comment: @Travis: Apparently you don't use a lot of compilers then. MS Visual C++ doesn't support VLAs, and I believe Intel's compiler doesn't either.
Comment: @interjay: gcc, clang and Intel C++ all do.
Comment: @Travis: Intel compiler on Windows doesn't support it, only on Linux where it has gcc compatibility. This is really a gcc feature, not a C++ feature.


Derive Fourier transform from what it should do?

Question: I was wondering about the following:
Imagine you want to figure out whether there is a transform that exchanges differentiation with multiplication and convoution with pairwise transformation for $L^2$ functions. Is there an analytical way to derive from this the Fourier transform?
Why am I asking this? In many practical examples, you want to have a transform that has certain properties like: get rid of differentiation. But in mostly all books, the Fourier transform is just introduced and the properties are derived afterwards. Is it a posteriori possible to derive an integral transform just by looking for something with these properties?
Comment: Do you mean that we don't know beforehand that the transform is an integral transform or that we know it is an integral transform and wish to derive the kernel?
Comment: The last one...
Answer: Assuming that we know beforehand that the required transform is an integral transform, I get the following with a bit of handwaving (though I guess this can relatively easily be proved rigorously).
Denote by $\mathcal{T}$ the unknown integral transformation and by $K$ the kernel of that transformation, i.e. let $\mathcal{T}[f](\omega) = \int_{-\infty}^\infty K(x,\omega) f(x)\,d x$.

For the $\delta$ distribution, denote $\delta_a(x) = \delta(x-a)$. We get [using $\delta$ is handwaving #1, but probably we could use limits just everywhere and require some form of continuity]
$$
\mathcal{T}[\delta_a](\omega) = K(a,\omega).
$$
Start from the convolution theorem, i.e.
$$
\mathcal{T}[(f \ast g)](\omega) = \mathcal{T}[(f)](\omega)\mathcal{T}[(g)](\omega).
$$
Plugging in $g=\delta_a$, the LHS becomes
$$
\int_{-\infty}^\infty K(x,\omega) \int_{-\infty}^\infty f(x-s) \delta_a(s)\,ds \,dx = \int_{-\infty}^\infty K(x,\omega) f(x-a)\,dx = \int_{-\infty}^\infty K(x+a,\omega) f(x)\,dx,
$$
and the RHS becomes
$$
\int_{-\infty}^\infty K(x,\omega) f(x)\,dx K(a,\omega) = \int_{-\infty}^\infty K(a,\omega) K(x,\omega) f(x)\,dx .
$$
Because they should be equal for every $f$, we get the equation ($\forall \omega, x, a$)
$$
K(a,\omega)K(x,\omega) = K(a+x,\omega).
$$
With some assumptions [handwawing #2; I think continuity is enough?], we get $K(x,\omega) = e^{\alpha(\omega) x}$ with some unknown function $\alpha$.

Now apply the "differentiation becomes multiplication", i.e.
$$
\mathcal{T}[f'](\omega) = \beta(\omega) \mathcal{T}[f](\omega),
$$
with some unknown function $\beta$. For functions $f$ with compact support, The LHS becomes
$$
\int_{-\infty}^\infty e^{\alpha(\omega) x} f'(x) \, dx = \left[ e^{\alpha(\omega) x} f(x) \right]_{x=-\infty}^\infty - \int_{-\infty}^\infty e^{\alpha(\omega) x} \alpha'(\omega) f(x) \, dx =  - \int_{-\infty}^\infty e^{\alpha(\omega) x} \alpha'(\omega) f(x) \, dx
$$
On the other hand, the RHS is
$$
\int_{-\infty}^\infty e^{\alpha(\omega) x} \beta(\omega) f(x) \, dx,
$$
so we get $\beta(\omega)=-\alpha'(\omega)$.

So from
$$
\mathcal{T}[(f \ast g)](\omega) = \mathcal{T}[(f)](\omega)\mathcal{T}[(g)](\omega)
$$
and
$$
\mathcal{T}[f'](\omega) = \beta(\omega) \mathcal{T}[f](\omega),
$$
we get
$$
K(x,\omega) = e^{-\gamma(\omega) x },
$$
where $\gamma$ is an antiderivative of $\beta$. Apparently we need more properties to define the exponent exaclty.


Erro com classe php Fatal error: Uncaught Error: Call to undefined function run_search()

Question: To tentado criar uma classe, e to obtendo o erro abaixo já pesquisei mais ainda não encontrei o por que está dando este erro.
Erro:
Fatal error: Uncaught Error: Call to undefined function run_search() in D:\xampp\htdocs\Github\astra\class\buscaAnimes.class.php:17 Stack trace: #0 D:\xampp\htdocs\Github\astra\index.php(11): buscaAnimes->get_busca('21') #1 {main} thrown in D:\xampp\htdocs\Github\astra\class\buscaAnimes.class.php on line 17

Class::
    <?php

    class buscaAnimes{

    private $idAnime;
    private $urlMal;

    public function __construct(){

    }

    //Pega a id passada pelo usuario e atribui ao $idAnime
    public function get_busca($b){
        $this->idAnime = $b;
        $resposta = run_search();
        return $resposta;
    }

    private function run_search(){
        if(!isset($this->idAnime) & empty($this->idAnime)){
            return 'Erro: É necessario um id para fazer a busca';
        }

        $this->urlMal = 'https://exemplo.com/anime/'. $this->idAnime .'/';

       $resposta = curlSearch($this->urlMal,'get');

       if($resposta[1] != 200){
           return $resposta[1];
       }else{
           $resposta = $resposta[0];
           return $resposta;
       }
    }
}

?>

Answer: Esse erro quer dizer que não existe uma função run_search, o que existe é a função run_search dentro da classe buscaAnimes, faltou adicionar o $this->:
//Pega a id passada pelo usuario e atribui ao $idAnime
public function get_busca($b){
    $this->idAnime = $b;
    $resposta = $this->run_search();
    return $resposta;
}

Comment: Entendi, Testei e funcionou. Brigado!


how to write code for this?

Question: In Verilog HDL describe a hardware that is able to generate a clock frequency f 0 of approximately 3Hz. Display this clock by connecting it to LED LD7 to verify your approach.
I tried a lot but not able to get right output.
Device:-Basys2 Spartan3e
Comment: what did you try? Post it here. Well be able to help
Comment: Also you must have an input clock of some frequency?
Answer: I will give the steps(not the code) to create a clock divider which is what you need here.

Say you clock has frequency f. Create a counter which counts from 1 to f/2.
Say your new divided clock name is clk_new. Initialize this clk_new to zero.
Whenever the counter value is in its maximum (which is f/2), toggle clk_new.
you can do this by clk_new = ~clk_new;
and also reset the counter to zero and let it begin the counting again.

Write the code and if it doesnt work, post here. We can help.

how to write code for this?


Running a HTTPS SSE server over Kubernetes/Ingress and Google Cloud Platform

Question: I'm running a SSE server on a VPS and it works perfectly, no problems at all, but due to scalability reasons I needed to move it to another server.
I moved the server to Google Cloud Platform/Google Container Engine and Kubernetes/Ingress. But now I've encountered that I can't keep a SSE connection effectively, it's completely unstable and it closes connections by itself.
Is there anything special I have to do to run a SSE server over Kubernetes/Ingress?
I assume my code/software runs perfect and that is not the issue, due it works perfectly in Kubernetes, VPS, on my machine, everywhere, just not when I add the Ingress configuration, and I'm doing this because I want HTTPS over the Kubernetes load-balancer.
Comment: What are you running on your client and server side for SSE? Have you tried using a different client like `curl` to confirm if the connection remains open or is getting closed?
Comment: It wasn't the client. I got it working, for no-closing connections like sockets I've found that you gotta set a really big timeout on Ingress, about 86,400 seconds (a day).
Answer: Seems that Ingress defaults timeout was 30 seconds for any type of connection, I've set it to 86,400 (a day) and now the socket works good.
You can change the timeout over the Google console like this:
<code>➜ export BACKEND=xxx-xxx-xxxxxx
➜ gcloud compute backend-services update $BACKEND --global --timeout=86400 # seconds
Updated [https://www.googleapis.com/compute/v1/projects/xxxxxxxxx/global/backendServices/xxx-xxx-xxxxxx].
</code>
Comment: What does "xxx-xxx-xxxxxx" means in "BACKEND=xxx-xxx-xxxxxx"  ?
Comment: Can the timeout be set in the yaml file or do you have to manually change it in Google's console?
Comment: @crickeys You have to do it over the Google's console. I have updated my answer.


php - How to get the group name under windows?

Question: I am using:
<code>getmygid();
</code>
to get the group id, I can get the name under linux by pulling it from the getegid array. Can you do something similar with windows?
Comment: What is the expected output?
Answer: Wikipedia whoami:

In computing, whoami is a command found on most Unix-like operating
  systems, Windows Vista, Windows 7, Windows 8, Windows Server 2003, and
  Windows Server 2008.

Windows whoami command at technet.microsoft.com:

Displays user, group and privileges information for the user who is
  currently logged on to the local system. If used without parameters,
  whoami displays the current domain and user name.

str_getcsv() php function:

Parses a string input for fields in CSV format and returns an array
  containing the fields read.

Here is the code:
<code>$groups_csv = shell_exec('whoami /groups /fo csv');
print_r( str_getcsv($groups_csv) );
</code>


How many hexagons can be constructed by joining the vertices of a 15 sided polygon if none of the sides of the hexagon is also the side of the 15-gon.

Question: How many hexagons can be constructed by joining the vertices of a 15 sided polygon if none of the sides of the hexagon is also the side of the 15-gon.
My attempt
First calculate in how many ways we can select 6 points from 15 points then subtract which have 1 side same as the 15-gon then 2,3....5 sides common.
But that is very long approach .Any better method.
Answer: Write down $9$ $\times$'s, like this
$$ \times\qquad \times\qquad \times\qquad \times\qquad \times\qquad \times\qquad \times\qquad \times\qquad \times$$
These determine $8$ gaps, plus $2$ "endgaps." We either choose $6$ gaps to put a $\circ$ into, or choose one of the two endgaps, plus $5$ real gaps to put a $\circ$ into. This can be done in
$$\binom{8}{6}+2\binom{8}{5}$$
ways.
To make a real hexagon inscribed in our $15$-gon out of the pattern of $\circ$ and $\times$, take a fixed vertex of the given $15$-gon, put the leftmost of our $15$ "letters" into it, and the rest counterclockwise as we travel to the right. The $\circ$ will be the vertices of the hexagon.
The method generalizes to $k$-gons in $n$-gons.
Answer: More generally drawing $n$-gons in a $k$-gon but not using any of the original sides,
suppose you know one of the vertices: then you need to divide the $k$ gaps into $n$ parts with each part at least $2$, which is the same as dividing $k-n$ into $n$ parts with each part at least $1$, and using stars and bars, this can be done in $\displaystyle{k-n-1 \choose n-1}$ ways.
But we need to adjust our answer for the fact that we could have had any of $k$ original vertices, but by adjusting for this we get each $n$-gon $n$ times.  So the answer is $$\frac{k}{n}{k-n-1 \choose n-1}$$ or here $\frac{15}{6}{8 \choose 5}$.  This is the same as André Nicolas's ${k-n-1 \choose n}+ 2 {k-n-1 \choose n-1}$.
Comment: hen you need to divide the k gaps into n parts with each part at least 2, which is the same as dividing k−n into n parts with each part at least 1,...??What does this means
Comment: @maths lover: Suppose you had to divide 7 into 3 parts at least 2: you could do this as 3+2+2 or 2+3+2 or 2+2+3.  It is the same question as dividing 7-3=4 into 3 parts at least 1: 2+1+1, 1+2+1 or 1+1+2


Truncated logs in Google Cloud Dataflow

Question: When I run my code in the Google Cloud Dataflow, I am getting some tracebacks in the the "Errors" view, but they are truncated.
<code>(cee7eb663424a856): Traceback (most recent call last):
  File "/usr/local/lib/python2.7/dist-packages/dataflow_worker/batchworker.py", line 578, in do_work
    work_executor.execute()
  File "/usr/local/lib/python2.7/dist-packages/dataflow_worker/executor.py", line 165, in execute
    op.start()
  File "dataflow_worker/shuffle_operations.py", line 49, in dataflow_worker.shuffle_operations.GroupedShuffleReadOperation.start (dataflow_worker/shuffle_operations.c:3442)
    def start(self):
  File "dataflow_worker/shuffle_operations.py", line 50, in dataflow_worker.shuffle_operations.GroupedShuffleReadOperation.start (dataflow_worker/shuffle_operations.c:3346)
    with self.scoped_start_state:
  File "dataflow_worker/shuffle_operations.py", line 63, in dataflow_worker.shuffle_operations.GroupedShuffleReadOperation.start (dataflow_worker/shuffle_operations.c:3261)
    with self.shuffle_source.reader() as reader:
  File "dataflow_worker/shuffle_operations.py", line 67, in dataflow_worker.shuffle_operations.GroupedShuffleReadOperation.start (dataflow_worker/shuffle_operations.c:3205)
    self.output(windowed_value)
  File "dataflow_worker/operations.py", line 139, in dataflow_worker.operations.Operation.output (dataflow_worker/operations.c:5717)
    cython.cast(Receiver, self.receivers[output_index]).receive(windowed_value)
  File "dataflow_worker/operations.py", line 72, in dataflow_worker.operations.ConsumerSet.receive (dataflow_worker/operations.c:3421)
    cython.cast(Operation, consumer).process(windowed_value)
  File "dataflow_worker/shuffle_operations.py", line 220, in dataflow_worker.shuffle_operations.BatchGroupAlsoByWindowsOperation.process (dataflow_worker/shuffle_operations.c:8094)
    self.output(wvalue.with_value((k, wvalue.value)))
  File "dataflow_worker/operations.py", line 139, in dataflow_worker.operations.Operation.output (dataflow_worker/operations.c:5717)
    cython.cast(Receiver, self.receivers[output_index]).receive(windowed_value)
  File "dataflow_worker/operations.py", line 72, in dataflow_worker.operations.ConsumerSet.receive (dataflow_worker/operations.c:3421)
    cython.cast(Operation, consumer).process(windowed_value)
  File "dataflow_worker/operations.py", line 395, in dataflow_worker.operations.DoOperation.process (dataflow_worker/operations.c:13546)
    with self.scoped_process_state:
  File "dataflow_worker/operations.py", line 396, in dataflow_worker.operations.DoOperation.process (dataflow_worker/operations.c:13500)
    self.dofn_receiver.receive(o)
  File "apache_beam/runners/common.py", line 195, in apache_beam.runners.common.DoFnRunner.receive (apache_beam/runners/common.c:5142)
    self.process(windowed_value)
  File "apache_beam/runners/common.py", line 267, in apache_beam.runners.common.DoFnRunner.process (apache_beam/runners/common.c:7201)
    self.reraise_augmented(exn)
  File "apache_beam/runners/common.py", line 281, in apache_beam.runners.common.DoFnRunner.reraise_augmented (apache_beam/runners/common.c:7609)
    raise
  File "apache_beam/runners/common.py", line 263, in apache_beam.runners.common.DoFnRunner.process (apache_beam/runners/common.c:7090)
    self._dofn_simple_invoker(element)
  File "apache_beam/runners/common.py", line 198, in apache_beam.runners.common.DoFnRunner._dofn_simple_invoker (apache_beam/runners/common.c:5288)
    self._process_outputs(element, self.dofn_process(element.value))
  File "apache_beam/runners/common.py", line 326, in apache_beam.runners.common.DoFnRunner._process_outputs (apache_beam/runners/common.c:8563)
    self.main_receivers.receive(windowed_value)
  File "dataflow_worker/operations.py", line 72, in dataflow_worker.operations.ConsumerSet.receive (dataflow_worker/operations.c:3421)
    cython.cast(Operation, consumer).process(windowed_value)
  File "dataflow_worker/operations.py", line 395, in dataflow_worker.operations.DoOperation.process (dataflow_worker/operations.c:13546)
    with self.scoped_process_state:
  File "dataflow_worker/operations.py", line 396, in dataflow_worker.operations.DoOperation.process (dataflow_worker/operations.c:13500)
    self.dofn_receiver.receive(o)
  File "apache_beam/runners/common.py", line 195, in apache_beam.runners.common.DoFnRunner.receive (apache_beam/runners/common.c:5142)
    self.process(windowed_value)
  File "apache_beam/runners/common.py", line 267, in apache_beam.runners.common.DoFnRunner.process (apache_beam/runners/common.c:7201)
    self.reraise_augmented(exn)
  File "apache_beam/runners/common.py", line 281, in apache_beam.runners.common.DoFnRunner.reraise_augmented (apache_beam/runners/common.c:7609)
    raise
  File "apache_beam/runners/common.py", line 263, in apache_beam.runners.common.DoFnRunner.process (apache_beam/runners/common.c:7090)
    self._dofn_simple_invoker(element)
  File "apache_beam/runners/common.py", line 198, in apache_beam.runners.common.DoFnRunner._dofn_simple_invoker (apache_beam/runners/common.c:5288)
    self._process_outputs(element, self.dofn_process(element.value))
  File "apache_beam/runners/common.py", line 326, in apache_beam.runners.common.DoFnRunner._process_outputs (apache_beam/runners/common.c:8563)
    self.main_receivers.receive(windowed_value)
  File "dataflow_worker/operations.py", line 72, in dataflow_worker.operations.ConsumerSet.receive (dataflow_worker/operations.c:3421)
    cython.cast(Operation, consumer).process(windowed_value)
  File "dataflow_worker/operations.py", line 395, in dataflow_worker.operations.DoOperation.process (dataflow_worker/operations.c:13546)
    with self.scoped_process_state:
  File "dataflow_worker/operations.py", line 396, in dataflow_worker.operations.DoOperation.process (dataflow_worker/operations.c:13500)
    self.dofn_receiver.receive(o)
  File "apache_beam/runners/common.py", line 195, in apache_beam.runners.common.DoFnRunner.receive (apache_beam/runners/common.c:5142)
    self.process(windowed_value)
  File "apache_beam/runners/common.py", line 267, in apache_beam.runners.common.DoFnRunner.process (apache_beam/runners/common.c:7201)
    self.reraise_augmented(exn)
  File "apache_beam/runners/common.py", line 281, in apache_beam.runners.common.DoFnRunner.reraise_augmented (apache_beam/runners/common.c:7609)
    raise
  File "apache_beam/runners/common.py", line 263, in apache_beam.runners.common.DoFnRunner.process (apache_beam/runners/common.c:7090)
    self._dofn_simple_invoker(element)
  File "apache_beam/runners/common.py", line 198, in apache_beam.runners.common.DoFnRunner._dofn_simple_invoker (apache_beam/runners/common.c:5288)
    self._process_outputs(element, self.dofn_process(element.value))
  File "apache_beam/runners/common.py", line 326, in apache_beam.runners.common.DoFnRunner._process_outputs (apache_beam/runners/common.c:8563)
    self.main_receivers.receive(windowed_value)
  File "dataflow_worker/operations.py", line 72, in dataflow_worker.operations.ConsumerSet.receive (dataflow_worker/operations.c:3421)
    cython.cast(Operation, consumer).process(windowed_value)
  File "dataflow_worker/operations.py", line 395, in dataflow_worker.operations.DoOperation.process (dataflow_worker/operations.c:13546)
    with self.scoped_process_state:
  File "dataflow_worker/operations.py", line 396, in dataflow_worker.operations.DoOperation.process (dataflow_worker/operations.c:13500)
    self.dofn_receiver.receive(o)
  File "apache_beam/runners/common.py", line 195, in apache_beam.runners.common.DoFnRunner.receive (apache_beam/runners/common.c:5142)
    self.process(windowed_value)
  File "apache_beam/runners/common.py", line 267, in apache_beam.runners.common.DoFnRunner.process (apache_beam/runners/common.c:7201)
    self.reraise_augmented(exn)
  File "apache_beam/runners/common.py", line 281, in apache_beam.runners.common.DoFnRunner.reraise_augmented (apache_beam/runners/common.c:7609)
    raise
  File "apache_beam/runners/common.py", line 263, in apache_beam.runners.common.DoFnRunner.process (apache_beam/runners/common.c:7090)
    self._dofn_simple_invoker(element)
  File "apache_beam/runners/common.py", line 198, in apache_beam.runners.common.DoFnRunner._dofn_simple_invoker (apache_beam/runners/common.c:5288)
    self._process_outputs(element, self.dofn_process(element.value))
  File "apache_beam/runners/common.py", line 326, in apache_beam.runners.common.DoFnRunner._process_outputs (apache_beam/runners/common.c:8563)
    self.main_receivers.receive(windowed_value)
  File "dataflow_worker/operations.py", line 72, in dataflow_worker.operations.ConsumerSet.receive (dataflow_worker/operations.c:3421)
    cython.cast(Operation, consumer).process(windowed_value)
  File "dataflow_worker/operations.py", line 395, in dataflow_worker.operations.DoOperation.process (dataflow_worker/operations.c:13546)
    with self.scoped_process_state:
  File "dataflow_worker/operations.py", line 396, in dataflow_worker.operations.DoOperation.process (dataflow_worker/operations.c:13500)
    self.dofn_receiver.receive(o)
  File "apache_beam/runners/common.py", line 195, in apache_beam.runners.common.DoFnRunner.receive (apache_beam/runners/common.c:5142)
    self.process(windowed_value)
  File "apache_beam/runners/common.py", line 267, in apache_beam.runners.common.DoFnRunner.process (apache_beam/runners/common.c:7201)
    self.reraise_augmented(exn)
  File "apache_beam/runners/common.py", line 281, in apache_beam.runners.common.DoFnRunner.reraise_augmented (apache_beam/runners/common.c:7609)
    raise
  File "apache_beam/runners/common.py", line 263, in apache_beam.runners.common.DoFnRunner.process (apache_beam/runners/common.c:7090)
    self._dofn_simple_invoker(element)
  File "apache_beam/runners/common.py", line 198, in apache_beam.runners.common.DoFnRunner._dofn_simple_invoker (apache_beam/runners/common.c:5288)
    self._process_outputs(element, self.dofn_process(element.value))
  File "apache_beam/runners/common.py", line 326, in apache_beam.runners.common.DoFnRunner._process_outputs (apache_beam/runners/common.c:8563)
    self.main_receivers.receive(windowed_value)
  File "dataflow_worker/operations.py", line 72, in dataflow_worker.operations.ConsumerSet.receive (dataflow_worker/operations.c:3421)
    cython.cast(Operation, consumer).process(windowed_valu
</code>
Notice how it is truncated at the very end...after around 10220 characters, and it hasn't even gotten to my actual code's stacktrace yet!
If I open the logs panel and go look at the logs, I'm luckily able to see the full thing...including the very last line that is pointing at my code, as well as the actual exception class/message itself.
Comment: What's the actual question?
Comment: Sorry, I guess it's a bug report of sorts. I filed it on a JIRA for Apache Beam (the code repository for Google Cloud Dataflow), but they told me to file it on stackoverflow, so I came here: https://issues.apache.org/jira/browse/BEAM-1791
Comment: I am having a similar issue with my logs getting truncated from a large exception in the logging of a cloud run service. Quite annoying and  I have yet to find a fix for this...
Answer: The error that shows up in the Dataflow UI is truncated around 10k characters, however if you look in Stackdriver Logging you should be able to see the entire exception.
Comment: Yes, I believe you're restating exactly what I said in the above post, but much more succinctly. :) Sorry, I guess I was trying to file a bug report on the Dataflow UI...I assume this is WAI / Will Not Fix then?

Truncated logs in Google Cloud Dataflow


Can one uniformly generate complex numbers of absolute value less than a given constant $R \neq 1$?

Question: Can one uniformly generate complex numbers of absolute value less than a given constant R?
This would appear to be equivalent to picking points $(x,y)$ uniformly in a disk of radius R, where $x$ is the real component of the complex number, and $y$, its complex component.
This question appears to differ from numerous others that have been asked, in that $R$ is not assumed to equal 1 (that is, the unit disc).
(Note: I am a Mathematica user MathematicaQuestions, not an R [no pun, intended] user.)
Comment: You may always take $R=1$ by choosing the disk's radius to be your unit of measurement.  Regardless, fully general answers have been posted in the duplicate threads.
Answer: The MathWorld entry DiskPointPicking asserts (without an explicit proof) that to generate uniformly distributed  points ($x,y)$ in the unit disk, one should employ
\begin{equation}
x=\sqrt{r} \cos{\theta},\hspace{.2in} y=\sqrt{r} \sin{\theta}.
\end{equation}
where $r \in [0,1]$, and $\theta \in [0, 2 \pi]$ are uniformly distributed
variables.
So for points ($x,y)$ in a disk of radius $R$, it appears then that
one should employ
\begin{equation}
x=\sqrt{\tilde r} \cos{\theta},\hspace{.2in} y=\sqrt{\tilde r} \sin{\theta}.
\end{equation}
where $\tilde r \in [0,R^2]$, and $\theta \in [0, 2 \pi]$ are uniformly distributed
variables.

Upon further reflection/application, I'm somewhat confused here by my original answer (trying to apply the MathWorld argument).
Say,
the maximum absolute value
$R$ of the complex numbers $x+ I y$, I want to generate
is $\frac{1}{2}$. Now (assuming $x=y$, which seems permissible), we have the relation,
\begin{equation}
\sqrt{(\frac{1}{\sqrt{8}})^2+(\frac{1}{\sqrt{8}})^2}=\sqrt{\frac{1}{4}}= \frac{1}{2}.
\end{equation}
So, it seems that I want to choose $\tilde{r}$--before taking its square root--from $[0,\frac{1}{8}]$, not $[0,R^2 =\frac{1}{4}]$.
???
Comment: $\mathbb I$ is an [indicator function](https://stats.stackexchange.com/search?q=indicator+function).
Comment: The proof for the radius distribution is that $(\rho,\theta)$ has density$$\rho\mathbb I_{0<\rho<R}\mathbb I_{0<\theta<2\pi}/R^2\pi$$ when moving from Euclidean to polar coordinates. Hence $r=\rho^2$ has density$$\mathbb I_{0<r<R^2}/R^2$$
Comment: @Xi'an    Don't understand the double-bar notation.


Operator norm on Lebesgue integrable functions

Question: Let $L_1([0,1],m)$ be the Banach space of $\mathbb{K}$-valued integrable functions with respect to Lebesgue measure $m$, where $\mathbb{K}$ is either $\mathbb{R}$ or $\mathbb{C}$. The norm on this space is defined like this: $||f||_1=\int_{[0,1]}|f| \ dm$. I have to show that:
$a)$ For $n \geq 2$ the operator $\varphi_n(f)=\int_{[0,1]}\ f g_n \ dm$, where $g_n(x)=n \sin(n^2x)$ for $x \in [0,1]$ is bounded with $||\varphi_n||=n$.
$b)$ Show that there exists $f \in L_1([0,1],m)$ such that $\lim_{n \to \infty} |\varphi_n( f)|=\infty$.
MY ATTEMPT:
 $g_n$ is Lebesgue integrable on $[0,1]$ since it's Riemann integrable. Hence $fg_n \in L_1([0,1],m)$ and $|\int_{[0,1]}fg_n\ dm| \leq \int_{[0,1]}|fg_n| \ dm$. We also have that $||fg_n||_1 \leq ||f||_1||g_n||_\infty$.
Thus $||\varphi_n(f)||=|\int_{[0,1]}fg_n\ dm| \leq \int_{[0,1]}|fg_n|\ dm=||fg_n||_1 \leq ||f||_1 ||g_n||_\infty$, i.e. $\varphi_n$ is bounded. Now $||g_n||_\infty=n$ since it's continuous on a bounded interval and the $essential$ $supremum$ is the same as the $max$. Now I would like to attain the equality with some function, and once that I find it I can use in part $b)$. Any ideas on the function?
Answer: Answer to part a):  it is not necessary to get equality in $|\int_{[0,1]} f(x)n\sin(n^{2}x)\,dx | \leq \|f\|_1\|g\|_{\infty}$. Instead, we get an 'approximate equality' as follows: let $\epsilon >0$. Choose $\delta >0$ such that $\sin\, x>1-\epsilon$ for $\frac {\pi} 2 -\delta <x <\frac {\pi} 2 +\delta $. Let $f=\frac {n^{2}} {2\delta} I_A$ where $A=(\frac {\pi} {2n^{2}} -\frac {\delta} {n^{2}},  \frac {\pi} {2n^{2}} +\frac {\delta} {n^{2}})$. Simple calculations show that $\|f\|_1=1$ and $\phi_n(f) >n(1-\epsilon)$. Hence $\|\phi_n\| \geq n(1-\epsilon)$ for all $\epsilon >0$. Hence $\|\phi_n\|\geq n$.


How to properly import a function for use in timeit

Question: I'm using the timeit function to run some metrics on two methods I've written, and I'm encountering an issue.  See the simplified example files below:
fileA.py, this runs stand alone, and I'm trying to test the function, foo with timeit:
if (len(sys.argv) < 2):
    print "Need a command line argument, exiting"
    sys.exit(1)

def foo(n):
    #does some stuff, returns an int

This function works fine standalone, I can run it as ./fileA.py 5
I have a similar file, fileB.py that is a different implementation of foo, but is exactly the same except the inside of foo.
Now I have a fileC, where I'm trying to use timeit on both fileA and fileB(fileB part omitted):
for n in range(0,10):
    setupStr = 'from fileA import foo'
    setupStr += '; from __main__ import n'
    mytime = timeit.Timer('foo(n)', setupStr)
    timeTaken = mytime.timeit(1)
    print #results, not important

The issue that I am getting, is that when I run fileC.py, I get "Need a command line argument, exitng" and it exits.  I understand that this is coming from fileA.py, but why is this portion of code being run at all? I was under the impression that the way timeit works, I am only importing foo from fileA.  Am I assuming wrong?  If so, what would be the best way to rectify this, so that I can test the method foo(n) and keep fileA's ability to run standalone with the required command line argument?
Comment: You can also simplify the approach for timing, although it doesn't solve the import problem: directly import the module first, and then use `functools.partial` to create a callable that you pass to `timeit` directly (instead of a string with code in it).
Comment: @KarlKnechtel Nifty, I'll be using timeit fairly frequently I think (this is for a course in data structures), so I'll give that a try next time.
Answer: Python has to evaluate the whole fileA module to resolve from fileA import foo - it would be perfectly legitimate to have foo be a module-level variable name rather than a function, created by code that would have to be evaluated to get the correct value. To avoid this, wrap the code that's supposed to only be run when fileA is being called standalone in:
if __name__ == '__main__':
    if (len(sys.argv) < 2):
        ...

See the accepted answer to this question for a more detailed explanation:
What does if __name__ == "__main__": do?
Comment: That worked perfectly, thank you! Extra thanks for the link to the detailed explanation.


Comentários pesam?

Question: Comentários pesam?
Eu deixar comentários em todo meu código, vai influenciar em alguma coisa no site?
Estou dizendo mais especificamente em HTML, CSS, JavaScript, PHP.
Comment: **Relacionado:** [É seguro e viável minificar os arquivos PHP?](https://pt.stackoverflow.com/a/113963/3635)
Answer: Pesar até pesam, mas você provavelmente usa um minificador, certo? Aí eles desaparecem e não pesam mais.
Eles pesariam se estivessem presentes porque é mais conteúdo para trafegar não só aumentando ligeiramente o tempo de espera do usuário, mas também consumindo banda que alguém tem que pagar. Pode não ser muito, mas se você serve milhões de páginas (dá diferença para você, menos para quem recebe). O processamento no cliente também pesa já que tudo isto precisa ser interpretado. Mas é ínfimo porque só pesará na fase inicial de interpretação que já costuma ser um consumo muito baixo.
Em PHP pesa também pela interpretação, cada caractere tem que ser interpretado. Mas também depois de fazer o parsing não tem peso mais.
Em linguagens compiladas não pesam. Assim como espaços e qualquer coisa que suma na compilação. Até pesam, mas não afetará o desempenho da execução, pesam no processo de compilação, e será ínfimo também, em geral imperceptível porque mesmo em exagero deve ser uma diferença bem inferior a 0,001%.
Então use comentários onde realmente precise deles para facilitar o entendimento e minifique depois para tirar esse irrisório peso. Mas antes faça um código legível que quase não precisará de comentários. Organize seu código para todos poderem ler bem, aprenda fazer isso porque é fácil, dá resultado e mostra profissionalismo.
Existe um mito que código bom é código cheio de comentários. Na verdade é o oposto disto. Quanto mais comentários, mais o código é ruim. Claro que tem casos que o comentário é necessário porque não pode ser expressado toda a complexidade de um problema em código. Em geral comentários devem dizer o porquê e não o que está fazendo. Se tiver que escrever o que, mude o código para ficar mais legível.
Leia:

Como é feito um compilador?
Qual a diferença entre linguagem compilada para linguagem interpretada?
Como saber a medida certa de comentários?

Coloquei no GitHub para referência futura.
Comment: É porque você usou um ruim. Ou o JS já tinha problemas e o minificador apenas expôs mais facilmente.
Comment: No *link* que eu postei tem uma lista deles.
Comment: Você disse "minificador" eu as vezes até penso em usar, mas fico com medo do mesmo "estragar" meu código, remover alguma coisa, etc... Pôs ja aconteceu de eu usar com JavaScript e ele parar de funcionar. Por isso nunca uso, e talvez seja um erro meu isso, não usar.
Comment: Recomenda algum? Que serve pra todos os tipos de linguagens?
Comment: Eu vi, muito obrigado!
Answer: Cada caractere contribui para o peso do arquivo, mas para influenciar negativamente no desempenho tem que escrever muuuuito, sendo assim, comente livremente. Os comentários são de muita ajuda quando formos fazer manutenção do código.
Visualmente eles não influenciam no site ou sistema, eles não aparecem.
Comment: Muito obrigado Gabriel!
Answer: Tendo HTML como base com certeza eles irão pesar, porém pode ser uma diferença insignificante.
Você pode utilizar algum preprocessador para comprimir seu site antes de envia-lo para produção, assim o Script removerá todos os comentários.
Dependendo da maturidade da sua aplicação isso não se faz necessário pois estará se preocupando com algo que na prática não trara resultados visíveis para o usuário. Pois a diferença no final serão de poucos kb, ou nem isso.
Comment: Você terá dois códigos. Um que irá enviar para o servidor e um que irá usar para edição. Antes de enviar para o servidor você pode usar o Gulp para cópia de seus arquivos removendo comentários
Comment: Obrigado, Mauricio!

"Você pode utilizar algum preprocessador para comprimir seu site antes de envia-lo para produção, assim o Script removerá todos os comentários."

No caso eu queria manter os comentários, pra melhor edição depois, se precisar. Melhor edição, digo, ser mais fácil me localizar. Mas então o recomendável é não ter comentários?
Comment: Entendi o que quis dizer. Muito obrigado!

Comentários pesam?


Find the domain of the given function

Question: Currently I am doing vector calculus and in one of the practice problems, it says:
Find the domain of the given function:
$$f(x,y)=y^2*e^{-x^2/2}$$
So for the Domain of this function, we should look at all the x-values which are possible.
Thus $Domain: x\in\Bbb R$
So the steps for this is just looking at the domain in the expression of $e^{-x^2/2}$ right?
So if this is the case, how do we do something for:
$$f(x,y)=\frac{(x+2y)^{\frac{1}{2}}}{x^2+y^1-1}$$
Do we look at both the case $f(x)=x^{\frac{1}{2}}$ and $\frac{1}{x^2}$ ?
Then would the domain be $Domain: x\in\Bbb Z$ because of the $\frac{1}{x^2}$ term?
Comment: Ah, but the domain of your first function should be two-dimensional, because there are two variables $x$ and $y$. So the domain should be a subset of the plane, $\mathbb{R}^2$.
Comment: Oh ok that makes sense. But after that would the first one be right?
Comment: It depends. Which subset of the plane do you get as the domain for the first one? You also need to think in a similar way for the second one - which points $(x,y)$ can you plug into the function.
Comment: Sorry but I don't follow what you mean by "which subset of the plane do you get as the domain for the first one?"
Comment: @HowDoIMath I think there's no second case. The second function is the OP trying to explain his rationale with an example.
Answer: To find function domain you should take the largest possible set and then reduce it if needed.
So here $(x,y) \in \mathbb R^2$ but denominator should be non-zero, so $x^2 + y \neq 1$, or $y \neq 1-x^2$. Thus, the domain is formed by the following rule: $D(f) = \{(x,y) \in \mathbb R^2 : y \neq 1-x^2\}$
Comment: Math does not distinguish variable names. You may have $f = f(a,z)$ or any other set of variables. Domain is not a set of possible values of some argument (like $x$ or some other) but a set of all values of a vector containing arguments as coordinates. Here you have function depending on two variables, so the argument is $2$-dimensional vector, so the domain is a subset of two-dimensional space.
Comment: That helps alot, and makes sense. Thanks
Comment: Wait why is the domain written with respect to (x,y)? not just x ? Isn't domain just x-values?
Comment: Thanks for the clarification!

Find the domain of the given function


Azure Storage in Commvault

Question: I'm busy investigating the Azure storage options for Commvault, and I noticed the article specifying that you need to configure Azure storage as Hot even though it's configured in Commvault as Archive. Am I interpreting this correctly?
https://documentation.commvault.com/commvault/v11/article?p=91299.htm
That does inflate the cost of Azure storage considerably, and I'm battling to understand why this is. the only thing I can think is because of any early access fees that apply to Azure Archive storage?
Can anyone give me the nod on this?
Thanks
Answer: The "must be hot" note on that page is only for Commvault Cool metadata / Archive data and Archive only storage classes. It reads:

Caution: The container must be created with the 'Hot' storage class in
  Azure even if you plan to use the Cool/Archive (Combined Storage
  Tiers) option. Additional cost will be incurred if the container is
  not created as 'Hot' in Azure.

The Hot, Cool, and Hot/Archive classes have just the note:

Note: Additional cost will be incurred if the container is created
  using a different tier.

Presumably, Commvault would change the tier of the blob, otherwise why offer these different classes.
Any tier change has read or write changes, and also early deletion fees apply when source tier is cool or archive.
Archive blobs must first be written as hot or cool first. Cool guarantees an early deletion fee if archived immediately, and has higher access fees than hot. So set hot at the account level if you use archive.
Comment: Thanks John, much appreciated.

Azure Storage in Commvault


How can I set the environment value which is begin from a single quote in systemd

Question: I've tried to set following in my systemd's service file
Environment=SETTINGS=\'{"a"=1}\'

But seems that both the single quotes are been removed, so I get {"a"=1} as the value for the environment variable SETTINGS
How I can set that correctly?
Comment: I think maybe you can do this in an `EnvironmentFile` with appropriate escaping. But you're deep into [undocumented territory](http://www.freedesktop.org/software/systemd/man/systemd.exec.html#Environment=) here. Though, for something like this you really ought to be using an `EnvironmentFile` regardless.
Comment: After reflecting on this a while, I think you have actually found a bug in systemd. This smells like a parser running twice on the same input.
Comment: To be clear: Do you actually _want_ the single quotes to be present in the environment value?
Comment: Unfortunately, I currently need to set something like `METEOR_SETTINGS='{"public":{"ga":{"account":"UA-xxxxxx-2"}}}'`
Comment: I've summit it to their bug tracker
Answer: This works for me:
$ cat /run/user/1000/systemd/user/envtest3.service
[Service]
Environment=SETTINGS=\'{"a"=1}\'
Environment=SETTINGS2='{"a"=1}'

Type=oneshot
ExecStart=/bin/env

then
$ systemctl --user start envtest3.service
$ journalctl --user -n 2
-- Logs begin at wto 2014-05-27 15:33:38 EDT, end at sob 2014-10-04 11:44:13 EDT. --
paź 04 11:44:13 fedora21 env[27607]: SETTINGS='{"a"=1}'
paź 04 11:44:13 fedora21 env[27607]: SETTINGS2='{"a"=1}'

As you can see, the variables get set properly.
You can also use those variables in the unit itself:
...
ExecStart=/bin/echo ${SETTINGS} ${SETTINGS2}
ExecStart=/bin/echo $SETTINGS $SETTINGS2

and there's surprising thing here:
paź 04 14:27:50 fedora21-amd64 echo[30304]: '{"a"=1}' '{"a"=1}'
paź 04 14:27:50 fedora21-amd64 echo[30306]: {"a"=1} {"a"=1}

The expansion with braces does not strip the quotes, but the other one does. I'm not sure if this is a bug, or not. The manpage says "split at whitespace".
Edit: I'm runninng latest git (v216-456-gba58907547).


how to get the data using whereHas clauses and relationship?

Question: user table
id
email
password

membership table
id
user_id
expiry_date
delivery_day_innum(eg:like 7,8 days)

deliverdetailes table
id
user_id
created_at
updated_at

goods table
id
user_id
name
qty

goods table
id
user_id
name
qty

Relationship
user->hasOne(Membership::class)
user->hasMany(Deliverdetailes::class)
user->hasMany(Goods::class)

now, i wan to get the goods whose account is not expired and deliver_day_innum is equals to the
  difference between the present day with the latest created_at date
Comment: what u actually want ?? The respective goods of the user with the conditions?
Comment: yes you are right @hitler_jr10
Answer: $myGoods= Goods::join('user','user.id','goods.user_id')
->join('membership','membership.user_id','=','user.id')
->join('deliverdetailes','deliverdetailes.user_id','=','user.id')
->whereDate('expiry_date','>',Carbon::now())
->whereRaw('DATEDIFF(maxDate, CURDATE())=membership.delivery_day_innum')
->select('goods.*',DB::raw('max(deliverdetailes.created_at) as maxDate'))->get();

Comment: would you mind writing using ORM?? i appreciate your work
Comment: it's generally ORM, except for using "raw" twice, it's necessary to use  (DATEDIFF ,max) function from mysql, and for 'join' it's necessary and i don't know other way to do it without join.
Comment: you can use advanced query but the complication would be the same:
https://laravel.com/docs/7.x/eloquent#advanced-subqueries
Answer: First problem: Goods for accounts that have not expired:
Adjust Carbon::now() to match the date format for expiry_date.
   $goods = Good::whereHas('user.membership', function($query){
       return $query->where('expiry_date', '<=', Carbon::now());
   })->get();

Required in App\Good: relationship with App\User.
public function user()
{
    return $this->belongsTo('App\User');
}

Second problem: please clarify: "deliver_day_innum is equals to the difference between the present day with the latest created_at date".


Client-Server application that can process multiple request depending on the client-side

Question: I have a client-side driven GUI (Swing) and I need to process more that one request. I can process one request, For example, 'logging in, the user' but I am unable to make any other request like 'fetch all users' from the server.
How can I process more than one request on the server and how would I set it up on the client-side.
Client-Side
    private Socket server;

    public ClientConnection() {
        try {
            server = new Socket("127.0.0.1", 12345);
        } catch(IOException e) {
            System.out.println("Connection Error - Client: " + e.getMessage());
        }
    }

    public void loginUser(User user) {
        try {
            ObjectOutputStream out = new ObjectOutputStream(server.getOutputStream());
            out.flush();
            ObjectInputStream in = new ObjectInputStream(server.getInputStream());

            //How would I write the request type to the server

            out.writeObject((User) user);
            out.flush();

            User getUserInfo = (User) in.readObject();
            //System.out.println("Response from the server: " + getUserInfo.getRole());

            out.close();
            in.close();
            server.close();
        } catch(IOException e) {
            System.out.println(e.getMessage());
        }
    }

Server-side
    private ServerSocket serverListener;
    private Socket client;

    public ServerConnection() {
        try {
            serverListener = new ServerSocket(12345, 10);
        } catch(IOException e) {
            System.out.println("Server-Side Error: Connection" + e.getMessage());
        }
    }

    public void server() {
        try {
            System.out.println("Server is listening");
            client = serverListener.accept();

            //How can I make a request and then process it depending on the type of
            //request

            //Gets the ObjectOutputStream and the ObjectInputStream and send a User object back to
            //the client-side
            loginUser();

        } catch(IOException e) {
            System.out.println(e.getMessage());
            e.getStackTrace();
        }

    }

My initial thinking is to have an Enum class with different request types and then have a switch statement in my server() method and depending on the type of request a method is called to perform those actions but I am not sure on how to send a request type to the server and if handling the request type in the server() method would be best practices.
Comment: If I understand correctly you want to be able to handle multiple behaviors based on what you are receiving?
Comment: Yes @Flav How would I handle that on the client-side and server-side?
Answer: What you need to think about is how to define the communication between your client and server. Define protocols and message structures.
Let's say you want to introduce multiple request types. It is up to you what those request types will be, but what is going to happen is that you will be introducing the logic to handle the new types of requests on both the client and server.
Just like in REST, both client and server know what GET/POST is - you will also need to have these protocols defined for your communication.
An example would be, your client is sending a request of type fetch-all-users. One way to structure this would be:
{
   "requestType": "fetch-all-users",
   "body": "..."
}

You can have a common module for the enum types, that is up to you.
Further on, we get to the question on how you would like to process the request on the server side.
A straightforward solution would be adding if-else logic to process the correct request type based on the provided type.
But to avoid the if else logic, you could play around with design patterns.
Create a factory for your requestProcessingActions:
class ActionFactory {

   public Action resolve(RequestType requestType) {
     final Action resolvedAction;

     switch(requestType) {
       case fetch-all-users:
          resolvedAction = fetchAllUsers();
          break;
       case log-in-user:
          resolvedAction = logInUser();
          break;
     }

     return resolvedAction;
   }
}

And call it in your server:
public void server() {
        try {
            System.out.println("Server is listening");
            client = serverListener.accept();

            RequestType type = getRequestTypeFromRequest();

            ActionFactory.resolve(type);
        }
    }

Comment: It might be wise adding a loop in the `server()` method to handle the next incoming requests
Comment: How would I be able to send a request type and information from the client-side to the server -side. Because I can only read one object through to the server, I don't get the other object. For example, if I need to send a request type and a user object to my server, how/what class, can I use that would help my process both objects on the server side?
Comment: Thanks for the detailed answer @Bon. Not exactly what I am looking for but I can see where you're going with it. The request type example, you provide is in JSON (if i am not mistaken), how can I work with JSON because I am not using a framework, and I would like it in pure Java (not using a framework).

If there is an easier way to handle this problem with JSON, how would I do it?
Comment: Yep I understand, one reason why I prefaced my answer with the point that you need to think about defining message structures.
Requests that you receive in the server are just a stream of bytes - how you interpret those bytes is up to you.
JSON is one way to structure the request, as it is properly defined, and you can use java serialization/deserialization to materialise the byte stream into a proper java class, and vice-versa.

Frameworks are different from a library - java has serialization libraries and you can use them regardless whether you use a framework or not.
Comment: If you really want to avoid JSON - you can make your own byte stream reader, with logic on how to properly read the requests.  For example you can send a request with the string "fetch-all-users;body;", and have a configured reader on the server that knows how to read it. For exampe - ok, request-type is until the first ';' character.
You are now writing serialization logic, which is good for learning, but of course it would be easier to use JSON and its serialization libraries in java.
Comment: I would like to use JSON if it its better, could you refer me to, where I could learn it or can you show an example of how you would make a request to the server using JSON?

Thanks @Bon
Comment: https://www.baeldung.com/java-serialization-approaches
You can choose what is best for you. There is an example on how to serialize an object into an output stream, which you need for sockets.

Basically, an approach to take would be - model a request structure (define a class) -> create instance of a request -> serialize and send from client to server -> deserialize the stream into a class -> work with it
Comment: As a beginning, you can experiment with one type of request. After that what you need to do is make a generic request structure - where the type is the type of the request, and a generic object property as the body value. This will enable you to send multiple types of requests.


Find the probability that a normal variable takes on values within .9 standard deviations of its mean?

Question: Find the probability that a normal variable takes on values within 0.9 standard deviations of its mean. (Round your decimal to four decimal places.)
Could someone explain to me how to do this one, I am currently struggling with these normal distribution problems, thank you for any tips that you can provide, I am not exactly even sure where to start
Not sure why this is getting down voted I am not asking for the answer, i just would like to know how to do it
Answer: Integrate the normal density function. I let you think about why you don't need to specify any mean or standard deviation explicitly and that the result is always:
$$P=\frac{1}{\sqrt{2\pi}}\int_{-0.9}^{0.9}e^{-\frac{x^2}{2}}\approx0.6319$$
Comment: Thank you for that explanation, I sincerely appreciate it.
Answer: It suffices to take a standard normal random variable $Z \sim \mathcal{N}(0, 1)$ (I encourage you to answer the question "Why?" for this). We're asked to compute $P(|Z| \leq 0.9)$, as z-scores tell us the number of standard deviations we are away from the mean.
We can then write, by definition of absolute value,
$$ P(|Z| \leq 0.9) = P(Z \leq 0.9) - P(Z \leq -0.9) $$
as this is how we compute probabilities using cumulative distribution functions (CDFs). These are easily read in any well-written table like this, and thus we obtain the answer to be $0.6318$.
This is the general approach: convert to z-scores and read things from your table (or a computer). I suggest you continue to read your notes and your texts for more information.
Comment: Thank you for this helpful explanation, I appreciate it.


multiple class selection targeting distinct children

Question: try the following:
add two divs to a page with the same class name.
add two elements within each div: for argument's sake paragraphs.
make the text color of the first paragraph of each div red.
why can't i figure out how to do this relatively simple task without having to use id's?
Comment: I think no one can answer this question. How should *we* know why you can't figure it out? We, or at least I,  don't even know you. ( ;) )
Answer: You can do it like this in jQuery (:first-child selector):
$(".myClass > :first-child").css('color', 'red');

But CSS will do it as well (CSS :first-child selector), and you should use this route if possible :)
.myClass > :first-child { color: red; }

Comment: thanks nic. i had tried both selectors, but didn't think to use them in combination. my example is a bit simplistic - i need to do some manipulation first, so css wouldn't be the way to go in my situation.


Iptables - Bridge and Forward chain

Question: I have setup ethernet bridge br0 that contains two interfaces eth0 and tap0
brctl addbr br0
brctl addif eth0
brctl addif tap0
ifconfig eth0 0.0.0.0 promisc up
ifconfig tap0 0.0.0.0 promisc up
ifconfig br0 10.0.1.1 netmask 255.255.255.0 broadcast 10.0.1.255

My default FORWARD chain policy is DROP
iptables -P FORWARD DROP

When i do not add following rule the traffic is not passing through bridge.
iptables -A FORWARD -p all -i br0 -j ACCEPT

As far as I understand iptables is only responsible for IP layer.
ebtables should be responsible for filtering traffic on the ethernet bridge.
So why do I have to add ACCEPT rule in iptable's FORWARD chain?
Answer: Because of the br-nf code that is available as a patch to linux 2.4 and used in linux 2.6:

The br-nf code makes bridged IP
  frames/packets go through the iptables
  chains. Ebtables filters on the
  Ethernet layer, while iptables only
  filters IP packets.

Since the traffic you are working is ip, iptables rules still apply because of br-nf passing the bridged packets to iptables.
This is a great resource to read about the interaction and this one details the functionality of br-nf code, including how to disable all or some of the functionalities (i.e. not passing bridge traffic to iptables).
Comment: Answering myself:
# Load br_netfilter
modprobe br_netfilter
 # Add to BROUTING chain rule to forward all ipv4 packets to iptables
 ebtables -t broute -A BROUTING -p ipv4 -i br0 -j DROP
Comment: The functionality is not working on 4.4.0-22-generic (ubuntu 16.04), even after I did `echo "1" > /sys/devices/virtual/net/br0/bridge/nf_call_arptables`. Any ideas?
Answer: You can disable this behaviour (letting iptables handling bridged packets) by typing:
echo "0" > /proc/sys/net/bridge/bridge-nf-call-iptables

(see http://ebtables.sourceforge.net/documentation/bridge-nf.html)
Comment: Also, /proc/sys/net/bridge/bridge-nf-call-ip6tables
Answer: If you do not have the need to use iptables with the bridge on your system you can permanently disable it by using either of the following:

Adding an iptables rule:

iptables -I FORWARD -m physdev --physdev-is-bridged -j ACCEPT

Or editing /etc/sysctl.conf:

net.bridge.bridge-nf-call-ip6tables = 0
 net.bridge.bridge-nf-call-iptables = 0
 net.bridge.bridge-nf-call-arptables = 0
Answer: The ebtables chains won't see frames entering on a non-forwarding bridge port. Might take a look at this: http://ebtables.sourceforge.net/br_fw_ia/br_fw_ia.html

Iptables - Bridge and Forward chain


Weird acciaccatura (?) notation in Chopin's polonaise

Question: I am not sure how to interpret the particular notation in Chopin's Op.53 Polonaise:

Here, we have a single (smaller font) Eb (just before the trill). I should interpret it as a grace note, but then there is a slash. Therefore, I assume it to be an acciaccatura, however, I am more used to see acciaccaturas to have a slur to the principal note:

while in the posted fragment, the slur-mark is missing. Moreover, it is an acciaccatura to the same note (Eb) – which would make an omitted (?) slur a tie.
So, what's the deal with that notation? Am I missing some message from Chopin or the editor?
Answer: There is nothing mysterious here.  As you say, if it were slurred that would make it a tie, and that wouldn't make much sense in this setting.  It all looks clear to me.  Simply play the slashed Eb slightly before the beat and then start the trill on another Eb.
Comment: That's how every major recording does it.  Nothing controversial.
Comment: In Chopin's time trills in his music were supposed to start on the beat. That means that when there is a grace note that note starts on the beat. If the grace note is the same note as the main note, which it is in this case, it just means that the trill starts on the main note on the beat. I do know that there are many pianists, even very famous ones, who starts before the beat, but that is not an authentic way of doing it. In generel trills in Chopin's music should start on the upper note, unless something else is indicated as it is here. @Anton Menshov
Comment: @LarsPeterSchultz that's interesting and seems to contradict what others are saying, if I understand your comment correctly. Just to confirm: are you suggesting that the only purpose of that slashed Eb is to indicate that the trill starts (on the beat) on Eb and then trills upward to the F (and not doubled the Eb the way others have mentioned - and most recordings have it?)
Comment: @TonAuger yes it means that trill starts on E♭. As a general rule of thumb Chopin's ornaments start on the beat. I know that many piano players start before the beat but that doesn't make it right, it only means that that is what they do. On this site https://starpianostudio.musicteachershelper.com/  you can find a document on Chopin's ornamentation. Here is the document:  https://starpianostudio.musicteachershelper.com/resources?download=true&download_link=877c21669853017fd1a7ba2e7117e2f4
Comment: An extra note.  If you look at my first comment you can see that I wrote something that is wrong, I wrote: "In generel trills in Chopin's music should start on the upper note, unless something else is indicated as it is here." But in the document that I linked to in my former comnent it clearly states that a trill should start on the principal note if there is no direction. So on this point I was wrong.
Comment: @LarsPeterSchultz As I have elaborated in my response to your comment to my post, the writer you cite as an authority doesn't present any evidence to back up his opinion. As such, you haven't presented any evidence to back up yours, either. As for whether to start the trills on the upper or lower note, I didn't find evidence in that book that this is anything more than the author's opinion either.
Comment: @TomAuger I find myself skeptical when people step up and assert that most experts are doing whatever wrong. Upon further investigation, it usually turns out that they do so with very little evidence to back up the assertion. As in the present case, where one only need read the preface of the book to find that its author states that his interpretations are based on "internal evidence," which boils down to the author's own reasoning about the score itself. There are lots of better Chopin interpreters than he who obviously draw different conclusions about the score.
Comment: @BobRodes the document I referred to is a book on Chpoin's ornamentation written by J  P. Dunn which can be found for free at the Internet. I have never seen any other book on that matter. It is an amazing work. Anyway, in the Library of the Paris Conservatoire you can find signs written with Chopin's own hand in the sheet music copies of Madane Dubois, signs that leave no doubt that his ornaments is intended to be played on the beat.
Comment: An extra note: The reference to the sheet music of Madam Dubois I found in my copy of Paderewski's edition of Chopin's mazurkas. I have also seen that reference mentioned on the Internet.
Comment: @LarsPeterSchultz I'm familiar with the Dubois notes, and we come to different conclusions based on the evidence. They leave no doubt that he wanted M. Dubois to play those particular ornaments that way. To infer that from those examples he intended his ornaments always to be played on the beat is to infer a great deal too much, unless I've missed a written statement in his handwriting to that effect.
Answer: The reason for a slash in a note is not that it is a grace note per se, but that it is to be played outside the context of the meter. In other words, it's a note that you "throw in" in whatever way sounds good to you. So, it's that a grace note is played outside of the meter, so it has a slash in it, not that because it has a slash in it, it's a grace note.
So, the common interpretation is just as Jomiddnz has it, and as C.G. mentions, that is how it is played in pretty much every major recording of the piece.
Another thing not to make too much of is the fact that the D natural and E flat are written as 16th notes, which would take up the entire value of the 8th note trill. All it's saying is to put a turn at the end of the trill. (Don't expect those "little notes" to precisely follow a meter; they usually don't.) So, the figure is generally played like this:

In the usual tempo range, most people just put a simple mordent for the trill as I have it here. I've looked at several recordings, and nearly all of them definitely use the notes I have here (as do I). I'd say that you're entirely safe doing the same.
Also note that most performances borrow the grace note's time from the previous sub-beat, meaning that the first Eb of the quintuplet falls directly on the second beat, and the grace note a little before. This appears to contradict your wikipedia link for the acciaccatura, which says this:

In the 19th century, the acciaccatura (sometimes called short appoggiatura) came to be a shorter variant of the long appoggiatura, where the delay of the principal note is quick.

In the performances I've listened to, there is no delay of the principal note at all, and the grace note borrows from the previous beat. I believe that this is the correct interpretation of the notation; it's certainly the one that pretty much everyone uses.
Comment: Despite the fact that many pianists play the grace notes by burrowing from the previous beat it is not authentic. Chopin's ornamentation should start on the beat as a general rule. On this site https://starpianostudio.musicteachershelper.com/  you can find a document on Chopin's ornamentation. Here is the document:  https://starpianostudio.musicteachershelper.com/resources?download=true&download_link=877c21669853017fd1a7ba2e7117e2f4
Comment: @LarsPeterSchultz I wouldn't make the assertion that it is not authentic based on a book in which the preface states that the "correct" interpretation of ornamentation is "based, and could indeed be based only on internal evidence, for the traditional knowledge that we possess regarding this aspect of Chopin's art is disappointingly vague." In other words, what you are calling "authentic" is simply the writer's opinion (what he rather evasively calls "internal evidence").
Comment: @LarsPeterSchultz Furthermore, your further conclusion that it "should start on the beat as a general rule" flies in the face of the fact that it is a rule to which most performers don't adhere. If it were really a general rule, one would not see it generally broken in practice.
Comment: In the Library of the Paris Conservatoire you can find signs written with Chopin's own hand in the sheet music copies of Madane Dubois, signs that leave no doubt that his ornaments is intended to be played on the beat. The reference to the sheet music of Madam Dubois I have in my copy of Paderewski's edition of Chopin's mazurkas. I have also seen that reference mentioned on the Internet.
Comment: @LarsPeterSchultz [This performance](https://www.youtube.com/watch?v=LC2lwbkzf78) sums up my opinion on the subject, which is that it is not a hard-and-fast rule either way. To extrapolate from a small sample of Chopin's directions to his students an edict for his entire body of work doesn't make sense to me. Study of the waltzes shows that he wrote out appoggiaturas often enough, sometimes on the beat, sometimes before it.
Comment: BobRodes try out playing some of those ornaments you usually play before the beat on the beat. Feel and listen how it is. I think when the ornaments are played before the beat they are often played very fast and there is a risk that it sounds a bit hectic.  If you play them on the beat there is more room for a delicate performance and sensitivity.  Also think about that Chopin is known to have suggested to his pupils to listen to singers in order to get inspiration.
Comment: @LarsPeterSchultz You mean, if I try this out (which of course I have never done before), I'll just have to see things the same way you do? LOL Silly human.
Comment: I certainly hope you will get your own experiences.
Comment: @LarsPeterSchultz I'm sorry, I was being sarcastic when I said "which of course I have never done before," pointing out your apparent assumption that the only way I could disagree with you is if I have never tried the ornaments both ways, because I simply couldn't possibly come to a different conclusion from your own if I had. I'll share something with you. (...)
Comment: (...) I'm currently working on Chopin's little Prelude No. 10, which has just such an ornament in a left-hand trill in the sixth full measure. I start that one on the beat. I've also worked on Chopin's third ballade fairly extensively. In the opening phrase, I start the small ornament in the answer in the bass before the beat. Finally, in the Funeral March movement in Sonata No. 2, I do the grace notes before the beat, and I play the turns on the trills in the left hand on the beat. That all is what sounds best to me.


Difference in cardinality of arranged subsets

Question: Prove that for any nonempty set, we can put its subsets in a row, so that any two neighboring subsets differ on their cardinality by $1$.
Here is my attempt on this:
Let the nonempty set be $S$. We use induction on the $|S|$.
For the base case, $|S|=1$, it only has one subset, which is $S$ itself, so the statement is clearly true.
For the inductive step, we need to prove that the condition is true for $n+1$ given that it is true for $n$. When we append the element $n+1$ to $S$,  then the new subsets formed are all of the subsets before along with $n+1$ appended to them.
Now, I'm not sure where to go from here. Could someone please help?
Comment: If $|S|=1$, then $S$ has two subsets, $S$ and $\varnothing$. Fortunately, they differ by just one element.
Comment: How does your approach work with infinite sets?
Answer: Sketch. Take any $a \in S$ and arrange the subsets as follows: first arrange the subsets of $S \setminus \{ a \}$ in a sequence using the induction hypothesis. Then write the same sequence backwards, appending $a$ to each subset. The two sequences one after another form the desired arrangement.
By the way, the resulting construction is known as the Gray code.
Comment: @CoolMath200 The "backwards" ensures that the last subset in the first (forward) half and the first subset in the second (backward) half differ by only one element, $a$.
Comment: Why are you writing the sequence backwards? Why not forwards?


Finding a projection matrix onto the $xz$-plane.

Question: I'm having some trouble with the following linear algebra question:
Projecting onto the $xz$-plane or the $yz$-plane can easily be performed through rotations. For instance, if you want to project onto the $xz$-plane,you need to rotate the $y$-axis to the $z$-axis (this is a rotation about the $x$-axis), then perform the projection, and rotate back. Write down the projection matrix which does just this.

So I'm pretty sure that the answer will be the product of $3$ matrices? Since we want to project on the $xz$-plane, we want to rotate about the $y$-axis around the $x$-axis to the $z$-axis.
I've tried for several hours, but I cannot come up with much. Any help is appreciated.
Comment: Isn't a projection onto the $xz$-plane simply changing the $y$-component to zero? i.e. $(x,y,z) \mapsto (x, 0, z)$? Or am I misunderstanding something?
Comment: Yes, but I also need to rotate the $y$-axis to the $z$-axis before I perform the projection (and then rotate it back afterward), right? I'm having trouble coming up with a matrix that performs this task.
Comment: The process you have described doesn't provide a projection onto $xz$-plane...
Comment: If we want to project onto the $xz$-plane, we can first rotate the $y$-axis to the $z$-axis (which is a rotation around the $x$-axis), then project, and rotate back. I need to find a matrix that performs this.
Answer: A projection matrix onto $xz$ plane is simply given by
$$P = \begin{bmatrix} 1 & 0 & 0 \\  0 & 0 & 0 \\  0 & 0 & 1 \end{bmatrix}$$
indeed for any $v=(a,b,c)$ we have
$$Pv=(a,0,c)$$
Comment: Thank you so much. Just one final question -- how can I use this matrix to project a point (say, (1, 2, 3)) with a center of perspective defined for $y$? (say, $y = 10$). I've been nonstop reading wikipedia pages, and I can't get anything...
Comment: wait, I'm not sure if the matrix is supposed to be that simple. shouldn't it be a product of three matrices? this is a  perspective projection in which the rays formed aren't all parallel
Comment: @blackmoon2031 Ah ok you are looking for a [Perspective_projection](https://en.wikipedia.org/wiki/3D_projection#Perspective_projection) problem.
Comment: do you know how to help me please? I have been struggling for very long


Como fazer cálculos em Javascript aceitando vírgula para separar casas decimais

Question: Estou fazendo um app onde em campos que aceitarem decimais, o cliente pode colocar a vírgula ao invés de ponto (que é o comum visualmente). Qual a melhor forma de eu transformar uma string "12,34" em um numeral como 12.34?
Comment: Você pensa em alterar no núcleo do JS?
Comment: Viste esta pergunta e respostas? -> http://pt.stackoverflow.com/q/11018/129
Answer: Use os seguintes métodos do Javascript

replace para trocar a virgula por ponto
parseFloat para converter para float/double
toFixed para definir quantas casas decimais você quer após a virgula

var string1 = '21,21';
var string2 = '10,8';

var numero1 = parseFloat(string1.replace(',', '.'));
var numero2 = parseFloat(string2.replace(',', '.'));

document.write('Número 1: ' + numero1 + '
');
document.write('Número 2: ' + numero2 + '
');
document.write('Soma: ' + (numero1 + numero2).toFixed(2) + '
');
Comment: @LeandroLUK a primeira resposta foi a minha, mas tudo bem, o importante é resolver seu problema. :)
Comment: vlw mas já tinha sido respondida anteriormente
Answer: Pode utilizar o replace onde você delimita o caracter a ser substituído e depois passá-lo para float:
var comVigula = "1,87";
comVirgula = parseFloat(comVirgula.replace(',','.'));
alert(comVirgula);

Após isto é só utilizar como quiser em seu código.
Answer: Vamos supor que o valor formatado em dinheiro seja: R$ 1.234,53
No exemplo acima você terá ponto e vírgula, neste caso, se usar o .replace(',','.'), seu número de saída seria algo assim: 1.234, mas o correto deveria ser 1234.53. Pense agora na casa de milhares (1.000.000.000,00), quantas formatações precisariam..., então seria ideal que tivesse uma regra geral para todo mundo, evitando futuros transtornos, você pode criar um método da seguinte maneira, independente do valor de entrada:
//em float
formatNumber(1234.53);
//em string real
formatNumber('1.234,53');
//em string real sem ponto
formatNumber('1234,53');
//em string americano
formatNumber('1,234.53');

//retornará 1234.53
function formatNumber(value) {
    value = convertToFloatNumber(value);
    return value.formatMoney(2, '.', '');
}
//retornará 1.234,53
function formatNumber(value) {
    value = convertToFloatNumber(value);
    return value.formatMoney(2, ',', '.');
}
//retornará 1,234.53
function formatNumber(value) {
    value = convertToFloatNumber(value);
    return value.formatMoney(2, '.', ',');
}

 //transforma a entrada em número float
 var convertToFloatNumber = function(value) {
     value = value.toString();
      if (value.indexOf('.') !== -1 && value.indexOf(',') !== -1) {
          if (value.indexOf('.') <  value.indexOf(',')) {
             //inglês
             return parseFloat(value.replace(/,/gi,''));
          } else {
            //português
             return parseFloat(value.replace(/./gi,'').replace(/,/gi,'.'));
          }
      } else {
         return parseFloat(value);
      }
   }

//prototype para formatar a saída
Number.prototype.formatMoney = function (c, d, t) {
    var n = this,
        c = isNaN(c = Math.abs(c)) ? 2 : c,
        d = d == undefined ? "." : d,
        t = t == undefined ? "," : t,
        s = n < 0 ? "-" : "",
        i = parseInt(n = Math.abs(+n || 0).toFixed(c)) + "",
        j = (j = i.length) > 3 ? j % 3 : 0;
    return s + (j ? i.substr(0, j) + t : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + t) + (c ? d + Math.abs(n - i).toFixed(c).slice(2) : "");
};

Answer: Só complementando a resposta do Ivan Ferrer, na linha:
            //português
         return parseFloat(value.replace(/./gi,'').replace(/,/gi,'.'));

Ficou faltando o "\." para escapar o ".". Ajustando ficaria assim:
            //português
         return parseFloat(value.replace(/\./gi,'').replace(/,/gi,'.'));

Com ajuste, funcionou perfeito para mim.
Answer: Eu suponho que você queira fazer alguns calculos com os numeros que seus clientes colocam e também acho que você deve querer salvar alguns valores na sua database. Então seria bom que ficasse padronizado e em todos os lugares você salvasse o número mesmo(Ex. 123123123 ao invez de 123.123.123) e apenas quando fosse mostrar para o seu cliente você colocaria as virgulas e os pontos que precisassem.
Desse modo, você pode usar as funções tanto na database como no seu backend como no seu front end e claramento so precisará mudar algo quando for mostrar pro seu criente.
Se você quiser colocar pontos e virgulas também, por examplo 123.232,32
Eu uso a seguinte função: (Vale lembrar que ela foi feita para preços de produtos, se você realmente quiser apenas trocar virgulas por pontos e pontos por virgulas é melhor usar num.replace(',', '.'))
function brl_comma_dot(num){
    var num_1 = parseInt(num);//Pega a parte inteira do numero
    var num_2 = Math.round((num-num_1)*100);//Pega a parte nao inteira
    var digits = [];
    while(num_1 >= 1){//Enquanto a parte inteira for maior que 1
        var digit = num_1 % 10;
        digits.push(digit);//Guarda cada digito neste array em ordem contraria
        num_1 = Math.floor(num_1/10);
    }
    num_1 ="";
    //Para todos os numeros no array adiciona "." a cada 3 numeros
    for(var i = 0; i< digits.length; i++){a
        if( i % 3 == 0 && i != 0){
            var comma = '.';
        }else{
            var comma = '';
        }
        num_1 = digits[i]+ comma +num_1;
    }

    if(num_2 < 10 && num_2 != 0){
        num_2 = "0" + num_2;
    }else if(num_2 == 0){
        num_2 = "00";
    }else if(num_2 % 10 == 0 && num_2 !=0){
        num_2 = num_2/10;
        num_2 = num_2+"0";
    }
    if(num_1 == 0){
        num_1 = "0";
    }
    var num_with_comma = num_1+","+num_2;
    return num_with_comma;
}


iOS: Sides of UITableViewCell showing a different color when cell background is changed (Xcode 8, Swift 3)

Question: When implementing a UITableView, I added a background image and set the table view to transparent. However, the sides of the table remain clear even when I change the table view cells to a different color (in order to see the text better), as shown in this image: Table View Cell.
The code I added to get the inner part of the table view:
func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
        cell.backgroundColor = UIColor(white: 1, alpha: 0.25)
        cell.accessoryView?.backgroundColor = UIColor(white: 1, alpha: 0.25)
        cell.contentView.backgroundColor = UIColor(white: 1, alpha: 0.25)
        cell.tintColor = UIColor(white: 1, alpha: 0.25)
}

And in viewWillAppear:
self.tableView.backgroundColor = UIColor(white: 1, alpha: 0.25)

I'm not sure why the sides don't show up as the same color. I thought it had something to do with the accessory button, but when attempting to change that as well, nothing was changed.
Answer: The contentView doesn't cover the whole cell. Try making the setting its background color to the clear color. Then only the cell's background view will show through.
Answer: Much of your code is sheer waste; it has nothing to do with the matter. The key lines are:
cell.backgroundColor = UIColor(white: 1, alpha: 0.25)
cell.contentView.backgroundColor = UIColor(white: 1, alpha: 0.25)

That's a silly thing to do, as you are overlaying the cell's translucent background color with another background color (the background color of the content view, which sits in front of the cell).
When you have a problem like this, solve it yourself by making a simpler, clearer test case. For example:
    cell.backgroundColor = .red
    cell.contentView.backgroundColor = .green
    cell.accessoryType = .checkmark

That makes it perfectly obvious what's going on: the green content view partially obscures the red cell. Your code does exactly the same sort of thing.
Comment: I know this. The problem is not with the color itself, it's with the alpha of the cell. The alpha factor doesn't get applied to the sides.
Comment: It does, you know. But as I said, in some areas you're overlaying one alpha with another.


Unable to convert docx to html using Java

Question: I need to convert .docx file content to HTML text in order to display in web ui.
I've used Apache POI's XWPFDocument class but haven't been able to get any results yet; getting empty string. My code is based on this sample.
Here's also my code:
public JSONObject uploadDocxFile(MultipartFile multipartFile) throws Exception {
        InputStream inputStream = multipartFile.getInputStream();
        XWPFDocument wordDocument = new XWPFDocument(inputStream);

        WordToHtmlConverter wordToHtmlConverter = new WordToHtmlConverter(DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument());
        org.w3c.dom.Document htmlDocument = wordToHtmlConverter.getDocument();
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        DOMSource domSource = new DOMSource(htmlDocument);
        StringWriter stringWriter = new StringWriter();

        TransformerFactory tf = TransformerFactory.newInstance();
        Transformer serializer = tf.newTransformer();
        serializer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
        serializer.setOutputProperty(OutputKeys.INDENT, "yes");
        serializer.setOutputProperty(OutputKeys.METHOD, "html");
        serializer.transform(domSource, new StreamResult(stringWriter));
        out.close();

        String result = new String(out.toByteArray());
        String htmlText = result;

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("content", htmlText);
        jsonObject.put("success", true);
        return jsonObject;
    }

Comment: possible duplicate of [Converting a .docx to html using Apache POI and getting no text](http://stackoverflow.com/questions/13103421/converting-a-docx-to-html-using-apache-poi-and-getting-no-text)
Comment: there's no proper answer at there.. owner of question opened that question with the same reason with me; but he added a comment that he has no problem while getting text.
Answer: even if it's too late I think that the previous code can be modified in this way (it works with word97 document)
    private static void convertWordDoc2HTML(File file)
    throws ParserConfigurationException, TransformerConfigurationException,TransformerException, IOException {
    //change the type from XWPFDocument to HWPFDocument
    HWPFDocument hwpfDocument = null;
    try {
        FileInputStream fis = new FileInputStream(file);
        POIFSFileSystem fileSystem = new POIFSFileSystem(fis);
             hwpfDocument = new HWPFDocument(fileSystem);

    } catch (IOException ex) {
        ex.printStackTrace();
    }

    WordToHtmlConverter wordToHtmlConverter = new   WordToHtmlConverter(DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument());
    org.w3c.dom.Document htmlDocument = wordToHtmlConverter.getDocument();
    //add processDocument method
    wordToHtmlConverter.processDocument(hwpfDocument);
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    DOMSource domSource = new DOMSource(htmlDocument);
    StreamResult streamResult = new StreamResult(out);

    TransformerFactory tf = TransformerFactory.newInstance();
    Transformer serializer = tf.newTransformer();
    serializer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
    serializer.setOutputProperty(OutputKeys.INDENT, "yes");
    serializer.setOutputProperty(OutputKeys.METHOD, "html");
    serializer.transform(domSource, streamResult);
    out.close();

    String result = new String(out.toByteArray());

    String htmlText = result;
    System.out.println(htmlText);

    }

I hope it can be usefull.
Answer: I am using docx4j to do this and it seems to be working. If you're using Maven you can just add the dependency (but use version 3.0.0) and then use one of the docx4j sample programs called ConvertOutHtml.java. Just change the filepath in ConvertOutHtml.java to point to your file and you should be fine.
Answer: Your code is generating an empty html output because you are not processing any document in the converter.
Anyway, if it is a docx you should be using XHTMLConverter to convert it to HTML instead of WordToHtmlConverter. See this answer


Invalid override copyWith

Question: I've been wondering are there a best way to implement copyWith in extends?
got error in Pwm class copyWith method
how to fix dat?
This Pin Code
class Pin{

  final String? name;
  final int io;
  final bool value;
  final Mode mode;
  final Usage? usage;
  const Pin({required this.io,required this.value, required this.mode, this.name, this.usage});

  factory Pin.fromList(List<dynamic> list){
    // "pin1" : (33,hardwareR4A.pin1.value(),"IN" if hardwareR4A.pin1.init() == Pin.IN else "OUT"),
    return Pin(io: list[0], value: convertValueToBool(list[1]), mode: Mode.values.firstWhere((element) => element.name == list[2]), usage: null);
  }

  Pin copyWith(
    String? name,
    int io,
    bool value,
    Mode mode,
    Usage? usage,
  ){
    return Pin(
      io: io,
      mode: mode,
      value: value,
      name: name,
      usage: usage
    );
  }

}

**And this error class **
class Pwm extends Pin {

  final int frequency;
  final int duty;
  final int resolution;

  const Pwm({
    required super.io,
    required super.value,
    required super.mode,
    super.name,
    super.usage,
    required this.frequency,
    required this.duty,
    required this.resolution,
  }) : super();

  @override
  Pwm copyWith({
    String? name,
    int? io,
    bool? value,
    Mode? mode,
    Usage? usage,
    int? frequency,
    int? duty,
    int? resolution,
  }) {
    return Pwm(
      duty: duty ?? this.duty,
      frequency: frequency ?? this.frequency,
      io: io ?? this.io,
      mode: mode ?? this.mode,
      resolution: resolution ?? this.resolution,
      value: value ?? this.value,
      name: name ?? this.name,
      usage: usage ?? this.usage,
    );
  }
}

Are there a best way to implement copyWith in extends?
do i need to extends pin with abstraction?
like :
class Controller{
}
class Pin extends Controller{}
class Pwm extends Controller{}
E32 mean esp32
Answer: (In the future, please copy-and-paste the error message that you received.)
Your problem is that Pin.copyWith takes only positional parameters:

 Pin copyWith(
   String? name,
   int io,
   bool value,
   Mode mode,
   Usage? usage,
 ){

but the Pwm.copyWith override takes only named parameters:

 @override
 Pwm copyWith({
   String? name,
   int? io,
   bool? value,
   Mode? mode,
   Usage? usage,
   int? frequency,
   int? duty,
   int? resolution,
 }) {

An override's signature must be compatible with the base method's; that is, it must be callable using the base method's signature (e.g. pwm.copyWith(name, io, value, mode, usage)).
You can fix it either by:

Changing Pin.copyWith to use optional, named parameters.
Changing Pwm.copyWith to use positional parameters for the parameters it shares.

Invalid override copyWith


a problem on permutation group and normal subgroup

Question: Let $H$= {$e, (1, 2) (3, 4)$} and $K$= {$e, (1, 2) (3, 4), (1, 3) (2, 4), (1, 4) (2, 3)$} be subgroups of $S_4$, where $e$ denotes the identify element of $S_4$ . Then which is/are true?
1. H and K are normal subgroups of $S_4$
2. H is normal in K and K is normal in $A_4$
3. H is normal in $A_4$ but not normal in $S_4$
4. K is normal in $S_4$ , but H is not.

How can I solve this?
Comment: Please ask 1,2,3,4 in seperate questions
Comment: What did you try?
Comment: I could not get it
Comment: H has order 2 and k has order 4
Comment: but then I have no idea
Comment: Hint: Think about how a conjugation acts on an element.
Comment: Do you know that conjugate elements in $S_n$ have the same cycle type?
Comment: I have not much idea about conjugacy classes
Answer: Some facts that should help you in answering the questions (here $G$ is a group):

If $L$ is a normal subgroup of $G$, then it is a normal subgroup of each subgroup $M$ of $G$ such that $L\subseteq M$.
If a subgroup $L$ of a group $G$ has index two, then $L$ is normal in $G$.
A subgroup $L$ of $G$ is normal in $G$ if and only if for all $g\in G$ it holds that $g^{-1}Lg=L$.
A subgroup $L$ of $S_{n}$ is normal in $S_{n}$ if and only if, for every $l\in L$, if $k\in S_{n}$ has the same cyclic structure of $l$, then $k\in L$ (this is due to the fact that two elements of $S_{n}$ belong to the same conjugacy class if and only if they have the same cyclic structure).
If $G$ is an abelian group, every subgroup of $G$ is normal in $G$.
Comment: So $H$ is a normal subgroup of $K$.
Comment: This seems like a rather arbitrary collection of facts about normality. For example I don't see why you would include the index 2 one and also the abelian one. Also why include the definition of being normal?
Comment: @TobiasKildetoft Different ways to get to the same result :) I gave no proofs of the mentioned facts because I think they are either elementary or proved in any Group Theory course (or book) (and, moreover, the OP did not ask for further explanation).
Answer: @Marco, noted you useful points. I am posting you the codes in which you can find these points better. I collect them using GAP. Now see how powerful this program is to epitomize the theoretical aspects. This is for $K$:
<code>gap> g:=AlternatingGroup(IsPermGroup,4);;
gap> K:=Group((),(1,2)(3,4),(1,3)(2,4),(1,4)(2,3));;
gap> Size(K);
                                         4
gap> IsSubgroup(g, K);
                                       true
gap> IsNormal(g,K);
                                       true
</code>
Comment: Ok then. If you want to fiddle with GAP 4.4.12 installation, then the only way of adding most recent packages safely is to get those which are included in the [latest GAP 4.4.12 distribution](http://www.gap-system.org/Releases/4.4.12.html).
Comment: thanks for showing how to do this in GAP, though my personal feeling is that GAP is not relevant to this question which is focused on the theoretical explanation (and Marco provided some hints that may be used on that way). Anyhow, if there is a GAP example here, I suggest to make it better: first, just `AlternatingGroup(4)` suffices since it will return permutation group by default. Second, at least `()` may be excluded from the list of generators of `K`.
Comment: by the way, which GAP installation do you use? It's interesting why the output is often centered in your examples.
Comment: @AlexanderKonovalov: Honestly, I am new in using GAP like an infant Prof. and that's why I employ the codes differently not like the Masters. Thanks for noting that useful points. I am using the version of Alexander Hulpke's one which can be installed on Win OS (not in Dos mode). I made them centered just for looking good :-)
Comment: Thanks for details. Please note that [Alexander Hulpke's page](http://www.math.colostate.edu/~hulpke/CGT/education.html) provides installers for GAP 4.4.12 (December 2008) while the latest version as of today is GAP 4.6.4 dated May 2013. There is a [Windows installer](http://www.gap-system.org/ukrgap/wininst/) which provides a common installation procedure. Since GAP 4.5, the default shell in which GAP is running under Windows is `mintty` which is more convenient then standard "Command Line" Windows shell. So I'd encourage you to try...
Comment: @AlexanderKonovalov: Thanks a lot Alexander. I appreciate you. :-)
Comment: @AlexanderKonovalov: Dear prof. I download your version. It is great and it is better the previous Dos version. May I ask you a question? As I said, I have been working with Alexander Hulpke's version as well.After downloading your version, I over wrote the packages of yours on folders inside the packages of A. Hulpke's. I thought may be I would have a better GAP. In fact, I wanted to make his better and updated. But this is a foolish idea because it didn't work. Was that good? Sorry if I got your time. Thanks.
Comment: It's not entirely clear what you've done - please feel free to contact [GAP Support](http://www.gap-system.org/Contacts/People/supportgroup.html) with more details. If I am right in my guess that you moved some packages from GAP 4.6.4 under GAP 4.4.12, then this hardly will work, since many packages require newer version of GAP than 4.4.12, and are also quite interdependent as [shown on this diagram](http://alexk.host.cs.st-andrews.ac.uk/gap/GAP_Packages.html)
Comment: @AlexanderKonovalov: This is exactly what I have done. Thanks Alexander. :)