Salvar arquivo txt com codificação windows

Question: Minha aplicação roda em um SO Unix, sendo assim, meus arquivos .TXT são criados no formato UNIX, preciso que estes arquivos sejam criados no formato WINDOWS.
Preciso que as quebras de linhas sejam no formato WINDOWS \r\n. Estou com problema com o formato UNIX porque ele insere somente o \n.
Hoje, crio os arquivos usando file_put_contents.
Comment: Pode descrever melhor? O que exatamente quer mudar no formato? Quebras de linha? Charset (acentuação)? Por favor, seja mais específico.
Comment: @DaniloOliveira és tu que estás a escrever nos ficheiros? Se sim basta escreveres o \r\n.
Comment: acho que ele se refere a quebras de linha
Comment: Isso, eu me refiro a quebra de linhas. Preciso que as quebras de linhas sejam no formato WINDOWS \r\n.
Estou com problema com o formato UNIX porque ele insere somente o \n.
Comment: @JorgeB, sim,  sou eu que estou estou escrevendo. Escrever \r\n não funciona, já fiz este teste.
Answer: Para isso basta que sempre que guarde alguma coisa no arquivo que já vá com a formatação correta, usando a função iconv:
<?php

$dados = "Eu não conseguia guardar texto em formato windows e agora já consigo.";

// Alterar o enconding do texto a gravar no ficheiro
$string_encoded = iconv( mb_detect_encoding( $dados ), 'Windows-1252', $dados );

// Escrever no ficheiro
$file = fopen( "meu_texto.txt", "w+" );
fwrite( $file, $string_encoded );
fclose( $file );

Answer: Você pode escrever o arquivo adicionando as quebras de linha manualmente com os caracteres #13 + #10 usando a função chr().
Comment: Obrigado pela resposta, Wellington.
Tentei da forma que você sugeriu e mesmo assim não obtive o resultado que esperava. Mesmo passando os caracteres em ascii, meu arquivo está no formato UNIX, sendo assim, ele só escreve o **LF** na quebra de linha, se eu alterar o formato do arquivo pelo notepad++ para DOS/Windows ele escreve **CRLF**, é desta forma que eu espero que o arquivo seja gerado.


retrieve an id from url to controller without using route parameter ? Laravel 5

Question: I'm wondering if there is a way to retrieve an id from url without using route parameter, for example I wanted to retrieve an id from this url : {{ url('edisi/' . $edisi->id) }} is there a way how to retrieve the id without using route parameter ? thank you
Answer: You can use segment() method. If URL is edisi/someparameter, you can use Request::segment(2) to get someparameter.
Comment: so in my case : jurnal/create?edisi=1 it would be Request::segment(2) as well ?
Comment: You've shown another example in you question, so `segment(2)` will get `create` from URL you posted in comment. If you want to get parameter, do this `$edisi = Input::get('edisi', false);`
Comment: Hey Alexey you still there ? I got another problem if you don't mind to take a look :)


Entity form Submissions automatic numbering over 1000

Question: I have reach an entity form submission count that has hit 1,000.
The problem I have is the URL is '/entityform/1,000' - notice the comma. This screws up the link to the url. I have searched and cannot find how to remove the comma when entityform creates the link.
I have check alias patterns, module settings and every where else I can look within the drupal/module configuration.
Can someone help me figure out where to make this update?
Thank you!
Answer: Okay after searching it was probably the 12 forum post I found another module that helps with this issue.
Install this module along with Pathauto.
https://www.drupal.org/project/pathauto_entity
The URL Alias is: [entityform:type:label]/[entityform:entityform-id]
Hopefully that helps someone.
Peace
Comment: Actually this didn't solve it. DOH!


How can I turn this row into a link?

Question: I want to make that row a link, but I dont know how to add an a href attribute... That row shows information from a DB and I just want to make ir clickeable and not only as plain text. Thank you
This is the row I wanna turn into a link...
echo '' . $row['nombre'] . '	';

Comment: This is HTML 101 stuff.
Comment: use anchor tag `your link`
Comment: What should the link point at? What should happen when the user clicks it?
Answer: Wrap the text in an anchor (a) tag.
echo '' . $row['nombre'] . '	';

You should also probably take a look at the W3schools HTML5 tutorial.
Answer: Just add the  to your HTML, and include the URL in it.
echo "{$row['nombre']}	";

Answer: echo "
     <a href='yourfile.php?subDom=$row['nombre']'
     	";

Then you can check for if link is clicked, you can trigger action for click. Like below:
if($_GET['whateverComingFromDB'] == "whatDoYouWantToCompare"){
    //...Anything you want to happen after click the link
}

How can I turn this row into a link?


how to make a div disappear if javascript is disabled

Question: i want to make an input disappear if javascript is disabled, i have tried,

so that if javascript is disabled the code will not put the input in the div
but in my browser console it says document.getelementbyid('myinput') is undefined, but if i put in a function  my browser console doesn't say anything is there a way i can make a function run immediately the page is loaded or to make the input show only when javascript is enabled
Comment: Just place the script after the element, and correct the spelling of the properties.
Comment: _"but in my browser console it says document.getelementbyid('myinput') is undefined"_ - because the element did not exist already at that point, where you tried to access it here. Change the order, so that the `script` element comes _after_ the element you are trying to access.
Answer: I think you wanna do this. Notice the spell corrections:

Answer: JavaScript is case sensitive, so getelementbyid is not the same as getElementById.
The correct function is document.getElementById.
The same problem with innerhtml. It should be innerHTML.
Also <input type=text> should be in quotes, because it is a string.


Issue a Conditional Redirect in Drupal 7

Question: I have a custom payment form that redirects to a 'Thank You' page on success. The page is just a Page type node, so someone can control the content of the page.
What I wanted to do was add a little extra, and prevent the page from being seen unless they had just come from the form.
I tried using 3 functions. hook_node_view, hook_node_view_alter, and hook_init.
I thought the first two would allow me to check the node path or nid, and redirect if I needed to, but they did not seem to be called. Additionally, I tried
mymodule_init() {
  global $user;
  krumo($user);exit;
}

That was not being hit, either. The rest of the module works fine, custom menu item, custom form, validate/submit/mail hooks. I am stumped.
How can I check a node value when loading, take action, and furthermore, why is hook_init() not dumping/exiting?
Answer: You should not use hook_init, but hook_boot as you want to perform the check when caching is turned on. That would also be the best explanation as to why your exit doesn't work. That or you forgot to clear cache after implementing the hook. (All hooks are cached in D7)
Comment: Hmm.. Had to clear the cache 3 times before it picked up changes.


"format" doesn't work with a specific date format

Question: I can format a date in a specific date format, but the formatted string seems not possible to format anymore.
It wouldn't be a problem, because I could save the old format. But the thing is that I also have to read a string in the specific format from an excel cell and format it.
I use the german date system. (Mi = Wednesday)
UI_Main.txt_BeginnDatum.Value = Format(UI_Date_Picker.Date_Picker.Value, "ddd dd mmm yyyy")

That's how I get the date from the datepicker. It's now formatted in the specific date format I'm talking about (Mi. 09 Jan 2019).
The default format from the picker is dd.mm.yyyy.
strBeginDate_g = txt_BeginnDatum.Value

strTemp = strTemp & "Nr. " & Format(strBeginDate_g, "yyyy-mm-dd")

Here I try to write the date in another format, but the output is just the same as before.
Of course I could write my own function but I am sure format is supposed to handle this.
Comment: There's very little to chew on IMO. It's not clear where `strBeginDate_g` is coming from, what its value is, how it relates to `UI_Main.txt_BeginnDatum.Value`, or what "output" is referring to. Please [edit] to clarify.
Comment: The *Format()* function will apply a format to **numbers** only.  If you attempt to format a value and the operation only returns the same as input, then the value is probably *Text*
Answer: The Format function can only format a numeric value. But you give it a string strBeginDate_g as parameter.
Instead give it the value as parameter:
strTemp = strTemp & "Nr. " & Format$(UI_Date_Picker.Date_Picker.Value, "yyyy-mm-dd")

Once you formatted a date with Format() it becomes a string, and you cannot calculate anymore with a string nor can you format it again.
Comment: @livior thats only because VBA casts the string `dd.mm.yyyy` automatically into a date because it cannot handle the string at all and then formats that into as string again. You cannot rely on that, because it highly depends on the default date format that is set for the operating system. Always use numeric values of the dates (or variables of type `date`) to calculate with them or format them. Otherwise you never know what you get.
Comment: But when I save the date from the picker as dd.mm.yyy, It works to format the same again in yyyy-mm-dd
Comment: Ok. Is it possible to cast this "Mi. 09 Jan 2019" into a date variable? I think I tried to cast string to date but I got type errors. Otherwise I guess I have to parse char for char...
Comment: @livior Why would you do that if you have the value of the date `UI_Date_Picker.Date_Picker.Value`? So use that numeric value instead of inventing a parser. If you need to convert date --> string --> date --> string then you are doing it definitely wrong.
Comment: The vba tool contains a user interface to set all data for a formular. When u press "save" the tool writes the data into the cells of the premade formular. But you can also open the excel file and edit the values with the tool. That's why I need to parse the data from the cells. The date is stored in the same cell as the time (Date -> new line -> Time).
Comment: If you save the date into a cell, don't save it as string save it as date value (numeric) and format the cell using [Range.NumberFormat](https://learn.microsoft.com/en-us/office/vba/api/excel.range.numberformat) for example: `cell.value = UI_Date_Picker.Date_Picker.Value` and then `cell.NumberFormat = "ddd dd mmm yyyy"`. This way the cell actually contains a date value but shows it in the desired format. This cell value can be used in `format` then. Just never convert dates into strings if you can avoid that, instead format them with numberformat. Anything else is doing it wrong.
Answer: You could write a custom format, like so
Function FormatYYYYMMDD(strDateIn As String) As Date

