When attempting to upload a UTF-8 text file to Google Drive with the Google API client for python, I get a UnicodeDecodeError

Question: This question is still unsolved! Please answer if you know
Bug
I have filed a bug here
http://code.google.com/p/google-api-python-client/issues/detail?id=131&thanks=131&ts=1335708962
While working on my gdrive-cli project, I ran into this error attempting to upload a UTF-8 markdown file, using the "text/plain" mime-type. I also tried with "text/plain;charset=utf-8" and got the same result.
Here is the stacktrace I got:
Traceback (most recent call last):
  File "./gdrive-cli", line 155, in <module>
    handle_args(args)
  File "./gdrive-cli", line 92, in handle_args
    handle_insert(args.insert)
  File "./gdrive-cli", line 126, in handle_insert
    filename)
  File "/home/tom/Github/gdrive-cli/gdrive/gdrive.py", line 146, in insert_file
    media_body=media_body).execute()
  File "/usr/local/lib/python2.7/dist-packages/apiclient/http.py", line 393, in execute
    headers=self.headers)
  File "/usr/local/lib/python2.7/dist-packages/oauth2client/client.py", line 401, in new_request
    redirections, connection_type)
  File "/usr/local/lib/python2.7/dist-packages/httplib2/__init__.py", line 1544, in request
    (response, content) = self._request(conn, authority, uri, request_uri, method, body, headers, redirections, cachekey)
  File "/usr/local/lib/python2.7/dist-packages/httplib2/__init__.py", line 1294, in _request
    (response, content) = self._conn_request(conn, request_uri, method, body, headers)
  File "/usr/local/lib/python2.7/dist-packages/httplib2/__init__.py", line 1231, in _conn_request
    conn.request(method, request_uri, body, headers)
  File "/usr/lib/python2.7/httplib.py", line 955, in request
    self._send_request(method, url, body, headers)
  File "/usr/lib/python2.7/httplib.py", line 989, in _send_request
    self.endheaders(body)
  File "/usr/lib/python2.7/httplib.py", line 951, in endheaders
    self._send_output(message_body)
  File "/usr/lib/python2.7/httplib.py", line 809, in _send_output
    msg += message_body
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe2 in position 4518: ordinal not in range(128)

And the command I had to issue to generate it was:
gdrive-cli --insert README.md "readme file" none "text/plain" README.md

You can get the exact README.md file at the time this problem occurred here, http://tomdignan.com/files/README.md
The relevant code from the SDK examples follows. The parameters going in are in order:
a service instance, "README.md", "readme file", None (python keyword), "text/plain", and "README.md"
def insert_file(service, title, description, parent_id, mime_type, filename):
    """Insert new file.

    Args:
        service: Drive API service instance.
        title: Title of the file to insert, including the extension.
        description: Description of the file to insert.
        parent_id: Parent folder's ID.
        mime_type: MIME type of the file to insert.
        filename: Filename of the file to insert.
    Returns:
        Inserted file metadata if successful, None otherwise.
    """
    media_body = MediaFileUpload(filename, mimetype=mime_type)
    body = {
        'title': title,
        'description': description,
        'mimeType': mime_type
    }

    # Set the parent folder.
    if parent_id:
        body['parentsCollection'] = [{'id': parent_id}]

    try:
        file = service.files().insert(
                body=body,
                media_body=media_body).execute()

        # Uncomment the following line to print the File ID
        # print 'File ID: %s' % file['id']

        return file
    except errors.HttpError, error:
        print "TRACEBACK"
        print traceback.format_exc()
        print 'An error occured: %s' % error
        return None

Comment: One bug is enough.  If you truly believe this is a bug, which it seems you do, then we will respond to the bug you filed.  Posting here just duplicates the number of responses that need to be given to you.
Comment: @VicFryzel I thought about it and you are right. But the question is stuck. Tried to delete and failed. If it makes any difference, I posted the question before the bug.
Answer: Traceback:
...
resp = pool.request(method, page, fields = fields)
  File "/usr/lib/python2.7/site-packages/urllib3-dev-py2.7.egg/urllib3/request.py", line 79, in request
**urlopen_kw)
  File "/usr/lib/python2.7/site-packages/urllib3-dev-py2.7.egg/urllib3/request.py", line 139, in request_encode_body
**urlopen_kw)
  File "/usr/lib/python2.7/site-packages/urllib3-dev-py2.7.egg/urllib3/connectionpool.py", line 415, in urlopen
body=body, headers=headers)
  File "/usr/lib/python2.7/site-packages/urllib3-dev-py2.7.egg/urllib3/connectionpool.py", line 267, in _make_request
conn.request(method, url, **httplib_request_kw)
  File "/usr/lib64/python2.7/httplib.py", line 958, in request
    self._send_request(method, url, body, headers)
  File "/usr/lib64/python2.7/httplib.py", line 992, in _send_request
    self.endheaders(body)
  File "/usr/lib64/python2.7/httplib.py", line 954, in endheaders
    self._send_output(message_body)
  File "/usr/lib64/python2.7/httplib.py", line 812, in _send_output
    msg += message_body
UnicodeDecodeError: 'ascii' codec can't decode byte 0x8b in position 181: ordinal not in range(128)

urllib3
filepost.py:
def encode_multipart_formdata(fields, boundary=None):
    ...
    body = BytesIO()
    ...
    return body.getvalue(), content_type

request.py:
def request(self, method, url, fields=None, headers=None, **urlopen_kw):
    ...
    else:
        return self.request_encode_body(method, url, fields=fields,
                                        headers=headers,
                                        **urlopen_kw)

def request_encode_body(self, method, url, fields=None, headers=None,
                            encode_multipart=True, multipart_boundary=None,
                            **urlopen_kw):
    ...
    if encode_multipart:
        body, content_type = encode_multipart_formdata(fields or {},
                                                       boundary=multipart_boundary)
    ...
    headers = headers or {}
    headers.update({'Content-Type': content_type})

    return self.urlopen(method, url, body=body, headers=headers,
                        **urlopen_kw)

httplib
httplib.py:
def _send_request(self, method, url, body, headers):
    ...
    if body and ('content-length' not in header_names):
        self._set_content_length(body)
    ...

def _set_content_length(self, body):
    # Set the content-length based on the body.
    thelen = None
    try:
        thelen = str(len(body))
    except TypeError, te:
        # If this is a file-like object, try to
        # fstat its file descriptor
        try:
            thelen = str(os.fstat(body.fileno()).st_size)
        except (AttributeError, OSError):
            # Don't send a length if this failed
            if self.debuglevel > 0: print "Cannot stat!!"

    if thelen is not None:
        self.putheader('Content-Length', thelen)

    ...

def _send_output(self, message_body=None):
    ...
    if isinstance(message_body, str):
        msg += message_body
        message_body = None
    self.send(msg)
    if message_body is not None:
        #message_body was not a string (i.e. it is a file) and
        #we must run the risk of Nagle
        self.send(message_body)

    ...

def send(self, data):
    ...
    blocksize = 8192
    if hasattr(data,'read') and not isinstance(data, array):
        if self.debuglevel > 0: print "sendIng a read()able"
        datablock = data.read(blocksize)
        while datablock:
            self.sock.sendall(datablock)
            datablock = data.read(blocksize)
    else:
        self.sock.sendall(data)

My script.py:
#!/usr/bin/env python

from io import BytesIO

data = BytesIO()

