Habilitar campos de formulário com JS com Radio Button

Question: Estou iniciando com Javascript e tenho um pequeno problema.
Tenho um formulário em HTML onde tenho um campo radio onde tenho duas opções, Texto e Página. Quando eu clicar na opção Texto ele carrega um campo  input para inserir o titulo, quando eu seleciono o Página ele me mostra dois campos um input com titulo e subtitulo.
Como eu faria essa logica?

    Tipo Título:

        <input name="title-type" type="radio" value="text" id="title-type" onclick="typeRadioButton()"> Texto

        <input name="title-type" type="radio" value="page" id="title-type" onclick="typeRadioButton()"> Página

    {{ Form::label('metadata', 'Título', ['class' => 'col-sm-2 col-form-label']) }}

        {{ Form::text('title', null, ['class' => 'form-control',  'placeholder' => 'Digite um Titulo', 'required' => true]) }}

    {{ Form::label('metadata', 'Sub-título', ['class' => 'col-sm-2 col-form-label']) }}

        {{ Form::text('pagetitle', null, ['class' => 'form-control',  'placeholder' => 'Digite um Sub-Titulo', 'required' => true]) }}

    {{ Form::label('metadata', 'Conteúdo', ['class' => 'col-sm-2 col-form-label']) }}

        {{ Form::textarea('slot', null, ['class' => 'form-control', 'required' => true]) }}

    {{ Form::label('metadata', 'Cor de fundo:', ['class' => 'col-sm-2 col-form-label']) }}

        {{ Form::checkbox('Usar Padrão do site', '', false) }} Usar Padrão do site
        <input type="color" name="background ">

    {{ Form::label('metadata', 'Cor do título:', ['class' => 'col-sm-2 col-form-label']) }}

        {{ Form::checkbox('Usar Padrão do site', '', false) }} Usar Padrão do site
        <input type="color" name="color-title">

    {{ Form::label('metadata', 'Cor do texto:', ['class' => 'col-sm-2 col-form-label']) }}

        {{ Form::checkbox('Usar Padrão do site', '', false) }} Usar Padrão do site
        <input type="color" name="color-text">

{{-- JQuert--}}

Comment: Se você quer uma solução em Javascript, seria melhor você postar o html renderizado em sua pergunta.
Comment: Beleza, está ai colocado.
Answer: Deverá ser algo deste género, depois metendo nas divs com id="inv" e id="inv2" os inputs que pretende que apareçam consoante o botão que está premido.

$(function() {
  $('#global').bind("keyup click", function() {
    hideShow();
  });
  hideShow();
});

function hideShow() {
  if ($('#texto').is(':checked')) {
    $('#inv').show();
  } else {
    $('#inv').hide();
  }
  if ($('#pagina').is(':checked')) {
    $('#inv2').show();
  } else {
    $('#inv2').hide();
  }
}

  Tipo Título:

    <input name="title-type" type="radio" value="text" id="texto"> Texto

    <input name="title-type" type="radio" value="page" id="pagina"> Página

  Coisas escondidas

  Outras Cenas escondidas

Comment: Valeu cara, muito obrigado!


Ambiguous Outer Join Error While Using OleDB to List all Stored Procedures and Queries

Question: I have to document several MS Access 2007 databases, each with hundreds of macros queries, etc and I'd like to automate the process in C#. For every .mdb file, myfirst goal is to extract schema information (tables, forms, macros and query names and definitions).
I'm using the following code using OleDB to get a list of all available tables by the user:
 private static List<String> getTableNames(OleDbConnection db)
 {
        List<String> tableList = new List<String>();
        DataTable schemaTable;
        try
        {
            object[] objArrRestrict = new object[] { null, null, null, "TABLE" };
            schemaTable = db.GetOleDbSchemaTable(OleDbSchemaGuid.Tables,objArrRestrict);
            foreach(DataRow row in schemaTable.Rows) tableList.Add((String)row["TABLE_NAME"]);
        }
        catch(Exception e) {
            Console.WriteLine(`"Table Name Querying Failed. Returning Empty List"`);
            Console.WriteLine(e.Message);
        }
        return tableList;
    }

For the columns I'm using a similar method simply feeding off the previous one like so:
object[] objArrRestrict = new object[] { null, null, tableName, null };
schemaCols = db.GetOleDbSchemaTable(OleDbSchemaGuid.Columns, objArrRestrict);
foreach (DataRow row in schemaCols.Rows) tableList.Add((String)row["COLUMN_NAME"]);

I'm not so sure how to get the macro information (name and definition), but after some research I decided to use the following to get the query information.
object[] objArrRestrict = new object[] { null, null, null, null };
schemaCols = db.GetOleDbSchemaTable(OleDbSchemaGuid.Procedures, objArrRestrict);

However when I run the last bit of code, I get the the very vaguely worded error message:

The SQL statement could not be executed because it contains ambiguous outer joins. To force one of the joins to be performed first, create a separate query in your SQL statement.

After some more research I modified the getTableNames method to grab queries through the  "VIEWS" restriction, but that only got the stored SELECT queries in the data base and I also need the stored INSERT, UPDATE and DELETE queries.
Finally, I'm now using the following code to query the MsysObjects table directly.
String cmdString;
OleDbCommand queries = new OleDbCommand(cmdString,db);
OleDbDataReader reader = queries.ExecuteReader();

Using the following two cmdStrings interchangeably:

SELECT MSysObjects.Name FROM MsysObjects WHERE (Left$([Name],1)<>"~") AND
    (MSysObjects.Type)=5 ORDER BY MSysObjects.Name

or

SELECT Name FROM MSysObjects WHERE (Name Not Like ""MSys*"") AND (Type In (1,4,6))  ORDER BY Name

Again, both strings also induce the same "Ambiguous Outer Join" error.
I've read up a little bit on this type of error and I know the general recommendation is to break apart the original query into multiple queries but as I'm using library functions to get this schema data, I'm not sure how exactly to go about doing that. I've aready spent days researching this and I'm at my wit's end. If someone could help me out with this issue or point me toward some way to sidestep this roadblock I would really appreciate it.
Comment: This is not a lot of help, but I tried a mock-up of your code and it worked for me.
Comment: @Remou It does help in a way, thanks. Most other people report that
'db.GetOleDbSchemaTable(OleDbSchemaGuid.Procedures, objArrRestrict);' should work as I'm using it. I rewrote the same code using VBA and I'm still getting an "Ambiguous Outer Join" error. I'm beginning to think that there is something wrong with the database itself. Also, I'm wondering if there is some way for me to fix this issue using the fact that I can get all the stored views (SELECT queries) to somehow filter them out before I call GetOleDbSchemaTable() on OleDbSchemaGuid.Procedures.
Comment: Also, to be clear, OleDbSchemaGuid.Procedures is the only filter that is giving me issues in OleDB right now. The others are working just fine. Thanks!
Comment: Have you tried working through the usually corrupt database routine: compact & repair, decompile etc ( http://www.granite.ab.ca/access/corruptmdbs.htm ) ? I would be wary of using the system tables outside of Access, there are permissions problems that are hard to work around.
Comment: I had those permissions issues very early on, but I've long since fixed them. Right now I'm just trying to deal with this mysterious "Ambiguous Outer Join" error that always breaks at the GetSchemaTable line. I could probably do all of it by hand but there are so many tables and queries, you can imagine how desperate I'm trying to avoid doing all of that column tracking manually.
Comment: Just ran compact and repair without a hitch. I'm still getting this error, thanks though.
Answer: What happens if you group it like this?
SELECT
Name
FROM
MSysObjects
WHERE
Name Not Like 'MSys*'
AND
Type In (1,4,6)
ORDER BY Name

or this one
SELECT
Name
FROM
MSysObjects
WHERE
(
(Name Not Like ""MSys*"")
AND
(Type In (1,4,6))
)
ORDER BY Name

Comment: Note I think the Like should be 'value' instead of quotes / double quotes.
Comment: The problem isn't that my query is not a well formed statement. I would be getting a completely different error message in that scenario. I just use double quotes as a C# specific thing. If I change my query as you suggest, I still get an Ambiguous Outer Join error message.


É possível com CSS fazer com que cada letra de uma palavra tenha uma cor diferente?

Question:

.two-colors{
   font-size: 160px;
   background: linear-gradient(to right, blue 50%, green 0);
   -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;

  font-weight: 900;
  font-family: Arial;

}

TESTE

TESTE
Comment: A sugestão de colocar cada letra dentro de um span e setar uma color é inviável se tratar de um texto por exemplo. Se for umas palavras, funciona perfeitamente.
Comment: Se você tiver controle sobre a fonte o próprio gradient dá certo, só faltou acertar as porcentagens (é uma gambiarra lascada, mas é só você fazer por exemplo blue 20%, green 20%, green 40%, red 40%, red 60%, etc (acertando os % pras cores)
Comment: Vc tem que dar mais detalhes, Pq não coloca cada letra dentro de um span e seta um color?
Comment: Queria chegar em um resultado igual dessa imagem https://http2.mlstatic.com/D_NQ_NP_665890-MLB31127748573_062019-O.jpg. Quase consegui com o exemplo do amigo @Bacco.
Comment: @douglasabnovato eu consegui colocando o span e setar color em cada letra. E também consegui com a reposta do nosso amigo Bacco. Mas para um texto fica muito complicado!
Answer: Considero "apelação", mas só pra dizer que esse caminho que começou na pergunta seria um jeito:

.two-colors {
   font-size: 160px;
   background: linear-gradient(to right,
      blue 20%,
      green 20%, green 40%,
      red 40%, red 60%,
      orange 60%, orange 80%,
      purple 80%
    );
   -webkit-background-clip: text;
   -webkit-text-fill-color: transparent;

    font-weight: 900;
    font-family: Arial;
}
Dá certo aqui:

TESTE

Aqui já precisaria ajustar tudo, mas ai fica errado pro outro texto:

WIDOW

Só que fatalmente para fontes com largura variada de caracteres vai ter que ajustar caso a caso manualmente e vai ficar cheio de falhas se o usuário tiver qualquer fonte diferente da que especificou (seja por falha na carga ou qualquer outra restrição).
Resumo: salvo alguma situação muito bizarra, melhor separar no HTML mesmo e usar, por exemplo, um span por letra para não afetar a semântica.


How to use volatile with 2D shared memory?

Question: I was wondering how to declare a volatile pointer to two dimensional shared memory and if this would have the same effect as for one dimensional arrays.
__shared__ float 2d_array[32][32];
// not working: volatile T ** smem = sdata;

Answer: Note that your "two dimensional" shared memory array is, in fact, only one dimensional. So something like this:
__shared__ volatile float array_2d[32][32];
volatile float *smem = &array_2d[0][0];
float val = *(smem + y + 32*x) // address of s2_array[x][y]

is what you want. The static array array_2d is stored in row major order and can be accessed as I have shown.


Representable functor from scheme to Groups

Question: I want to do the following question (6.6k) in Vakli's Foundations of algebraic geometry

Suppose we have a contravariant functor $F$ from $Sch$ to $Groups$. Suppose further that $F$ composed  with the forgetful functor is represented by the object Y. Show that the group operations on $F(X)$ uniquely determine $m:Y×Y \rightarrow Y$, $i:Y \rightarrow Y$, $e:Spec\mathbb{Z} \rightarrow Y$. And the group operation on $Mor(X,Y)$ is the same as on $F(X)$

Suppose $F$ composites with the forgetful functor is equal to $h_Y$
I know that $m:Y×Y \rightarrow Y$ must be the product of  the projection morphism $π:Y×Y \rightarrow Y$ with itself and $e$ must be identity element of the group $Mor(spec\mathbb{Z} ,Y)$ For the morphism $i$, it composites with $f \in Mor(Y,Y) $ to give $f^{-1}$. But I have no idea why this morphism is unique. Also I don't know why $F(X)$ should have group structure induced by $Y$. I'm sorry if this is a stupid question. Any help or hints are appreciated.
Comment: What does "product of the projection morphism with itself" mean?
Comment: I mean the group product in $Mor(Y×Y,Y)$ because $(\pi,\pi): Y×Y \rightarrow Y$ is the identity morphism and it composites with $m$ to give $m$
Answer: Consider the diagram given to you by the problem
$$
\begin{matrix}
& & \textbf{Groups} \\
F\nearrow & & \downarrow \\
\textbf{Schemes}^{op} & \xrightarrow{h_X} & \textbf{Sets}
\end{matrix}
$$
The question can be answered purely from a functor of points perspective since morphisms between representable functors can be turned into morphisms of schemes; so, what does it mean for $h_X$ to have the structure of a group schemes? You should have natural transformations
$$
\begin{align*}
&m:h_X\times h_X \to h_X \\
&\iota:h_X\to h_X \\
&e:h_\mathbb{Z} \to h_X
\end{align*}
$$
but what is a natural transformation? It's a map described on the functor evaluated on objects in your source category. So, because of the factorization of $h_X$ as $\text{Forget}\circ F$ we have for any morphism of schemes $S \to T$ a commutative diagram
$$
\begin{matrix}
h_X(T)\times h_X(T) & \xrightarrow{m(T)} & h_X(T) \\
\downarrow & & \downarrow \\
h_X(S)\times h_X(S) & \xrightarrow{m(S)} & h_X(S)
\end{matrix}
$$
where each row satisfies the diagrams for a group object in a category. You can do the same argument for the other group operations and call it a day.
Comment: You're welcome! This is an excellent theoretical example of the advantage of using the functor of points.


Como Carregar uma Activity usando a ProgressBar

Question: Código Da ProgressBar em  XML
<?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_height="match_parent"
    android:layout_width="match_parent">

    <ProgressBar
    android:layout_height="11px"
    style="?android:attr/progressBarStyleHorizontal"
    android:layout_width="300px"
    android:id="@+id/load"
    android:layout_centerInParent="true"
    android:layout_alignParentBottom="true"
    android:layout_marginBottom="52px"/>

</RelativeLayout>

Código da ProgressBar em Java
package game.app;

import android.app.*;
import android.os.*;

public  class LoadActivity extends  Activity {

  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.loadlayout);
  }
}