Dim a() As String
Dim s As String

a = Split(strDateIn, Chr(32))
a(0) = vbNullString

FormatYYYYMMDD = CDate(Format(a(1) & "/" & a(2) & "/" & a(3), "yyyy-mm-dd"))

Erase a

End Function


How should I continue on with this proof by contraposition?

Question: I've been working on this question, but I am not sure if I am actually doing it right or wrong. So far, I have these steps down, about which I am not entirely sure.

Show that if $n$ is an integer and $n^3 + 5$ is odd then $n$ is even using the technique of proof by contraposition.

My work so far:
If $n^3 + 5$ is not odd, but even, then $n^3+5=2a$.  Thus $n^3= 2a-5$, and  $$n=\sqrt[3]{2a-5}$$
I can tell my work is far off from the answer, but I thought I'd show my work in case people thought I haven't tried at all yet... Can someone show me the correct way of doing it?
Comment: There is absolutely no reason this should be voted to be closed. This is an excellent question and the person asking the question has shown plenty of work.
Comment: @nayrb "Excellent" is a bit of an exaggeration. But it's definitely good.
Answer: You are proving the converse instead of the contrapositive. Instead, prove that if $n$ is odd, then $n^3+5$ is even.
Answer: The contrapositive of a statement "If p, then q" is "If not q, then not p". Showing one implication is equivalent to showing the other implication holds. More formally, we can write this as
$$(p \Rightarrow q) \Leftrightarrow (! q \Rightarrow !p),$$
but don't worry if that isn't entirely clear.
The statement you are asked to show is "if $n^3+5$ is odd, then $n$ is even". The contrapositive is thus "if $n$ is not even, then $n^3+5$ is not odd". This is simplified to "if $n$ is odd, then $n^3+5$ is even."
Well, $n=2m+1$ if odd, and so we have
$$n^3+5 = (2m+1)^3+5 = 8m^3+12m^2+6m+1+5 = 2(4m^3+5m^2+3m+3)$$
which means it is even. Hence the contrapositive is true and hence the original statement is true.
Comment: Ohh, it was the other way around.. Thank you for clarifying.
Comment: Yes! You swap the $p$s and $q$s. As mentioned elsewhere, you were trying to show the converse, which is "not p implies not q" (and which is equivalent to "q implies p" using the contrapositive).
Answer: Start in another way, assume that n is odd (and derive that $n^3+5$ is even)


Python: Kill thread after loop/Pause execution of Thread

Question: As a new programmer, I'm trying to create a Python3 script that creates a Countdown timer based on the KeyCombination used which is then written to a text file used by StreamlabsOBS. The idea is that when a KeyCombo is pressed (e.g ctrl+alt+z) a function starts a timer, and at the same time, another function writes the current time in the countdown to a txt file. This script would ideally be running during the entire stream.
So far, I can get the countdown working and writing to the file exactly how I want it to. But it seems the Thread is still alive after finishing the countdown. I'm not sure if this is a problem or not. Another thing is that I want to implement some kind of pause feature, that would pause the timer function. I'm not sure how to even start on that part.
The print statements are for me to know what part of the function I am at.
from pynput import keyboard
from pathlib import Path
from threading import Thread
import queue
from time import sleep

script_location = Path(__file__).absolute().parent
timer_queue = queue.Queue()

def storeInQueue(function):
    print("Sent Start Thread msg")
    def storer(*args):
        for time in function(*args):
            timer_queue.put(time)
            print(f"stored {time}")

    return storer

@storeInQueue
def timer(t):
    print("Iterating Timer Loop")
    while t > -1:
        yield t
        sleep(1)
        t -= 1

def speakKorean():
    print("starting Thread")
    timer_thread = Thread(target=timer, args=(5,))
    timer_thread.start()
    ctime = timer_queue.get()
    while ctime >-1:
        with open(script_location / 'ChronoDown.txt', "w") as timer_file:
            timer_file.write(f"Speak Korean for {ctime}s")
            timer_file.flush()
        sleep(1)
        ctime = timer_queue.get()
        if ctime == 0: break
    print('Speak Korean done!')
    with open(script_location / 'ChronoDown.txt', "w") as timer_file:
            timer_file.write(f"Done!")
            timer_file.flush()
    while timer_thread.is_alive:
        print("timer thread still running?")
        timer_thread.join()
        break
    if timer_thread.is_alive:
        print("didn't work")

def on_activate_z():
    timer_file = open(script_location / 'ChronoDown.txt', "w")
    timer_file.write("other keywords")
    timer_file.close()

def on_activate_c():
    korean_thread = Thread(target=speakKorean,)
    korean_thread.start()
    print("Working")

def on_activate_x():
    timer_file = open(script_location / 'ChronoDown.txt', "w")
    timer_file.write("No cursing for time")
    timer_file.close()

with keyboard.GlobalHotKeys({
        '<ctrl>+<alt>+z': on_activate_z,'<ctrl>+<alt>+c': on_activate_c,
        '<ctrl>+<alt>+x': on_activate_x}) as h:
    h.join()

My console output looks like this after I run it. I'm not sure why "Sent Start Thread msg" sends before I start thread too.
Sent Start Thread msg
starting Thread
Working
Iterating Timer Loop
stored 5
stored 4
stored 3
stored 2
stored 1
stored 0
Speak Korean done!
timer thread still running?
didn't work

Also if you have any optimization tips that would be appreciated. Thank you in advance for any help.
Comment: if you need pause then you should use global variable `paused = False` and run code in `while True`, `if not paused: .. code ...` - and when you change `paused = True` then it will skip code, and if you set again `paused = True` then it will run code.
Comment: `while timer_thread.is_alive: ... break` seems weird  - you could write it using `if` without `break`
Comment: you forgot `()` in function `is_alive()` - in two places.
Comment: @furas Thank you for your help so far! I hadn't realized that `is_alive` needed the `()` and that fixed the check and properly ended the Thread. The Pausing Method you proposed also worked beautifully. Thank you for your help!
Answer: Thanks to @furas , I've now implemented a pause function that properly resumes as well. This is my updated code :
from pynput import keyboard
from pathlib import Path
from threading import Thread
import queue
from time import sleep

script_location = Path(__file__).absolute().parent
timer_queue = queue.Queue()
paused = False

while paused == False:
    def storeInQueue(function):
        print("Sent Start Thread msg")
        def storer(*args):
            for time in function(*args):
                timer_queue.put(time)
                print(f"stored {time}")

        return storer

    @storeInQueue
    def timer(t):
        print("Iterating Timer Loop")
        while t > -1:
            if paused == False:
                yield t
                sleep(1)
                t -= 1
            else: continue

    def speakKorean():
        print("starting Thread")
        timer_thread = Thread(target=timer, args=(5,))
        timer_thread.start()
        ctime = timer_queue.get()
        while ctime >-1:
            with open(script_location / 'ChronoDown.txt', "w") as timer_file:
                timer_file.write(f"Speak Korean for {ctime}s")
                timer_file.flush()
            sleep(1)
            ctime = timer_queue.get()
            if ctime == 0: break
        print('Speak Korean done!')
        with open(script_location / 'ChronoDown.txt', "w") as timer_file:
                timer_file.write(f"Done!")
                timer_file.flush()
        timer_thread.join()
        if timer_thread.is_alive():
            print("didn't work")
        else: print("its dead")

    def on_activate_z():
        global paused
        timer_file = open(script_location / 'ChronoDown.txt', "w")
        timer_file.write("Paused")
        timer_file.close()
        if paused == True:
            paused = False
            print(f'Paused = {paused}')
        else:
            paused =True
            print(f'Paused = {paused}')

    def on_activate_c():
        korean_thread = Thread(target=speakKorean,)
        korean_thread.start()
        print("Working")

    def on_activate_x():
        timer_file = open(script_location / 'ChronoDown.txt', "w")
        timer_file.write("No cursing for time")
        timer_file.close()

    with keyboard.GlobalHotKeys({
            '<ctrl>+<alt>+z': on_activate_z,'<ctrl>+<alt>+c': on_activate_c,
            '<ctrl>+<alt>+x': on_activate_x}) as h:
        h.join()

The main differences:

My entire code is now encapsulated in a While paused == False loop, which allows me to pause my timer function based on the state of paused using an if statement

I've added the missing ( ) to timer_thread.is_alive() which allowed me to properly end the timer Thread


Write $\cos^8(x)$ in terms of $\sin(x)$?

Question: I am currently working on an integral using u substitution and have hit a wall at the above point. The integral in question is $\int$$\sin^7(x)$$\cos^9(x)$ using $u=sin(x)$.
After finding $du=cos(x) dx$, I am asked to express $\cos^8(x)$ in terms of $u$, at which point I am stuck. My current attempt was to reduce the power down from 8 to 2, and express it as $(1-u^2)$, but that gives me a wrong answer (this assignment checks for us before submission).
Any help is appreciated.
Thanks.
Comment: What did you find the integral to be (your "wrong" answer)?
Comment: I hadn't got to that point yet as the next few steps required it expressed in terms of u still.
Comment: OK, your "wrong" answer in terms of $u$?
Comment: I'd only gotten to the point of $u^7(1-u^2)$, but seeing as the assignment said it was wrong I didn't try going ahead and solving for that.
Comment: $\displaystyle \int u^7(1-u^2)^4\,du$ with a power of $4$ seems more likely
Comment: Yeah that's correct. I made the mistake of trying to reduce it as we covered that in the same lecture; seems it wasn't necessary for this question.
Answer: If $$\cos^2 x = 1-\sin^2 x$$ then $$\cos^8 x = (1-\sin^2 x)^4.$$
Answer: Using $u=\sin x$, you have $du=\cos x\,dx$, and also $\cos^2x=1-u^2$, so $\cos^8x=(1-u^2)^4$. Thus your integral becomes
$$
\int u^7(1-u^2)^4\,du
$$