print type(data.getvalue()

$./script.py
<type 'str'>
My solution:
#!/usr/bin/python

from urllib3 import HTTPConnectionPool, filepost
from io import BytesIO, SEEK_SET

pool = HTTPConnectionPool('web')

archive_name = '/var/archives/mock.tar.gz'

fields = {'uploadedfile' : (archive_name, open(archive_name).read())}

value, content_type = filepost.encode_multipart_formdata(fields)

headers = {'Content-Type' : content_type, 'Content-Length' : len(value)}

# or any temporary file. without Content-Length

data = BytesIO()

data.write(value)

data.seek(0, SEEK_SET)

resp = pool.urlopen('POST', '/upload/uploader.php', data, headers)

print resp.status

$./upload.py
200
/var/www/upload# ls
mock.tar.gz upload.html upload.php
Answer: Try encoding your message_body string:
msg += message_body.encode('utf-8')

This post really helped me when it comes to python strings and unicode.
Comment: This error is probably being caused by the line "Q. Why am I am getting "The authenticated user has not installed the app with client id†error?" in your readme.  A cheap solution to fixing this would be to replace "idâ€".


Why are my forecast intervals so large? (ARIMA)

Question: I am trying to perform a forecast on jet fuel prices (from FRED), where i total 260 observations running from jan. 2000 to august 2021 with monthly frequency and no apparant seasonality

From looking at the residuals

it suggests that the ts should be differenced, where an augmented Dickey-fuller test confirms this, as it leaves a test-statistic of -6.71, which is lower than the critical values.
From here I simulated an ARIMA and ARMA function, to find out if the trend is stochastic or determistic running the codes:
<code>model.arima <- auto.arima(y, d=1, seasonal = FALSE, ic = "aic",
                          stepwise = FALSE, approximation = FALSE,
                          trace = TRUE)

model.arma <- auto.arima(y, d=0, xreg=1:T, seasonal = FALSE, ic = "aic",
                         stepwise = FALSE, approximation = FALSE,
                         trace = TRUE)

screenreg(list(model.arima,model.arma))
</code>
By looking at the EIC score, it suggest that an ARIMA(1,1,2) model best describes the relationship, and I will thereby assume that the trend is stochastic, but I find no significant drift.

When running the forecast, where I compare it with a determistic trend (ARMA(3,2) model, I get insanely large forecast intervals
.
Does this make sense?
I spoke with my professor, who suggested that the parameters of the model is very small and thereby the intervals is represented a large deal by the error term, which implies that my model is faulty. However, I have no clue on how to fix this.
Answer: Your data is noisy, there is no clear pattern. The wide intervals tell you about the uncertainty, the intervals for the predictions are wide because the model is uncertain. If you had a clear, repetitive pattern that could be predicted, they would be narrower. For example, here you can find an example of SARIMA results for such time-series from the great forecasting handbook by Rob Hyndman and George Athanasopoulos.

Wide intervals do not necessarily tell you that the model is faulty. It can be as well that the data is hard to predict, no matter what model you choose. A simple sanity check is to answer yourself if there is any visible pattern in the data, in case of your data it doesn't seem to be the case. In fact, if you had much thinner prediction intervals for the data you're showing, I would expect you to prove me that the model is not overfitting.


Python script calling other script, terminate first, keep second

Question: Python newbie here. Sorry if I am a bit unclear.
I have a Python script that reads temperature, and I have another script that grabs the temperature value from the first one. If the first script terminates, the second will terminate with it.
How can I keep the second sript from terminating?
Thank you ;)
Comment: [Relevant reading](http://stackoverflow.com/questions/2846653/python-multithreading-for-dummies)
Answer: This isn't a direct answer to your question, but it's more of a directional consideration that you need to think about.
Since you're talking about temperature monitoring, it's a classic example for a Publish Subscribe model. Recently protocols like MQTT have gained in popularity, and is really helpful for the scenario that you're in.
You should really design your application with scalability in mind and explore before just using threaded python code. There's a cool python example here for MQTT.


Tension for nylon strings on Lyre

Question: I'm currently in the process of restoring my [alto] Lyre, and I was wondering if there would be implications from using nylon strings instead of steel.
There would be two reasons to use nylon over steel: apparently nylon strings need a lower tension to reach the same pitch, so this would reduce stress on the instrument's frame (gaps are currently forming at some joints from the steel strings' tension). The other reason would be for a softer, more harp-like sound (not really necessary, just interesting and possibly more true to the original lyre sound)

Now, I know that, for example, the lowest string (0.064-inch gauge steel) needs about 16kg of tension to reach it's pitch (C2), and the highest string (0.009-inch, G5), needs about 11kg. The rest of the strings range approximately between the two.
Knowing this information (and noting I've never played a nylon-stringed instrument), is there a way to determine which nylon strings I'll need?
Comment: C2 to G5 is a pretty wide range for a lyre - how many strings does this have?  Are you thinking of an instrument like this: http://www.earlymusicshop.com/product.aspx/en-GB/1003359-ems-22-string-lute-harp
Comment: @Andy It has 44 strings, and stands at about waist-height: http://ibin.co/2UGWL2hjA08B
Comment: 44 strings - personally I'd ask a harp maker and see what nylon or gut strings they can recommend.  The tension depends partly on the string length so the longest and shortest string measurements would be needed I think... fantastic instrument by the way...
Answer: Apparently nylon Lyre strings are not readily available but I was able to locate one on-line seller offering the equivalent of nylon Lyre strings.  From the site:

These modern Fluorocarbon strings are a better alternative to plain nylon and are very popular with harp and ukulele as they produce a clear and strong sound,  On lyres this is very effective on Plywood or thicker topped lyres that are otherwise dull with guitar nylon or too quiet with gut.  Once settled in they are very stable in tuning,  impervious to moisture these strings are usual first choice on my Standard models Lyres

Here is a link to the site.
Nylon Lyre Strings For Sale
Another option is to extrapolate from guitar string gauges as steel strings compare to nylon strings.  For example I found this on a web site that sell's Lyres.

Looking at a set of standard gauge classical nylon guitar strings I find this for listed string gauges:

Comparing that to a similar set of plain steel for electric guitar (so we get a plain steel G string) I find this:

The common denominator between Lyre strings are the .12 the .16 and .20 which correspond to the 1st, 2nd and 3rd string from a plain steel set of guitar strings.  Extrapolating from there to the corresponding nylon guitar strings we get:
1st string - Steel .012 ... Nylon .028 = a 2.3333 multiplier
2nd string - Steel .016 ... Nylon .032 = a 2.0 multiplier
3rd string - Steel .020 ... Nylon .040 = a 2.0 multiplier
So I think we can conclude that assuming the relative tension of nylon vs. plain unwound steel guitar strings to allow for equivalent tuning - is a 2 to 1 ratio in terms of gauge - you could take the gauge of the steel strings in a set of Lyre strings and simply double the diameter for a corresponding nylon string.
If it works with guitar strings I see no reason why it would not work the same with Lyre strings.  It's really just a matter of which gauge nylon string tunes up equivalent to which gauge steel string.  The overall tension will be lower on nylon but the relative tuning properties nylon vs. steel strings should be the same regardless of what instrument the strings are on.
Good luck and enjoy playing your Lyre.
Comment: @Jugale  Thanks.  I don't know why the Lyre is not a more popular instrument but apparently not many musicians know much about them.  I'm thinking I might want to add one to my collection of instruments.  I have a Dulcimer - which is another instrument that is not so common.  The Lyre appears to be more versatile than would at first appear.  Have fun with yours.
Comment: This is great information, thank you so much! Don't see how someone could top it, so I'll mark it as correct :) Thanks again!

Tension for nylon strings on Lyre


Sql, sum de varios counts

Question: Olá, tenho um banco com 3 tabelas importantes, estado,cidade e pedidos preciso rankear os estados do que tem mais pedidos ao q tem menos porem os pedidos estao relacionados apenas a tabela de cidade. então eu preciso fazer um count pra cada cidade e somar os counts das cidades que pertencem ao mesmo estado. porém não tenho ideia de como fazer isso. alguém pode me ajudar?
estrutura da tabela do estado:

estrutura da tabela de cidades:

estrutura da tabela de pedidos:
Comment: Poste a estrutura das 3 tabelas, isso facilita te ajudarmos.
Answer: Considerando nomes genéricos das tabelas e campos:
SELECT es.nome as estado, ci.nome as cidade, COUNT(pe.id)
FROM pedidos pe
LEFT JOIN cidade ci ON ci.id = pe.cidade
LEFT JOIN estado es ON es.id = ci.estado
WHERE pe.datapedido BETWEEN '01/01/2018' AND '31/01/2018'
GROUP BY es.nome, ci.nome

Na sua estrutura:
SELECT es.estado, COUNT(pe.id)
FROM pedidos pe
LEFT JOIN cidades ci ON ci.id = pe.cidade_id
LEFT JOIN estado es ON es.id = ci.estado_id
GROUP BY es.estado

Comment: Olá obrigado pela ajuda, a saida que preciso seria estado-numero de pedidos
a sua query retorna bem diferente
Comment: @MatheusLima Alterei. Veja agora.
Comment: agora funcionou, muito obrigado pela ajuda

Sql, sum de varios counts


Constructing the Complex Numbers

Question: This lecture on complex analysis constructs the complex numbers.
At 55:08, the lecturer leaves the nature of the contradiction as an exercise.
I am trying to understand what the contradiction is. My understanding (after some thinking) is that by defintion:
$$z=x+ye$$
And hence
$$\sqrt{a+b^2/4}=e$$
and if this is real, then $z=x+ye$ itself must be completely real.
However, I am not sure. Can someone guide me what is the correct contradiction.
Note: I am quite new to Complex Analysis. Hence, this very basic question.
Comment: Please do not rely on a link for the central point of your question. *What* was claimed by the lecturer to be a contradiction?
Answer: This video assumes $\Bbb R\cdot1\oplus\Bbb R\cdot e$ is a field and claims having "nearly proved" that this field must contain a square root for $-1.$ Its lengthy "proof" needs some cleaning to not look circular (and its "Case 1" was completely useless). You can replace it by the following (dropping the "$\cdot1$" and considering $\Bbb R$ as a subfield):
Let $a,b$ be the two real numbers s.t. $e^2=a+b\cdot e,$ and let
$$f:=-\frac b2+e.$$
Then,
$$f^2=a+\frac{b^2}4.$$
Therefore, $a+\frac{b^2}4<0,$ otherwise we would have
$$\left(f-\sqrt{a+\frac{b^2}4}\right)\left(f+\sqrt{a+\frac{b^2}4}\right)=0$$
and derive $f=\pm\sqrt{a+\frac{b^2}4}\in\Bbb R,$ whence the following contradiction:
$$e=\frac b2+f\in\Bbb R.$$
To conclude, simply check that
$$\left(\frac f{\sqrt{\left|a+\frac{b^2}4\right|}}\right)^2=-1.$$
Comment: Cam you elaborate on what precisely is the contradiction? I agree that your formulation is rhe same argument presented in a cleaner and shorter format.
Comment: The contradiction is $e\in\Bbb R$, i.e. $\Bbb R\cdot1$ (it is impossible since $\{1,e\}$ is linearly independent).
Answer: The value under the square root could be negative, and you'd then need to solve within the complex domain, i.e. it (the square root term as well as linear combinations of it like $x+ye)$ has complex roots.
However, if $a+\frac{b^2}{4}$ is positive, than it has a root $e=\sqrt{a+\frac{b^2}{4}}$ which is in the domain of the reals.
Anyway, it's a boring way to introduce the complex numbers. All you take out of it is: if the radicand - what's under the square root sign, is negative, then it - the radical - has complex roots.
Comment: The video says it is a construction of the complex numbers. Not if X, then Y. Hence, the contradiction is supposed to prove that the quantity inside the square root is negative.

Constructing the Complex Numbers


Textarea not populating with previous value

Question: So I have been buildign a simple form used to populate a block on the sidebar of my drupal 7 site. However I have run into a problem, the textarea on this form does not seem to populate with the sidebars previous value.
What has me stumped is that a textfield with the same defaultvalue code populates correctly.
<code>//a debug textfield that works
$form['debug'] = array(
    '#type'        => 'textfield'
       ,'#title'       => 'Debug'
       ,'#default_value' => $sidebar_content[$key] ? $sidebar_content[$key] : ''
       ,'#description' => t('Please enter a suitable heading for the left sidebar.')
     );

//the broken textarea
 $form['body'] = array(
        '#type' => 'textarea'
        ,'#title' => t('Body')
        ,'#rows' => 15
        ,'#description'   => t('Body text for sidebar')
        ,'#value' => $sidebar_content[$key] ? $sidebar_content[$key] : ''
    );
</code>
Edit: After disabling WYSIWYG the text area started populating again. More digging revealed the reason it wasn't populating as a rich text box was because when an editor is used it submits the value as an array with two items; value and format. Consequently, this meant that the text editor was being given an array to display rather than a string.
Altering the #default_value to $sidebar_content[$key]['value'] resolved this issue.
Comment: It does not appear to me that there is any default_value code in the broken input.
Comment: apoligies in the live code value is #default_value
Answer: After disabling WYSIWYG the text area started populating again. More digging revealed the reason it wasn't populating as a rich text box was because when an editor is used it submits the value as an array with two items; value and format. Consequently, this meant that the text editor was being given an array to display rather than a string.
Altering the #default_value to $sidebar_content[$key]['value'] resolved this issue.
Answer: Your code is correct (except #default_value instead of #value)
If you have a wysiwyg, try to inactivate it for testing
Or maybe 'body' is already taken in your form, try to change this field name
Comment: I disabled WYSIWYG and it started working, it seems rich text areas pass data as an array('value' => $val, 'format' => 'filtered_html') so the reason it wasn't displaying is it was trying to output an array rather than a string.


In clinical trials, what is the benefit of using a composite rather than individual outcome

Question: I have read that composite outcomes are common in cardiovascular trials because they give a holistic view of a treatment effect. Assuming outcomes are frequent enough for statistical power to not be an issue, why would this be the case? Wouldn't it always be beneficial to measure the effect of treatment on outcomes individually?
Answer: Suppose you have a new treatment that you expect to reduce the risk of heart attack (acute MI), but that you worry might cause an increase in deaths from non-cardiovascular causes. This was exactly the situation with the statin drugs when they were new.
Using acute MI as the outcome would measure the intended effect of the treatment, but it would miss any increase in deaths from other causes.  You might decide you wanted to use a composite of all-cause mortality and non-fatal MI, to capture both issues.
You could measure non-fatal MI, coronary death, and death from other causes as separate outcomes (and, of course, you would measure them all separately). But you'd still need to specify some preferred way of combining them, and that isn't meaningfully different from having a composite outcome.
Another setting is where other interventions are part of the composite outcome.  If you are trying to prevent heart attacks (or even just reduce coronary atherosclerosis) and a trial participant gets their coronary arteries cleaned out (angioplasty) or gets new coronary arteries (CABG), how do you count that?  It's undesirable to treat them as lost to follow-up, but it's also a bit strange to ignore the intervention.  It's fairly common to add angioplasty and CABG as part of the (bad) outcome.  This is a bit more controversial, but you can see the reasoning.
Two further notes

it's not always unambiguous whether something is a composite outcome. If you expect to present death from cardiovascular causes, and that would be your preferred outcome, is death from any cause a composite outcome or not?
statistical power is always an issue in randomised trials to some extent, because it's unethical to randomise more people than you need to answer the question.
Comment: In the end, your decisions about whether the new treatment is Good or Bad will require combining them. In principle that could be left to the individual patient, but there's a strong norm in favour of having a primary outcome in clinical trials.   And, yes, my first example is one where you would definitely expect the the effects to be different across outcomes, and that's *why* it's important to combine them, to assess the tradeoff.
Comment: Thanks, this is a great answer (It's interesting to hear about the historical context, I'll read up on it)! I just had a couple of follow up questions: 1) why do we have to specify some preferred way of combining them, isn't it ok to just have separate effect estimates?: not sure if I'm missing something obvious here ; 2) if frequencies of events or if it is plausible to assume before that treatment effects are different across outcomes, would it still make sense to combine them?