Activity que a ProgressBar vai carregar
package game.app;

import android.app.Activity;
import android.os.Bundle;
import android.widget.*;
import android.view.*;
import android.view.View.*;
import android.content.*;

public class MenuActivity extends Activity {

  private Button btiniciar;

  @Override

  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.menulayout);

    btiniciar = (Button) findViewById(R.id.btiniciar);
    btiniciar.setOnClickListener(new View.OnClickListener(){
      public void onClick(View v) {

        @Override

        Intent it = new Intent(MenuActivity.this,LoadActivity.class);
        startActivity(it);
        finish();
      }
    });

    Button btconfig = (Button) findViewById(R.id.btconfig);
    btconfig.setOnClickListener(new View.OnClickListener(){
      public void onClick(View argO) {

      }
    });
  }
}

Comment: Para mim não ficou claro o que você quer fazer. Só colou os códigos aqui
Answer: O ProgressBar é um elemento da interface do usuário que indica o progresso de uma operação, nessa ação que você esta fazendo não há nenhuma ação que precise de ProgressBar.
Um exemplo onde pode se usar o ProgressBar é uso de AsyncTasks para carregamento de dados de API, download de imagem e etc... a não ser que para simular o progress você use algum postDelayed determinando um tempo para simular um delay na transição de tela.
 btiniciar = (Button) findViewById(R.id.btiniciar);
    btiniciar.setOnClickListener(new View.OnClickListener(){
      public void onClick(View v) {

                //MOSTRAR PROGRESS
                final Handler handler = new Handler();
                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                     //ESCONDER PROGRESS
                       Intent it = new Intent(MenuActivity.this,LoadActivity.class);
                       startActivity(it);
                       finish();
                    }
                }, 2000);
      }
    });


Cloud SQL External Access suddenly restricted

Question: I have an Google Cloud Endpoint with an configured Cloud SQL - Database with an dedicated IPv4 for external access.
It all worked fine until today, where suddenly the access was restricted from EVERY IP I allowed.
Also "allow all" with 0.0.0.0/0 is not working any more.
I have checked the IP and it's all the same, server and client.
Anyway its possible for my Endpoint to access it ( its locally there, so no ip check required).
Is there any way how to check if they currently have problems with it on their servers? I don't know what i can/should to in this case.
Thanks for your help in adanvance
Comment: did you try to reboot your Cloud SQL instance to see if it fix the issue?
Comment: I rebooted the instance several times. Also changing password was not possible.

I created now another user, which worked. And THEN i was able to re-change the root password and then it worked -.-
Must be a strange server issue.
Answer: After adding a new user, i was able to access the SQL instance again,...
Then I changed the password several times and back to the old one. Obviously it's working again. But I don't know why it didn't work before.


How to extract header, paragraph, table structure from pdf using azure form recognizer in python

Question: I would like to extract the data like Header, paragraphs, tables, pagenumber, pagefooter from the pdf in the dataframe format using the azure form recognizer using python.
PFB expected output.

I have tried using layout model but the from the response i am not able to identify the header, paragraph or table
https://learn.microsoft.com/en-us/azure/ai-services/document-intelligence/quickstarts/get-started-sdks-rest-api?view=doc-intel-3.1.0&viewFallbackFrom=form-recog-3.0.0&preserve-view=true&pivots=programming-language-python
import os
from azure.ai.formrecognizer import DocumentAnalysisClient
from azure.core.credentials import AzureKeyCredential

endpoint = "<your-endpoint>"
key = "<your-key>"

def format_polygon(polygon):
    if not polygon:
        return "N/A"
    return ", ".join(["[{}, {}]".format(p.x, p.y) for p in polygon])

def analyze_layout():
    # sample form document
    formUrl = "https://raw.githubusercontent.com/Azure-Samples/cognitive-services-REST-api-samples/master/curl/form-recognizer/sample-layout.pdf"

    document_analysis_client = DocumentAnalysisClient(
        endpoint=endpoint, credential=AzureKeyCredential(key)
    )

    poller = document_analysis_client.begin_analyze_document_from_url(
            "prebuilt-layout", formUrl)
    result = poller.result()

    for idx, style in enumerate(result.styles):
        print(
            "Document contains {} content".format(
                "handwritten" if style.is_handwritten else "no handwritten"
            )
        )

    for page in result.pages:
        print("----Analyzing layout from page #{}----".format(page.page_number))
        print(
            "Page has width: {} and height: {}, measured with unit: {}".format(
                page.width, page.height, page.unit
            )
        )

        for line_idx, line in enumerate(page.lines):
            words = line.get_words()
            print(
                "...Line # {} has word count {} and text '{}' within bounding box '{}'".format(
                    line_idx,
                    len(words),
                    line.content,
                    format_polygon(line.polygon),
                )
            )

            for word in words:
                print(
                    "......Word '{}' has a confidence of {}".format(
                        word.content, word.confidence
                    )
                )

        for selection_mark in page.selection_marks:
            print(
                "...Selection mark is '{}' within bounding box '{}' and has a confidence of {}".format(
                    selection_mark.state,
                    format_polygon(selection_mark.polygon),
                    selection_mark.confidence,
                )
            )

    for table_idx, table in enumerate(result.tables):
        print(
            "Table # {} has {} rows and {} columns".format(
                table_idx, table.row_count, table.column_count
            )
        )
        for region in table.bounding_regions:
            print(
                "Table # {} location on page: {} is {}".format(
                    table_idx,
                    region.page_number,
                    format_polygon(region.polygon),
                )
            )
        for cell in table.cells:
            print(
                "...Cell[{}][{}] has content '{}'".format(
                    cell.row_index,
                    cell.column_index,
                    cell.content,
                )
            )
            for region in cell.bounding_regions:
                print(
                    "...content on page {} is within bounding box '{}'".format(
                        region.page_number,
                        format_polygon(region.polygon),
                    )
                )

    print("----------------------------------------")

if __name__ == "__main__":
    analyze_layout()

Answer: I realise this only answer a part of your question but it may help a bit :
Here is a fonction to get the tables and store them in a list of dataframe:
def get_tables(result):
    result_dict = result.to_dict()
    all_tables = []
    for idx, atable in enumerate(result_dict["tables"]):
        l = list()
        row_count = atable["row_count"]
        column_count = atable["column_count"]
        for aval in atable["cells"]:
            l.append(aval["content"])
        df = pd.DataFrame(np.array(l).reshape(row_count, column_count))
        df.columns = df.iloc[0]
        df = df.drop(df.index[0])
        all_tables.append(df)
    return all_tables

You get the whole text content by using result.content
If anyone as a quick way to get the content paragraph per paragraph I very interested :)


Show that $\mathbb{Q}(\sin\theta)$ is a field

Question: QUESTION:

Show that $F_{\theta}=\mathbb{Q}(\sin\theta); \theta\in\mathbb{R}$ is a field. Moreover, Show that $E_{\theta}=\mathbb{Q}(\sin\frac{\theta}{3}); \theta\in\mathbb{R}$ is a field extension of $F_{\theta}$ and find the maximum value of [$E_{\theta}:F_{\theta}$]

I am unable to show that for every $x\in F_{\theta}$, it has an inverse.
Also, I have shown that for some specific values of $\theta$, $E_{\theta}$ is a field extension of $F_{\theta}$.
But I can't prove for a general $\theta$.
Comment: What does $\Bbb Q(\sin\theta)$ mean to you? Because to me, it is _by definition_ a field. The literal meaning of those symbols in my book is "The smallest subfield of $\Bbb R$ which contains $\Bbb Q$ and $\sin\theta$".
Comment: @Kumar Yeah, that's not going to be a field most of the time. And it's not the standard definition of $\Bbb Q(\sin\theta)$. Are you _certain_ that that's your definition? I mean, $\Bbb Q(\sqrt2)$ _looks_ like that, for instance, but it's not usually _defined_ that way.
Comment: Sorry, but what you defined will be a field only if $\sin\theta$ is algebraic over $\mathbb{Q}$ with degree at most $2$. This is not even close to being true for all $\theta$.
Comment: Maybe you defined it specifically for elements like $\sqrt{2}$.
Comment: @Kumar Arthur and Mark are right. I gave an explanation of what they said by editing my answer.
Comment: @Arthur I mean that I am unable to find the inverse for every $x\neq 0$ $\in F_{\theta}$
Comment: What is your definition of $\mathbb{Q}(\sin\theta)$?
Comment: $\mathbb{Q}(\sin\theta):=\{a+b\sin\theta|a,b\in \mathbb{Q}\}$
Comment: @Arthur Sorry for the confusion, but we were given the definition as $\mathbb{F}(X):=\{a+bX|a,b\in \mathbb{F}\}$. I will check with the instructor.
Comment: Is your set even closed with respect to multiplication? In particular, how were you able to express $\sin^2\theta$ as a linear expression in $\sin\theta$?
Answer: Hint: $\forall x\in\mathbb R, \sin(3x)=3\sin(x)-4\sin^3(x)$.
Edit: Didn't see your first question concerning inverses in $F_\theta$, my bad. As Arthur said in comment, $\mathbb Q(\sin(\theta))$ should be by definition the smallest field containing $\mathbb Q$ and $\sin(\theta)$. Also for some values of $\theta$, $\sin(\theta)$ is not algebraic over $\mathbb Q$. Hence for such a value $\theta$, you can't express $\dfrac{1}{\sin(\theta)}$ as a $\mathbb Q$-linear combinaision of powers of $\sin(\theta)$.
Edit 2: (See Edit 3 for mistakes) The definition you gave in comments is the one for Q[sin(theta)]. It is only normal that you struggle to show that it is a field, because in fact it is a field if and only if $\sin(\theta)$ is algebraic over $\mathbb Q$, otherwise it's merely an integral domain. For example, if you take $\theta\in\mathbb R$ such that $\sin(\theta)=e^{-1}$, then knowing that $e^{-1}$ is not algebraic over $\mathbb Q$, then $\dfrac{1}{\sin(\theta)}=e\notin\mathbb Q[e^{-1}]$, because otherwise there exists a polynomial $P(X)$ with coefficients in $\mathbb Q$ such that $P(e^{-1})=e$, and by multiplying in both sides of the expression with a high enough power of $e$, you get $Q(e)=1$ for some polynomial $Q(X)\in\mathbb Q[X]$, which contradicts the transcendence of $e$ over $\mathbb Q$.
Edit 3: As Mark said in comment, the definition you gave doesn't even make the structure a ring, and the smallest ring containing it is $\mathbb Q[\sin(\theta)]:=\{P(\sin\theta)\mid P(X)\in\mathbb Q[X]\}$ where $\mathbb Q[X]$ is the ring of polynomials with coefficients in $\mathbb Q$. As for $\{a+b\sin\theta\mid a,b\in\mathbb Q\}$, all that can be said in a general matter about it ($\theta\in\mathbb R$ arbitrary) is that it is a $\mathbb Q$-vector space, of dimension $1$ if $\sin\theta\in\mathbb Q$, and $2$ otherwise.
Comment: Using the above identity only, I was successful in showing the extension, for specific values of $\theta$.
Comment: @Kumar I think it depends on how you understand what $\mathbb Q(\alpha)$ is for $\alpha\in\mathbb R$. Normally $\mathbb Q(\alpha)$ is by definition the smallest field containing $\mathbb Q$ and $\alpha$. Please see the edit above as to why you may struggle for some values of $\theta$.
Comment: Actually this is not even a definition for $\mathbb{Q}[\sin(\theta)]$. Let's assume it is a ring, then $\sin^2(\theta)$ has to be there. But then we can write $\sin^2(\theta)=a+b\sin(\theta)$, so $\sin(\theta)$ must be algebraic over $\mathbb{Q}$ with degree at most $2$. So if $\sin\theta$ is transcendental or even algebraic of a higher degree then $\{a+b\sin\theta:a,b\in\mathbb{Q}\}$ will not be closed to multiplication.
Comment: @Mark Woops you're right. Thank you for pointing that out! Gonna fix it.
Answer: $sin(\theta)=3sin(\theta/3)-4sin^3(\theta/3)$
so $[E_\theta:F_\theta]\leq 3$
to show that max = 3, let $\theta=30^\circ$
$1/2=sin(30^\circ)=3sin(10^\circ)-4sin^3(10^\circ)$
$8x^3-6x+1=0$ does not have rational roots by the rational root theorem, so it is irreducible.
$[E_{30^\circ}:F_{30^\circ}] = 3$
Comment: the question title is misleading; the crux of the qn is more like: what is the maximum value of the degree of the field extension?