Return text from output stream in c#

Question: I have a scenario where i need to get string as output stream in c#. I need to get those string value in javascript. Following is code
JS
var timestampUrl : "getTime.aspx" // Used somewhere in plugin. Syntax is fine

Originally was written as var timestampUrl : "getTime.php" but i changed it to work in .aspx also
getTime.php code
<?php
echo time();
?>

getTime.aspx.cs
var ts = ((long)(DateTime.Now - new DateTime(1970, 1, 1)).TotalMilliseconds) / 1000;
Response.ContentType = "text/plain";
byte[] bytes = System.Text.Encoding.UTF8.GetBytes(ts.ToString());
Response.OutputStream.Write(bytes, 0, bytes.Length);

But i get the output as
1436538190%3C!DOCTYPE%20html%3E%3Chtml%20xmlns=%22http://www.w3.org/1999/xhtml%22%3E%3Chead%3E%3Ctitle%3E%3C/title%3E%3C/head%3E%3Cbody%3E%20%20%20%20%3Cform%20method=%22post%22%20action=%22getTime.aspx%22%20id=%22form1%22%3E%3Cdiv%20class=%22aspNetHidden%22%3E%3Cinput%20type=%22hidden%22%20name=%22__VIEWSTATE%22%20id=%22__VIEWSTATE%22%20value=%22oyHYMIrhkYo9Ho3QkkQWovQ9tbRhQ2wRTHQfGgw4jJwaPeQsTPcZzR1s5K/dHFoH+p82j3XOogiKTqnH0MB/T9K/8kizxTDiLPwKPNWHHp0=%22%20/%3E%3C/div%3E%20%20%20%20%3Cdiv%3E%20%20%20%20%20%20%20%20%3C/div%3E%20%20%20%20%3Cdiv%20class=%22aspNetHidden%22%3E%3Cinput%20type=%22hidden%22%20name=%22__VIEWSTATEGENERATOR%22%20id=%22__VIEWSTATEGENERATOR%22%20value=%22EA09725A%22%20/%3E%3C/div%3E%3C/form%3E%3C!--%20Visual%20Studio%20Browser%20Link%20--%3E%3Cscript%20type=%22application/json%22%20id=%22__browserLink_initializationData%22%3E%20%20%20%20%7B%22appName%22:%22InternetExplorer%22,%22requestId%22:%22f532ae409a044422a3178fdad51fb6a0%22%7D%3C/script%3E%3Cscript%20type=%22text/javascript%22%20src=%22http://localhost:62796/df94eb33421548aca703559a9bdf2a2c/browserLink%22%20async=%22async%22%3E%3C/script%3E%3C!--%20End%20Browser%20Link%20--%3E%3C/body%3E%3C/html%3E

Instead of only 436538190
What could be the cause ?
Answer: You need to close off the stream.
var ts = ((long)(DateTime.Now - new DateTime(1970, 1, 1)).TotalMilliseconds) / 1000;
Response.ContentType = "text/plain";
byte[] bytes = System.Text.Encoding.UTF8.GetBytes(ts.ToString());
Response.OutputStream.Write(bytes, 0, bytes.Length);
Response.Flush();
//now signal the httpapplication to stop processing the request.
HttpContext.Current.ApplicationInstance.CompleteRequest();

See: issue with Response.OutputStream.Write adding html code in the resulting file
Comment: I able to do so using `Response.End`. But anyway thanks for guidance.. You can edit your answer if you want

Return text from output stream in c#


Why is $\partial f(x)/\partial x_i$ homogeneous of degree $k-1$ if $f(x)$ is homogeneous of degree $k \geq 1$?

Question: It's as (simple) as the title says, but I can't figure out why that is.
How can I show (I think I need small, tiny steps) that
$$\frac{\partial f(tx)}{\partial (tx_i)}t=t^k\frac{\partial f(x)}{\partial x_i}$$?
My textbook says "If $f(x)$ is homogeneous of degree $k \geq 1$, then $\partial f(x)/\partial x_i$ is homogeneous of degree $k-1$". How come?
Where f is a function $f:\mathbb{R}_+^n \mapsto \mathbb{R}$
Answer: Fix $t>0$. Then
$$\frac{\partial f}{\partial x}(tx)=\lim_{\Delta x\to 0}\frac{f(tx+\Delta x)}{\Delta x}=\lim_{\Delta x\to 0 }\frac{f(t(x+\Delta x))}{t\Delta x}=t^{k-1}\lim_{\Delta x\to 0}\frac{f(x+\Delta x)}{\Delta x}=t^{k-1}\frac{\partial f}{\partial x}(x)$$
Comment: @triple_sec - thanks :)
Comment: Nice answer (I like it better than mine). +1
Answer: Since $f$ is homogenenous of degree $k\geq 1$, the following must be true for any $t>0$ and $x\in\mathbb R^n_+$: $$f(t x)=t^kf(x).$$ Fix $t>0$ and differentiate both sides with respect to $x_i$ (where $i\in\{1,\ldots,n\}$). By the chain rule, you obtain $$f_{x_i}(t x)\cdot t=t^k f_{x_i}(x),$$ where the subscripts denote partial derivatives. Canceling $t$ yields the desired result: $$f_{x_i}(tx)=t^{k-1}f_{x_i}(x).$$
Answer: As you have a polynomial of degree $k$, each term consists of a total of $k$ factors. If you now take the derivative by one of the $x_i$, each term which has an $x_i^{r_i}$ ($r_i\geq 1$) as a factor will convert to $r_i x_i^{r_i-1}$, i.e. the degree is one less than before.
All other terms that has no $x_i$ will yield $0$ in the derivative.
Now coming to the first part of the question:
As $f$ is homogeneous of degree $k$ we can conclude that $f(tx)=t^k f(x)$. As factors can be taken outside of the derivative we get:
$$
\frac{\partial f(tx)}{\partial (tx_i)} t = \frac{t^k \partial f(x)}{t \partial x_i}t = t^k \frac{\partial f(x)}{\partial x_i}
$$
Comment: That is a good intuition, but take into account that not all homogeneous functions are polynomials.
Comment: I didn't know that. However, my second part is correct for arbitrary homogeneous functions. Isn't the last equation showing (after dividing by $t$) just the condition for being $k-1$ homogeneous?


Show stand alone dialog box

Question: I have a problem that I would like some help with. I am developing a Qt application, and I am currently working on the GUI portion of it. So I have developed a MainWindow (ContentManager) that users will be able to select options from. This MainWindow should handle information sent back from stand alone dialog boxes. The issue I am having is that I can't even get the MainWindow to call and open said dialog boxes.
The dialog boxes were made as follow:
Qt->Qt Designer Form->Dialog Without Buttons->addContentDialog.ui (NameofDialog.ui)

This just created an addContentDialog.ui file, and nothing else (no .h, or .cpp). I was following this http://www.qtcentre.org/archive/index.php/t-43157.html?s=9503de67fb7a2b4ec8e1f28007838fae but I am having no luck as my Qt form did not create a .h file. I have included the code for the MainWindow below
#include "contentmanager.h"
#include "ui_contentmanager.h"
#include "ui_addContentDialog.h"

ContentManager::ContentManager(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::ContentManager)
{
    ui->setupUi(this);
}

ContentManager::~ContentManager()
{
    delete ui;
}

void ContentManager::on_addContentBtn_clicked()
{
    Ui::AddContentDialog uiAddNewContent;
    QDialog d;
        uiAddNewContent.setupUi(&d);
        d.exec();

}

I eventually want the main window (which is a .cpp file) to handle information inputted into the dialog box.
Comment: Is this resolved now?
Answer: ui_addContentDialog.h is created on the fly by the UIC (UI compiler) when you run qmake. You just need to rerun qmake.

Show stand alone dialog box


NulledPointer Exception on Changing from support-v4 to appcompat-v7

Question: My app uses Theme.Holo.light using com.android.support:support-v4:21.0.3. Now I changed my app theme to Theme.Appcompat and Changed the gradle dependencies too from "com.android.support:support-v4:21.0.3" to  "com.android.support:appcompat-v7:21.0.3".
After these changes my app get crashed whenever I launch it.
and getting the log

at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
       Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void
  android.app.ActionBar.setHomeButtonEnabled(boolean)' on a null object
  reference
              at com.viter.android.navigationdrawerexample.MainActivity.onCreate(MainActivity.java:99)

My function is
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    //Code for Tabs
    mAppSectionsPagerAdapter = new AppSectionsPagerAdapter(getSupportFragmentManager());
    // Set up the action bar.
    final ActionBar actionBar = getActionBar();

    actionBar.setHomeButtonEnabled(false);

    actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);

    mViewPager = (ViewPager) findViewById(R.id.pager);
    mViewPager.setAdapter(mAppSectionsPagerAdapter);
    mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
        @Override
        public void onPageSelected(int position) {
            actionBar.setSelectedNavigationItem(position);
        }
    });

        actionBar.addTab(
                actionBar.newTab()
                        .setText(mAppSectionsPagerAdapter.getPageTitle(i))
                        .setTabListener(this));
    }

    // Navigation Drawer
    mTitle = mDrawerTitle = getTitle();
    mPlanetTitles = getResources().getStringArray(R.array.planets_array);
    mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
    mDrawerList = (ListView) findViewById(R.id.left_drawer);

    // set a custom shadow that overlays the main content when the drawer opens
    mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);
    // set up the drawer's list view with items and click listener
    mDrawerList.setAdapter(new ArrayAdapter<String>(this,
            R.layout.drawer_list_item, mPlanetTitles));
    mDrawerList.setOnItemClickListener(new DrawerItemClickListener());

    // enable ActionBar app icon to behave as action to toggle nav drawer
    getActionBar().setDisplayHomeAsUpEnabled(true);
    getActionBar().setHomeButtonEnabled(true);

    // ActionBarDrawerToggle ties together the the proper interactions
    // between the sliding drawer and the action bar app icon
    mDrawerToggle = new ActionBarDrawerToggle(
            this,                  /* host Activity */
            mDrawerLayout,         /* DrawerLayout object */
            R.drawable.ic_drawer,  /* nav drawer image to replace 'Up' caret */
            R.string.drawer_open,  /* "open drawer" description for accessibility */
            R.string.drawer_close  /* "close drawer" description for accessibility */
            ) {
        public void onDrawerClosed(View view) {
            getActionBar().setTitle(mTitle);
            invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
        }

        public void onDrawerOpened(View drawerView) {
            getActionBar().setTitle(mDrawerTitle);
            invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
        }
    };
    mDrawerLayout.setDrawerListener(mDrawerToggle);

    if (savedInstanceState == null) {
        selectItem(0);
    }
}