Solving the linear system $XL + L^TX = M$ efficiently

Question: I'm wondering of an efficient way to solve the following system for the symmetric matrix $X$, given a positive semi-definite matrix $S$ and any matrix $M$:
$$ LL^T = S $$
$$ XL + L^TX = M $$
$$ (XL) + (XL)^T = M$$
The problem:
You have parameters $a_i \in \mathbb{R}^n$ $i=1 \dots N$ and $\mu$. You have a random variable $x \sim \mathcal{N}(\mu,\Sigma)$, where $\Sigma = \sum a_i a_i^T$. You are also given a function to optimise $f(x)$. Thus given a final set of samples you want to calculate $\nabla \mu$ and $\nabla a_i$. You also know $\nabla_x f$. Thus you can do the following:
$$ LL^T = \Sigma $$
$$ x = \mu+ L \epsilon$$
$$ \nabla \mu = \nabla_x f $$
$$ \nabla L = \nabla_x f \epsilon^T $$
$$ \nabla a_i = 2 \nabla \Sigma a_i$$
Now unfortunately, there I can't still calculate $\nabla \Sigma$. So I use the following relation:
$$ \nabla L = \nabla \Sigma L + L^T \nabla \Sigma $$
Thus note the initial equation. However, obviously $\nabla L$ is not symmetric, which means that $\nabla \Sigma$ should also not be symmetric or ...? Where is the mistake in this?
Comment: What does efficient mean to you? If $X$ is an $n\times n$ matrix, then you have $n^2$ linear equations here. Proceeding naively and solving these $n^2$ linear equations takes (I believe) time on the order of $O(n^6)$ time. (I remember this, but in my head it seems to take $O(n^4\log^\alpha n)$, but I suspect I'm forgetting something). This ignores all structure of this problem, though
Comment: Well yeah I was hoping for something better like $O(n^3)$ or $O(n^4)$, also updated my question since should note that X is symmetric
Comment: If $X$ is symmetric, so is $X L + L^T X$, so you'd better make $M$ symmetric.
Comment: Hmmm, you actually have a point, but that means I have a mistake, guess I need to explain everything, maybe someone will find the mistake
Comment: Looks similar to an algebraic Ricati equation.
Comment: Updated where this comes from, so maybe some of you could find my mistake?
Comment: Gradient with respect to what?
Comment: In the end it's with respect to $a_i$
Comment: And $a_i$ are ...?
Comment: Vector parameters
Answer: Disregarding the problem in itself, just answering the question as posed above "The problem":
You can vectorize and use the Kronecker product, using some of the formula found here. Also after vectorization the transposition operation can be represented by a permutation matrix as explained here.
You will end up with linear equation system $n^2\times n^2$ sparse matrix with a maximum of $2n$ non-zero values each row. If efficiency is important you can strip it down using the symmetric property of $X$ and instead of a vectorization using a half-vectorization although at the cost that maybe the formula can become more difficult to express with the extra Kronecker product abstraction layer.
How feasible this will be completely depends on the size of the matrices. As mentioned in the comments solving with a naiive method having $O(N^3)$ complexity, $N$ matrix side could give $O(n^6)$ where $n$ the side of $X$ matrix. But since the equation system has a very special structure and also is sparse, that would be a very pessimistic estimate. The fact that only square root of the side is non-zero elements for each row could for example invite for usage of Krylov subspace methods.


How to reach first member of List?

Question: class DrawAction
{
    public Rectangle Dortgen { get; set; }
    public Brush Firca { get; set; }
    public PointF Koordinat { get; set; }
    public DrawAction(Brush color_, Rectangle rect_ )
    { Dortgen = rect_; Firca = color_; }
    public DrawAction(Brush color_)
    { Firca = color_; }
    public DrawAction (PointF k_)
    { Koordinat = k_; }
}
       n1 = new PointF(Start.X, Start.Y - (Start.X - End.X) * 173 / 100 * 2 / 3);
       n2 = new PointF(Start.X + (Start.X - End.X), Start.Y + (Start.X - End.X) * 173 / 100 * 1 / 3);
       n3 = new PointF(Start.X - (Start.X - End.X), Start.Y + (Start.X - End.X) * 173 / 100 * 1 / 3);
    ucgen.Add(new DrawAction(n1));
    ucgen.Add(new DrawAction(n2));
    ucgen.Add(new DrawAction(n3));
    List<DrawAction> ucgen = new List<DrawAction>();

Here is some of my code. I list the points to use later. I want to reach this lists first member. I tried
     Point p1 = ucgen[0];

but this is wrong. How can I reach it ?
r
Comment: The stuff outside of the class scope doesn't make sense.  Is it in another class, does it need to be in a method?
Comment: Your question is not completed and understandable, please edit it.  https://stackoverflow.com/help/mcve
Comment: Yes, it's in a method. I forgot to write. I will edit
Comment: Adem abi yardım edebilir misin burdan türkçe yazsam ingilizce yazmak zor oluyor
Comment: I glad to see your problem is solved :)
Comment: Adem abi I'm glad olacak o
Answer: If you haven't done something wrong, like @Felix Castor said, you can always use FirstOrDefault:
var test = YourList.FirstOrDefault();

Answer: Making some assumptions about how your code is structured (the code in the question as it stands is not very helpful), I would say the problem is that you are getting a DrawAction from the list and trying to assign it to a Point.
The simplest answer would be to do:
PointF p1 = ucgen[0].Koordinat;

or perhaps
DrawAction d1 = ucgen[0];

Note also that your DrawAction class uses a PointF, but you seem to be trying to get a Point out.  Either change the type of the variable in the code (as I have done) or cast PointF to Point (with loss of precision) if that is what you intend.
However, I must point out that blindly accessing element 0 without testing this is going to cause problems when the list is empty.  Without knowing more of the code I wouldn't be able to make a firm recommendation, except to suggest foreach, or the Linq FirstOrDefault() as suggested by user9190331.
Hope this helps

How to reach first member of List?


Hypergeometric series

Question: If found that : "Assume further that this equation has e series solution $\sum a_ix^i$   whose coefficients are connected by two term recurrence formula. Then, such a series can be expressed in terms of hypergeometric series." [Bragg, 1969]
how can we do this conversion?
thanks in advance
Comment: I would both like to know what "this equation" is and what kind of coefficients your two term recurrence is allowed to have.
Comment: A bit more context and/or an example would be nice. Also, a quote should go with a reference.
Comment: Here is the reference : "Hypergeometric operator series and related partial differential equations", [Bragg,1969]
Comment: Satisfied with my answer?
Answer: The (freely downloadable) book A = B, by Petkovsek, Wilf, and Zeilberger, is, generally speaking, a must-read. The authors explain, in particular how to deduce a hypergeometric series from a recurrence relation and the other way round.

Hypergeometric series


Positioning vertical center

Question: I want to center these 4 images. Horizontally it is working but vertically it won't work. Does anybody knows how to solve this problem? At the moment I've got a black header/footer section with 4 images centered horizontally. Everything is scalable but not the height of the images.
Am doing it right?
HTML:

CSS:
body {
    margin:0;
    padding:0;
    max-width: 100%;
    max-height:100%;
}
section {
    position:absolute;
    top:5%;
    bottom:5%;
    left:0;
    width:100%;
    height:90%;
}
section img {
    width:12.5%;
    float:left;
    margin-left:10%;
}

Comment: Does the section element need to have a height of 90%?
Comment: @j08691 I assume it's because the header/footer has a totaled height of 10%
Comment: yeah, header and footer 5 % so section 90%
Answer: Assuming the width of the image equals the height of the image (like the code you gave has), you can just use margin-top of 50% - imageHeight. That would look like
section img {
    width:12.5%;
    margin-top:32.5%;
    float:left;
    margin-left:10%;
}