Joining two streams

Question: Is it possible to join two separate PubSubIo Unbounded PCollections using a key present in both of them? I try to accomplish the task with something like:
Read(FistStream)&Read(SecondStream) -> Flatten -> Generate key to use in joining -> Use Session Windowing to gather them together -> Group by key then rewindow with fixed size windows -> AvroIOWrite to disk using windowing.
EDIT:
Here is the pipeline code I created. I experience two problems:

Nothing get's written to the disk
Pipeline starts to be really unstable - it randomly slows down processing of certain steps. Especially group by. It's not able to keep up with ingestion speed even when I use 10 dataflow workers.

I need to handle ~ 10 000 sessions a second. Each session comprises of 1 or 2 events, then needs to be closed.
<code>    PubsubIO.Read<String> auctionFinishedReader = PubsubIO.readStrings().withTimestampAttribute(TIMESTAMP_ATTRIBUTE)
            .fromTopic("projects/authentic-genre-152513/topics/auction_finished");
    PubsubIO.Read<String> auctionAcceptedReader = PubsubIO.readStrings().withTimestampAttribute(TIMESTAMP_ATTRIBUTE)
            .fromTopic("projects/authentic-genre-152513/topics/auction_accepted");

    PCollection<String> auctionFinishedStream = p.apply("ReadAuctionFinished", auctionFinishedReader);
    PCollection<String> auctionAcceptedStream = p.apply("ReadAuctionAccepted", auctionAcceptedReader);

    PCollection<String> combinedEvents = PCollectionList.of(auctionFinishedStream)
            .and(auctionAcceptedStream).apply(Flatten.pCollections());

    PCollection<KV<String, String>> keyedAuctionFinishedStream = combinedEvents
            .apply("AddKeysToAuctionFinished", WithKeys.of(new GenerateKeyForEvent()));

    PCollection<KV<String, Iterable<String>>> sessions = keyedAuctionFinishedStream
            .apply(Window.<KV<String, String>>into(Sessions.withGapDuration(Duration.standardMinutes(1)))
                                            .withTimestampCombiner(TimestampCombiner.END_OF_WINDOW))
            .apply(GroupByKey.create());

    PCollection<SodaSession> values = sessions
            .apply(ParDo.of(new DoFn<KV<String, Iterable<String>>, SodaSession> () {
                @ProcessElement
                public void processElement(ProcessContext c, BoundedWindow window) {
                    c.output(new SodaSession("auctionid", "stattedat"));
                }

    }));

    PCollection<SodaSession> windowedEventStream = values
            .apply("ApplyWindowing", Window.<SodaSession>into(FixedWindows.of(Duration.standardMinutes(2)))
                    .triggering(Repeatedly.forever(
                            AfterProcessingTime.pastFirstElementInPane()
                                    .plusDelayOf(Duration.standardMinutes(1))
                    ))
                    .withAllowedLateness(Duration.ZERO)
                    .discardingFiredPanes()
            );

    AvroIO.Write<SodaSession> avroWriter = AvroIO
            .write(SodaSession.class)
            .to("gs://storage/")
            .withWindowedWrites()
            .withFilenamePolicy(new EventsToGCS.PerWindowFiles("sessionsoda"))
            .withNumShards(3);

    windowedEventStream.apply("WriteToDisk", avroWriter);
</code>
Comment: Have you seen the JoinExamples at https://github.com/apache/beam/blob/master/examples/java/src/main/java/org/apache/beam/examples/cookbook/JoinExamples.java?
Comment: It sounds like your approach should work. What isn't working?
Comment: I've edited my post and provided more information on the problem. Are there some other ways of joining streams?
Answer: I've found an efficient solution. As one of my collection was disproportionate in size compared to the other one so I used side input to speed up grouping operation. Here is an overview of my solution:

Read both event streams.
Flatten them into single PCollection.
Use sliding window sized (closable session duration + session max length, every closable session duration).
Partition collections again.
Create PCollectionView from smaller PCollection.
Join both streams using sideInput with the view created in the previous step.
Write sessions to disk.

It handles joining 4000 events/sec stream (larger one) + 60 events/sec stream on 1-2 DataFlow workers versus ~15 workers when used Session windowing along with GroupBy.

Joining two streams


PostgreSQL insert select multiple column values

Question: I have a table with three columns:
Name Surname NameSuname
Bob  Marley  NULL
John Doe     NULL

I want to insert values from Name and Surname columns into NameSuname column. How can I do that?
Answer: You need to update the coumn instead of inserting
UPDATE MyTable
  SET NameSuname = Name || ' ' || Surname

Comment: Of course, you combine the 2 by using a trigger that fires after table insert, which will do the update for you, getting you back to the impression that you're only doing an insert. Plus it will be part of the same transaction, thus all fail or all succeed.


Como colocar 2 background-image sendo um deles semi-transparente

Question: Resumo:
Preciso colocar dois background 1 por cima do outro sendo que o que fica por cima deve ficar semi-trasparente de forma a aparecer o background debaixo e sem afectar os outros elementos da página background-screen2 background-screen1

 .background-screen2{
background-image: url("https://images.pexels.com/photos/949587/pexels-photo-949587.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500");
 background-size: auto;
 opacity:0.6
}

.background-screen1
{
     background-image:  url("https://definicao.net/wp-content/uploads/2018/10/significado-de-background-810x506.jpeg");
    background-size: auto;

}

Hello

Hello

Hello

Hello

Hello

Comment: Provavelmente você vai ter que utilizar duas div's, uma sobre a outra, estilizando o background de cada uma.
Answer: Não tem como aplicar opacidade ao background-image. Neste caso você poderia criar um pseudo-elemento ::before flutuante e aplicando a opacidade nele. É preciso também que todos os elementos dentro da div possuam position: relative para que o pseudo-elemento criado não fique por cima deles:

.background-screen{
   position: relative;
   background-image:  url("https://definicao.net/wp-content/uploads/2018/10/significado-de-background-810x506.jpeg");
   background-size: auto;
   color: white;
}

.background-screen *{
  position: relative;
}

.background-screen::before{
   content: '';
   background-image: url("https://images.pexels.com/photos/949587/pexels-photo-949587.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500");
   background-size: auto;
   position: absolute;
   width: 100%;
   height: 100%;
   top: 0;
   left: 0;
   opacity: 0.6;
}

Hello

Hello

Hello

Hello

Hello


Can this line be parallel with each other?

Question: A ,B,C,D are four points each four different planes. If we draw all the lines between the points , can some or all of them be parallel with each other?
Comment: it's a tricky question: if there are two parallel lines that contain all 4 points, all points are on the same plane.
Comment: I do not interpret this question as being that the four points must not be coplanar, just that they come from four distinct planes.  If you wish to ask the question where the four points may not be coplanar, then specify that.
Comment: all of them - no (i.e. $AD$ and $BD$ will intersect), some of them - possible
Comment: Is there any proof that they could be parallel?
Comment: A proof by example would work that some *could* be parallel (*but a proof by example does not prove that they MUST be parallel*).  If you have trouble visualizing such an example... consider looking at a cube and considering the planes that contain each of the respective faces.  You could pick the points from the planes such that the points form a square.
Comment: @JMoravitz agreed .. though that interpretation would make the planes irrelevant. We could find four such different planes even if $A=B=C=D$
Comment: consider the case where all four points are on the same line. you can draw four distinct planes perpendicular to the line thru each point.
Answer: It is possible to project 4 parallel lines from the 4 points on the first plane to each of the other 3 planes. With no restriction on the position of the points, this is easy to visualize.
Answer:
Every set of 3 non-collinear points define a plane, and if there is a set of 3 co-linear points then those 3 points and the fourth define a plane (unless those 4 points are collinear that is, then there are many planes containing all 4 points). So what you (probably) mean is

no set of 3 co-linear points, and every point not coplanar with the plane specified by the other 3 points.

Assuming the shaded: There are 6 lines specified here: the lines defined by $(A,B), (A,C), (A,D),(B,C), B,D)$, and $(C,D)$. Each line necessarily intersects with 4 other lines  e.g., $(A,B)$ intersects with the lines specified $(A,C),(A,D), (B,C), (B,D)$.

However, the line specified by $(A,B)$ is necessarily parallel to the line specified by $(C,D)$. Why?

Fact 1: Let $P$ be a plane and let $L$ be a line. If $L$ is not a line in $P$ then $L$ intersects $P$ at most once.

By Fact 1, the line specified by $(C,D)$ [as $D$ is not on the plane specified by $A,B,C$] intersects the plane specified by $A,B,C$ at exactly one point, namely $C$. However, the line defined by $(A,B)$ has every point in the plane specified by $A,B,C$ so if it were to intersect the line specified by $(C,D)$, it would do so at $C$. However, the line specified by $(A,B)$ does not contain $C$ because no 3 points are collinear.
Likewise the line specified by $(A,D)$ is necessarily parallel to the line specified by $(B,C)$, and the line specified by $(A,C)$ is necessarily parallel to the line specified by $(B,D)$.

The argument breaks down if there is a plane containing all 4 points, in fact if $A,B,C,D$ are 4 randomly chosen points on a plane then the line specified $(A,B)$ interscts the line specified by $(C,D)$, and likewise for the other lines.


Composition of function with linear functional is Lipschitz implies function itself is Lipschitz