Please help me out resolving this.
Comment: @Dave S no. build success but app get crashed again.
Comment: Just something to keep in mind, `.setNavigationMode()` has become deprecated as of API Level 21.
Answer: You should probably use getSupportActionBar() instead of getActionBar() (and also extend ActionBarActivity instead of FragmentActivity).
Comment: I tried but I'm unable to use getSupportActionBar(). as my class is "public class MainActivity extends FragmentActivity implements ActionBar.TabListener"
Comment: @Vrangle Hmm, I think you should extend `ActionBarActivity` too.
Comment: Already I extended FragmentActivity. then how can I extened to ActionBarActivity again. Class cannot extened multiple classes.
Comment: `ActionBarActivity` extends `FragmentActivity`
Comment: @ianhanniballake tried. this time some thing un expected errors at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
     Caused by: java.lang.ClassCastException: com.example.android.navigationdrawerexample.MainActivity cannot be cast to android.support.v7.app.ActionBar$TabListener
            at com.viter.android.navigationdrawerexample.MainActivity.onCreate(MainActivity.java:123)
Answer: With AppCompat v21 you can add a Toolbar and use that as the ActionBar. It isn't hard to do, and most of the code won't need to be changed. The main thing is to add the toolbar to the activity_main.xml
<android.support.v7.widget.Toolbar
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/my_awesome_toolbar"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:minHeight="?attr/actionBarSize"
android:background="?attr/colorPrimary" />

And then use this to make your Actionbar
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

Toolbar toolbar = (Toolbar) findViewById(R.id.my_awesome_toolbar);
setSupportActionBar(toolbar);

ActionBar actionBar = getSupportActionBar();

}
Depending on the rest of your code their might be a few other things to update. But this should get you most of the way. Further details here: https://chris.banes.me/2014/10/17/appcompat-v21/
Comment: Note: Toolbars are totally optional in AppCompat v21 - AppCompat will inflate a Toolbar for you (and return it via `getSupportActionBar()`).
Comment: @Alt-Cat I tried the way answered. but nothing much and a error Caused by: java.lang.ClassCastException: com.example.android.navigationdrawerexample.MainActivity cannot be cast to android.support.v7.app.ActionBar$TabListener
            at com.viter.android.navigationdrawerexample.MainActivity.onCreate(MainActivity.java:123)
Comment: Try making the MainActivity extend ActionBarActivity if you haven't already. You may also need to remove some of the imports you are using in the class and adding them back for the v7 support library. I can't remember which one, but some v7 and v4 methods share the same name.
Comment: @Alt-Cat no more improvements. If you wish let me revert back all the changes and give you working app, you please change the theme and give me
Answer: Check if your
final ActionBar actionBar = getActionBar();

is returning null for an actionBar.
You're probably calling the code in the wrong class.
Comment: no chance of returning null. by the way when I revert back to Theme.Holo.light and gradle dependecies to com.android.support:support-v4:21.0.3 it works as usual.


jansson library for cross compilation with arm-linux-gnueabi-gcc

Question: I have application that uses jansson library. I want to change our architecture to ARM board. I was searching for how to compile / or source for ARM jansson library, but without any succeed.
Does someone has any idea how to tailor the existing jansson lib to ARM or how to find the source-code for this library and how to compile it suitable for ARM.
I use arm-linux-gnueabi-gcc compiler.
Answer: This thread seems to answer your question:
https://groups.google.com/d/msg/jansson-users/VDDswPWS490/MS4bD6o0cM0J
./configure --build=x86_64-linux --host=arm-poky-linux-gnueabi --target=arm-poky-linux-gnueabi

You will need to alter the host and target lines to match your cross-compiler. For example, my cross-gcc is arm-poky-linux-gnueabi-gcc.
Make sure you source your environment before.


How would I write a function to replace things?

Question: I am trying to work on an assignment in python and am completely stumped. Please help.
Write a function called myReplace() that performs a task similar to the string.replace() method. This function should take three parameters: The first, called the content string, can be any string. The second, called the token, should be a string containing a single character which is to be replaced in the content string. The third, should denote the new character(s) that will be in the resulting string. The function should return a new string with the token letter(s) replaced by the new characters. Your function should ensure valid input is provided, and return the original string if not. Note: You may not use the built-in replace() method for this question.
E.g.:
>>> result = myReplace("Hello world!",'l','q')

>>> print(result)
  Heqqo Worqd!

>>> result2 = myReplace("This is a sentence."," ","\t")

>>> print(result2)
  This     is     a     sentence.

>>> result3 = myReplace("Failure case","ail","oil") #only needs to work for single letter tokens

>>> result3
  'Failure case'