Demo
If they're not, you can use this pure CSS approach
Comment: Sorry but the height's of the images aren't the same as the width's
Comment: @user2438434 Added an alternative
Answer: You can give the section position:relative; and then do a trick with the images.
The sample below makes them centered of the section, if you want to have the images spread out, but vertically aligned, you need to do this trick on  the containing element (like a dive around the images in the section:
section {
    position:relative;
    top:5%;
    bottom:5%;
    left:0;
    width:100%;
    height:90%;
}
section img {
    /*width:12.5%;
    float:left;
    margin-left:10%;*/
    position:absolute;
    top:50%;
    margin-top:-25%;/* should be half the height of the image */
    left:50%;
    margin-left:-25%;/* should be half the width of the image */
}

Comment: You cannot have both `top` and `bottom` values, only the `bottom` value is being used. Also this will position all four images in the same location, not with space in between
Comment: @ZachSaucier correct, I forgot to clean the OP's code. And yes this an vertical and horizontal centered example as indicated in the answer. To space in between you need to add an element.Your answer is generally better hence I upvoted it ;-)
Answer: I think its easier to wrap the images in a container and then center the container in the container's parent, in this case you could use an Article tag to wrap the images an then center that article in the section like this
HTML

CSS
html, body {
    height: 100%;
    width: 100%;
}

section {
    top: 5%;
    left: 0%;
    width: 100%;
    height: 90%;

    /* strech */
    overflow: hidden;
}

article {
    width:80%;
    height:40%; /* change this to set height */

    /* CSS absolute center begin */
    border: 2px solid #0000ff;
    margin: auto;
    position: absolute;
    display: inline-block;

    top: 0;
    bottom: 0;
    left:0;
    right:0;
    /* CSS absolute center end*/
}

.pic {
    position: relative;
    float: left;
    width: 12.5%;
    height: 100%;
    margin-left: 10%;
}

.pic img{
    position: relative;
    width:100%;
    height:100%;
}

Hope it help you
Comment: It works, thanks man. need to adjust the stretch, but okay. thanks

Positioning vertical center


Login to craigslist to retrieve account page using Delphi and Indy and SSL

Question: I am trying to log into craigslist using Delphi, and retrieve my account page (in order to gather a listing of all my posts)
However, I can't seem to get the login to work, what Am I doing wrong?
function TfrmMain.Login: string;
var
  IdHTTP: TIdHTTP;
  Request: TStringList;
  Response: TMemoryStream;
begin
  Result := '';
  try
    Response := TMemoryStream.Create;
    try
      Request := TStringList.Create;
      try
        Request.Add('op=login');
        Request.Add('redirect=http://newyork.craigslist.org/');
        Request.Add('login=' + myEmail);
        Request.Add('password=' + myPassword);
        IdHTTP := TIdHTTP.Create;
        try
          IdHTTP.AllowCookies := True;
          IdHTTP.HandleRedirects := True;
          IdHTTP.Request.ContentType := 'application/x-www-form-urlencoded';
          IdHTTP.Post('https://accounts.craigslist.org/login', Request, Response);
          Result := IdHTTP.Get('https://accounts.craigslist.org/');
        finally
          IdHTTP.Free;
        end;
      finally
        Request.Free;
      end;
    finally
      Response.Free;
    end;
  except
    on E: Exception do
      ShowMessage(E.Message);
  end;
end;

I get a exception class EIdIOHandlerPropInvalid with message 'IOHandler value is not valid' on the line:
IdHTTP.Post('https://accounts.craigslist.org/login', Request, Response);

thanks
Comment: As first, you're not using SSL IO handler.
Comment: @Johnny, get a copy of the OpenSSL library [`from here`](http://indy.fulgan.com/SSL/), from the archive extract the `libeay32.dll` and `ssleay32.dll` files, so that they'll be visible to your project output (so e.g. into the same directory as your project output is) and modify your code [`this way`](http://pastebin.com/AFAhEjHW). You were missing SSL IO handler, which must be used when working with SSL secured sites.
Comment: @JohnnyHolmes I don't understand your reaction to Rob's comment. That comment is polite and helpful. View it in the light of the original version of the post, the one that you posted, in which the error message was not visible without scrolling through the code block. You need to develop a slightly thicker skin to ask questions on SO. If people ask for more information, try and understand their point of view.
Comment: @JohnnyHolmes I'm not down voting! I've answered loads of your questions. I am trying to help you. So is Rob.
Comment: TLama, I think we are almost there. on the same line that I got my exception in my original post, it is now throwing a socket error #0
Comment: I'm sorry. You buried your problem description in a code block. I didn't read all the code, so I didn't see your question. Mjn has fixed that for you.
Comment: Your question should be updated to indicate that the program now throws a socket error #0
Comment: @TLama - im using Delphi 2010 and I get the error.
Answer: See (Indy) TIdHTTP EIdSocketError Socket Error # 0 exceptions when downloading files and the suggestions in the comments. It looks like you should upgrade to a more recent version of Indy.
Comment: Actually I jumped to conclusion. That didn't throw and error, and it did return HTML, but it return the login page back instead of the accounts page. I am re-opening a new question


Tratando a lógica e exeções - jQuery

Question: Eu tenho alguns botões do qual no onclick dos mesmos trabalham com duas requisições Ajax para um arquivo externo que adicionam produtos, mas isso não é de extrema importância nessa questão. O meu problema é o seguinte: se o botão comprar for clicado, o produto é adicionado, porém se a página for atualizada o mesmo estará lá, mas eu só posso ter um produto do mesmo de cada vez e se depois da página atualizada o botão comprar for clicado novamente, outro produto é adicionado e isso não pode acontecer, pois o que já estiver adicionado deve ser retirado a partir da função removeCartaotoCart para que o novo seja adicionado, para que eu tenha somente um produto por vez.
Código dos botões:
 <button type="button" class="button btn-cart" onclick="addCartao('<?php echo $_product->getId(); ?>')" name="cartaoMensagem<?php echo $_product->getId(); ?>" id="cartaoMensagem<?php echo $_product->getId(); ?>">Comprar</button>
 <button style="display: none;" type="button" id="cartaoMensagemRemover<?php echo $_product->getId(); ?>" title="Remover" class="button btn-cart" onclick="removeCartaotoCart('<?php echo $_product->getId(); ?>')" name="cartaoMensagem<?php echo $_product->getId(); ?>">Remover</button>

Código das requisições Ajax:
var productSelected = "";
            function addCartao(product_id){
                if( productSelected != "" ){
                    removeCartaotoCart(productSelected);    // Remove the item in cart, if there is one.
                  }
                $j('#cartaoMensagem'+product_id).hide();
                $j('#cartaoMensagemRemover'+product_id).show();
                $j('#cartaoMensagemRemover'+product_id).css({'background-color': '#000000'});
                $j.ajax({
                  type: "POST",
                  url: "adiciona.php",
                  data: {
                    product_id: product_id
                  },
                  dataType: 'json',
                  cache : false,
                  beforeSend: function () {

                  },
                  success: function (retorno) {
                    var button = $j('#cartaoMensagemRemover'+product_id);
                    productSelected = product_id;
                    $j('.item-custom').append('

' + retorno['name'] + '
	1	 R$ ' + retorno['price'] + '
');
                    getSubTotal();
                    getGrandTotal();
                  },
                  complete: function () {

                  },
                  error: function (x,y,z) {
                    alert("error");
                    alert(x);
                    alert(y);
                    alert(z);
                    window.location.reload();
                    history.go(0);
                    window.location.href=window.location.href;
                  }
              });
            }

            function removeCartaotoCart(itemId){
                productSelected = "";
                $j('#cartaoMensagemRemover'+itemId).hide();
                $j('#cartaoMensagem'+itemId).show();
                $j.ajax({
                    type:"POST",
                    url:"remove.php",
                    data:{
                        itemId: itemId
                    },
                    cache: false,
                    beforeSend: function(){

                    },
                    success: function(retorno){
                        var button = $j('#cartaoMensagemRemover'+itemId);
                        $j('.item-custom #trAppend'+itemId+'').remove();
                        getSubTotal();
                        getGrandTotal();

                    },
                    complete: function () {

                    },
                    error: function (x,y,z) {
                    alert("error");
                    alert(x);
                    alert(y);
                    alert(z);
                    window.location.reload();
                    history.go(0);
                    window.location.href=window.location.href;
                  }
                });
            }

Observação: A partir da variável productSelected, eu consigo tratar uma exceção: se o botão comprar for clicado e já houver um produto adicionado, o mesmo é removido para o novo ser adicionado, porém essa outra exceção com relação a atualizar a página não sei como devo prosseguir para soluciona-lá. Acho que o correto a se fazer é na atualização da página ele remover o produto que foi adicionado segundo o botão comprar, a partir do seu id.
Comment: Você gastou 80% do seu texto para descrever uma situação sem relevância pro problema. E o problema está mal explicado. Por favor, seja sucinto e claro.
Comment: @BrunnoVianna eu atualizei a questão, agora sendo mais claro e explicando mais o problema.
Comment: Por que vc precisa dar um reload na página?? Já que está usando Ajax, não seria mais fácil remover o botão "comprar" e o item relacionado a ele com jQuery `.remove()`?
Comment: @Dvdsamm Sim, ou na atualização da página, o item clicado vir com o botão remover ativo, não o comprar, que seria o que eu precisaria no caso.
Comment: Então, se vc apagar os reloads do código não funciona?
Comment: @Dvdsamm Funciona, porém eu queria que tipo, o botão comprar foi clicado, em seguida ele é "trocado" pelo remover. Se a página é atualizada, ele vem como comprar novamente, mas eu precisaria que nesse caso ele viesse como remover.
Comment: Agora entendi. O caso é o seguinte: quando a pessoa clica em comprar, vc precisa guardar essa informação em algum lugar, para quando a página for carregada novamente, puxar essa informação e fazer a comparação. Não sei como vc está fazendo essa "guarda" de informação. Se for no banco, vc deve puxar isso do banco e ver se o item que foi "comprado" está lá, e, se estiver, vc exibir o botão "remover"  em vez do "comprar".
Comment: @Dvdsamm Isso, seria isso mesmo que você disse, porém estou tento dificuldades em "guardar" essa informação, pois não sei como devo prosseguir para fazer o mesmo.
Comment: Vamos [continuar esta discussão no chat](http://chat.stackexchange.com/rooms/65603/discussion-between-dvdsamm-and-matheus-portela).
Answer: A solução da qual achei muito tempo depois foi no carregamento da página é feita uma requisição ajax para poder verificar se há produto adicionado e o valor do retorno da requisição é adicionado em dois input do tipo hidden, para pegar esse valor e fazer a requisição que remove o produto.
Código dos input's:
<input type="hidden" name="cartao_adicionado" id="cartao_adicionado" value="0" />
<input type="hidden" name="cartao_adicionado_product_id" id="cartao_adicionado_product_id" value="0" />

Código da requisição Ajax:
$j(document).ready(function(){
        //Requisição Ajax para ver se existe produtos na atualização da página
        $j.ajax({
            type: "POST",
            url: "verifica.php",
            data:{

            },
            dataType: 'json',
            cache: false,
            beforeSend: function(){
            },
            success: function(retorno){
                $j('#cartao_adicionado').attr('value', retorno['adicionado']) ;
                $j('#cartao_adicionado_product_id').attr('value', retorno['id_produto']);
                isCartaoAdicionado = $j('#cartao_adicionado').val();
                isCartaoAdicionadoProductId = $j('#cartao_adicionado_product_id').val();
                removeCartaotoCart(isCartaoAdicionadoProductId); //chama a requisição para remove o produto a partir do seu id.
            },
            complete: function(){

            },
            error: function(x,y,z){
                alert(x);
                alert(y);
                alert(z);
                alert("Erro!");
                window.location.reload();
                history.go(0);
                window.location.href = "{{store url=''}}";
            }
        });
    })

Tratando a lógica e exeções - jQuery


Lang's Theorem 7.3 wording, what does he mean?

Question:

Above is the first part of proof Theorem 7.3, Lang's Algebra, p41.
Why could we apply Lemma 7.2?
Isn't this only a consequence of this line? (Which was stated after application?)

Since $f(B)$ is either $0$ or infinite cyclic...$B$ is free.

EDIT: I clarified question a bit.
Answer: The free group on the empty set is $0$.
The free group on $\{g\}$ is the infinite cyclic group generated by $g$.
So in both cases considered $f(B)$ is free.
So $B_1$ is isomorphic to a restricted direct sum of copies of the group of integers because it is free by induction and abelian. Furthermore $\mathbb{Z}_1$ is not induced in this decomposition.
On the other hand $f(B)=C_1$ is isomorphic to $\mathbb{Z}_1$ or $\{0\}$, so $B$ is isomorphic to a direct sum of copies of the group of integers, so $B$ is free.
Comment: I believe your $B_1$ and $C_1$ are reverse of the proof? (I will continue my question with the original one) So my problem is, in order to apply the lemma, we need the image of $f|B$ to be free, so we get that $C_1$ is free (from isomorphism) (or $B_1$ in your case). So the line I quoted was necessary?
Comment: you just needed $f(B)$ to be free and NOT generated by $x_1$ or $x_2$ and so on
Comment: Sorry, but I am now confused with what you mean by "not generated by $x_1$ or $x_2$... " may you elaborate? My understanding is: We obtain $B=B_1 \oplus C_1$ from lemma; all is required is that $f(B)$ is free.
Comment: Sorry I made a mistake I meant you need $f(B)$ not generated by $x_2, x_3 ...$ but it is obvious by definition of $f$. Indeed if $x_2$ for example was one of the generators of $f(B)$ then the sum would not necesarely be direct and you would not be able to conclude.
Comment: Do we need to check that though? All we need is image of $f$ to be free, then we can decompose $A = \ker f \oplus C$, where $C \cong Im f $ by lemma(?)
Comment: You don't need to check it but it is a part of the idea behind this lemma. This is what makes this lemma work
Comment: Ok, thanks a lot!


What does the caret symbol ^, mean in guitar tablature?

Question: I'm reading a piece of acoustic guitar music containing both tablature and standard music, and I've come across a symbol I'm unfamiliar with in the tab.
^
The tab shows:
0^24 but the ^ is on top of the numbers in that the first "leg" lies on the 0 and the right "leg" lies on the 2 of the 24. The section immediately preceding the symbol is an arpeggiated chord
I've looked it up and people keep saying that it's usually a bend. Which in this case makes no sense (you can't bend an open string 2 octaves now can you?). This may be the case if writing a bend for Ultimate Guitar but a bend in true tab I've seen is usually a curved upwards line followed by 1/4 or 1/2 etc.
The music is very difficult to read in this case as it's quite compact and some symbols overlap so I can't tell the meaning of the tab symbol from that.
At first I assumed it was some kind of harmonic, so I was playing the natural harmonic at fret 12. But then later on I see <12> on the tab. Which I've always read as the natural harmonic at 12th fret.
So now i'm confused. Is it denoting some kind of pinch harmonic at "fret 24" (which my fringerboard length doesn't reach)?
Or is it a really short tie/slur?
Thanks in advance.
Comment: If it did mean a pinched harmonic, at fret 24,  the fact that your fingerboard doesn't reach is neither here nor there. There is a point along the string which is over 'fret 24'. You just have to find it. And, its matching harmonic is over fret 5, so you could find it there.    It would really help to see the tab.
Answer: Ah it seems to be just a short tie. Simply being a hammer-on from 0 to 2 and a quick 4 ie: --0h2-4--
Answer: It may be a hammer-on to the 24th fret.
Answer: This question is over a year old so you may have found it already.  If not, the caret is usually found in music notation and, of course, would mean the same thing in tablature.  It means, "a strong accent".
http://www.violinist.com/discussion/response.cfm?ID=16794


What constitutes to the grading of a guitar piece?

Question: Let's say RockSchool for now to keep it simple.
I'm aware that it's a bit more flexable than the grading scheme on piano, and I'm applying to a music college this year and looking at my options for songs to play for the audition.
I want to perhaps play Over The Hills and Far Away by Led Zeppelin, and perhaps this question could use some rephrasing, but bonus points for giving a rough estimate of the over the hills grade(I reckon 8 for the solo)
What are the main factors influencing a graded piece
Answer: I'd put this at grade 6 at the most. It seems to be a lot of pentatonics, has a bit of form, but doesn't really 'hit you in the face'.
For this grade level, there needs to be a lot more 'inventiveness'.I.e. more structure to the solo, certainly using most of the fingerboard, slides, hammer-ons, pull-offs, bends (and not just simple ones), probably a signature vibrato,and  use of more than 3 or 4 chords - not just maj. or min. either.
I have far more experience with R.G.T. than Rockschool, and am aware that one of the main differences is that for R.G.T.(electric) there are no set solos to learn and reproduce, so criteria will differ.However, the quality of playing of your example would put it, as said, around grade 6.
The double stop part at the end sounds to me like two players, but at grade 6 level, you would be expected to play both parts simultaneously. Hope this helps.
Comment: I didn't realise RGT had a grading system.  I thought they were just for Teachers.  Would you say RGT is more difficult/more technical than Rockschool? I've noticed that grade 8 Rockschool doesn't seem that difficult comparatively
Comment: Rockschool and RGT was all new to me.  I did some googling...  Rockschool: http://www.rockschool.co.uk/ RGT: http://www.rgt.org/
Comment: RGT is unusual in that there are no set pieces to learn. 30% marks are awarded for reading a hitherto unseen chord chart, another 30% for playing lead over ,again, a hitherto unseen chart, while the examiner plays the chords. Both skills which a lot of gigging guitarists need. Rockschool is of the old school type, where pieces, or sections of them, are played for the exam.That way, to my mind, is making the player  become a 'one trick pony'.
Comment: do you know which school(if any) is likely to be more respected by music schools?
Comment: I feel that RGT gives a player a more rounded palette to work with, where Rockschool is rather what it says, so I'm going with RGT. Some examiners have hinted similarly too.


Composition of groups

Question: Let's say we have a system of interacting particles that can divided into two populations. The symmetry group of each population is $G$, and the two populations are identical, so that I can exchange them and the system remains invariant (see figure). I think the symmetry under exchange of the two populations should be described by the symmetric group $\mathfrak{S}_2$, see here.

My question is: what is the symmetry group of the whole system? Intuitively it should be some kind of composition between $\mathfrak{S}_2$ and $G$, but which one? Thanks in advance for your help!
Answer: Let us formalize it the following way :
$$Y=X_1\cup X_2 $$
This is a disjoint union. Set $S(*)$ to be the symmetry of $*$. We know that $S(X_1)=S(X_2)=G$. Then $S(Y)$ acts on $Y$, set $S_1$ the set of symmetry fixing $X_1$ then they fix $X_2$, hence $S_1$ is $S(X_1)\times S(X_2)=G^2$. Now we have that $S(Y)/S_1$ is the group of permutation of $\{X_1,X_2\}$ hence it is $\mathfrak{S}_2=\mathbb{Z}/2\mathbb{Z}$. Now I claim that the quotient admits a section hence you have :
$$S(Y)=(G\times G)\rtimes_{\phi} \mathfrak{S}_2$$
Finally we have to determine $\phi$, I claim that $\phi((1,2)).(g_1,g_2)=(g_2,g_1)$ so that it is non trivial and it just permuts both coordinates. So you have your group.
Furthermore the same technique can be used to show that if $Y=X_1\cup...\cup X_n$ then :
$$S(Y)=G^n\rtimes_{\phi}\mathfrak{S}_n $$
Where $\phi(\sigma).(g_1,...,g_n)=(g_{\sigma(1)},...,g_{\sigma(n)})$. We actually say that this is the wreath product of $G$ with $\mathfrak{S}_n$ (see https://en.wikipedia.org/wiki/Wreath_product) :
$$S(Y)=G\wr \mathfrak{S}_n $$
Edit : the fact that $S(Y)/S_1$ admits a section obviously depends on your situation, but it most certainly has. Anyway the wreath product is usually what you need to formalize this situation : $n$ objects with each the same symmetries ($G\times...\times G=G^n$) and the symmetries of their configuration ($S(Y)/G^n$).
Comment: @user2983638 Yes, for the section, if you know a little group theory, say you have $N\triangleleft G$ and $G/N=Q$, you must have seen that this doesn't imply (at all) that $G=N\times Q$. If you know more group theory (semi-direct product) you would think that $G=N\rtimes_{\phi}Q$ but this is not always the case either. It appears that there is a good caracterisation of semi-direct product namely if $\pi:G\rightarrow Q$ is the canonical projection then $G$ is a semi-direct product iff $\exists$ a group morphism $s: Q\rightarrow G$ such that $\pi\circ s=Id_Q$.
Comment: @user2983638, in that case $s$ is called a section. If you haven't such a section then it is kind of hopeless to understand the group $S(Y)$ (there are techniques though but it is rough). Now for your last question it will have a section if $a\geq 3$ and $b\geq 3$. The reason is that $Z((\mathfrak{S}_a\times\mathfrak{S}_b)^n)$ is trivial. But it is not explainable in one comment I am afraid. If you are brave you can read : http://sierra.nmsu.edu/morandi/notes/GroupExtensions.pdf. It is related to the classification of extensions.
Comment: Many thanks! If I understand it correctly, you use the notation $\mathfrak{S}_2$ for the symmetric group, while I used the notation $S_2$. So I have just edited my question in order to unify the notation.
Comment: I'm not an expert of the topic, so I'm not completely sure to understand the problem of the section that you mentioned. In my case $G=\mathfrak{S}_a\times\mathfrak{S}_b$, so does $S(Y)/S_1$ admit a section in this case?
Comment: Thanks Clément, your help has been very precious!

Composition of groups


Does this derivative exist at 0

Question: The function $$f(x)=\cos(e^{|x|}-1)$$
At x=0
The left and right hand limit are 0
$$\lim_{h\to 0^{\pm}}\frac{f(0+h)-f(0)}{h}=0 $$
This must mean the function is diffrentiable at zero. But wolfram alpha is contradicting this, say in it is undefined. Even the online derivitive calculator is showing undefined. Is this an error?
WOLFRAM ALPHA
SYMBOLAB
Comment: I think the derivative exists at 0 and is 0.
Comment: WA is at fault here. Learning math via software tools should be avoided.
Comment: The chain rule isn't wrong. It just doesn't apply in this situation, where the inner function $g$ isn't differentiable. That doesn't prevent the composite function $f \circ g$ from being differentiable; it all depends on what $f$ is. (Trivial example: if $f$ is a constant function, then so is $f \circ g$, no matter what $g$ is, so $(f \circ g)'=0$.)
Comment: How did you evaluate the limit ?
Comment: http://math.stackexchange.com/questions/991475/why-is-the-absolute-value-function-not-differentiable-at-x-0/991559 the same manner as this link except with my function, then used l'hopital
Comment: #paramanand   I understand if the left hand derivitive= right hand the derivitive is that finite number. But how can the chain rule be wrong?
Comment: Even though the chain rule has denominator |x| there is always a way to simply this. I am Still searching for a way to do so. Sinx is odd so I'm Still working with this
Comment: Actually you are all right. It satisfies the formal definition of a derivitive at a point. So it MUST hold. Thanks for clarifying
Comment: Even though WA is wrong about the derivative, using it for plotting the function provides pretty convincing evidence (although not a proof, of course) that $f'(0)=0$: [link](http://www.wolframalpha.com/input/?i=plot+cos(e%5E%7Cx%7C-1),+x%3D-0.01..0.01).
Comment: Please verify this sir: $e^{|x|}$ is NOT diffrentiable at 0 as the left hand derivitive and right hand derivative are not equal at this point.
Comment: I don't know why this was downvoted. The function in question is very good example which shows the limitation of chain rule. +1 for the same. Also I would request you to unaccept the wrong answer.
Answer: Using the chain rule we have that for $x\in\Bbb R\setminus\{0\}$
$$f'(x)=-\sin(e^{|x|}-1)e^{|x|}\operatorname{sign}(x)$$
and
$$\lim_{x\to 0}f'(x)=0$$
where the above limit is equivalent to
$$f'(0)=\lim_{x\to 0^+}\frac{\cos(e^x-1)-1}{x}=\lim_{x\to 0^-}\frac{\cos(e^{-x}-1)-1}{x}=0$$
due to L'Hôpital rule.
P.S.: dont trust wolfram alpha or any other mathematical software.
Comment: so you are saying it is differentiable at 0?
Comment: @Sid yes, it is. The two limiting process are equivalent... remember L'Hôpital rule!
Comment: yes, i have used l'hopital in evaluating the limits. but how can all famous mathematical softwares be wrong? wolfram, symbolab, online derivitive calculator?
Comment: @Sid they are wrong all the time, believe me. Intelligence cannot be copied as easily!
Comment: yes but they are right for other limits. IS this function a special case, where it is differentable at x=0?
Comment: @Sid Just evaluate the right and left side limits with WA and also there are many examples of WA being wrong with limits.
Comment: @Sid Special case in what sense ? there are infinitely many functions differentiable at 0.
Comment: anyway probably wolfram-alpha is taking $f$ as a function defined in $\Bbb C$, that is, by default the wolfram language take all variables as complex. Anyway all CAS fail most of the time in many evaluations, so dont trust so much except for boring but easier calculations.
Comment: then why is symbolab and the online derivative calculator showing error too? and not to $cos|x|$ or $x^2e^{|x|}$
Comment: the denominator of the derivative has |x| that is not possible to simplify!
Comment: @Masacroso why would the chain rule ever be incorrect?
Comment: Just other example more of WA being wrong. There are many, and reading posts in ME one can surely find dozens of cases. Most probably WA wants to apply directly the chain rule, and since the derivative of $\;|x|\;$ at $\;x=0\;$ doesn't exist the mistake follows. Don't over trust WA or similar programs.
Comment: Actually you are all right. It satisfies the formal definition of a derivitive at a point. So it MUST hold. Thanks for clarifying
Answer: It appears that you have a hard time trying to come to terms with this example where chain rule does not apply. But then you have to understand that chain rule is a one way implication:
If $g$ is differentiable at $a$ and $f$ is differentiable at $g(a)$ then $f\circ g$ is differentiable at $a$.
The following converse does not hold:
If $f\circ g$ is differentiable at $a$ then $g$ is differentiable at $a$ and $f$ is differentiable at $g(a)$.
In your example the function $G(x) = e^{|x|} - 1$ is not differentiable at $0$ and $F(x) = \cos x$ is differentiable at $G(0) = 0$ and yet $F\circ G$ is differentiable at $0$. Here is an intuitive way to look at this. Since we are only interested in the troublesome point $x = 0$ we need to analyze the behavior of $f(x) = \cos(e^{|x|} - 1)$ near point $x = 0$. Now if $x$ is near $0$ then $e^{|x|} \approx 1 + |x|$ and hence $f(x) \approx \cos |x| = \cos x$ so that the modulus sign goes away and we should expect $f$ to be differentiable there.
Note that the even nature of $\cos$ plays a significant role here. The function $g(x) = \sin (e^{|x|} - 1)$ looks similar but is not differentiable at $0$. You should be able to show in general that if $F$ is an even function differentiable at $0$ then $F'(0) = 0$ and if $g(x) = F(e^{|x|} - 1)$ then $g'(0) = 0$.
Comment: Yes, this is the correct answer, but will the OP be able to recognize it as such?
Comment: @AlexM.: Don't worry, OP already has taken a step in right direction by unaccepting the wrong answer.
Comment: Yes but $\cos(e^{|x|})$ is NOT diffrentiable at 0 and the left hand ad right hand derivatives are not equal.
Comment: @Sid $F(\color{red}{e^{|x|} - 1})$ not $F(e^{|x|})$. Anyway don't use capitals because they are against the policy. Don't ask me I still don't get why.

Does this derivative exist at 0


Private folder issues with NGINX

Question: So I have been setting up my Drupal 8 installation and I'm having troubles with my private folder setup.
I went on to settings.php and specified the path which I wanted for my private folder as sites/default/files/private. It seemed to be working well for a while, but now it isn't.
I have configured Drupal to use the private folder as default location for file uploads and it shows the sites/default/files/privatepath as the private folder path.
Now my issue is that I created a custom content-type with a private folder file upload field. This is for a restricted area I have in the website which I only want authorized (logged in) users to be able to access - both that area, and the files linked there.
The area was successfully blocked via role permissions and works great. The files attached to content - even though the content-type settings are explicitly and correctly set to use the private folder for upload - result in the following behavior:

files served by direct HTTP in sites/default/filesare accessible, regardless of Drupal login state - as intended
files served by direct HTTP in sites/default/files/private are blocked with a 403 forbidden by NGINX regardless of Drupal login state - as intended
restricted files served by Drupal in the restricted area with an URI similar to system/files/YEAR-MONTH don't show Drupal's access denied 403 page (the intended effect), BUT INSTEAD:

if they are images, I get an NGINX 404 NOT FOUND error page
if they are other file-types, they are accessible without restriction (exactly what I'm trying to prevent).

Right now I'm lost as I've been searching around for answers on these issues, but I can't seem to find them.
I'm using a shared web server setup in which I don't have direct access to NGINX's .conf files. I'm also using the IMCE File Manager module. I think that the images issue is related to some NGINX conf and as such I'll have to contact the web server maintainer to fix it, but I'd like to have some insight to share with them about this. Also, what can possibly explain the files being uploaded to the private folder being accessible without any restriction?
Any help would be very welcome, thanks!
Comment: Hi @jorum were you able to fix this issue. Please let us know what you did.
Comment: Note that _system/files/*_ files are accessible by default unless you protect them explicitly for example by unpublishing a content they belong to.
Answer: It has been a while since I created this question, and as such I might be missing quite a few details, but I eventually did find a solution.

TL;DR It should probably relate to NGINX, so cover all the bases related to it. NGINX's official Drupal recipe helped me a lot,
  you might want to check that first. Although, if you're using Drupal 8, you'll need to update/change some settings for it. You might find some of them here.

Can't recall much about my specific case, but this checklist might be worth checking out in your setup:

settings.php be careful and mindful of the options you have setup in your settings file. IIRC, I think the private folder path value was all I changed regarding this issue.
Drupal configuration - in Drupal's admin backend, go to Configuration > Media > File System and make sure you have the correct option selected for your use case, either public/private. This will setup your default file upload location, but can be overridden in the content type's definition, if I'm not mistaken.
Content type definition - make sure that your content type using the file field is setup properly and also according to your needs. I think at some point I even re-created my content-types just to make sure there wasn't stale info in the DB.
Drupal role permissions -  this was probably one of my biggest headaches with this issue. Make sure they are properly setup and test them thoroughly. In this process I discovered the Masquerade module, which has helped me a lot ever since.
Folder permissions - The folders you want to use for both private and public uploads should be writable by Drupal/NGINX, but NGINX should not enable HTTP access to them.
NGINX -  this is definitely the most important part. What you basically need to absolutely make sure of is that Drupal handles it's own URLs, and everything else is handled by NGINX accordingly. This can get confusing really fast, so here are some more tips:

Drupal will have it's own file URL being generated internally and saved to the DB. This should make Drupal respond and take over HTTP requests to a system/files/YEAR-MONTH-type URL.
NGINX on the other hand, must let Drupal handle those requests, while intercepting and preventing direct access to sites/default/files/private, or whatever folder you have setup for private files.
This should be fixed by setting up the correct NGINX directive regarding the path you want/need it to handle. This might help. Also, go read about Perusio's NGINX setup, as there are a lot of valuable nuggets of information there (D8's setup is equivalent to D7).
I think some specific NGINX directives may target certain file-types differently (maybe something related to MIME types, not sure). This could explain if your issue happens with, ie, JPG, but not PDF or vice-versa. Couldn't find info on this, though.

@GokulNK I'm sorry if this isn't enough help, but I really can't recall what I did to fix it. Hopefully it'll point you in the right direction, though.
EDIT: I found an old email with the webserver's maintainer discussing some NGINX directives that has some info that might be relevant:
# handled by NGINX
location ~ ^/sites/default/files/private/ {
    return 403;
}

# Handle private files through Drupal.
location ~ ^/system/files/ { # For Drupal >= 7
    try_files $uri /index.php?$query_string;
}

Comment: If you find yourself being able to award yourself _any_ bounty, whether it's been offered by you or someone else, please do let us know as that would be a major bug :)
Comment: Thanks @Joum the Nginx directive solve my problem.
Comment: @GokulNK if this ends up helping you, let me know so I mark the answer as accepted - I won't take your bounty if it isn't. If other answer shows up that is better than mine, let me know so I can mark it as accepted and they other user gets the bounty.
Comment: @Clive, I didn't know that! :D I thought it might happen if I marked my own answer as accepted, but obviously it doesn't make much sense.

Private folder issues with NGINX


JPA findAll(spec,Sort)

Question: I have this code to get all transaction between 2 dates. I would like to get a desc sorted list. What are the possibilities?
<code>@Override
public List<Transaction> searchBySubmitDate(final Date startDate,
                                            final Date endDate) {
    return transactionRepository.findAll(new Specification<Transaction>() {
        @Override
        public Predicate toPredicate(Root<Transaction> transaction,
                                     CriteriaQuery<?> q, CriteriaBuilder cb) {
            Predicate between = cb.between(transaction.get(Transaction_.dateSubmit), startDate, endDate);

            return between;
        }
    });
</code>
Answer: <code>@Override
    public List<Transaction> searchBySubmitDate(final Date startDate,
                                                final Date endDate) {
        return transactionRepository.findAll(new Specification<Transaction>() {
            @Override
            public Predicate toPredicate(Root<Transaction> transaction,
                                         CriteriaQuery<?> q, CriteriaBuilder cb) {
                Predicate between = cb.between(transaction.get(Transaction_.dateSubmit), startDate, endDate);

                return between;
            }
        },new Sort(Direction.DESC,"dateSubmit"));
</code>
Answer: The repository has another method taking a Sort as additional argument. Call this method with an appropriate Sort instance.
Comment: I tried that it doesnt work, i might use it in a wrong way. List list= new ArrayList();
  list.add("dateSubmit");
  Sort sort= new Sort(Direction.DESC, list);
Comment: what SQL query does it generate?
Answer: I thought I would leave a more up-to-date answer, since it's been 7 years. This is how we do it now:
<code>interface TransactionRepository extends Repository<Transaction, Long> {
    @Query(value = "SELECT * FROM Transaction AS t " +
        "WHERE t.date >= :since AND t.date <= :until", nativeQuery = true)
    public List<Transaction> findTransactionBetween(@Param("since" String since,
                                                    @Param("until" String until);
}
</code>
You can read more in the Spring JPA documentation

JPA findAll(spec,Sort)


Purpose of "views_date_format_sql" module

Question: i got back a projet which is using the module views_date_format_sql. This module is not compatible with D9, so I'm trying to find a replacement
But I don't get what this module is supposed to do.
If I disable it, it doing a cascade of disabling config views/node etc...
Can anyone tell me what's the purpose of this plugin ?
Answer: From the Views Date Format SQL project page:

The Views Date Format SQL module allows to format date fields using
SQL. This enables group aggregation for date fields using the choosen
granularity.
The core functionality is to remove the date formatting from render()
and put it in query(). I.e. format date values using SQL's DATE_FORMAT
rather than PHP's format_date. This is achieved by assigning a new
default handler to node 'created' and 'changed' date fields. This
handler extends and overrides views's built in
views_handler_field_date.

After a review of the module, you'll see that this new default handler is "views_date_format_sql_field".
As far as how this is being used on your site, you'll need to figure that out for yourself. I'd start by reviewing the views that get disabled when you would uninstall the module - check for any timestamp fields, e.g. 'created' or 'changed'. The fastest way might be to scan the config files for "views_date_format_sql_field", the new default handler the module adds. Once you know where the module is being used, you can determine what effect removing it would have.

Alternatively, it may be simpler to make the module D9 compatible. Many Drupal 8 modules are Drupal 9 compatible after a simple change to their .info.yml file - replacing core: 8.x with core_version_requirement: ^8 || ^9.
Comment: I appreciate your help. For now, the module was forked to be D9 compatible, but I didn't know what it was doin.


Checking what attributes of a population made objects more likely to do certain action

Question: I'm pretty lost at how to approach this, and particularly with regards to the terminology; so please feel free to point to resources, fix my question name, etc. Thanks.
I used R back in college, I've got Orange installed. I've heard of MiniTab. I've got Excel installed. I've got access to SQL Server 2008 w/ Analysis Services. That's the breath of my toolkit. [I'm a developer, but that's all I know of for statistical analysis.]
I'm marketing a product, and I've got a few datasets.
Customers:

Customer_id
Campaign they clicked on, and the date.
Campaign they converted on, and the date.
The amount of biz they did with us in Q1 2010
The amount of biz they did with us in Q2 2010
The amount of biz they did with us in Q3 2010 ... etc.

Campaigns:

Day of the week
Time of Day
Specific pitch

Results:

Number of purchases per customer
Value of purchases per customer

I could easily go hogwild, guessing at patterns and testing them to see if there's any accuracy; but it's not a best use of time. What I'd like to know are a few things...

A ranking of the various pitches in their effectiveness, and an indication of how much the pitch affects the result.
Same for the day of the week and time.
And, trickier -- How much of a correlation does their previous business have to do with who converts now? Is it the previous big spenders that convert? Are they the ones buying the most product?
And finally, of all the attributes above, how do they rank in their importance to conversions?

I assume these would all come with something like an R-squared indicating their 'accuracy.'
How would I go about starting? What reading would be essential to understanding this? Is there an approach/tool I can use that'll allow me to do a basic version of these sorts of analyses [and what would they be called] rapidly? I'm just looking for trends and hints of where it might be best to focus our energy; it can be rough.
Finally, does anyone know of a resource for basic data mining? analysis? for advertising in particular?
Much obliged,
Answer: I will just try to share my experience as I did some marketing research. Of course everything depends on the data itself, type of business, frequency constraints, etc... So I want you to understand that there is no exact answer for your question.

A ranking of the various pitches in their effectiveness, and an indication of how much the pitch affects the result.

I would just compare the cumulative results of the customers who were involved into pitch with the cumulative results for all the rest. Then you can see relative success of each pitch and rank them afterwards.

Same for the day of the week and time.

This depends a lot of the nature of your pitches. You can either do the same procedure as described above for every day of the week, or for a pair "pitch+day".

And, trickier -- How much of a correlation does their previous business have to do with who converts now? Is it the previous big spenders that convert? Are they the ones buying the most product?

You are right, that's a little trickier. I would first segment your customers into groups (as you said "previous big spenders" can be one of the groups). And after that I will have a look at the impact of the pitch for every group separately. You will see that some groups are converted more (the relative success of the pitch is higher).

And finally, of all the attributes above, how do they rank in their importance to conversions?

That can vary a lot from one industry to another. So I cannot answer.
Hope some of my suggestions would help!
Answer: In general, what you want is a covariance matrix.
In MatLab, this is relatively simple to implement. The function corrcoef (correlation coefficient) will tell you the correlation between every pair of variables.
You will want an nx11 matrix, where n is the number of instances (one per customer) and 11 is your number of variables (6 customer variables, 3 campaign variables, and 2 results)
Corrcoef will multiply (and normalize) M'M to get you an 11x11 result. The diagonal of this matrix will just be how the i'th variable correlates with itself, namely, a diagonal of 1's. Any i,j entry in the correlation matrix will represent how variable i correlates to variable j. Answers close to 1 mean very high correlation. Answers close to -1 mean anti-correlation. Values near 0 mean no correlation.


How is this differential equation simplified? Is $\frac{d(v_a + v_b)}{dt} = \frac{dv_a}{dt} + \frac{dv_b}{dt}$ with $v_a$ and $v_b$ functions of $t$?

Question: How can this equation
$$
(v_i - v_1)g_1 - C_1\frac{dv_1}{dt}+C_2\frac{d(v_o - v_1)}{dt} = 0
$$
be simplified to this?
$$
v_i g_1 = g_1 v_1 + (C_1 + C_2)\frac{dv_1}{dt} - C_2\frac{dv_o}{dt}
$$
I see how to simplify it if
$$
\frac{d(v_o - v_1)}{dt} = \frac{dv_o}{dt} - \frac{dv_1}{dt}
$$
but is this true in general?
Comment: The differential operator is linear.
Comment: Please don't use pictures of text or formulas. See
[here](https://math.meta.stackexchange.com/questions/34121/why-image-cannot-be-used-for-explaining-my-maths-problem),
why. Use MathJax. Here is a
[tutorial](https://math.meta.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference).
Comment: Hi! Yes, please typeset your mathematics using [MathJax](https://math.meta.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference). Doing so will help keep your answer from being poorly received. Of course, MathJax has a learning curve, but if you make an honest initial attempt, experienced users will generally be happy to help you improve and fix whatever errors you experience. ¶ For example, `$\frac{d(v_o-v_1)}{dt}$` yields $\frac{d(v_o-v_1)}{dt}$ and `$(v_i-v_1)g_1 = v_ig_1-v_1g_1$` yields $(v_i-v_1)g_1 = v_ig_1-v_1g_1$.
Comment: I corrected the title.
Comment: @whpowell96 The title is relevant to the question because his confusion is cleared up if differentiation is a linear operator (as later confirmed by JMoravitz). Sorry, OP, I'd probably have left the second part of the title in there, and just MathJaxed it up. :-)
Comment: I replaced the pictures by MathJax.
Comment: If $F$ and $G$ are differentiable, then so is $aF + bG$ for any constants $a$ and $b$, and it is true that $(aF+bG)' = aF' + bG'$. As @JMoravitz says, the differential operator is linear.
Answer: If $v_0$ and $v_1$ are functions (of $t$) and if $v_i = v_1$ (a typo?) then the property in question is true in general. Derivatives have this property.
Comment: Yes, $v_x$ are all functions. And I corrected the typo.
Answer: If you're asking whether this:
$$\dfrac{d(v_o - v_i)}{dt} =\dfrac{d}{dt}v_o - \dfrac{d}{dt}v_i$$
then yes, it is true.

Looking at it step-by-step you have:
$$\dfrac{d(v_o - v_i)}{dt}$$
so we understand that the expression $(v_o - v_i)$ is differentiated with respect to $t$
$$\dfrac{d}{dt}(v_o - v_i)$$
and this $d/dt$ can be distributed to each term in the same way as you mentioned in your question
$$\dfrac{d}{dt}v_o - \dfrac{d}{dt}v_i$$
Answer: I know this will be unpopular, but you can separate differentiation in general from differentiation with respect to something, as a derivative is merely a ratio of differentials.
Let's start with the expression $x - y$.  To differentiate, you simply perform the differential operator (without respect to anything), which yields:
$$d(x - y) = dx - dy$$
You can freely divide any expression by any non-zero value.  $dt$ is such a value, so you can freely divide both sides by $dt$:
$$\frac{d(x - y)}{dt} = \frac{dx}{dt} - \frac{dy}{dt}$$
Comment: This is unsettling.  Even if it may not be strictly wrong, in general settings and contexts most people are taught not to treat these as numbers.  It would be far more comforting to me to see this written as $\frac{d}{dt}$ as the differential operator and noting that $\frac{d}{dt}[x-y] = \frac{d}{dt}[x] - \frac{d}{dt}[y]$ rather than talking about "dividing by $dt$."
Comment: It's only "merely" a ratio of differentials in non-standard analysis, no?


Criar tabela mysql

Question: Preciso criar, no banco de dados, a tabela abaixo, e inserir os valores apresentados.
A minha duvida é **qual seria a chave primaria nessa tabela ?

**O ID_NF ?No exercicio pede para só criar essa tabela, mas ainda não sei se devo criar outra tabela para ter sentido o id_nf, id_item e cod_prod.
Poderiam me ajudar com isso ?
Não tenho nenhum outro dado da tabela, só isso e que a partir dela serão feitas consultas como por exemplo Pesquisar os itens que foram vendidos sem desconto.
Comment: Como existem diversos registros com o mesmo valor de `ID_NF` então este campo não poderia ser uma chave primária pois não identifica univocamente uma linha da tabela. Será que seu professor não quer que você aplique o processo de normalização?
Comment: Pode ser, mas olhando assim não sei como faria a normalização pois para mim ai já esta normalizado. Acho que seria coisa de ver chave primaria composta ou se preciso fazer as outras tabelas para usar foreign key nessa.
Comment: Você considera que, por exemplo, `valor_unit` não depende apenas do `cod_prod` mas pode variar com cada `id_nf` ou `id_item`, para concluir que a tabela apresentada está normalizada?
Comment: Eu estou começando em banco de dados, não sei muito.Por isso eu disse que não sei como fazer a normalização pois não sei como normalizar mais. Por mais que achasse qualquer coisa, não saberia normalizar essa tabela.
Answer: Uma chave primária identifica univocamente uma linha da tabela. Em seu caso, ela seria composta de ID_NF e ID_ITEM. Em qualquer banco de dados (e o MySQL não é exceção) há funções para criar chaves primárias através de funções. Contudo, isto poderá trazer futuros problemas de desempenho e uma complexidade inicial indesejada. Assim, uma ideia básica seria criar uma coluna adicional, chamada, por exemplo id -- que seria gerado automaticamente pelo próprio gerenciador da base de dados.
Não há uma padronização muito rigida nestes casos, mas é comum usar-se como chave primária um nome no estilo id_TABELA. Por exemplo, se o nome da tabela for notas, sua chave primária seria id_notas.
Uma sugestão para a estrutura da tabela é
CREATE TABLE notas (
        notas_id INT AUTO_INCREMENT PRIMARY KEY,
        id_nf INT NOT NULL,
        id_item INT NOT NULL,
        cod_prod INT NOT NULL,
        valor_unit DECIMAL (10, 2) NOT NULL,
        quantidade INT NOT NULL,
        desconto FLOAT
    );

Caso não queira criar uma chave adicional, a segunda forma da tabela poderia ser
CREATE TABLE notas (
        id_nf INT NOT NULL,
        id_item INT NOT NULL,
        cod_prod INT NOT NULL,
        valor_unit DECIMAL (10, 2) NOT NULL,
        quantidade INT NOT NULL,
        desconto FLOAT,
        PRIMARY KEY (id_nf, id_item)

    );

Um tutorial em português que explica grande parte dos itens (se não todos) dessas estruturas pode ser encontrado em Definição de Dados - DDL
Há alguns cuidados que não foram mencionados aqui: criação de um banco de dados que vai acomodar a tabela, e destruição da tabela caso exista. Mas deve haver o suficiente para um bom começo.

Criar tabela mysql


Android: Images in recycler view item shuffle a lot on scrolling fast

Question: I have a recycler view in my app. Each recycler view item has an imageView. I use an asyncTask to load the bitmaps and add them to the disk cache before setting them into the imageview in onPostExecute.
The problem is that if I scroll through the list fast I can see the images shuffling a lot before the correct image is set for that item. What I understand of this behavior is that as I scroll the list the recycler view item content is replaced with the content of the new item. But since images take some time to load this results in the shuffling effect.
My question is that is there any way to prevent this effect or at least minimize it so that very little shuffling occurs?
Edit: I have tried setting image bitmap to null but it doesn't seem to make any difference.
<code> @Override
    public void onBindViewHolder(DataObjectHolder holder, int position) {
        holder.title.setText(list.get(position).getTitle());
        holder.subTitle.setText(list.get(position).getSub());
        holder.image.setImageBitmap(null);
        loadBitmap(position, holder.image);
    }
</code>
Comment: If the image for an item isn't available yet, you can set a `null` `Bitmap` on the `ImageView` in the Adapter's `bindViewHolder()` method, so the recycled `ImageView` doesn't still show the image previously set on it.
Comment: @MikeM. I can't get it to work, though I have seen this suggestion at some other place as well. I have added the code of my bindViewHolder. Is this the way I should do it?
Comment: It depends on what your `loadBitmap()` method does. I had assumed you were using some sort of cache/loader implementation that could tell you if an image is already in local storage.
Comment: Yes I am using that, and this problem occurs only when the app is installed for the first time. After that i.e. when the images are stored in the disk cache this doesn't happen at all again.
Answer: Add below line in onBindViewHolder();
holder.setIsRecyclable(false);
Answer: You shouldn't use asyncTask to load multiple bitmaps in recycler views. You can either choose to create your own ThreadPool or using 3rd party library like Picasso or Glide. AsyncTask will tried to load the bitmap into your list item that you've referenced, however because you're scrolling too fast it's all messed up.
Answer: Use 3rd party library like Universal Image Loader(UIL) or Picasso or Glide.


Alterar as cores do google charts

Question: Estou usando o google charts gerando 4 pizzas.
 Como faço para alterar as cores que aparecem ?
Segue meu código:
<?php
include("conn_user.php");
include("conn_sys.php");
if (!isset($_SESSION)) session_start();
if (!isset($_SESSION['usu_login'])) {
  session_destroy();
  header("Location:logout.php"); exit;
}

ini_set( 'display_errors', true );
error_reporting( E_ALL );

@session_start();
$v_id_usuario = $_SESSION['usu_id'];
$v_login      = $_SESSION['usu_login'];
$v_nome       = $_SESSION['usu_nome'];
$v_loja       = $_SESSION['usu_loja_id'];
$v_nivel      = $_SESSION['usu_area_admin'];

?>

 <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
 <meta http-equiv="X-UA-Compatible" content="IE=edge">
 <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>CONTROLE DE DESPESAS</title>
  <link rel="stylesheet" href="includes/style.css">
  <link rel="stylesheet" href="includes/css/bootstrap.min.css">
  <link rel="stylesheet" href="includes/css/datatables.css">

  <link rel="stylesheet" href="//code.jquery.com/ui/1.12.0/themes/base/jquery-ui.css">

      <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
        Toggle navigation

      </button>
      S

  Solicitacao

  Minhas Solicitações

  Administração

  Dashboard Loja

  Dashboard Admin

  Sair

Answer: Acredito que na documentação voce possa ter uma passe de quais parametros devem ser atualizados:
var options = {
  width: 400,
  height: 240,
  title: 'Toppings I Like On My Pizza',
  colors: ['#e0440e', '#e6693e', '#ec8f6e', '#f3b49f', '#f6c7b6']
};

chart.draw(data, options);

https://developers.google.com/chart/interactive/docs/customizing_charts
Comment: não tinha visto;Obrigado!
Comment: Por nada, @OtácioBarbosa

Alterar as cores do google charts


how to put "add friend" link with flag friend with views

Question: Flag Friend Add Friend Link with views. Flag friends shows a link to add friend in my account page but i want to display this link on in a field for a view.
Answer: In views you have to go to advanced setting and in relationship you can add your flag.

After that you will be able to add your field.
Comment: Ok I see it now... After adding the relation it gives me the option of the link... there is also a php way to do it as well... uid);
?>
Comment: What I am looking for is a field that allows a one click to add friend?
Comment: Yes after you add the relationship you have many fields available but i have actually a problem when the view is rendered, i don't know why.
Comment: It works fine for me with the javascript... What is your problem?
Comment: I have `Undefined offset: 0 in flag_friend_handler_field_links->render()`, i never had this before but it's not really important.
Answer: If I understood you correctly you want to add flag link to the view (as a field).
Here is a video demonstrating it. Quoting from this:

Install the Views PHP module and enable it. This will allow you to embed php into a view cell.
Add a new nid/node id field to your View. Make sure to check the "Exclude from display" checkbox.
Rearrange your fields so that your hidden nid field is at the top of all fields. This is important. It needs to be "available" as an element to the custom php field we are about to add, and if it's after, the custom php field won't see it.
Add a new Global: PHP field. add the following code to the "Output Code" section of the field (in php): <?php print flag_create_link("the_machine_name_of_your_flag", $row->nid); ?>
Click the apply button
Comment: The "Views PHP" module is unnecessary for this. @Epok's answer should work with the latest versions of Views and Flags. The important step is to add the Relationship to the Flag first, then you'll be able to add a "Flags: Flag link" field.


ordering and orientation for CW complexes

Question: The vertices of each cell of a simplicial complex are often assumed to have an ordering, for example in these notes, this exercise, and this blog post.
From the ordering of the vertices of a simplex $\sigma$ and the ordering in a face $\tau$, you can calculate the incidence number $[\sigma : \tau]$ between them by evaluating the sign of a permutation.
From the incidence numbers you can define boundary operators on chains and everything you need for homology.
For example, in 2D Euclidean space this means that all the triangles go around counterclockwise.
Many statements about ordering can be turned into statements about determinants of matrices formed from the vertices of each triangle.
The incidence numbers between cell and faces in CW complexes, on the other hand, seem to always be defined through the degree of the attaching map.
There's no ordering assumed at all, but if you can define the incidence numbers then you can also define boundary operators and thus homology.
Is ordering a special property of simplicial complexes?
For example, one could also define incidence numbers and ultimately calculate homology for more general spaces constructed from gluing together polyhedra with arbitrary numbers of faces and vertices.
In every reference I've seen (for example this paper or Rourke and Sanderson, Introduction to Piecewise-Linear Topology) that does so, the incidence numbers are defined through the degrees of the attaching maps and there's no mention of ordering.
Why is that?
Can the incidence numbers be calculated through some ordering of the vertices of each cell and it's merely inconvenient computationally?
Or is there some polyhedral complex for which the incidence numbers between a cell and its faces cannot be recovered from any ordering of the vertices?
My hunch is that ordering is meaningful only for simplices.
The Herschel graph is both polyhedral and non-Hamiltonian, which seems to me to imply that there's no way at all to recover the incidence numbers from any ordering of the vertices.
But I'm not great in algebraic topology so I might have misunderstood everything.
Comment: Your question isn't particularly clear to me, because, while it's true that *choosing* an ordering of the vertices of a simplicial complex is convenient for writing down the simplicial homology, it is not the case that "the vertices of each cell of a simpicial complex are usually assumed to have an ordering". Take a look at the standard definition [here](https://en.wikipedia.org/wiki/Abstract_simplicial_complex#Definitions).
Comment: I'm not really sure I understand the premise of your question. Sure the simplices of a simplicial complex have an orientation, but as far as I know this doesn't extend to anything like an orientation of the simplicial complex.
Comment: There is an analogous *choice* for a CW-complex, serving as a convenience for writing down the CW homology, namely, a choice of a characteristic function for each cell.
Comment: Sorry if the question was unclear -- I've changed the terminology. I probably shouldn't have said "usually", I'm aware of abstract simplicial complexes, I'm just more accustomed to oriented complexes because I'm coming at this through finite element mesh generation.
Answer: The key fact about an ordinary rectilinear simplex $\Delta=\Delta[x_0,...,x_m] \subset \mathbb R^n$ is that an ordering of its vertex set $\{x_0,...,x_m\}$ determined an orientation of $\Delta$, in such a way that two orderings $x_{i_0},...,x_{i_m}$ and $x_{j_0},...,x_{j_m}$ determine the same orientation if and only if the "change of order permutation" defined by the formula $i_k \mapsto j_k$ is an even permutation.
Now, suppose that you have a simplicial complex $K$ with $0$-skeleton $K^0$. When you choose an ordering of the entire set $K^0$, that determines an ordering of the vertex set of each individual simplex in $K$, which in turn determines an orientation of each individual simplex, which in turn determines the incidence number $\pm 1$ for every pair consisting of a simplex and a co-dimension~1 face, which in turn determines the integer matrices that express all of the boundary homomorphisms $C_m(K) \mapsto C_{m-1}(K)$ in the simplicial chain complex of $K$.
But let's unravel this a bit. You don't need a total ordering of the entire set $K^0$ to do this; there's a lot of wasted information in that total ordering. For example, all you really need is a partial ordering on $K^0$ which restricts to a (total) ordering of the vertex set of each individual. For example, the first barycentric subdivision of a simplicial complex does have a natural partial order of exactly that type.
For a more pertinent example of wasted information, suppose that you choose two different orderings of the set $K^0$, and suppose that they just so happen to have the following property: for every simplex $\Delta=\Delta[x_0,...,x_m]$, the restrictions to the set $\{x_0,...,x_m\}$ of the two given orderings determine the same orientation of $\Delta$ (i.e. the change-of-order permutation is even). In that case, the incidence numbers are identical for the two orderings of $K^0$.
So in that sense, I agree with your hunch: ordering the entire vertex set of a simplicial complex is an artifact special for simplicial complexes, containing lots of extra information that is not particularly useful or pertinent. The key information contained in that ordering, for purposes of computing chain complexes and hence cohomology groups, is the set of orientations, one per simplex, and the set of incidence numbers, one per pair of simplex and codimension 1 face. With that in mind, one can see that this exactly matches the relevant information (for purposes of computing homology) for other types of complexes, particularly for very general CW complexes. As hinted at in my earlier comment, for each cell of a CW complex there are two orientation classes of characteristic maps, and the choice of one orientation per cell determines the incidence numbers (i.e. the degrees of attaching maps, as you say).