Question: This is taken from Conway's A course in functional Analysis (p. 98, Exercise 9):
If $(S,d)$ is a metric space and $X$ is a normed space, show that if $f:S\rightarrow X$ is a function such that for all $L\in X^*$ (the continuous dual of $X$) $L\circ f:S\rightarrow\mathbb C$ is Lipschitz, then so is $f$.
I tried deriving the claim using the Uniform Boundedness Principle but it seems the wrong tool, for to apply it I somehow need to be looking at a Banach space and bounded operators from it. The natural choice seems to consider $X^*$ and $A_s\in\mathcal B(X^*,\mathbb C)$ given by $A_s(L)=L(f(s))$ for any $s\in S$, but both the fact that the Lipschitz constants can depend on $L$ and no obvious way of relating a bound on $||A_s||$ to $|f|$ make me a little bit puzzled.
Any pointer would be greatly appreciated, thanks!
Answer: Define $$A=\left\lbrace\frac{f(x)-f(y)}{d(x,y)}\colon x,y\in S \,, \, x\neq y \right\rbrace \subseteq X $$
then $A$ is weakly bounded.


How to crop an image into a circle with java?

Question: I really need some help with that.
I'm trying to crop an image into a circle and it's fine but the pixels outside the circle stay white. How can I put them transparent?
My code it's:
static ColorImage Circulo(ColorImage img, int radius) {
    for (int x=0; x < img.getWidth(); x++ ) {
            for(int y=0; y < img.getHeight(); y++) {
                if((x - (img.getWidth()/2)) * (x - (img.getWidth()/2)) + (y - (img.getHeight()/2) )* (y - (img.getHeight()/2)) <= (radius*radius)) {
                    img.setColor(x, y, img.getColor(x, y));
                }else {
                    Color c = new Color (255, 255, 255);
                    img.setColor(x, y, c );
                }
             }
        }
        return img;
    }

Comment: Typically the transparency is stored in the alpha channel, if the image format supports that.  You can try using `Color c = new Color(255, 255, 255, 0);`.  Keep in mind that 1) Only some image formats support an alpha channel and 2) Programs reading the image file are free to interpret the alpha channel in any way they choose, so some may use it for a bump map or something.  There's no sure fire way to make something transparent.
Comment: What image format is that?
Answer: If you want to crop the image and save as new image, then you can do this:
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.geom.Ellipse2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

public class ImageInCircle {
    Image img;
    public void cropImageIntoCircle(String imgFile) {
        try {
            img = ImageIO.read(new File(imgFile));
        } catch (IOException fne) {
            fne.printStackTrace();
        }
        int width = img.getWidth(null);
        int height = img.getHeight(null);

        BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
        Graphics2D g2 = bi.createGraphics();

        g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                RenderingHints.VALUE_ANTIALIAS_ON);
        int circleDiameter = Math.min(width,height);
        Ellipse2D.Double circle = new Ellipse2D.Double(0,0,circleDiameter,circleDiameter);
        g2.setClip(circle);
        g2.drawImage(img,0,0,null);
        try {
            ImageIO.write(bi, "PNG", new File("assets/" + imgFile.substring(0, imgFile.lastIndexOf(".")) + ".png"));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}

Similar to @WJS solution, but just a tweak on saving the image
Answer: Try this.  This will paint the image on the screen inside a circle.  If you want to create a new image, get the Graphics context from a BufferedImage and write the image to that instead of the graphics context in paintComponent. Any image format will work as this does not rely on any transparency mode of the graphics image.
The main idea behind this is setting the clip region to that of a circle.  Then whatever you paint will only appear in that region.
In this example, I made the diameter of the circle the minimum of the width and height of the image.  This way, the entire circle will fit in a rectangle.
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.RenderingHints;
import java.awt.geom.Ellipse2D;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;

public class ImageInCircle extends JPanel {
    JFrame f = new JFrame();
    Image img;
    int width;
    int height;
    static String imgFile =
             "location/of/image/img.gif";

    public static void main(String[] args) {
        SwingUtilities.invokeLater(()->new ImageInCircle().start());

    }
    @Override
    public Dimension getPreferredSize() {
         return new Dimension(width, height);
    }
    public ImageInCircle () {
        f.add(this);
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    }
    public void start() {
        try {
        img = ImageIO.read(new File(imgFile));
        } catch (IOException fne) {
            fne.printStackTrace();
        }
        width = img.getWidth(null);
        height = img.getHeight(null);
        revalidate();
        f.setVisible(true);
        f.pack();

        f.setLocationRelativeTo(null);
        repaint();
    }

    public void paintComponent(Graphics g) {
         super.paintComponent(g);
          setBackground(Color.white);
          Graphics2D g2 = (Graphics2D) g;

          g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                RenderingHints.VALUE_ANTIALIAS_ON);
          int circleDiameter = Math.min(width,height);
          Ellipse2D.Double circle = new Ellipse2D.Double(0,0,circleDiameter,circleDiameter);
          g2.setClip(circle);
          g2.drawImage(img,0,0,this);
    }

}


rtl in WpF Medinova template

Question: I am learning web designing in self-study fashion. As a practice, I am using the  WpF Medinova template freely availabe from here . My requirement is to include Arabic content and display it properly. I tried to change the CSS direction to rtl and float to right in the menu-area in the file style.css line 184.  But it does not work. While the Home should appear first, it appears at the end as if it is in English webpage. See this screenshot:
The word with three dots underneath should appear exactly in the firt position.
I would appreciate if you show me how to change the navigation menu direction to appear from right to left.
Comment: just try  to start from right
Comment: @Edison I tried but it did not work, though. Thanks for your comment.
Answer: Here is the solution how you convert LTR to RLT, just follow this link instruction, hope it will help..
https://codex.wordpress.org/Right-to-Left_Language_Support
Comment: Thank you so much for suggesting these magical tools. I used the CSSJanus and I got all the webpages displayed from right to left. Shukran Jazeelan!!

rtl in WpF Medinova template


Full Calendar color/textColor not working

Question: I am using Full Calendar with server-side processing.
PHP
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
  $event_array = array();

  $event_array['id'] = $row['id'];
  $event_array['title'] = $row['forename'] "" $row['surname'];
  $event_array['start'] = $row['start'];
  $event_array['end'] = $row['end'];
  $event_array['allDay'] = true;
  $event_array['color'] = $row['colour'];
  $event_array['textColor'] = "white";

  array_push($return_array, $event_array);
}

Problem
The color and textColor values are not having an effect on the calendar. I have read http://fullcalendar.io/docs/event_data/events_array/ and these are both valid options but I am not sure if I am using them correctly in the array.
$row['colour'] is the row in the database storing the colour value such as black.
Comment: look at the fullcalender link color and textColor add after the event array not in every event array
Comment: @ankurbhadania I need it per event.
Comment: see this question http://stackoverflow.com/questions/2441695/jquery-full-calendar-and-dynamic-event-colors
Comment: or you can try to add "className" http://fullcalendar.io/docs/event_data/Event_Object/
Answer: Solution
I used $event_array['className'] = $row['colour']; where row['colour'] returned for example black.
I then used:
.black div {
  background-color: black;
  border-color:     black;
  color:            white;
}

in CSS.
Answer: use like this.
    eventRender: function(info) {
        if (moment(info.event.end) < moment()){
            info.el.style.backgroundColor  = "#e3e3e3";
            info.el.style.borderColor ="#e3e3e3";
        } else {
            info.el.style.backgroundColor  = "#6a49fc";
            info.el.style.borderColor ="#6a49fc";
            info.el.style.color = "#ffffff";
          }
      },


ASP.Net can read SQLite database but can't insert in win 7

Question: I am using asp.net with sqlite database, I can read inserted records but can't insert records into sqlite database.
I faced with same problem in win vista and 7 with win app and I fixed by using Right Click->Run as Administrator.
Can I use asp.net to run as administrator.
I am using Windows 7.
Thanks,
Comment: Where do you keep your database? Not in program files, i hope?
Answer: Most likely your SQLite database file is in a folder that does not have write permissions for the account that your ASP.NET account is running under.


javascript getting hour and min from epoch value

Question: i am using the below code to get the hh:mm from epoch
 var dt = new Date(t*1000);
    var hr = dt.getHours();
    var m = "0" + dt.getMinutes();
    return hr+ ':' + m.substr(-2)

for below values:
1542895249079  prints: 19:37  Expected: 2:00 PM
1542897015049  prints: 6:10  Expected: 2:30 PM
1542902445344  prints: 2:35  Expected: 4:00 PM

I am sort of lost on this as the conversion values from above code looks totally weird to me.
Comment: what is `t` here?
Comment: t is timestamp retrieved from server
Answer: Two problems with your code:

For the example values you specified, there's no need to multiply by 1000 as they're already expressed in milliseconds.
If you want to leave local timezone information out of account, you have to use getUTCHours() and getUTCMinutes().

function convert(t) {
  const dt = new Date(t);
  const hr = dt.getUTCHours();
  const m = "0" + dt.getUTCMinutes();

  return hr + ':' + m.substr(-2)
}

console.log(convert(1542895249079));
console.log(convert(1542897015049));
console.log(convert(1542902445344));
Comment: Another issue was i was having t a string rather a number and i did the conversion and now it works good
Answer: Not what you need, but someone is useful to get a really quick approximation.
I use to process large amounts of intervals. Conversions would be painful.
Example: The epoch time 1621271327 as Monday, 17 May 2021 17:08:47 GMT
1621271327 % 86400 / 3600 => 17.14 // hours
1621271327 % 3600 / 60 => 8.78 // minutes
1621271327 % 60 => 47 // seconds


solving a calculus problem without the area-under-a-graph approach

Question: I am working through Kline's calculus book and am absolutely stumped by a certain problem (3.23). I have googled up solutions to it using the area-under-the-curve approach, but the book has not discussed graphs in the context of derivative and integrals yet, so they must be looking for more of an algebraic solution. Here's the problem:
A subway train travel over a distance (s) over (t) seconds. It starts from rest and ends at rest. At the first part of its journey, it moves with a constant acceleration (f) and in the second, with a constant negative acceleration (r). Show that s = [fr / (f+r)] t^2 / 2
I've tried working out the formula starting with acceleration being (f), then speed being (ft), and position (f * t^2 / 2), and using (x) to denote the point in time when acceleration becomes negative, and ended up with a formula that's similar to the one being asked for, but not an exact match. I have now exhausted my ideas on how to approach the problem, and would appreciate some help in deriving the correct answer without the use of graphs.
EDIT: According to the expected solution, we start off by looking at the first part of the journey, with acceleration a = f, velocity v = ft and position s = ft^2 / 2 . So far, so good. Then they look at the second part, with a = -r (deceleration), and v = -rt + C. In determining C, it is suggested that if we treat the length of the first part of the journey as x, then when t = x, v = fx, and C = (f + r) * x. This is where I get lost - why is r (the negative acceleration part of the second part of the journey) a part of the constant? Shouldn't C only relate the the first part of the journey - the accumulated, starting speed from which we are now decelerating? And even if somehow the presence of r is justified here, why is it positive?
They then go on with stating that
v = -rt + (f+r)x , and
s = -rt^2 / 2 + (f+r)xt + C.
When t = x, s = fx^2 / 2 . Then
C = -[t^2 / 2] * (f+r) [I am not understanding where this is coming from either - why is f suddenly replaced by (f+r)?]
When trip ends, V = 0 or
-rt + (f+r)x = 0
Now that t is specified
x = rt / (t+r)  [I did obtain the same result in my attempts as well, but by writing v = -r(t-x) + fx = -rt + rx + fx => if v=0, tr = rx + fx => x = tr/(f+r); r is negative because we are decelerating and (t-x) denotes amount of time elapsed since we started decelerating, with t being total trip time and x being time when deceleration started]
Then substituting t for x, they get
s = [fr/(f+r)]t^2 / 2
Overall, their solution seems much simpler then either my attempts or the solutions presented here, but I am having difficulty following the logic of it all the way through. I've contacted the publisher for permission to post a picture of their solution here.
Comment: Pay attention: for the second part of the journey, you need an integration constant (the initial position is no longer $0$ but the position reached after the first part of the journey).
Comment: By "first part of its journey", do you mean the first half of the distance, first half time, or something else?
Comment: @abcd123 I don't think it is any special kind of part. There are two parts to the journey, and that's it. Equal times or equal distance would mean basically $f=r$ and this problem becomes a bit more boring.
Comment: Presumably the velocity at the end of the first part of the journey matches that at the beginning of the next half (i.e., the velocity is continuous).
Comment: Yes, I worked (x) - the point in time when acceleration changes - out to be [ rt / (f+r) ] based on the 0 final speed, and added final part-1 speed (fx) to the second-part speed formula, and total distance traveled in part-1 (fx^2 / 2) to the second-part distance formula. Working out that final equation results in a somewhat-similar but different answer for me.
Comment: I have a (rather easy) solution with $s=\tfrac{fr}{r-f}t^2$ which does not agree with the "official" expression. Is it this one you find ? (assuming that $r<0$)
Comment: My latest attempt gave me $s=-\tfrac{r^2 t^2}{2 (f+r)}$ . I did figure out that a solutions manual may be requested from the publisher, which I just did. Hopefully, I'll hear back soon. Thank you, I appreciate you trying to help me with this - especially since it's not clear how detailed/confusing the manual is going to be with its solutions.
Comment: Don't we need the distance where the acceleration suddenly becomes negative?
Answer: The following figure