I'm not looking to get anyone to write this for me. But I have no idea what to do
Comment: `myReplace=lambda c,t,r:"".join([x,r][ x==t ] for x in c)` a good thing to do for starters is to open your textbook and go to class, take notes, ask questions of the teacher(or classmates) if you dont understand the concepts ... otherwise future lessons that will build off this concept will be locked to your brain
Comment: Can we see your current `myReplace` function?
Comment: Are you allowed to use regular expressions?
Comment: Hint: try to assign a string to a variable `repstring = "Hello World"` and see what happens when you do `repstring[0]`
Comment: Take a look at related [string methods](https://docs.python.org/2/library/string.html#string.find) `find`, `rfind`, `index`, and `rindex`.
Answer: def replace(stringname,oldletter,newletter):
    newstring = ''
    for i in range(len(stringname)):
        if stringname[i] == oldletter:
            newstring = newstring + newletter
        else:
            newstring = newstring + stringname[i]
    return newstring

stringorig = "Hello World!"
displayname = replace(stringorig,'l','o')
print displayname

You take the index of the string and compare it to the letter you need to change it to. I am sure R Nar's answer is the the shortest and best answer but more answers can't hurt.
Answer: def myReplace(s,old,new): new.join(s.split(old))

is a small version of what you want. You will want to add error checking and all that with things like type(s) or len(old) then returning s if necessary.


Heteroskedasticity and Type I, Type II Error

Question: If one is conducting a hypothesis test for heteroskedasticity, would one generally consider a Type I or a Type II error more serious? What is the reasoning behind this?
Comment: If you don't mention the actions that would result from rejection or non-rejection, how could we even guess at their relative consequences? Please describe the situation and why you are testing this. What difference does it make to what you're doing if you reject or not?
Comment: @DJohnson It's true enough for point nulls, but composite nulls can easily be true
Comment: Andrew Gelman has been quoted as saying, "We are rarely concerned with Type I error because we rarely believe it is possible for the Type I hypothesis to be strictly true/"
Comment: @DJohnson You mean the [distinction between a point (/simple) null and a composite null](https://en.wikipedia.org/wiki/Null_hypothesis#Terminology)? The simplest case would be a one-tailed test ... *point*: $H_0: \mu=\mu_0$ vs *composite* $H_0: \mu\leq\mu_0$. While there's little chance in general that $\mu$ exactly equals $\mu_0$ it's not hard to think of cases where the composite null above might actually occur.
Comment: I don't understand the question. Andrew Gelman is certainly capable of answering questions about hypothesis testing within the framework of hypothesis testing. He does so regularly. So I'm not sure what you're asking in relation to a question framed as a question about how hypothesis tests work. The quote you offer appears to be within that framework
Comment: @Glen_b  Interesting! Would you clarify the distinction?
Comment: @Glen_b Thanks for the explanation. Is it relevant or would it change your answer that AG is a Bayesian? In other words, since Bayesians don't subscribe to the N-P hypothesis framework, would they also reject the N-P distinction that you've proposed?
Comment: @Glen_b Is your assumption that there is a single framework for hypothesis testing? My understanding is that Bayesians don't subscribe to the N-P framework.
Answer: If you reject homoscedasticity and opt for using robust standard errors instead when homoscedasticity is actually present, you lose efficiency and finite sample properties. Asymptotically however your model inference will be still be valid.
However, if you opt for non robust standard error, and heteroscedasticity is present, your inference is always plain wrong.
If you do applied research (or industry work) you should clearly always use robust errors, you lose nothing if your wrong - provided your sample is large - whereas the other way around you loose the ability to do valid inference.
Answer: The answer to the question is contained in @Glen_b 's initial comment:  To know if a type I or type II error is more serious, you have to know the consequences of each.
Is it better to be late to a party or early to a party?  Well, the Red Queen imprisons all those who show up late for her parties, and the White Queen imprisons all those who show up early for her parties.  So, it depends on whose party you are going to.
The OP doesn't give any context to why this hypothesis test is being conducted.
But imagine you are conducting an initial screening trial of several treatments, with only a few observations for each treatment.  Here, our hypothesis tests are likely to have low power, and we want to be sure to retain several treatments for future testing. In this case, we are likely to be more tolerant of type I errors, and want to avoid type II errors.  False positives can be weeded out later.  But we don't want to miss a potentially-useful treatment by making a false-negative error.
For an opposing case, if we are comparing a new medical treatment to an established one, we will likely want to accept a type-II error over a type-I error.  A false positive will cost lives and money.  A false negative may mean we miss out on a new potentially-important treatment.  But what's lost with the false negative is only the marginal improvement of the new treatment relative to the established one.
Obviously, there are other considerations that come in to play in these kinds of decisions.
As a side note, the answer by @Repmat suggests that the question is posed relative to testing for homogeneity of variance as a precedent to conducting another analysis, say, a t-test or anova.  The OP doesn't indicate that this is in the context of the question.  But if it is, it's worth pointing out that it is generally not recommended to determine the type of test conducted (e.g. Student's t-test vs. Welch's t-test) contingent on the results of another hypothesis test (e.g. a test for homogeneity).

Source:  I've used similar examples here.


Erro no efeito de transição de imagem

Question: Criei uma pagina com efeito de transição na imagem com jquery e Javascript baseado em um tutorial, porém ao adiconar o Jquery e javascript não aparece as imagens.
Segue o codigo JS:
       $(window).scroll(function(){
        var $window = $(window),
        $body = ('body'),
        $panel = $('.section');

        var scroll = $window.scrollTop() + ($window.height() / 3);

        $panel.each(function(){
            var $this = $(this);
            if ($this.position().top <= scroll && $this.position().top + $this.height() > scroll){
                $body.removeClass(function (index, css){
                    return (css.match (/(^|\s)color-\s+/g) || [].join(' '));});

                    $('.section').removeClass('active');
                    $this.addClass('active');

                    }
                    });
                    }).scroll();

Esse é o codigo com o js que daria o efeito nas imagens: http://ugla.us/com-javascript/
Sem o Javascript ta a parte HTML e CSS ta 100% porém falta o js não está funcionando: http://ugla.us/sem-javascript/
Se alguemm poder dar uma força, fiz e refiz o tutorial porém não deu certo.
Comment: Não sei se notou no console do navegador, mas, está acusando erro: **$body.removeClass is not a function**!
Answer: Adicionei um $ na quarta linha. Estava ('body') e agora $('body')
Também adicionei o comando de abertura do Jquery na primeira e fechamento na última linha.

$(function(){
$(window).scroll(function(){
            var $window = $(window),
            $body = $('body'),
            $panel = $('.section');

            var scroll = $window.scrollTop() + ($window.height() / 3);

            $panel.each(function(){
                var $this = $(this);
                if ($this.position().top <= scroll && $this.position().top + $this.height() > scroll){
                    $body.removeClass(function (index, css){
                        return (css.match (/(^|\s)color-\s+/g) || [].join(' '));});

                        $('.section').removeClass('active');
                        $this.addClass('active');

                        }
                        });
                        }).scroll();
})
html{
    height: 1.68;
}
body{
    font-family: sans-serif;
}
.background{
    background-color: #498dff;
    position: fixed;
    top: 0;
    left: 0;
    width: 50%;
    height: 100vh;
    z-index: 1;
}
.section{
    display: flex;
    min-height: 100vh;
    position: relative;
    z-index: 2;
}
.section > *{
    width: 50%;
}
.section-img{
position: relative;
display: flex;
}
.section-img-inner{
    height: 100vh;
    position: fixed;
    left: 5%;
    width: 40%;
    top: 0;
    mix-blend-mode: multiply;
    background-size: contain;
    background-repeat: no-repeat;
    background-position: 50% 50%;
    filter: blur(30px);
    opacity: 0;
    background-position: 50% 40%;
    transition: 0.6s ease, opacity 0.6s ease, background-position 0.8s ease;

}
.section-body{
    display: flex;
    align-items: center;
}
.section-text{
    padding: 5vw;
}
.section.active .section-img-inner{
    opacity: 1;
    background-position: 50% 50%;
    filter: blur(0);
}
h2{
    font-size: 3vw;
    margin-bottom: 0.5em;
    margin-top: 0;
}

<!DOCTYPE html>

      <link rel="stylesheet" href="imagem-texto-scroll.css">
      <meta charset="UTF-8">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <title>Document</title>

Air Advance

Lorem ipsum dolor sit amet consectetur adipisicing elit. Debitis tempora praesentium facilis officia sunt, aut atque corporis necessitatibus, itaque fugit aliquid optio dicta amet. Aliquam corporis exercitationem eveniet at quidem.

Lorem ipsum dolor sit, amet consectetur adipisicing elit. Laboriosam officia quibusdam quae beatae dolor, voluptate dolorem doloremque iste molestiae eos culpa repellat consequatur ipsum ratione eaque voluptatum repudiandae necessitatibus impedit!

Air Advance

Lorem ipsum dolor sit amet consectetur adipisicing elit. Debitis tempora praesentium facilis officia sunt, aut atque corporis necessitatibus, itaque fugit aliquid optio dicta amet. Aliquam corporis exercitationem eveniet at quidem.

Lorem ipsum dolor sit, amet consectetur adipisicing elit. Laboriosam officia quibusdam quae beatae dolor, voluptate dolorem doloremque iste molestiae eos culpa repellat consequatur ipsum ratione eaque voluptatum repudiandae necessitatibus impedit!

Lorem ipsum dolor sit amet consectetur adipisicing elit. In quibusdam, harum enim libero, dicta deserunt exercitationem asperiores, ad accusantium voluptatibus tempore dolores laudantium rem earum quas nobis ex placeat itaque!

Lorem ipsum dolor sit amet consectetur adipisicing elit. Necessitatibus ea maxime culpa, expedita ipsum sed reprehenderit placeat perferendis minus? Quas, non ea placeat earum quia error iure quae provident totam!

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Aliquid omnis adipisci in alias expedita autem veritatis molestiae facilis officia, quasi minima! Suscipit accusamus harum dolorum, quae laudantium quis officiis cum.

Air Advance

Lorem ipsum dolor sit amet consectetur adipisicing elit. Debitis tempora praesentium facilis officia sunt, aut atque corporis necessitatibus, itaque fugit aliquid optio dicta amet. Aliquam corporis exercitationem eveniet at quidem.

Lorem ipsum dolor sit, amet consectetur adipisicing elit. Laboriosam officia quibusdam quae beatae dolor, voluptate dolorem doloremque iste molestiae eos culpa repellat consequatur ipsum ratione eaque voluptatum repudiandae necessitatibus impedit!

Air Advance

Lorem ipsum dolor sit amet consectetur adipisicing elit. Debitis tempora praesentium facilis officia sunt, aut atque corporis necessitatibus, itaque fugit aliquid optio dicta amet. Aliquam corporis exercitationem eveniet at quidem.

Lorem ipsum dolor sit, amet consectetur adipisicing elit. Laboriosam officia quibusdam quae beatae dolor, voluptate dolorem doloremque iste molestiae eos culpa repellat consequatur ipsum ratione eaque voluptatum repudiandae necessitatibus impedit!

Air Advance

Lorem ipsum dolor sit amet consectetur adipisicing elit. Debitis tempora praesentium facilis officia sunt, aut atque corporis necessitatibus, itaque fugit aliquid optio dicta amet. Aliquam corporis exercitationem eveniet at quidem.

Lorem ipsum dolor sit, amet consectetur adipisicing elit. Laboriosam officia quibusdam quae beatae dolor, voluptate dolorem doloremque iste molestiae eos culpa repellat consequatur ipsum ratione eaque voluptatum repudiandae necessitatibus impedit!

Comment: Mano fico 100% vlw mano vlw msm, vou fechar a pergunta obg.

Erro no efeito de transição de imagem


How to deal with the fear of auditions?

Question: A lot of people have a problem with auditions. They can perform their music in a decent manner when they are alone, or when they are playing for a small, prepared audience. But when they get into that audition room, suddenly they are no longer playing that same music well.
Many of my friends always tense up right before an audition. This obviously doesn't help, because they can't move their fingers as fast. This is a particularly large problem at All-State. For those that don't know what All-State is, it is a very elite honor band that students from all around our state audition to try to be in. For sections such as saxophone or clarinet, there can be 100 people that audition, but only 10 or so get in. So this causes a lot of stress inside your head.
How do you deal with this? At least in my case, it is usually never a problem with being prepared with my music, so "practice more" won't help much in this case. What are some of the ways that you deal with auditioning in front of that terrifying human being?
Some of the things I have tried

Telling myself I am the worst player out of all of them. This theoretically makes your mind think that because you are so bad, you have nobody to impress, so you shouldn't worry about doing good.
Singing the Alphabet when you are listening to other people practice the audition music. That way you can feel better about your music.
Comment: I used to have a big fear of auditions. But like many things, practice makes perfect. The more I do it the easier it gets. Still not a breeze, still get stressed out, but I can play more reliably.
Answer: Do you get scared when you go to the supermarket? Do you fear going to macdonalds? What about when you go to the bathroom?
Why or why not? "Fear" is usually directly caused by an unnatural fear of the unknown. If you are walking down a long stretch of road in the country side late at night your mind plays tricks on you. It's part of survival(you need to be ready in case a bear or ghost attacks you ;).
Now, why would you fear an audition? Is it because you know you will screw up or because you know you suck? Aren't both related to practice?
Ok, you say "I practice all the time in my bedroom and I play it perfect there"...
But then let me ask you, how many times have you practiced in front of an audience or at an audition?
The simple trick!!!! You must believe in yourself and think that your good enough to play, not that you suck(that is actually the wrong thing to do). I have asked many good musicians this question cause I too have/had such a fear and they always tell me they don't care what people think and if they make mistakes(most have learned to turn mistakes into music).
If you can play it in your bedroom and you are happy with your performance then there is absolutely no reason you can't do that in front of people... except your own mind playing tricks on you trying to keep you alive(which, of course, is something you don't have to worry about in an audition... at least 99.999% of the time).
What you must really learn to believe is that you will never get better if you don't go through the trial and tribulations of performing in front of people... YOU MUST CRAVE it! This is what will make you better. This is like practice on steroids and the more you do it the better you will get at doing it.
Unless you want to be a rock god only in your bedroom alone you must seek out the things that will make you a better player in the way that counts. The bedroom is step one... once you have learned your material and are comfortable with it you must get out in front of people.
Go play at places where you can suck and no one cares(just about anywhere)... Make mistakes intentionally so you can learn to deal with them. Play out of key then try and recover, play the wrong solo to a song! Play jazz over country! Throw some metal licks in there for good luck while your at it!
The more you put yourself in the situations you fear the less you will fear them. Almost all fear modern humans have are exaggerated and are a result of our basal ganglia trying to keep us alive(it's too stupid to know when to shut off, on the other hand, without it, we would be dead).
My biggest piece of advice to you is: If you don't do it then you'll surely suck. It's your choice...
Answer: This question has been answered over on productivity.stackexchange.com - it isn't an audition question, but a stress/fear issue.
The real answer answer is practice, familiarity and relaxation. Once you have taken part in many auditions they will not affect you the same way.
Comment: Can you put a link to the Q there?
Comment: This is probably the most relevant, but there are a few: http://productivity.stackexchange.com/q/3002/54
Answer: It does have some music playing problems.
Some people attempt to do auditions with pieces of music that they haven't learnt properly.
Playing something just fine means that it is so well known that you never ever make any mistakes anywhere.  If there are occasional mistakes on some days then the piece hasn't been learnt well enough. The playing needs to be almost automatic.  Only at this stage can the stress/fear management systems work.
Answer: Start off by being by far the best player!  The confidence will soon follow.

How to deal with the fear of auditions?


The images are displayed different with PHP and HTML

Question: I have a website and I built a function which displays photos.
The problem is that when I display a gallery with this PHP function ...
<?php

function gallery_1()
{
    $picture_ids = array(   1,10,100,101,102,103,
                            104,105,106,107,108,109,
                            11,110,111,112,113,114,
                            115,116,117,118,119,12,
                            120,121,122,123,124,125,
                            126,127,128,129,13,130,
                            131,132,133,134,135,136,
                            137,138,139,14,140,141,
                            142,143,144,145,146,147,
                            148,149,15,150,151,152,
                            153,154,155,156,157,158,
                            159,16,160,161,162,163,
                            164,165,166,167,168,169,
                            17,170,171,172,173,174,
                            175,176,178,18,19,2,
                            20,21,22,23,28,29,
                            3,30,31,32,33,34,
                            35,36,37,38,39,4,
                            40,41,42,43,44,45,
                            46,47,48,49,5,50,
                            51,6,69,7,8,86,
                            87,88,89,9,90,91,
                            92,93,94,95,96,97,
                            98,99);

    $n = 6;  // number of pictures in each row

    echo '
' . PHP_EOL;
    for ($i = 0; $i < count($picture_ids); $i++)
    {
        // start a new row after each $n pictures
        if (($i > 0) && ($i % $n === 0))
        {
            echo '
' . PHP_EOL;
            echo '
' . PHP_EOL;
        }

        echo '
' . PHP_EOL;
        echo '' . PHP_EOL;
        echo '
' . PHP_EOL;
    }
    echo '
' . PHP_EOL;
}

?>

... the gallery looks like this: Gallery with PHP
But if I write the same code in HTML, so like this ...

... the gallery looks like this: Gallery with HTML
Notice the white space when it's displayed with PHP? What am I doing wrong? If you need some other code or want to se it live in action on website just let me know.
Thank you for your help. :)
Comment: Check the php generated HTML, compare it with the manual written code and look for differences.
Answer: In your html code 2n article tags(2nd, 4th,...) has "6u$" class instead of "6u". So if you change your php code like below i think it will work as you want.
echo '
' . PHP_EOL;
for ($i = 0; $i < count($picture_ids); $i++)
{
    // start a new row after each $n pictures
    if (($i > 0) && ($i % $n === 0))
    {
        echo '
' . PHP_EOL;
        echo '
' . PHP_EOL;
    }

    if($i % 2 === 0)
    {
        echo '
' . PHP_EOL;
    }
    else
    {
        echo '
' . PHP_EOL;
    }

    echo '' . PHP_EOL;
    echo '
' . PHP_EOL;
}
echo '
' . PHP_EOL;


What would be the effect of a modulation downward by a small amount?

Question: Imagine one plays a chorus in, say, A major, then repeats it later for the second chorus, but this time in G major. What would that do? I know that moving upwards by a whole or half step usually seems to "raise the energy" (Truck Driver's Gear Shift), but would going downward reduce the perceived energy/intensity? Or would it sound darker?
If that's too subjective, then I guess my question should be "What can I use a modulation downwards to achieve when composing?"
Answer: I've heard that this should provide a release of energy (though I'd think this isn't where such a release should be in a short song.) I think it sounds unusual.
Conway Twitty: "I'd Love to Lay You Down."
Answer: A lot of modulations are perceived only by musicians as modulations. I believe that a lot of modulations go un-noticed by listeners, even as far as a mood change goes. Some are subtle, and those in particu;ar are the ones that are likely to slip by.
Going, as an example, from key C to key B♭. Using F as the change over harmony, it can be subtle. F is diatonic to both keys, so the transition is smooth, and possibly the listener won't realise the key has gone down, or maybe not even changed. As a truck-driver's gear change, it's going to be somewhat different though.
Rather like minor = sad (to some!) the change of mood will vary between listeners. I feel a related question coming on...
Answer: If we could describe musical effect in words, we wouldn't need music!   We can show you some examples.
Here's a classic one.  First chorus in Db then (at 0'55") a shift down to C for the vocals.  Can you label how it 'feels'?  No, neither can I.   But it certainly isn't the obvious 'downer' that you might expect.  As so often, the modulation to what theory classes as a pretty remote key is achieved with basically a simple ii, V, I in the new key.
Why did the arranger do this?  To give the band a nice 'easy' key for their featured section, but Db lay a little high for the vocals?  Or just because a key change seemed a good idea and he thought he'd be a bit clever?
Anyway, put 'going down a semitone' in your bag of tricks.
Answer: I guess it depends on your way of looking at it.
What's your definition of down?
What's your definition of small amount...?
I can just give you some examples from Ragtime, because there I transcribed some songs lately. Almost 90% of all rags have a modulation one step down / counterclockwise on the circle of fifths, but often go up in pitch with the note itself:

In this one it goes from Bb to Eb. Which would be 7 semitones down, but also 5 semitones up. This is the regular type of modulation you get in rags and sounds like this (at ~0:20). Bb to Eb
Now let's do your example from A to G which would be 2 steps on the circle of fifths. So this one is down from Bb to Ab
And just to give you a comparison, this is the same moldulation but going from Bb up to Ab. So let's put Ab up an octave:
Bb to Ab +1 octave
Does one sound better to you than the other? I think it's just personal preferences... You can basically modulate up or down to any key you want. Some might sound more pleasant than others. But if that's the sound you're going for, just do it ;)
Comment: Yes, Ragtime, like the classic March, typically has a central section in the subdominant key.  But that's not what this question's about.
Comment: Fair point about "what is down". I meant comparing the root motion, not steps around the circle of fifths. As an example, E major going to E♭ major.


Prove $\max f(x) = -\min -f(x)$

Question: How do I prove :
$$\max f(x)= - \min -f(x)$$
I am trying to prove this, and have tried to use my book but I am stuck.
Comment: If $f(x) \leq \alpha$ for all $x$, then $-f(x) \geq -\alpha$ for all $x$. Therefore $\max f = \min -f$.
Comment: It should state: max f(x) = - min -f(x), I didn´t find it :/
Comment: did u used definitions?
Comment: Sorry, my fault: $\max f = -\min (-f)$, of course ;-)
Comment: It really does follow almost immediately from the fact that $a\leq b$ if and only if $-b \leq -a$.
Answer: Let $A\subset\mathbb R$ have a maximum; i.e. some
$m\in A$ exists such that $a\leq m$ for each $a\in A$.
If $-A$ denotes the set $\left\{ -a\mid a\in A\right\} $ then $-m\in-A$
and $-m\leq-a$ is true for each $a\in A$.
This tells us that $-m$ is a minimum
of $-A$.
Denoting $m=\max A$ and $-m=\min\left(-A\right)$ we have: $$\max A=m=-\left(-m\right)=-\min\left(-A\right)$$

Prove $\max f(x) = -\min -f(x)$


Techniques for plotting PCA projections in more than three dimensions

Question: After running PCA on my data set, I noticed that using the three first eigenvectors, a separation between two different classes is still achievable (doing PCA on data from two classes). Unfortunately, it doesn't scale up very well and when I feed in data from 15 different classes, I get a big blob of dots when I plot the reprojected data in three dimensions. I want to find out if those classes are actually separated in higher dimensions. Is there techniques used to visualize scatter plots of data in more than 3 dimensions?
I have read about using different shapes (dots, triangles, squares, and their respective area) to fit more information in a 3D scatter plot but how would you code that relative to the values delivered by PCA?
Comment: First, you can plot all possible 2d scatterplots ("scatterplot matrix"), like e.g. in this answer http://stats.stackexchange.com/a/101490. Second, you can try to use a supervised method such as LDA, see here http://stats.stackexchange.com/questions/161362.
Answer: Answered in comments by amoeba:

First, you can plot all possible 2d scatterplots ("scatterplot
matrix"), like e.g. in this answer stats.stackexchange.com/a/101490.
Second, you can try to use a supervised method such as LDA, see here
stats.stackexchange.com/questions/161362.


Hazard or survival function for data with different right-censor timings and different starting periods

Question: I have 15 years of data of patients (2001-2015). T0 differs between them, i.e. the starting year for the survival period is strongly heterogenous. I want to model their survival rate, i.e. what is the probability that they survive after T0 each year? More so, I want to see how the survival rate differs by one or more characteristics of the patient. What would be the best way to model and estimate this?
My first option would be a survival function/hazard function. However, I am uncertain how to deal with (1) differing starting periods, i.e. T0 could be 2004 for one patient, 2012 for another, (2) different right-censoring times, i.e. if T0 is 2012, I only have 3 years of data to observe death compared to 12 years if T0 is 2003 and (3) varying probability rates dependent on a patient characteristics, which I am unsure how to incorporate and even if it is feasible.
My second option which looks more feasible in my opinion is a logit model where the dependent variable is death in a certain year or not, and the independent variable interacts time after T0 with the patient characteristic I am interested in. But if this is a valid option, I am not sure why I would even consider a survival or hazard function.
Answer: A simple way to proceed with issue (1) in a survival model is to include the actual year of T0 as a covariate in the model, ideally fit flexibly with a spline.
Issue (2) of right censoring is inherently incorporated into a survival model. Yes, you might have more uncensored data at longer times for patients with earlier T0 years, but that's OK. Mostly, that just means that estimates of baseline hazards at long times after T0 won't be as precise as those at early times. But with a standard Cox proportional hazards model, the precision of coefficient estimates has mostly to do with the total number of events, not their distribution in time. (Actual time isn't explicitly included in a Cox model, except for the ordering of events in time.)
Patient characteristics (issue 3) are readily incorporated into a survival model. You could include interactions of patient characteristics with the T0 year in the model, if you think that the association of a patient characteristic with outcome changed over calendar time.
Having "the independent variable [interact] time after T0 with the patient characteristic I am interested in" sounds like having a time-varying regression coefficient for that patient characteristic in a survival model. See the R time dependence vignette. That might ultimately be necessary, but it's not usually the way to start. The initial assumption is typically that a covariate has a particular association with the extra hazard of an event that is constant over time, even as the baseline hazard might change over time.
Your proposed set of logistic regressions year by year is a type of discrete-time survival model. If you have survival values in continuous time, a standard survival model is typically more informative as it keeps more detail about individual survival times.
Comment: Thanks a lot for your comment. It's very useful. I had a follow-up question. The survival values are in discrete times; i.e. I know the year the hazard occurred but not the exact day. Is there any benefit using a survival model compared to a logistic regression in this case? Thanks a lot.
Comment: @OhHiClark iA discrete-time survival model is a set of binary regressions, one for each time period. Analysis for each time period is restricted to those at risk during that period, which handles censoring. Setting up such a set of logistic regressions is thus a form of survival analysis. If you do that, a [complementary log-log link](https://stats.stackexchange.com/a/517668/28500) better matches a Cox survival model than does a logit link. With discrete time, such sets of binomial regressions are preferred to Cox or other models that assume continuous time.
Comment: Thanks a lot for your comments, I read through your links and have a much better understanding now!


Configurar virtual host no Ubuntu

Question: Estou tentando configurar o virtual host no meu Deepin OS e nada que fiz funciona. Antes que marquem a pergunta como duplicada, todas as alternativas que eu vi aqui no fórum eu tentei e não tive sucesso, vi vários e vários vídeos no youtube e tbm não funciona. Atualmente meu virtualhost está assim
<VirtualHost *:80>
    ServerAdmin email@example.com
    ServerName gymdoctor.dev
    ServerAlias www.gymdoctor.dev
    DocumentRoot /var/www/gymdoctor.dev/public/
    ErrorLog ${APACHE_LOG_DIR}/error.log
    CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>

já tentei também com as opções de directory e apontar para a pasta public do projeto em laravel e nada. Alguém sabe alguma maneira de resolver isso ou o problema está no SO que eu uso já que todos os tutoriais para Ubuntu eu tentei.
RESOLVIDO: eu estava utilizando meusite.dev para criar o vhost, troquei para meusite.test e funcionou corretamente.
Comment: Você editou qual arquivo exatamente do Apache? E em que pasta? A instalação do Apache foi via `apt-get` ou instalou algo independente do repositório oficial? Dê detalhes para que possamos saber o que fez e assim conseguir orienta-lo.
Comment: O apache foi instalado via apt-get. Os arquivos que eu editei foi na pasta /etc/apache3/sites-available/meusite.dev `
 ServerName meusite.dev
 ServerAlias www.meusite.dev
 ServerAdmin email@example.com
 DocumentRoot /var/www/gymdoctor/public
 ErrorLog ${APACHE_LOG_DIR}/error.log
 CustomLog ${APACHE_LOG_DIR}/access.log combined
` e no /etc/hosts apenas acrescentei 127.0.0.1 meusite.dev
Comment: você adicionou no *hosts* o endereço `meusite.dev` para apontar para 127.0.0.1?
Comment: Sim, adicionei. No chrome não funciona e no firefox ele pega o index da pasta /var/www/html e não /var/www/meusite.dev/public
Comment: Felipe eu respondi
Answer: Mude a extensão de:
/etc/apache3/sites-available/meusite.dev

Para .conf
/etc/apache3/sites-available/meusite.dev.conf

O mesmo para:
/etc/apache3/sites-available/gymdoctor.dev

Para .conf
/etc/apache3/sites-available/gymdoctor.dev.conf

Notas extras:
As notas aqui são para futuros visitantes:
Não esqueça de adicionar no hosts, para isto edite o arquivo /ect/hosts (provavelmente requer sudo), um exemplo se tiver o nano:
sudo nano /etc/hosts

Então deixe-o semelhante a isto:
127.0.0.1   localhost
127.0.1.1   meusite.dev

Configurar virtual host no Ubuntu


Network printer install best practices

Question: I know an end-user (Windows 7 workstation part of a domain with NO admin privileges) can install a network printer (with static IP installed on a server) basically through two different ways:

adding a TCP/IP printer

Open Control Panel / Device and Printers    Click Add Printer
Select Add Local Printer then click Next    Select create new port,
choose Standard TCP/IP from menu, then click Next    Type static IP
assigned to printer in Hostname or IP address field    (port name is
automatically IP_129.107.X.X where X is defined by static IP)
Check option to Query Printer and Automatically Select Driver then
click Next    Click Finish in the Completing TCP/IP window    If
driver is not found in list click Have Disk and select Driver when
prompted then click OK    Use default name for printer then click
Next    Select option to Not Share Printer then click Finish

Through the command: <code>\\SERVER_NAME\PRINTER_NAME</code> then double clicking
   on the printer icon

Are there any differences between these two methods, and which one is considered to be best practice?
Thanks a lot.
Answer: The best practice is the one which you have evaluated in your environment and determined to be most appropriate for your admins and users.
Comment: So there's no difference..am I right? Both techniques are correct
Comment: They end in totally different configurations, neither of which is better for all environments.

Network printer install best practices


auto-click the SUBMIT button?

Question: If the user manually clicks the 'submit' button, i use this code:
if (isset($_POST['submit_findall'])) {  ...
But what what code should I use if I want to activate this from within a script ?
Thanks!
Comment: if it's not javascript but PHP script, why not just to fake this variable, `$_POST['submit_findall']=1; include 'register.php';`? I don't understand why you have to double this code anyway
Answer: if($_SERVER['REQUEST_METHOD']=='POST')  is bullet proof indicator of the POST form submit
Answer: Change:
if (isset($_POST['submit_findall'])) {
    // Something
}

to:
// Something

Comment: yes, but I don't want to duplicate the code, i.e. it should be working both on button press, as well as activated from within the script.
Comment: Pressing the button will cause the script to be reloaded, so you don't need to duplicate the code; just change it as above.
Comment: What does "activated" by a script mean? If you need to call code twice, just push it into a function and call the function twice.

auto-click the SUBMIT button?


Orchestration: how to know a comfortable playable speed to low register instruments?

Question: During the orchestration of a piano piece, sometimes there are fast passages (with long intervals) in the lower register, like that Villa-Lobos "Saudades das Selvas Brasileiras" passage:

Or this passage in Debussy's "L'isle Joyeuse":

However, for low-register instruments (for example, double bass, bass clarinet, contrabassoon, bass/contrabass tuba and trombone), it's not easy to play fast passages that involve jumps (notes 2 or more semitones apart).
I would like to know how to transcribe passages like these for low-register instruments, making them playable for musicians with average skills.
Comment: It's not as difficult as you might think.  Certainly allowing a slurred passage is much easier than requiring each note to be attacked.  Another option is to remove some of the "passing notes",  keeping the first and last note in a run and perhaps every other note in between.
Comment: @RogérioDec, no problem, I'm glad you're happy with it. You should keep in mind that (besides double bass and trombone) those instruments are rarely going to be played by intermediate musicians, given their price and availability. I cannot think of any difficulties that double bass and trombone players would face with those passages, but Carl Witthoft provides a good solution. It also depends on your orchestration. If you have 2+ instruments within the same "type", you can separate "voices" (passages) between them.
Comment: Where are you getting your facts about bass from?  Is it an assumption, based on a text on orchestration?  There are some seriously mean bass solos in symphonies, and solo pieces that are very fast.
Answer: This is a misconception: low brass/woodwind instruments (as you mentioned: bassoon, tuba, trombone) are faster than you'd think. A bass clarinet is not slower than a B♭ clarinet, a tuba isn't slower than a trumpet.
In the two passages you provided, no low wind instrument should have trouble playing the bottom staff, assuming a decently skilled player.
Comment: There are certain physical limits involved with playing "low-register" instruments nevertheless. A contrabassoon is indeed not that different from a plain bassoon, but things do get funky with "low-register" instruments from the saxophone family. Of course, it is rare to find an intermediate musician playing a bass saxophone, but bass saxophones and below (contrabass, subcontrabass) do face certain difficulties. Given saxophones' notorious low range, most players need to perform embouchure adjustments that are simply impossible at high speeds and with fast staccato articulation.
Comment: @RogérioDec, while there is a limit to everything I'd let a bassist try the passage at the tempo you need before butchering it.  As I mention in my previous comments there are some very fast bass passages in symphonies.


How to write a sub query within another subquery?

Question: How do I go about writing a query for: for each coral that has at least 2 samples during 1/1/2007 and 1/1/2008, list the coral name and the number of samples.
I think it needs a sub query but I have tried putting things around other ways and it's just  no working for me. Would some be able to just 'spell it out' for me so that I can understand what is actually going on and attempting similar queries to this.
TABLES
REEF [reefname, latitude, longitude, 2006_bleachedarea, summer_maximum_monthly_mean_temperature]
Key: reefname
REEFTEMP [reefname, dateofreading, temperaturereading]
Key: reefname, dateofreading
CORAL [coralcode, coralname, thermalthreshold]
Key: coralcode
CORALSAMPLING [sampleno, coralcode, reefname, dateofsampling, bleachpercent]
Key: sampleno

This is what I have so far. I doubt it is correct at all.
SELECT coralcode, sampleno
FROM coralbleach__coralsampling
WHERE
dateofsampling BETWEEN '2007/1/1' AND '2008/1/1'
GROUP BY sampleno

Comment: Not quite understand what exactly you are looking at. Please add the tables and some data in http://sqlfiddle.com and expected result to the question.
Answer: You should be able to do a simple join, something like;
SELECT coral.name, COUNT(coralsampling.sampleno) number_of_samples
FROM coral
JOIN coralsampling
  ON coral.coralcode = coralsampling.coralcode
 AND coralsampling.dateofsampling BETWEEN '2007/1/1' AND '2008/1/1'
GROUP BY coral.name
HAVING COUNT(coralsampling.sampleno) > 1

This query will get all corals, join them with their respective samples and group by the coral name (that means we can use COUNT to count the number of sample rows per coral name)
We then use HAVING to filter out all corals that don't have 2 samples or more.
Joins are a bit too complex to describe in detail in a short answer format, but I strongly suggest you read up on JOIN and GROUP BY to be able to construct queries like these easily.


Half time duration

Question: I have read through the FIFA laws of the game and can see that the half time interval says:
Half-time interval
Players are entitled to an interval at half-time.
The half-time interval must not exceed 15 minutes.
Competition rules must state the duration of the half-time interval.
The duration of the half-time interval may be altered only with the consent of
the referee.
We play amateur U18 football in the UK, with 45 minutes per half. I have looked through our leagues handbook and can find no mention of the duration.
Is it reasonable for the referee to insist on only 5 minutes half time interval?
The above rule was taken from the FA laws of the game.
Answer: Yes, but for normal the ref asks both teams if they're ok with it.
On the otherside, if it's realy cold weather mostly the teams asking the ref for a shorter halftime interval.
(If the ref blows the whistle after only 5min halftime interval, it's easy to max it for another 5min.)
Answer: Not more than fifteen minutes but not less than five minutes
Comment: Do you have a reference for this information?

Half time duration


Residue Rings of Polynomial Rings over $\mathbb F_p$

Question: Let $\mathbb Z$ be the ring of integers, $p$ a prime and $\mathbb F_p = \mathbb Z/p\mathbb Z$ the field with $p$ elements. Let $x$ be an indeterminate. Set $R_1 = \mathbb F_p[x]/(x^2-2)$, $R_2 = \mathbb F_p[x]/(x^2-3)$. Determine whether the rings $R_1$ and $R_2$ are isomorphic in each of the following cases:
(a) $p = 2$
(b) $p = 5$
(c) $p = 11$
I'm pretty sure about my answer to (c), but not very sure about (a) & (b). Any comments would be greatly appreciated for PhD Quals prep. Thank you.
Attempt at Solution:
(c) When $p = 11$, $x^2 - 2$ is irreducible but $x^2 - 3$ is reducible [$2$ is a quadratic nonresidue $\bmod 11$; $3$ is a quadratic residue]. So $(x^2 - 2)$ is a maximal ideal and hence $R_1$ is a field, whereas $R_2$ is not. So they are not isomorphic.
(b) When $p = 5$, both $x^2 - 2$ and $x^2 - 3$ are irreducible, so both $R_1$ and $R_2$ are fields. As any polynomial in $R_1$ or $R_2$ of degree $\ge2$ is equal to some polynomial of degree $0$ or $1$, effectively, the elements of $R_1$ and $R_2$ can be represented by $a_0 + a_1x$, where $a_0, a_1 \in \{0,1,2,3,4\}$. So $R_1 = R_2 =$ finite field with $5^2$ elements, i.e. they are isomorphic.
(a) When $p=2$, both $x^2 - 2 = x^2$ and $x^2 - 3 = x^2-1$ are reducible. So although $R_1$ and $R_2$ can each be represented by $a_0 + a_1x$, where $a_0, a_1 \in \{0,1\}$. I am not sure whether each of them is isomorphic to $\mathbb Z/4\mathbb Z$ or the Klein $4$-group.
Comment: Dear Conan, concerning your last sentence, be very careful: the question is about rings not groups. An $\mathbb F_2$- algebra will never be isomorphic to $\mathbb Z/4\mathbb Z$, but that is irrelevant: $\mathbb F_2/(x^2+x+1)$ and $\mathbb F_2/(x^2)$ both have the Klein group as underlying group but yet they are not isomorphic *as rings* .
Comment: Thanks Georges - sadly I have to admit that I have made a similar mistake before. Thank you for the reminder.
Answer: (a) $R_1 = F_p[t]$, where $t$ is the image of $x$.
$R_2 = F_p[s]$, where $s$ is the image of $x + 1$.
Since $t^2 = 0$ and $s^2 = 0$, $R_1$ and $R_2$ are isomorphic.
(b) and (c) were solved by you.


attaching binary file to an event in cumulocity

Question: I have a scenario where in my code creates a file and an event in cumulocity as well. I need to attach the binary file to the event, however none of the API's provide me the functionality, any guidance as to how to go ahead please?

Update:
On having a look at the documentation https://cumulocity.com/api/10.11.0/#tag/Attachments , the binaryElement has a following structure

I have modified my JAVA code in the following manner:
<code>String pathEvent = platform.getUrl().get()+"/event/events/{{eventId}}/binaries";
    String pathEventAttachment = pathEvent.replace("{{eventId}}", event.getId().getValue());

    HttpHeaders headers = RequestAuthenticationEncoder.encode(getCredentials());
    headers.setContentType(MediaType.MULTIPART_FORM_DATA);
    MultiValueMap<String, Object> map = new LinkedMultiValueMap<>();
    map.add("file",new ByteArrayResource(FileUtils.readFileToByteArray(file)));//anychanges here fails the code
    map.add("filename", file.getName().getBytes());

    HttpEntity<MultiValueMap<String, Object>> request = new HttpEntity<>(map,headers);
    restTemplate.postForObject(pathEventAttachment, request, String.class);
    log.info("Binary file added to the event {}", event.getId().getValue());
</code>
Binary is created for the event, however the filename is incorrect:

Please let me know some insights as to why the name is not changing?
Answer: You need to create a POST on /event/events/{{eventId}}/binaries with the appropriate Content-Type and body.
Here is a code snippet in python where a binary (log file) is attached to an event. It just POSTs the file content (bytes) as application/octet-stream
<code># Create event
logfileEvent = {
    'type': 'c8y_Logfile',
    'text': 'See attached logfile',
    'time': datetime.utcnow().strftime('%Y-%m-%dT%H:%M:%S.%f')[:-3] + 'Z',
    'source': {
        'id': DEVICE_ID
    }
}
res = client.post(C8Y_BASE + '/event/events/', data=json.dumps(logfileEvent))
eventId = res.json()['id']

# Attach Binary
res = client.post(C8Y_BASE + '/event/events/' + eventId + '/binaries', data=bytes(FILE_CONTENT, 'utf-8'), headers={'Content-Type': 'application/octet-stream'})
binaryRef = res.json()['self']

# Update operation
logfileFragment = logfileOperation['c8y_LogfileRequest']
logfileFragment['file'] = binaryRef
updatedOperation = {
    'status': 'SUCCESSFUL',
    'c8y_LogfileRequest': logfileFragment
}
client.put(C8Y_BASE + '/devicecontrol/operations/' + logfileOperation['id'], data=json.dumps(updatedOperation))
</code>
Comment: could you look into the update and provide me some insights
Comment: I am not sure about the correct way in Java but in general the HTTP request needs to have a header "Content-Disposition" with the value "filename=myfile.txt"


Relation between linear independence and matrix inversion

Question: My friend was wondering, suppose the invertible matrices $A_i$, $1 \le i \le k$, are linearly independent as vectors in $\mathrm{M}_{n \times n}(\mathbb{R})$. Is it true that the $A_i^{-1}$ are linearly independent if $k \ge 3$?
Answer: No. Take$$A_1=\begin{pmatrix}1&0&0\\0&\frac12&0\\0&0&\frac13\end{pmatrix},\ A_2=\begin{pmatrix}\frac12&0&0\\0&\frac13&0\\0&0&\frac14\end{pmatrix},\text{ and }A_3=\operatorname{Id}_3.$$They are linearly independent, but their inverses are not.