represents, on the same graphics 2 different curves (this is why the ordinate axis has no ticks):

the distance as a function of elapsed time; its curve (in red) is the union of two parabolic arcs with a common speed at their junction (red circle).

its derivative, the speed function ; its curve (in blue) is the union of two line segments meeting in a common point (blue circle) ; expressing the coordinates of this common point in two ways gives the following relationship :

$$T_1=\dfrac{r}{r-f}T_2\tag{1}$$
Besides, splitting the total travelled distance $s$ into

the distance $s_1$ travelled during the acceleration phase, i.e.

$$fT_1^2/2\tag{3}$$

the distance $s_2$ travelled during the deceleration phase, i.e.

$$-r(T_2-T_1)^2/2$$
(I have use for that formula (3) with elapsed time $T_1$ replaced by $(T_2-T_1)$ by symmetry); please note that $r$ being $<0$, we have taken $|r|=-r$),
gives
$$s=s_1+s_2=fT_1^2/2-r(T_2-T_1)^2/2\tag{2}$$
Taking (1) into account in (2) gives :
$$s=\dfrac{-fr}{f-r}\dfrac{T_2^2}{2}$$
in agreement with the formula you mention under the condition that $r$ is replaced by $-r$, i.e., taken with a positive sign.
Remark: the curves have been generated (with Matlab) by the following program
<code>  f=2;r=-3;
  t2=10;t1=r*t2/(r-f);
  t=0:0.01:10;
  g=min(f*t,r*(t-t2));
  plot(t,g);
  plot(t,3*cumsum(g)/1000,'r')
</code>
Comment: No comment ?...
Comment: I was trying to stay away from graphs in solving the problem, as the book has not yet gone into the graphical treatment of derivatives and integrals. However, a different graph-based approach does produce an answer that's identical to the official one: https://scienceanswers.wordpress.com/2012/10/03/problem-3-3-23-page-53/ . I am not sure which one is incorrect or where the difference is coming from in these two graph-based approaches. Please see my edited question for the official solution, which I still do not fully grasp.
Comment: Thanks for you comments and seriousness in your approach.
Answer: Can you use some standard kinematics equations?
$v(t) = at\\
s(t) = \frac 12 at^2  + v_0 t$
$v_0 = 0$
While the train is accelerating
$s(t) = \frac 12 f t^2\\
v(t) = ft$
until some time $t = \tau$
For the back half of the journey....
We will be using $t$ for the time after $\tau$ for the rest of the work.
$v(t + \tau) = v(\tau) - rt\\
s(\tau + t) - s(\tau) = v(\tau)t - \frac 12 rt^2\\
s(\tau + t) = \frac 12 f\tau^2 + (f\tau)t - \frac 12 rt^2$
The trip ends when $v(t + \tau) = 0$
$v(t + \tau) = v(\tau) - rt = 0\\
f\tau - rt = 0\\
t = \frac fr\tau$
We will substitute for $t$ into $s(\tau + t) = \frac 12 f\tau^2 + (f\tau)t - \frac 12 rt^2$ from above.
$s(\tau + \frac fr\tau) = \frac 12 f\tau^2 + (f\tau)\frac fr\tau - \frac 12 r(\frac fr\tau)^2\\
s(\tau + \frac fr\tau) = \frac 12 f\tau^2 + \frac {f^2\tau^2}{r}  - \frac 12 (\frac {f^2\tau^2}{r})\\
s(\frac {f+r}r\tau) = \frac 12 f\tau^2(1+\frac {f}{r})$
The total time will be $t^* = \tau +  {f}{r}\tau = \frac {r+f}{r}\tau$
Substitute $\tau = \frac {r}{r+f}t^*$
$s(t^*) = \frac {fr}{2(f+r)}t^{*2}$
Comment: This might actually be the solution I am looking for, since it agrees with the official solution and is not using graphs. I will review and try to work through this over the next couple of days, and will comment further then. Thank you!
Comment: I am able to follow until the $t = \frac fr\tau$ part (I used different notation to denote time, but obtained the same total S equation via integration), but I get lost after that point. I'll keep poking at it over the next couple of days and comment further then.
Comment: I added a little bit more detail in the steps.
Comment: I was able to work through your logic and confirm my own integration-based approach, which took a very similar form. Once I knew that the starting formulae were correct, I was able to concentrate on the calculation side of it (which did become a bit messy) and - voila - finally arrive at the same answer. I am still wondering if integrating the (s) formula further should've given us the sum total of distance traveled as well, but that's a different question, I suppose. Thank you for your help!
Answer: Note that the "constant negative acceleration" in the second part of the journey is not a negative number  $r$, but is $-r$ with $r>0$.
The journey of length $t$ is partitioned into two parts of time lengths $t_1$, $t_2$. We then have
$$t_1+t_2=t,\qquad ft_1=rt_2 \quad(=v_\max)\ .$$
Solving these equations for $t_1$ and $t_2$ gives
$$t_1={r\over f+r}\,t,\qquad t_2={f\over f+r}\,t\ .\tag{1}$$
On the other hand: With initial velocity $=0$ and constant acceleration $f>0$ (resp. $r>0$) you travel $f{t_1^2\over2}$ in time $t_1$, and  you travel $r{t_2^2\over2}$ in time $t_2$. Using symmetry with respect to $t\leftrightarrow -t$ and $r\leftrightarrow -r$ it follows that
$$f{t_1^2\over2}+r{t_2^2\over2}=s\ .$$
Inserting $(1)$ here we obtain
$$s=\left(f{r^2\over(f+r)^2}+r{f^2\over(f+r)^2}\right){t^2\over2}={fr\over f+r}\,{t^2\over2}\ .$$
Comment: $f{t_1^2\over2}+r{t_2^2\over2}=s$  - I understand the first part ($a_1=f$ => $v_1=ft_1+c$, where $v_1(0)=0$, so $c=0$ and $v_1=ft_1$ => $s_1 = ft_1^2 + c$, where $s_1(0)=0$ and so $c=0$). Why is the second part missing the other components though - shouldn't it follow the same logic: $a_2=-r$ => $v_2=-rt_2+c$, where $c=[maximum-speed-from-part1]=ft_1$, thus making $v_2= -rt_2 + ft_1$? And $s_2$ would then be $= -rt_2^2 / 2 + ft_1t_2 + c$, where c is the distance traveled in part 1 and thus $s_2 = -rt_2^2 / 2 + ft_1t_2 + ft_1^2 / 2$ ? What am I missing?
Comment: @CaptainPouches: The result is the same. See my update.
Answer: The most concise solution use the suvat equations $s=\frac{v^2-u^2}{2a},\,t=\frac{v-u}{a}$ for the two constant-acceleration legs. Let $V$ denote the greatest speed, achieved before changing the acceleration from $f$ to $-r$. The distance travelled is $s=\frac{V^2-0^2}{2f}+\frac{0^2-V^2}{-2r}=\frac{V^2}{2}(1/f+1/r)$. Similarly, $t=V/f+(-V)/(-r)=V(1/f+1/r)$. Comparing these,$$s=\frac{Vt}{2}=\frac{t^2}{2(1/f+1/r)}=\frac{frt^2}{2(f+r)}.$$In particular, no area- or diagram-based arguments were needed to prove $S=\frac{Vt}{2}$.
Comment: I was looking for more of a general integration-based approach (which I was able to deduce from the kinematics-based accepted answer) as opposed to relying on a specific formula, but I appreciate the help!
Answer: I will just try to fill in some details of the book's solution.
But first, a review of the names of the parameters.

A subway train travel over a distance ($s$) over ($t$) seconds. It starts from rest and ends at rest. At the first part of its journey, it moves with a constant acceleration ($f$) and in the second, with a constant negative acceleration ($r$).

The solution then proceeds (paraphrased):

we start off by looking at the first part of the journey, with acceleration $a = f,$ velocity $v = ft$ and position $s = \frac12 ft^2.$

This is easy to understand, and also at odds with the problem statement, where $t$ was defined to be the total trip time. The velocity cannot be $ft$ at any point during the first part of the trip, because the elapsed time during that period is always less than $t,$ the total elapsed time at the end of the trip.
Let's follow the practice that the names in the problem statement are "official." So if there is a naming conflict in the solution, the conflicting name in the solution must change. I'll use the Greek letter $\tau$ as the name of a variable representing any elapsed time in the range from $\tau=0$ to $\tau=t.$
With that change, the solution now says that during the accelerating part of the trip,

velocity $v = f\tau$ and position $s =\frac12 f\tau^2 .$

Proceeding ahead, using $\tau$ variable elapsed time,

Then they look at the second part, with $a = -r$ (deceleration),

OK, again a little confusion: the problem statement says $r$ is negative acceleration, but apparently the numeric value of $r$ is positive.

and $v = -r\tau + C.$ In determining $C,$ it is suggested that if we treat the length of the first part of the journey as $x,$ then when $\tau = x,$ $v = fx,$

So at $\tau=x,$ (at the instant when we change from acceleration to deceleration),
$v = fx$ because we have been accelerating at a rate $f$ for $x$ seconds.
But we also just said that $v = -r\tau + C$ during the second part of the trip,
including the instant when the second part starts, namely when $\tau = x.$
Plugging $\tau = x$ into $v = -r\tau + C$, we get $v = -rx + C$.
So now we have two ways to calculate the velocity at time $\tau=x.$
Since the train can have only one velocity at that time, the two ways must produce the exact same answer, that is,
$$ -rx + C = fx $$
with the first formula on the right and the second on the left.
Now solve for $C$:
$$ C = fx + rx = (f+r)x. $$
It's just plain algebra. But an intuitive reason why $r$ shows up in the constant is that the term $-r\tau$ causes a problem that needs to be fixed: at time $\tau = x,$
we have just started decelerating and have not actually decelerated at all yet,
so the deceleration rate $-r$ should not yet have affected the velocity.
But since $\tau = x,$ the term $-r\tau$ comes out to $-rx$, which is not zero.
In order to stop this from unbalancing the formulas, we need to cancel this term by adding $rx$ back into the formula somewhere.

They then go on with stating that
$v = -r\tau + (f+r)x ,$

This is the formula for velocity during the deceleration part of the trip,
$v = -r\tau + C,$ with the value of the constant $C$ that was just calculated.

and $s = -\frac12 r\tau^2 + (f+r)x\tau + C.$

This reuses yet another variable name: $C$ was already used as the name of the constant in $v = -rt + C$ and now is being used as the name of a different constant.
Let's use a different name:

and $s = -\frac12 r\tau^2 + (f+r)x\tau + C_1.$

So that's the formula for the position during the deceleration part of the trip.

When $\tau = x,$ $s = \frac12 fx^2 .$

This is because $\tau = x$ occurs at the end of the acceleration, so the position must be $s =\frac12 f\tau^2 .$
But again the train can have only one position at this time, so the formula for the position during deceleration has to come up with the same answer at the start of the deceleration as we got at the end of the acceleration.
When  $\tau = x$ the formula for the deceleration says
$s = -\frac12 rx^2 + (f+r)x^2 + C_1,$ so
$$ -\frac12 rx^2 + (f+r)x^2 + C_1 = \frac12 fx^2 .$$
Solve for $C_1$:
$$ C_1 = \frac12 fx^2 - \left(-\frac12 rx^2 + (f+r)x^2\right)
= -\frac12  (f+r)x^2. $$
Note: the constant is not $-\left[\frac12 t^2 \right] (f+r).$
It may be calculated using the square of the elapsed time $x$ to the end of the acceleration, but not the elapsed time $t$ at the end of the trip nor any other time.
Again, an intuitive reason why we need both $f$ and $r$ in the constant here is because the formula for $s$ during the deceleration has terms with $r$ that need to be canceled out (there should not be any accumulated effect of the deceleration $r$ already at the very start of deceleration), and it also has "too much $f$" ($fx^2$ when it should be only $\frac12 fx^2$).
So now the complete formula for the distance at any time during the deceleration part of the trip is
$$ s = -\frac12 r\tau^2 + (f+r)x\tau - \frac12  (f+r)x^2. $$

When trip ends, $v = 0$ or $-rt + (f+r)x = 0.$

Solving the last equation for $x,$
$$ x = \frac{rt}{f+r}, $$
which you can plug into the equation for the position during deceleration,
\begin{align}
 s &= -\frac12 r\tau^2 + (f+r) \left( \frac{rt}{f+r} \right) \tau
     - \frac12 (f+r)\left( \frac{rt}{f+r} \right)^2 \\
 &= -\frac12 r\tau^2 +  (rt) \tau
     - \frac12 \left( \frac{r^2}{f+r} \right) t^2.
\end{align}
At the end of the trip, $\tau = t,$ so we plug that in:
\begin{align}
 s &= -\frac12 rt^2 +  rt^2 - \frac12 \left( \frac{r^2}{f+r} \right) t^2 \\
  &= \frac12 rt^2 - \frac12 \left( \frac{r^2}{f+r} \right) t^2 \\
  &= \frac12  \left( r - \frac{r^2}{f+r} \right) t^2 \\
  &= \frac12  \left( \frac{ (f+r) r - r^2}{f+r} \right) t^2 \\
  &= \frac12  \left( \frac{fr}{f+r} \right) t^2.
\end{align}
If the book's solution really did use $t$ for two different things, then it would have been impossible to spell out the steps in this much detail.
This seems very confusing (and not technically correct) to me.
Comment: I was finally able to arrive at the same result after using an earlier answer as confirmation for my initial formula / approach. Thank you for the detailed review of the official solution - even though my initial question has been answered, I will be working through this over the next couple of days as well, to make sure I'm understanding the intricacies of mathematical reasoning at play here.


Como passar o this.state de uma tela para outra tela com React Native

Question: Galera, sou novo no React Native, o que eu quero fazer é pegar um this.state da tela 1 por exemplo e utilizá-lo na tela 2 para printar esse mesmo this.state. Fiz um exemplo bem grotesco para tentar explicar:
import React, { Component } from 'react';
import {
    View,
    Text,
    StyleSheet,
    TextInput,
    TouchableHighlight,
} from 'react-native';

export default class Inputs extends Component {
    constructor(props) {
        super(props);

        this.state = {
            num1: 0,
            num2: 0,
            resultadoSoma: 0,
        };

        this.calcularSoma = this.calcularSoma.bind(this);
    }

    calcularSoma() {
        let calculoSoma = 0;

        calculoSoma = parseFloat(this.state.num1) + parseFloat(this.state.num2);

        let s = this.state;
        s.resultadoSoma = calculoSoma;
        this.setState(s);
    }

    render() {
        return (
            <View>
                <TextInput
                 onChangeText={num1 => {
                     this.setState({ num1 });
                 }}/>
                <TextInput
                 onChangeText={num2 => {
                     this.setState({ num2 });
                 }}/>
                <TouchableHighlight activeOpacity={0.3} onPress={this.calcularSoma}>
                    <Text style={styles.textoBotaoContinuar}>CALCULAR</Text>
                </TouchableHighlight>

                <Text>RESULTADO: {this.state.resultadoSoma}</Text>
           </View>
        );
    }
}

Como pego esse
<Text>RESULTADO: {this.state.resultadoSoma}</Text>
e mostro ta tela 2?
Qualquer ajuda será de grande valor.
Answer: Para passar dados de uma tela para outra você poderá utilizar o componente react-native-navigation conseguindo de maneira bem simples passar os valores para a tela que deseja.
Exemplo de uso para este caso
Utilizando dois componentes (telas). Gostaríamos de passar o estado resutadoSoma da tela1 para a tela2
Componente que passa o valor(tela1):
this.props.navigation.navigate('tela2', {resultado: this.state.resutadoSoma})

Componente que recebe o valor(tela2):
this.props.navigation.state.params.resultado

Comment: Consegui passar os valores de uma tela para outra usando esse recurso do react-native-navigation. Muito obrigado :D


How to apt-get install a package for Ubuntu Quantal from Ubuntu Precise 12.04

Question: On Ubuntu Precise 12.04, the package osm2pgsql is currently at 0.70.5+r25090-2ubuntu2. However I need to install a newer version 0.80 but apt-get update does not provide the newer version.
Question: I found the 0.80 version in the Ubuntu quantal's repo at https://launchpad.net/ubuntu/+source/osm2pgsql/0.80.0+r27899-1ubuntu1, is there any way to install this when I'm on Ubuntu 12.04?
Answer: You can't install packages for one version of Ubuntu on another version, or more accurately, you REALLY shouldn't.
You will create a mess of dependencies that will need to be resolved, and can easily dig down so far into your system that you wind up with an unstable or unusable machine as a result.

If you need a particular version of some package you have three real options:

Upgrade the OS to a release that distributes and supports the version of the package you need.
Find someone who has packaged the software for your platform/version (check PPAs)
Build it yourself and assemble a package.
Comment: backporting quite often is as easy as adding a new changelog entry in debian/changelog.  or via dch.


Operation of complement and interior to open set

Question: Let $X$ be a topological space and $I$ is an open set in $X$. Let $E$ be its exterior, i.e. $E=\text{Ext}(I)=(X-I)^o$.
I assume that equality $\text{Ext(E)}=I$ holds but I cannot prove it.
It is the same as to prove that $I=I^{coco}$, where $*^c$ - operation of complement and $*^o$ - operation of interior.
I was able to show that $I^{coco}\subseteq I$ holds and it is quite trivial.
But how to prove the converse?
Would be grateful for help!
Comment: Do you mean *exterior* in the first line?
Comment: Ohh, thanks! Yes i meant exterior! Edited.
Answer: Note that $\text{Ext}(S) = \overline{S}^c$. Consider the open set
$$
U =\ ]-\infty, 0[ \ \cup\  ]1,2[\ \cup\ ]2,3[\ \cup\ ]4, + \infty[
$$
Then
\begin{align}
\overline{U} &=\ ]-\infty, 0] \ \cup\  [1,3]\ \cup\ [4, + \infty[ \\
\text{Ext}(U) = \overline{U}^c &=\ ]0,1[\ \cup\ ]3,4[ \\
\overline{\text{Ext}(U)} &=\ [0,1]\ \cup\ [3,4]  \\
\text{Ext}(\text{Ext}(U)) = \overline{\text{Ext}(U)}^c &=\ ]-\infty, 0[ \ \cup\  ]1,3[\ \cup\ ]4, + \infty[
\end{align}
Thus $\text{Ext}(\text{Ext}(U)) \not= U$.


Clock battery broken on Solaris - how to workaround until I can fix the battery

Question: My main Solaris server has an issue with its battery and thus I lose around 20 seconds per day.
Currently I am using rdate once in the morning to synchronise the time. Which approach should I use until I can change the battery on a weekend? Should I switch from rdate to ntp? The machine runs plenty of cronjobs and thus I need to ensure that everything is started even when the time is changed.
Answer: You should definitely run ntpd. Not only it automatically synchronizes with one or several servers, if you leave it running for a while, it calculates a correction factor for your hardware clock and can keep quite accurate time even if you lose connectivity to your time server(s).
The main issue with rdate however that it sets the correct time immediately. Suppose it's 10:30, but your server's clock shows 10:25. If you set the time, you effectively lose 5 minutes. NTP on the other hand adjusts time gradually.
Comment: To clarify that second comment: You (usually) want the time to be updated immediately at first, especially in your case where it's likely to be so incorrect.
So the init script for ntpd should run rdate once to "jump" to the right time and then run ntpd to keep it in sync.
Comment: Exactly, sorry I wasn't clear on that.


Inserir um valor em uma variável no formulário

Question: Tenho um cadastro de grupo e subgrupo.
Meu idGrupo está recebendo um valor e tenho que inseri-lo no formulário para ir no post.
<code>@Input() idGrupo: any;

configurarFormulario() {
    this.formulario = this.formBuilder.group({
      name: [null, Validators.required],
      groupItem: this.formBuilder.group({
         id: []
      })
    });
 }

  salvar() {

    this.service.postSubgroup(this.formulario.value);
    console.log(this.formulario.value);
   // console.log(`O id do grupo é esse: ${this.idGrupo}`);
  }
</code>
Ele deve enviar este json:
<code>{
    "name": "test", **<- Input que vou mandar no post**
    "groupItem": {
        "id": 1      **<- id que nao consigo enviar**
      }
}
</code>
Answer: Voce pode usar o spread operator do es6
<code>salvar() {
      this.service.postSubgroup({...this.formulario.value, id: this.idGroup});
}
</code>
Comment: Faltou eu passar a informação de como queria o json, mas já foi uma grande ajuda a resposta.
Answer: Meu código final ficou :
this.service.postSubgroup({
      ...this.formulario.value,
      groupItem: ({
        id: this.idGrupo
      })
    });


Stuck on this proof that $ord(f) = ord(g)$

Question: Let $f, g: \mathbb R \to \mathbb R$ be smooth maps such that $f(a) = g(a') = 0$ and let $\tau, \sigma : \mathbb R \to \mathbb R$ be diffeomorphisms such that
$$ \tau \circ f = g \circ \sigma$$
Define $ord(f) = \min \{ n \in \mathbb N_{>0} \mid f^{(n)} (a) \neq 0\}$.
I am trying to show that $ord(f) = ord(g)$. I wanted to do induction but the induction step is broken since $ \tau \circ f = g \circ \sigma$ does not imply that there are diffeomorphisms $\phi, \pi$ such that
$ \phi \circ f' = g' \circ \pi$
Next I thought I could derive a closed form for the $n$-th derivative of $ \tau \circ f = g \circ \sigma$ but I can't see a pattern. The sums get rather long.
Now I am starting to wonder whether the thing I'm trying to show is even true. If it is I think the proof should be short and simple very unlike what I've tried so far.

Does anyone have any ideas on whether this is true and if it is on how
  to prove it?
Answer: Let's begin with properly defining the function ${\rm ord}$. Given a sufficiently differentiable function $f: \>{\mathbb R}\to{\mathbb R}$ one defines
$${\rm ord\,}_a(f)=\inf\{n>0\>|\>f^{(n)}(a)\ne0\}\ .$$
Note that ${\rm ord}$ needs two inputs. In your question you introduced ${\rm ord\,}_a(f)$ but forgot to pin down the point $a_*$ at which ${\rm ord\,}_{a_*}(g)$ should be computed. This has to be the point $\sigma(a)$, because otherwise it is easy to give  counterexamples, e.g., the following:
Assume $a'\ne a$ and put $$f(x):=(x-a)^2, \qquad g(x):=(x-a)^2-(a'-a)^2,\qquad \sigma:={\rm id},\qquad \tau (x):=x-(a'-a)^2\ .$$
Then one has $\tau\circ f=g\circ\sigma$, $f(a)=g(a')=0$, but
$${\rm ord\,}_a(f)=2,\qquad {\rm ord\,}_{a'}(g)=1\ ,$$
since $g'(a')=2(a'-a)\ne0$.
(For this reason in my original answer I tacitly assumed $a'=\sigma(a)$ and then $a=a'=0$, which made $\sigma$ and $\tau$ diffeomorphisms with $\sigma(0)=\tau(0)=0$.)
Now the positive result: The function ${\rm ord}$ satisfies a sort of chain rule:
$${\rm ord\,}_a(g\circ f)={\rm ord\,}_{f(a)}(g)\cdot{\rm ord\,}_a(f)\ .$$
Proof. We may assume
$$a=f(a)=0,\qquad {\rm ord\,}_a(f)=p\geq1,\qquad {\rm ord\,}_{f(a)}(g)=q\geq1\ .$$
The following principle is an immediate consequence of Taylor's theorem:
$${\rm ord\,}_0(f)=m<\infty\quad\Longleftrightarrow\quad f(x)=x^m\bigl(\alpha+r(x)\bigr)\quad  {\rm with} \quad  \alpha\ne0, \ \lim_{x\to0}r(x)=0\ .$$
So there are constants $\alpha\ne0$, $\beta\ne0$, and  functions $x\mapsto r_1(x)$,  $y\mapsto r_2(y)$ with $\lim_{x\to0}r_1(x)=\lim_{y\to0}r_2(y)=0$ such that
$$f(x)=x^p\bigl(\alpha+r_1(x)\bigr),\qquad g(y)=y^q\bigl(\beta+r_2(y)\bigr)\ .$$
It follows that
$$g\bigl( f(x)\bigr)=x^{pq}\bigl(\alpha+r_1(x)\bigr)^q\bigl(\beta+r_2\bigl(f(x)\bigr)\bigr)=x^{pq}\bigl(a^q\beta+r(x)\bigr)$$
for some function $x\mapsto r(x)$ with $\lim_{x\to0}r(x)=0.\qquad\square$
Since diffeomorphisms $\sigma:\>{\mathbb R}\to{\mathbb R}$ have ${\rm ord\,}_a(\sigma)=1$ at all points $a$ your original conjecture, interpreted correctly, follows.
Comment: Wonderful, thank you. At least I now know that the statement is actually true!
Comment: Did someone downvote this answer? If so, why? Is it wrong?
Comment: When you say that $\sigma$ and $\tau$ are "diffeomorphisms near $0$", do you mean that $\sigma (0) = \tau (0) = 0$? I fail to see how you get this only from the hypotheses. As I have written in my own answer, if $\sigma (a) \ne a$ (you have taken $a = a'$) then the OP's statement is false. Strangely, you do not encounter this in your considerations.
Comment: @Alex M. : My answer was more general than the OP had in mind. Your editing has degraded it, but I left it at that. Assuming $a=a'=0$ is of course no restriction of generality. The OP wrote ${\rm ord}(f)$ instead of ${\rm ord\,}_a(f)$ (or similar) when defining the order of a zero.
Comment: Your assumption indeed does not restrict generality, but under it how do you prove $\sigma (0) = 0$ only from $\tau ( f (0) ) = g ( \sigma (0) )$ and $f(0) = g(0) = 0$?
Comment: Concerning the edit, I have only replaced $\Bbb R ^n$ by $\Bbb R$, otherwise the problem would no longer hold together ($g$ would be defined on $\Bbb R ^n$, while $f$ would be defined on $\Bbb R$, so you could no longer have $a = a'$, and plenty of other complications). If you find my edit abusive, please roll it back. Still, I think that it fixes things, not damages them. I am not a "professional downvoter", I just think that your proof omits some significant details.
Comment: @Alex M. : In my answer both $f$ and $g$ were defined on ${\mathbb R}^n$ (superfluously, of course). I had explicitly $\sigma:{\mathbb R}^n\to{\mathbb R}^n$ and $\tau:{\mathbb R}\to{\mathbb R}$. – That's my last word on this matter.
Comment: Dear Christian Blatter, many thanks for your answer. I am still studying it. Would you point me to a reference where I can read up on the $C$ you can find to bound the diffeomorphisms from below? It's not clear to me why it can be chosen to be greater equals $1$. The only thing that I do understand there is that because the diffeos are continuous they are bounded (on the closure of some open ball containing $0$).
Comment: @astudent: See the appendix to my answer.
Comment: Thank you! One more question: In the equation where you bound $g$ using $f$, isn't there a $\tau$ missing? It seems to me that since $g = \tau \circ f \circ \sigma^{-1}$ there should also be a $\tau$. But perhaps I am mistaken...
Comment: In the appendix I am trying to understand why $|\sigma' (x)|$ can be made $\le C$ on a suitably small neighbourhood. It seems to me that if $\sigma'$ was for example the function $-x^2 + 2$ then this would not hold. I'm now trying to figure out what I'm missing.
Comment: I got it: sorry, I didn't the factor of $2$ before the maximum. The other thing with $\tau$ is still not clear to me tough.
Comment: Thank you, I see you replaced the previous proof with a new proof (which at first glance appears neater). Just for the sake of my personal mathematical education I would still like to understand the inequality in the previous proof where you bound $g$ using $f$ and $C$. Concretely, my question remains as to whether $\tau$ is missing from that equation or not. Please would you be so kind as to tell me if the inequality indeed needed a $\tau$ or not?
Answer: First, you do not define $ord(g)$; I shall presume it to be like $ord(f)$
but with $a$ replaced by $a'$.
Second, your statement is true if and only if $\sigma(a) = a'$ (read the proof for $org(g) = 1$ to understand why).
Third, we shall make essential use of the following formula which generalizes Leibniz's formula:
$$(f_1 f_2 \dots f_n) ^{(p)} = \sum \limits _{i_1 + i_2 + \dots + i_n = p} \frac {p!} {i_1 ! i_2 ! \dots i_n !} f_1 ^{(i_1)} f_2 ^{(i_2)} \dots f_n ^{(i_n)}$$
(if you want, it is easy to prove it by induction).
Note that since $\tau$ is a diffeomorphism, we may invert it, getting $f = \tau ^{-1} \circ g \circ \sigma$.
Let us see what happens when $ord(g) = 1$ (i.e. $g'(a') \ne 0$). We have
$$f'(a) = (\tau ^{-1})' \circ g \circ \sigma (a) \cdot g' \circ \sigma (a) \cdot \sigma ' (a) = (\tau ^{-1})' (g(a')) \cdot g' (a') \cdot \sigma ' (a) = \\ (\tau ^{-1})' (0) \cdot g' (a') \cdot \sigma ' (a) .$$
Note that since $\tau ^{-1}$ and $\sigma$ are diffeomorphisms, their derivatives cannot cancel anywhere; since $g'(a') \ne 0$ by assumption, this gives $f'(a) \ne 0$, i.e. $ord(f) = 1$.
Now let us see the induction step: assume $ord(g) = n \ge 2$. We shall prove that $f^{(k)} (a) = 0 \; \forall k<n$ and $f^{(n)} (a) \ne 0$.
Note that
$$f^{(k)} (a) = (f')^{(k-1)} (a) = ((\tau ^{-1})' \circ g \circ \sigma \cdot g' \circ \sigma \cdot \sigma ') ^{(k-1)} (a) = \sum \limits _{i_1 + i_2 + i_3 = k-1} \frac {(k-1)!} {i_1 ! i_2 ! i_3 !} \big( (\tau ^{-1})' \circ g \circ \sigma \big) ^{(i_1)} \cdot \big( g' \circ \sigma \big) ^{(i_2)} \cdot \big( \sigma ' \big) ^{(i_3)} .$$
Now stop calculating and think: in the above sum, the only derivatives of $g$ showing up will be of order at most $k$, because $i_1$ and $i_2$ can go up to at most $k-1$. Since $ord(g) = n > k$, all these derivatives are $0$, from which follows $f^{(k)} (a) = 0 \; \forall k<n$.
In order to see that $f^{(n)} (a)\ne 0$ we shall use the same formula above, but with $k$ replaced by $n$:
$$f^{(n)} (a) = (f')^{(n-1)} (a) = ((\tau ^{-1})' \circ g \circ \sigma \cdot g' \circ \sigma \cdot \sigma ') ^{(n-1)} (a) = \sum \limits _{i_1 + i_2 + i_3 = n-1} \frac {(n-1)!} {i_1 ! i_2 ! i_3 !} \big( (\tau ^{-1})' \circ g \circ \sigma \big) ^{(i_1)} \cdot \big( g' \circ \sigma \big) ^{(i_2)} \cdot \big( \sigma ' \big) ^{(i_3)} .$$
The only non-zero term will be the one with $i_2 = n-1$ (which implies $i_1 = i_3 = 0$), which is $(g' \circ \sigma) ^{(n-1)} (a)$. Now, you either understand at a glance what happens here, or you can use induction once more to show that, in fact, this is equal to $( g^{(n)} \circ \sigma ) (a) = g^{(n)} (a') \ne 0 $ by assumption. Therefore, $f^{(n)} (a) = g^{(n)} (a') \ne 0$, so $ord(f) = n$.


Search for page title

Question: I want to search for page name.
I have a title of page news and events. if i search event. i want news and event page will come on search results. when i click on that news-events page will open.
Any idea how to do this?
Comment: What is the difference from the normal drupal search behaviour?
Comment: it doesnt show pages
Comment: your search yield no result or not displaying one particular content type in search result?
Comment: its not content type.. its page.. i need to search by title not content
Answer: Take a look at this one: https://www.drupal.org/project/search_by_page
Hope this is what you require.
Comment: this is not working

Search for page title


Prove that $T$ factors through $\pi$ if and only if $A\subset \ker(T)$

Question: Let $V$ and $W$ be vector spaces and $A$ a subspace of $V$. Suppose $T:V\rightarrow W$ is a linear transformation and let $\pi:V\rightarrow V/A$ be the canonical projection map. Show that $T$ factors through $\pi$ if and only if $A\subset \ker(T)$.
I've got the forward implication. I am having trouble with the suppose $A\subset \ker(T)$ and coming up with a suitable factoring function. Essentially I need a mapping $f:V/A\rightarrow W$ such that $T=f\circ \pi$. I've tried messing around with basis but I just can't seem to work out how $A$ being in the kernel of T lets me do anything. The closest I've come up with is,
\begin{align*}
f([\vec{k}]_A)=
\begin{cases}
\vec{0}_W,&\text{ if }\vec{k}\in A\\
T(\vec{k}),&\text{ if }\vec{k}\notin A.
\end{cases}
\end{align*}
But $f$ is not well defined on equivalence classes. Any help would be greatly appreciated.
Answer: Hint:
Define $f: \frac VA\to W$ by $f(v+A)=T(v)$.
Suppose $v+A=u+A$. Then $u-v\in A\subseteq\ker T$. So $T(v)=T(u)$.


How to access table cells from jquery

Question: Ok, I have a table which contains multiple rows. Each row contains some data and a hyperlink. When this link is clicked, I need to open up jquery's dialog form and let the user able to edit the data of the corresponding rows. So when the link is clicked, I need to access the values of the corresponding row cells from jquery.
How can I do that ?
Answer: Basic structure:
$("#tableId a").click(function() {
  var row = $(this).closest("tr");
  ...
  return false;
});

Inside that you can then access cells most easily by giving marker classes to your cells and then doing things like:
var total = row.children("td.total");

assuming a class of total.
Answer: cletus is right... but if you're just up to editing data cell, might as well use Jeditable

How to access table cells from jquery


How to display scrolling index for scrollController in flutter?

Question: I would like to display the index at the bottom of the listView by utilizing the scrollController, the same way it's displayed in the follow image :

After the user scrolls down, or scrolls up, the count on the left, highlighted by red, gets increased/decreased based on the scroll direction of the user.
What I want to achieve is to automatically update the displayed item's index, indicated by red on the picture. So whenever the user scrolls down or up, this index gets updated by the displayed item's index.
The picture shows that I have reached the 26th item. Whenever I scroll down or up, this index gets updated.
I have tried using the offset that is getting emitted for the scrolling event with no luck.
Answer: The way is using the scroll controller like you were doing.
You need to use a known item size and a listener.
<code>// Declaring the controller and the item size
ScrollController _scrollController;
final itemSize = 100.0;

// Initializing
@override
void initState() {
  _scrollController = ScrollController();
  _scrollController.addListener(_scrollListener);
  super.initState();
}

// Your list widget (must not be nested lists)
ListView.builder(
      controller: _scrollController,
      itemCount: <Your list length>,
      itemExtent: itemSize,
      itemBuilder: (context, index) {
          return ListTile(<your items>);
      },
),

// With the listener and the itemSize, you can calculate which item
// is on screen using the provided callBack. Something like this:
void _scrollListener() {
  setState(() {
    var index = (_scrollController.offset / itemSize).round() + 1;
  });
}
</code>
Adding a listener to a scrollController will call the callback provided every time the list is scrolled. You can handle many behaviours of the list using the same logic, including identifying the type of event that fired the listener, the direction of the scroll, etc.
Comment: Well I have used some different solution. I needed the equation to calculate the item size to increment the index.

One thing I found about your solution is that I don't know where _controller comes from, it would be more helpful if I knew its initialization.
Comment: Sorry, its all the same, controller is ScrollController. Im correcting the answer.
Answer: https://medium.com/flutter-community/create-shop-list-with-flutter-d13d3c20d68b
Maybe this one can help you. Also source code is available. A simple math about item height might help.


Finding the surface area $\iint_{s} f \, dS$ of $z=\sqrt{x^2+y^2}$ lying inside $x^2+y^2=x$

Question:
$z=\sqrt{x^2+y^2}$ is the surface we working on.
I am a bit stuck on choosing the limits for this problem, I have done the following:
$J(\text{jacobian})=\sqrt{Z^2_x+Z^2_y+1}=\left(\dfrac{x^2+y^2}{(\sqrt{x^2+y^2})^2}+1\right)^{\frac{1}{2}}=\sqrt{2}$
$$\iint_S f \, dS=\iint \sqrt{2} \, dz \, d\theta.$$

I can't explain why I chose $dz, d\theta$,  I guess since the one surface is bounded by $z$ and $x^2+y^2=x$ looks like the equation of a circle so $\theta$ :)
Anyway, I know that $z \left[0:\sqrt{x^2+y^2} \right] \rightarrow \left[0:r \right]$
and
$x^2+y^2=x\rightarrow r^2=r\cos(\theta)$, I tried to solve for $\theta$ from that but no luck. Please assist -Thanks.
I looked at this post here and it doesn't really address my issue.
Answer: No need to solve for $\theta$. Notice that $z$ is not an independent variable, thus not a good choice. Using $x = r \cos(\theta)$ and $y = r \sin(\theta)$ you obtain $z=r$. The length of the normal vector is $$\sqrt{ \left( \frac{\partial z}{\partial r} \right)^2 + \left( \frac{\partial z}{\partial \theta} \right)^2 + 1 } = \sqrt{2}.$$ The surface area is $$\iint_S dS = \iint_S \| {\mathbf r}_u \times {\mathbf r}_v \| \, dA.$$ Notice that this is not a Jacobian. Jacobians arise in changes of variable of the form $\mathbb{R}^2 \to \mathbb{R}^2$ or $\mathbb{R}^3 \to \mathbb{R}^3$. Since this is the graph of a function, the natural parameterization is $${\mathbf r} = (r \cos(\theta), r \sin(\theta), r).$$ The limits for $\theta$ are $0 \leq \theta \leq 2 \pi$ and for $r$ are $0 \leq r \leq \cos(\theta)$. Your area integral becomes $$\iint dS = \int_0^{2 \pi} \int_0^{\cos(\theta)} \sqrt{2} r \, dr \,d \theta.$$
Comment: @Ozwurld You can, it just may not be useful. And yes, the number of independent variables has to do with the dimension of the object you are dealing with. In this case the easiest method we could use to solve the problem involved letting $z$ be a dependent variable. Generally polar coordinates are only useful for objects with cylindrical symmetry.
Comment: $\theta=0 \rightarrow 2\pi$ because we have a full circle correct?
Comment: @Ozwurld Yes, that's correct. I've added more explanations to account for misconceptions in your post.
Comment: So should i always parametrize using independent variables?, and can i use $${\mathbf r} = (r \cos(\theta), r \sin(\theta)).$$
for functions that do not contain circular regions?


Migrate VMware Server to ESXi

Question: What's the recommended approach/tool to migrate VMs from VMware Server 1.0.7 (under Win2003 x64 Enterprise) to ESXi 4 ?
Some of the VMs are running Win2003 Enterprise x86, others run Ubuntu JeOS 8.04.
Answer: vmware converter will be the simplest way to do it. Once you have ESXi built and the vms copied to a location, just launch converter, you will be asked for the source machine then to give it a destination, that will be your ESXi server, then follow the steps, even if the import fails it will not affect your source vm.
Comment: +1 - This is the easiest way to do it. @mausch: It runs under Windows, but it will migrate any type of VM.
Comment: isn't vmware converter just for windows?
Answer: There is also a standalone, commercial version of Vmware converter. It is a boot CD (coldclone.iso) that you can use to convert a machine while it is off. The disc contains a pre-installed Windows 2003 image that runs a built-in version of converter. Since you boot from the CD, none of the server's processes start-up so you can get a good clone of the hard drive.
To be able to to download this CD image you need to be properly licenced.
Answer: VMWare Converter is the simple and easy way. If you have issues with a straight convert, I would suggest two other ideas:
Point the VMWare Converter at the live system and select convert physical machine.
Boot Ghost from Unix (or the cloner of your choice) inside of the VM, store the output to an external server, Create a VM in ESXi, boot from the cloner disk and download the image.
When I tried to upgrade using the VMServer files, the Converter kept crashing because it didn't like the linked clone VMs with multiple drives. I used the second method to due my first round of migrations and then when VMWare Converter 4.0 came out, I found that the first method started working for me.
Answer: Just and FYI the converted VM would not run.  I got an error about  a line in the VMX file.   Something about a variable having been already defined.  I had to delete the offending line to get the vm to run.
Just a heads up for those who might run into a similar issue.
Cheers,
Dave.

Migrate VMware Server to ESXi


D7 - hook_menu causes page duplicates

Question: I want to create a page that render a template (.tpl) file with this:
hook_menu
    $items['news'] = array(
    'title callback' => 'check_plain',
    'title arguments' => array('News'),
    'page callback' => 'theme',
    'page arguments' => array('news', array()),
    'access callback' => TRUE,
    'type' => MENU_CALLBACK,
);

hook theme
$items['news'] = array(
    'template' => 'templates/news',
);

All works well if i go to www.mydomain/news
But if i go to www.mydomain/news/aaaaa (that is a non existing page) i will see again the template page and not a 404 error page, why?
Is this a normal d7 behaviors and i need to fix this in a callback function?
...or i need to check into other code/modules that cause this bug ?
Answer: Yes, that's expected behaviour. From the hook_menu() docs:

If there is no other registered path that fits the requested path better, any further path components are passed to the callback function.

Here's the bug report that was closed as "works as designed":
https://www.drupal.org/node/1091068
Answer: You can use a wildcard in your hook menu item like this: $items['news/%'].
But why you are using theme function as a page callback? How do you handle loading news?
Please review this link: create .tpl file for a single custom page then you can load your news by EntityFieldQuery.

D7 - hook_menu causes page duplicates


Passar dois arrays para uma view no Kohana

Question: Preciso passar dois arrays para uma view, é possivel fazer isso?
Os arrays são criados da seguinte forma:
$cliente = ORM::factory('cliente')->where('id', '=', $id)->find();
$usuario = ORM::factory('usuario')->where('codCliente', '=', $cliente->id)->find_all();

Preciso passar o array $cliente e o array $usuario para a minha view, alguém sabe como posso fazer isso?
Answer: Assim:
$this->template->cliente = $cliente;
$this->template->usuario = $usuario;

Ou assim:
$this->template->content = View::factory('sua/view/aqui')
    ->bind('cliente', $cliente)
    ->bind('usuario', $usuario);

Neste caso (usando bind()) você está referenciando as variáveis em $this->template->content.
Comment: Obrigado amigo, funcionou


Why does $\text{dim } \text{null} A = 1$ lead to the fact that solutions of $Ax=b$ are multiples of a nonzero solution?

Question: I'm reading a textbook about linear algebra and there is a solved question that in some point came to $\text{dim } \text{null} A = 1$ and conclude that solutions of $Ax=b$ are multiple of a nonezero solution.
And in another one $\text{dim } \text{null} A = 2$ leads to the conclusion that there is no nonzero solution for $Ax=b$ that we can write other than solutions as a multiple of it.
The question is
Suppose a nonhomogeneous system of nine linear equations in ten unknowns has a solution for all possible constants on the right side of the equation. Is it possible to find two nonzero solutions of the associated homogeneous system that are not multiples of each other?
The answer
When $Ax=b$ has a solution for every $b$ in $\mathbb{R}^n$ then we conclude every row of the matrix has pivot positions, so $\text{dim } \text{row} A = \text{rank} A = 9$. According to a theorem we know, for every $m \times n$ matrix $\text{rank} A + \text{dim } \text{null} A = n$, so here $\text{dim } \text{null} A = 10 - 9 = 1$. The author then concludes that we cant find two solutions that are not multiple of each other.
Why is it that we can conclude this? How can we conclude this? (Using theorem or direct intuition is equally good).
Thank you guys
Comment: Are you talking about 3 dimensional systems here?
Comment: @DhanviSreenivasan not necessarily. I know a theorem that states $Rank A + dim Null A=n$ for anu m*n matrix A. So as i said , not necessarily.
Comment: I think maybe you've read them out of context.. could you provide more context?
Comment: @DhanviSreenivasan please check the question again.I edited it
Answer: You have a system such that $A \in R_{9,10}, x\in R^{10}, b \in R^{9}$
Now, if the system has a solution for every $b$, we can interpret this as there always is a way to express $b$ as a linear combination of the columns of the matrix $A$. Since this is true for any $b$, the columns of matrix $A$ must span the vector space of $b$, that is $R^9$
If we write $A$ as
$$A = [v_1 \space v_2 \space v_3 \space ... \space v_{10}]$$
Then we have a basis of $R^9$ among these 10 vectors, hence 9 are linearly independent (this is interpreted as having rank = 9)
WLOG, we can assume that these independent vectors are $v_1$ to $v_9$. Hence, we can express $v_{10}$ as follows
$$v_{10} = \sum_1^9\lambda_iv_i$$
Now, consider the homogeneous system $Ax = 0$.The solutions to thise all belong to the null space of $A$ from the definiton of the null space. Using the rank-nullity theorem, we have that the nullity is 1. Therefore, all vectors in this space can be written as a scalar time some base vector - hence all solutions are scalar multiples of each other


How do you update the default value for a field programmatically?

Question: How do you update the default value for a field programmatically?  I know you can get the field instance info by calling field_info_instance, but how do you update that info?
Answer: The field_update_instance() function is the standard method

Updates an instance of a field.

You can take the array returned by field_info_instance(), make your changes, then pass it back to field_update_instance() and the changes will be saved.
Comment: I literally searched for an hour to find that function, assuming such a thing existed.  Apparently I just suck at searching today.  Must be a carryover from Monday.  Thanks Clive.
Comment: I remember this (and `field_update_field()`) taking me ages to find too. They seem to be named intuitively enough but my brain didn't seem to agree when searching!


ggplot2 - change line width in function graph

Question: Say I have function like:
quad <- function(x)
{
    return (x^2)
}

That I plot using ggplot:
plot <- ggplot(data.frame(x=c(0,4)), aes(x = x)) +
        stat_function(fun = quad)

So far, so good, but the line is really thin. I thus add some specific geometry to the line:
plot + geom_line(size=2)

But it returns this error:

Error: geom_line requires the following missing aesthetics: y

How can I manipulate line geometry in this type of graphs?
Comment: You need `stat_function(fun = quad, size = 2)`.
Answer: After playing around a while I found out that an argument named size can be passed into stat_function. It has the same effect as gem_line:
plot <- ggplot(data.frame(x=c(0,4)), aes(x = x)) +
        stat_function(fun = quad, size=1.5)