How to set every data in my ES as non-analyzed?

Question: I have a lots of json data in form of json stored in a SQS queue. I have a python script which basically pulls the data from SQS and then indexes it to ES. The code snippet looks like :
doc = {
      "settings" : {
      "number_of_shards" : 1
       },
    "mappings" : {
             "_default_":{
                      "_timestamp" : {
                      "enabled" : 'true',
                      "store" : 'true'
                            }
                        }
              }
            }
es = Elasticsearch()
h = { "Content-type":"application/json" }
res = requests.request("POST","http://localhost:9200/"+index_name+"/",headers=h,data=json.dumps(doc))
post = es.index(index=index_name , doc_type='server' , id =1 , body=json.dumps(new_list))

So basically my search is not very effective and I read about https://www.elastic.co/guide/en/elasticsearch/guide/current/aggregations-and-analysis.html , I basically want to make sure ES doesn't break my data-objects into smaller chunks. What/How can i do to solve this issue ?
Comment: So you want to make every string field in your index as `not_analyzed`.
Comment: yes exactly , i have a lot of data in a central location and that can't be changed . what can be changed is this code which indexes in the ES .
Comment: You will have to re-index your existing data if you want to change the mapping.. Is that possible for you?
Comment: yeah i can.. probably change this source code with something along the lines of `"type": "string", "index": "not_analyzed"` , not sure if this is the right way of doing so
Answer: If you want every string field in your index becomes a not analyzed string you need to use Dynamic templates.
 PUT index_name
 {
 "mappings": {
  "type_name": {
     "dynamic_templates": [
        {
           "strings": {
               "match_mapping_type": "string",
              "mapping": {
                 "type": "string",
                 "index": "not_analyzed"
              }
           }
        }
       ]
    }
   }
 }

Comment: You will have to take backup of existing data, delete the index, create the index with new mapping and then move the data from backup to newly created index. Read https://www.elastic.co/blog/changing-mapping-with-zero-downtime
Comment: so, if i understand correctly this will only match for `string` and then map/convert them to string ? what does   `"match_mapping_type": "string",` this mean ?
Comment: By default all strings are `analyzed`. this will make all strings not_analyzed.Please note : ** This will not make any change in existing data**. You will have to reindex your existing data.
Comment: by reindex ; do you mean i have to delete my previous index and then reindex the data (new data) ?
Comment: i tried the code as you suggested but still i can see that these fields are analyzed . nothing seems to be changed
Comment: Have you created a new index with these `dynamic mappings`?
Comment: Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/106611/discussion-between-nishant-singh-and-richa).


A subspace of $\mathbb{R}$ is zero-dimensional iff it is totally disconnected

Question: A topological space (X, T) is zero-dimensional iff it has a basis consisting of clopen sets.
A topological space (X, T) is totally disconnected iff every non-empty connected subspace is a singleton.
I am wondering how we can show the right to left direction of following:
A subspace of $\mathbb{R}$ is zero-dimensional if and only if it is totally disconnected.
I already know how to show the left to right direction, using the fact that zero-dimensional Hausdorff spaces are always totally disconnected. But I cannot find a way to prove the other direction.
Thanks!
Comment: Yes, this equivalence holds in all ordered spaces. In general metric spaces these notions can differ a lot, though. There are even infinite-dimensional totally disconnected complete separable metric spaces.
Answer: Suppose that $X \subseteq \Bbb R$ is totally disconnected, i.e. has no non-singleton connected non-empty subsets.
Let $O$ be open in $X$, so $O = U \cap X$ with $U$ open in $\Bbb R$, and $x \in O$ aritrary.
Let $(a,b)$ be an open interval containing $x$ and such that $(a,b) \subseteq U$. Then there are points in $(a,x)$ that are not in $X$ (otherwise $(a,x)$ would be a non-trivial connected subset of $X$ which cannot be), so pick $p \in (a,x)\setminus X$. Likewise pick $q \in (x,b)\setminus X$. Then $(p,q) \cap X = [p,q] \cap X$ and this implies that $(p,q) \cap X$ is a clopen (in $X$) subset of $O$ that contains $x$, showing that the clopen subsets of $X$ form a base, i.e. $X$ is zero-dimensional.
Answer: HINT: Let $X\subseteq\Bbb R$ be totally disconnected. Show that $\Bbb R\setminus X$ is dense in $\Bbb R$, and use points of $\Bbb R\setminus X$ to define clopen sets in $X$.


In Activity.class want to get Spinner Item Text from Fragment.class

Question: im still confused about to get spinner item text.
So, In Activity.class i want to get Spinner Item Text from Fragment.class but idk how to get Spinner Item Text from fragment,
anyone can help?
Fragment.class
final Spinner spinner = (Spinner) rootView.findViewById(R.id.choices);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

            @Override
            public void onItemSelected(AdapterView<?> parent, View v,
                                       int postion, long arg3) {
                // TODO Auto-generated method stub
                String SpinerValue3 = parent.getItemAtPosition(postion).toString();

                if (SpinerValue3.equals("Item 1")) {
                    Toast.makeText(getActivity().getBaseContext(),
                            "Try Choose : " + SpinerValue3,
                            Toast.LENGTH_SHORT).show();=
                } else if (SpinerValue3.equals("Item 2")) {
                    Toast.makeText(getActivity().getBaseContext(),
                            "Try Choose : " + SpinerValue3,
                            Toast.LENGTH_SHORT).show();
                }else if (SpinerValue3.equals("Item 3")) {
                    Toast.makeText(getActivity().getBaseContext(),
                            "Try Choose : " + SpinerValue3,
                            Toast.LENGTH_SHORT).show();
                }else if (SpinerValue3.equals("Item 4")) {
                    Toast.makeText(getActivity().getBaseContext(),
                            "Try Choose : " + SpinerValue3,
                            Toast.LENGTH_SHORT).show();
                }else if (SpinerValue3.equals("Item 5")) {
                    Toast.makeText(getActivity().getBaseContext(),
                            "Try Choose : " + SpinerValue3,
                            Toast.LENGTH_SHORT).show();
                }else if (SpinerValue3.equals("Item 6")) {
                    Toast.makeText(getActivity().getBaseContext(),
                            "Try Choose : " + SpinerValue3,
                            Toast.LENGTH_SHORT).show();
                }

            }
            @Override
             public void onNothingSelected(AdapterView<?> arg0) {
                // TODO Auto-generated method stub

            }
        });

if above im explain for make a toast, but how to get text spinner item on Activity.class
Activity.class  Iwant to change SPINNERITEM (On code below) with get Spinner item text from Fragment
import android.app.Dialog;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.CheckBox;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.VolleyLog;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.NetworkImageView;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

public class RekomendasiExercise extends AppCompatActivity implements AdapterView.OnItemClickListener{

    // Log tag
    private static final String TAG = AbdominalFragment.class.getSimpleName();

    private static final String url = "http://........php";
    private ProgressDialog pDialog;
    private List<Exercise> exerciseList = new ArrayList<Exercise>();
    private ListView listView;
    private CustomListAdapter adapter;

    public RekomendasiExercise() {
        // Required empty public constructor
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_list);

        final ListView listView = (ListView)findViewById(R.id.list);
        final Spinner spinner = (Spinner) findViewById(R.id.choices);
        adapter = new CustomListAdapter(this, exerciseList);
        listView.setAdapter(adapter);

        pDialog = new ProgressDialog(this);
        // Showing progress dialog before making http request
        pDialog.setMessage("Loading...");
        pDialog.show();

        if(exerciseList.isEmpty()) {
            // Creating volley request obj
            JsonArrayRequest exerciseReq = new JsonArrayRequest(url,
                    new Response.Listener<JSONArray>() {
                        @Override
                        public void onResponse(JSONArray response) {
                            Log.d(TAG, response.toString());
                            hidePDialog();

                            exerciseList.clear();

                            // Parsing json
                            for (int i = 0; i < response.length(); i++) {
                                try {
                                    String text = spinner.getSelectedItem().toString();
                                    int positionitem = spinner.getSelectedItemPosition();

                                    JSONObject obj = response.getJSONObject(i);
                                    Exercise exercise = new Exercise();
                                    if (obj.getString("type").equals("SPINNERITEM")) {
                                        exercise.setNama(obj.getString("name"));

                                        exercise.setTipe(obj.getString("type"));
                                        exercise.setMainmuscle(obj.getString("mainmuscle"));

                                        exerciseList.add(exercise);
                                    }
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }

                            }

                            // notifying list adapter about data changes
                            // so that it renders the list view with updated data
                            adapter.notifyDataSetChanged();
                        }
                    }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    VolleyLog.d(TAG, "Error: " + error.getMessage());
                    hidePDialog();

                }
            });

            // Adding request to request queue
            AppController.getInstance().addToRequestQueue(exerciseReq);
        }else{
            hidePDialog();
        }

        listView.setOnItemClickListener(this);

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        hidePDialog();
    }

    private void hidePDialog() {
        if (pDialog != null) {
            pDialog.dismiss();
            pDialog = null;
        }
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View convertView, int position, long id) {
        // Create custom dialog object
        final Dialog dialog = new Dialog(this);

        // Include dialog.xml file
        dialog.setContentView(R.layout.dialog); // layout of your dialog

        // Set dialog title
        dialog.setTitle("Detail");

        // set values for custom dialog components - text, image and button
        TextView nama = (TextView) dialog.findViewById(R.id.nama);
        nama.setText("Nama = " + exerciseList.get(position).getNama());
        // similar add statements for other details

        dialog.show();
    }
}

Comment: Please include the code that you have so far (see [How to create a Minimal, Complete, and Verifiable example](http://stackoverflow.com/help/mcve)), this a) shows that you've not just fishing for someone to write code on your behalf and b) it would likely highlight more specifically about what is confusing and thus a more specific and helpful answer could be given.
Comment: Update my code for Fragment.class when im declare the spinner, but idk how to `get spinnet item text on` **Activity.class**
Comment: Tip on java terminology: You are editing java files that contain definitions of classes, not class files themselves
Comment: Instead of making a String, You can create a View which stores the selected view from the spinner and then use 'getText()' on that view
Answer: This is how you could do in OOPS ways
Step 1) Make a spinner Item Value variable in Activity Class
    public class RekomendasiExercise extends AppCompatActivity implements AdapterView.OnItemClickListener{

    private String currentSpinnerItem ;

    /*
     set current spinner item value
    */

    public void setCurrentSpinnerItem(String itemValue)
    {
    this.currentSpinnerItem  = itemValue ;

    //Do stuffs in activity with new value
    }

Step 2) Now in your fragment class update currentItemSpinner value like this
@Override
        public void onItemSelected(AdapterView<?> parent, View v,
                                   int postion, long arg3) {

            String SpinerValue3 = parent.getItemAtPosition(postion).toString();

    //Update spinner selected item value in activity
((RekomendasiExercise) getActivity).setCurrentSpinnerItem(SpinerValue3);
  }

Answer: My recommendation would be to follow the standard communication model for Activity and Fragment where the Activity implements a callback interface defined in the Fragment.
Check this link for details.
In your onItemSelected method of the spinner, you can call the callback method of the Activity with the selected spinner value.
Comment: im already follow from Android Developer, but can you explain it from my code ?
Comment: If you are already following the Android developer guide, then could you please post your code for the Activity where you have implemented the Fragment listener interface?
Comment: Update My code with Activity.class, in activity class you can see `SPINNERITEM` , and exactly this is place for me get spinnet item text from Fragment


Why does this sprite scale?

Question: Here's a very simple AS3 project consisting of one class which draws a rectangle. When I run it, the rectangle is clearly larger than 100x100 pixels.  After pulling out my hair for a few hours I thought I'd ask: why?
Edit: I know that it isn't correct because, though I have my screen resolution set to 1280x800, if I set the width to 500 it takes up almost all of my screen.
package
{
import flash.display.Sprite;
import flash.events.Event;

public class Draw extends Sprite
{
    private var screen:Sprite;

    public function Draw():void
    {
        this.addEventListener(Event.ADDED_TO_STAGE, stageHandler);
    }

    private function stageHandler(e:Event):void{
        screen = new Sprite();
        screen.graphics.clear();
        screen.graphics.beginFill(0x333333,.9);
        screen.graphics.drawRect(0,0,100, 100);

        screen.graphics.endFill();
        addChild(screen);
        trace(stage.width + "," + stage.height);
    }
}
}

:
Comment: It shows up as 100x100 for me when I run your code in a new SWF ([screenshot](http://i.stack.imgur.com/RUV51.png))... how large does your sprite scale to?
Comment: Hi - see my edit, above. If I set it to 500x500 it takes up almost all of my screen. Its width is closer to 1000. I'm running it in Flash Builder. Thanks, David.
Answer: Somehow your scalemode settigns for your flash player are set in a strange mode from FlashBuilder.
Try setting
stage.scaleMode = StageScaleMode.NO_SCALE;

in your stageHandler function. You code has no errors. The problem is in your publish preview settings somewhere.
Comment: Yeah, that's it, thanks. I don't know whether to be angry at myself for forgetting, or at Flash for requiring such an obvious setting.

Why does this sprite scale?


É possivel setar resolução Câmera Android?

Question: Estou desenvolvendo uma aplicação Android, e gostaria de saber se teria como fazer que a minha aplicação ao chamar a câmera passe os valores de resolução de Foto, ex: 1024 X 1024?
Comment: É possível setar resolução para vídeo também?
Answer: Nunca utilizei essa funcionalidade, mas já estudando outras funcionalidades da Câmera, vi que existia essa possibilidade.
Há um método em Camera.Parameters, que se chama setPictureSize (int width, int height), segue link da documentação da funcionalidade.
Exemplo de implementação:
Parameters parameters = camera.getParameters();
parameters.set("jpeg-quality", 70);
parameters.setPictureFormat(PixelFormat.JPEG);
parameters.setPictureSize(2048, 1232);
camera.setParameters(parameters);

Obs¹: Você só deve usar tamanhos de imagem que estão disponíveis a partir de getSupportedPictureSizes(). Usar qualquer outra coisa pode travar o aplicativo.

List<Camera.Size> sizes = parameters.getSupportedPictureSizes();

Obs²: Nunca utilizei está funcionalidade, mas na documentação diz que funciona.
Edit: Segundo @Gomes isso funcionou para o caso.
Comment: @Gomes, não esqueça que você tem que utilizar uma resolução entre as que retornarem no método `getSupportedPictureSizes()`, pois pelo que vi se você utilizar algo fora disso o aplicativo vai dar _crash_.
Comment: Vou verificar aqui, e tentar fazer desta forma


Apache VitualHost Proxy to Non-Stardard URL

Question: I have Apache2.2 and want to configure a virtual host such that a subdomain request gets content from a non-standard URL (site on another server), without rewriting the URL shown to the client in the browser. I want "sub.domain.com" to look and behave like "another.domain2.net:100/some/thing". Thus, requesting "sub.domain.com/test.php" should obtain content from "another.domain2.net:100/some/thing/test.php" How do I configure the VirtualHost to do that?
What I have so far:
<VirtualHost *:80>
    ServerName sub.domain.com
    ProxyPreserveHost On
    ProxyPass / http://another.domain2.net:100/some/thing/
    ProxyPassReverse / http://another.domain2.net:100/some/thing/
</VirtualHost>

When I request http://sub.domain.com, the URL in the browser that fails is shown as http://sub.domain.com:100/some/thing/. Looks like it is only replacing the domain name.
Comment: What you're trying to do is called a reverse-proxy. Check the [manual for mod_proxy](http://httpd.apache.org/docs/2.2/mod/mod_proxy.html#proxypass).
Comment: Yes, I have see that. It fails to display the page, appends :/ to URL shown in the browser.
Comment: That config seems mostly correct, in most cases `ProxyPreserveHost` should be switched off though.
Comment: Ah. I switched it off but to no avail. When I request `http://sub.domain.com`, the URL in the browser that fails is shown as `http://sub.domain.com:100/some/thing/`. Looks like it is only replacing the domain name.
Comment: That can have many reasons, what happens when you enter a longer url, e.g. `http://sub.domain.com/index.htm`  or whatever is correct?
Comment: With a long URL, it still fails the same way. I see in the browser: `Firefox can't establish a connection to the server at http://sub.domain.com:100.`, which I think is valid because the proxying server does not listen on port 100.
Comment: Is `http://another.domain2.net:100/some/thing/` reachable from your browser ? If not, what gives `curl -I http://another.domain2.net:100/some/thing/` from the fron-end server ?
Comment: Yes, in the same browser, `http://another.domain2.net:100/some/thing/` is reachable. I wonder whether this is a case when the URL should be re-written to make it conform?
Answer: Why use the proxy for this?
Have you tried mod_rewrite?
http://httpd.apache.org/docs/2.4/mod/mod_rewrite.html
I'm pretty sure it can rewrite the URL as you wish.


Vectors are a special case of matrices or it is other way around?

Question: I studied "vectors are special representation of matrices" but here on mathstackexchange many high rputational users say "matrices are special represtation of vector"
My Opinion is based on Manga book By Shin Takashi : "Vectors are special representation of matrices" Is an Introductory statement of vectors.Which i found very much true in many concepts of vectors like addition subtraction dot products and cross products.
Comment: Do you have a question and not a mere opinion you want to air?
Comment: Question must be ok now?
Answer: When people say 'vectors' what they mean is 'elements of a vector space'. Certain collections of matrices ($n$ by $n$ matrices over $\mathbb{R}$ for example) form vector spaces and hence the matrices in these spaces are 'vectors'.
The idea of such 'vectors' is much more general than that of matrices - the continuous functions (over a closed interval in $\mathbb{R}$, mapping to $\mathbb{R}$) is an infinite dimensional vector space. The function $f(x)=x^2$ is a vector in this space. How does this relate to a matrix however? In $\mathbb{R}^n$ we can write  a vector as a $1$ by $n$ matrix, however in this continuous function setting we can not write $f(x)$ as some 'restricted matrix'.
My guess is that your reason for thinking matrices are 'more general' is because as I wrote above, in $\mathbb{R}^n$, one can think of a vector as a $1$ by $n$ matrix. The point is that this idea doesn't generalise to more abstract settings. We can't always relate a specific matrix to a vector.
Comment: Yes, it's not a linear transformation; however, it is a vector in the vector space of continuous functions over a bounded interval.
Comment: f(x)=x^2  is not a linear transformation
Comment: So any function that is continuous on some [a,b] is a vector and element of vector space over R
Comment: Yes, any continuous function over $[a,b]$ can be considered as a vector in the vector space consisting of all such functions. Polynomials (over one variable) with coefficients in $\mathbb{R}$ can also be considered as a vector space. You can consider polynomials as vectors in this setting.
Comment: Why not write a continuous function as a column vector but with continuum many entries :)?
Comment: What would the entries represent?


expected value of multiplication of random matrices

Question: Suppose $X\in R^{n \times n}$ is a symmetric positive definite random matrix and $A\in R^{n \times n}$ is a symmetric constant matrix. how can I compute the below expression
$$
E[X^TAX]
$$
Answer: Write $X=[x_1\ x_2\ \cdots\ x_n]$ where $x_i$ are the columns vectors of $X$. Then, the $(i,j)$th element of the matrix $E(X^TAX)$ will be $$E(x_i^TAx_j)=E(Tr(x_i^TAx_j))=E(Tr(Ax_jx_i^T))=Tr(AE(x_j x_i^T))=Tr(AC_{ij})$$ where $C_{ij}$ is the cross correlation of $x_i,x_j$


Why are these two definitions of a connection equivalent?

Question: I'm working through Kai Köhler's "Differentialgeometrie und homogene Räume" (Differential geometry and homogenous spaces) and struggle to understand the notion of a connection on a vector bundle. In particular, I do not completely understand why two definitions are equivalent. The main definition that the author gives is the following:

Let $ E \to M$ be a vector bundle. A (covariant) connection $\nabla$ on $E$ is a $\mathbb{R}$-linear map $\nabla:\Gamma(M,E)\to \Gamma(M,T^*M \otimes E)$, that satisfies Leibniz's rule: $\forall f\in C^\infty(M),s\in \Gamma(M,E): \nabla(f\cdot s) = df \otimes s + f\nabla s$.

Apparently, it is equivalent to ask for $\nabla$ to be a map $\nabla:\Gamma(M,TM) \times \Gamma(M,E) \to \Gamma(M,E)$, that is $C^{\infty}$-linear in the first and satisfies the Leibniz rule in the second argument. Why does this hold? Also, what is a good intuition to think about $df \otimes s$ ?
Comment: [Related](https://math.stackexchange.com/questions/3114283/two-definitions-of-a-connection).
Answer: Let $X \in \Gamma(M, TM)$ and $s \in \Gamma(M, E)$.
If $\nabla$ is a connection according to the first definition, then we can produce $D$, a connection according to the second condition, by defining $D(X, s) := (\nabla s)(X)$ which is usually denoted $\nabla_Xs$.
Conversely, if $D$ is a connection according to the second definition, then we can produce $\nabla$, a connection according to the first condition, by defining $\nabla s := D(\cdot, s)$.

As for $df\otimes s$, note that $df \in \Gamma(M, T^*M)$ and $s \in \Gamma(M, E)$, so $df\otimes s \in \Gamma(M, T^*M\otimes E)$. Given a vector field $X \in \Gamma(M, TM)$, then $(df\otimes s)(X) = df(X)\otimes s = X(f)\otimes s = X(f)s$.
Comment: @Danny: Note that $D: \Gamma(M,TM) \times \Gamma(M,E) \to \Gamma(M,E)$, so for $s \in \Gamma(M, E)$, we have $D(\cdot, s) : \Gamma(M, TM) \to \Gamma(M, E)$. Therefore, given a vector field $X \in \Gamma(M, TM)$, we obtain the section $D(X, s) \in \Gamma(M, E)$.
Comment: But given $\nabla$ according to definition 1, how can we show $C^{\infty}$-linearity of $\nabla(s)$ or equivalently $\nabla(s)\in$Hom$(E,T^*M \otimes E)$?
Comment: I'm not exactly sure what you're asking. Note that $\nabla s \in \Gamma(M, T^*M\otimes E)$ not $\operatorname{Hom}(E, T^*M\otimes E)$. Also, $\nabla$ is not $C^{\infty}$-linear as $\nabla(fs) \neq f\nabla s$ in general.
Comment: There is a lemma in my book saying that for another bundle $F\to M$ we have that $P:\Gamma(M,E)\to \Gamma(M,F)$ $C^{\infty}$-linear $\Leftrightarrow P\in\Gamma(M,$Hom$(E,F))$. So I think one can consider it also as a map $\nabla(s)\in \Gamma(M,$Hom$(E, T^*M \otimes E))$ if pointwise it gives a linear map between fibres.
Comment: $\nabla$ is a map $\Gamma(M, E) \to \Gamma(M, T^*M\otimes E)$, not $\nabla s$. However, $\nabla$ is not $C^{\infty}$-linear, so $\nabla \not\in \Gamma(M, \operatorname{Hom}(E, T^*M\otimes E))$.
Comment: On the other hand, fixing $s \in \Gamma(M, E)$, the map $\nabla s : \Gamma(M, TM) \to \Gamma(M, E)$ is $C^{\infty}$-linear, so $\nabla s \in \Gamma(M, \operatorname{Hom}(TM, E))$.
Comment: I wonder why $\nabla s := D(\cdot, s)$ is well-defined. What do you put for the poistion at $\cdot$? Also $D(\cdot, s)\in \Gamma(M,E)$ while $\nabla s$ is supposed to be in $\Gamma(M,T^*M\otimes E)$. Do you just define $\nabla(s) := \sum_{i=1}^n dx^i \otimes D_{\frac{\partial}{\partial x^i}} s.$ with a local coordinate $x_1,...,x_n$?


Interval calculation (Eb-B#)

Question: I'm trying to name the interval Eb-B#.
We know that E-B is a perfect fifth. And by taking Eb-B, it becomes an augmented fifth. But what about Eb-B#? I cannot find a suitable name for this one.
Thank you in advance!
Comment: Eb-C would be a major 6th, so C# would be an augmented 6th
Comment: I am interested in Eb-B#. It was my fault mentioning the other one.
Comment: Highly related https://music.stackexchange.com/questions/99339/is-b%e2%99%af-to-f-an-impossible-interval.
Comment: Also related https://music.stackexchange.com/questions/102242/double-augmented-4th/
Answer: I would say Eb - B# is a doubly augmented fifth.
https://en.wikipedia.org/wiki/Interval_(music)#Example
The letter name distance says it's a fifth: E - F - G - A - B, five different letter names (staff positions).
You probably already knew this, but just for future readers: what you call the interval depends on what you call the notes. As you can see from the tables on the Wikipedia page, the proper name for an interval isn't unambiguously defined by the semitone distance alone. (Except if you call your interval by the number of semitones.)
In the interval naming convention, the presence of a diatonic scale with letter-named staff positions is assumed. Five positions means it's a "fifth".

In case there's a key signature, you take that into account, but still, the distance in staff positions decides if the interval is called a fourth, fifth, sixth, etc. In this example, the key signature declares that by default, B notes are flat.

...and for someone who doesn't know how the staff and accidentals i.e. natural/sharp/flat work, a couple more pictures. The pitch of each staff position can be modified with accidentals, which are sort of like three-position switches (not caring about rare cases like double-sharps/flats):

What's happened in the example case is, an E has been made flat and a B has been made sharp:

On a piano keyboard you would play the B# note with the same key as you'd use for C, but since it was called a B# and not a C by the person who wrote the notation, you take it as a B# and name the interval accordingly.
Answer: Start with the letter names - E-F-G-A-B. That's going to be a 5th - of some sort.
Drop the E down a semitone, the interval's an augmented fifth. If, instead, the B goes up a semitone, that's also an augmented fifth. So, by dropping E to E♭, and taking B to B♯, it's a double augmented fifth interval.
Which sounds exactly like a far more common major 6th.
Comment: Please explain what you felt was wrong with this answer.
Comment: No justification 2.5 yrs on - *because there is none*.

Interval calculation (Eb-B#)


Aceder à posição de um Transform numa lista em Unity

Question: Tenho uma lista de Transform que contém os SpawnPoints que tenho dentro do jogo, gostaria de encontrar para cada um dos SpawnPoints a sua posição.
<code>[SerializeField] List<Transform> spawns;
</code>
O problema consiste em dar Spawn aos carros se estiverem dentro dos limites da câmara, porém os SpawnPoints necessitam de estar fora para dar a ilusão que já nascem fora e não dentro. Como posso aceder à posição de cada SpawnPoint na lista?
<code>IEnumerator SpawnCars()
    {
        while (OnCamera==true)//enquanto os spawns estiverem dentro do ecra
        {
            yield return new WaitForSeconds(0.5f);//esperar um segundo para spawnar
            Instantiate(car, spawns[Random.Range(0, spawns.Count)].position, Quaternion.identity, transform);//spawnar o carro na lista de spawns
        }
    }
</code>
Answer: Olha, não sei se entendi a pergunta muito bem, porém se sim, eu te falaria para criar um foreach para percorrer a lista de Transform passando o position dela como parametro do instantiate.
<code>    IEnumerator SpawnCars()
        {
            while (OnCamera==true)//enquanto os spawns estiverem dentro do ecra
            {
                yield return new WaitForSeconds(0.5f);//esperar um segundo para spawnar
                foreach(Transform spawn in spawns){
                     Instantiate(car, spawn.position,Quaternion.identity,transform);//spawnar o carro na lista de spawns
                }
            }
       }
</code>


Ajuda - C++ Ler Arquivo e substi

Question: Boa noite pessoal
estou com uma dúvida em c++
preciso ler um arquivo e substituir alguns caracteres por outro e gerar um novo arquivo.
Alguém poderia me ajudar
Comment: Sim. Para isso, vá em [edit] e refaça sua pergunta colocando o código que já fez até agora, descreva as dificuldades encontradas, os erros que deram, liste aquilo que ainda falta fazer, descreva os resultados obtidos até agora, os resultados desejados e faça uma comparação entre ambos. Busque também elaborar um [mcve], ler o guia de [ask] e fazer o [tour] para aprender melhor o funcionamento do site. Se restar alguma dúvida, acesse a [help] e o [meta].
Comment: https://www.devmedia.com.br/forum/substituir-uma-sequencia-de-caracteres-em-c/505368 Isto te ajudaria?
Answer: Veja se isto ajuda.. (testado no onlinegdb)
<code>#include <iostream>
#include <string>
#include <fstream>
#include <streambuf>
#include <sstream> //std::stringstream
#include <boost/algorithm/string/replace.hpp>

using namespace std;

int main()
{

// CRIO O ARQUIVO
std::ofstream outfile ("test.txt");

outfile << "conteudo do arquivo!" << std::endl;

outfile.close();
//FIM DA CRIACAO DO ARQUIVO

//ABRE ARQUIVO
std::ifstream inFile;
inFile.open("test.txt"); //open the input file

std::stringstream strStream;
strStream << inFile.rdbuf(); //read the file
std::string str = strStream.str(); //str holds the content of the file

std::cout << str; //you can do anything with the string!!!

std::string s = str;
boost::replace_all(s, "arquivo", "ficha"); // REPLACE -> SUBSTITUI
//std::replace( s.begin(), s.end(), 'arquivo', 'ficha'); // replace all 'x' to 'y'

std::cout << s;
return 0;
}
</code>
teste do codigo
https://onlinegdb.com/B1vCwLOOV

Ajuda - C++ Ler Arquivo e substi


When to use the Product Rule with the Multivariable Chain Rule?

Question: Hello Math StackExchange,
I am struggling to understand the multivariate chain rule. I have been working on a problem in which I have been given $f=F(x^2 + y^2)$ and I need to find $f_x, f_y, f_{xx}, f_{yy}$.
I have been able to find the first derivatives only when I think about $f$ as the composition of $F(s)$ and $s(x,y)$. Then, it is apparent that
$$f_x = \frac{dF}{ds} \frac{\partial s}{\partial x} = 2x\frac{dF}{ds}$$ and
$$f_y = \frac{dF}{ds} \frac{\partial s}{\partial y}=2y\frac{dF}{ds}$$.
However, when I go to take the second partial derivatives, I get confused as to whether or not a function depends on a variable or not. I can write the operator: $$f_{xx} = \frac{\partial}{\partial x} \left({2x\frac{dF}{ds}} \right) $$
But, I am confused as to why I must use the product rule in the next step. I think that the notation is making me confused. Ultimately $F'(s)$ is a function of x, so changing $x$ will change the function, correct? As such, the product rule is needed. And $$f_{xx} = 2x\frac{dF_s}{ds} \frac{\partial s}{x} + 2\frac{dF}{ds}$$.
Solving problems of this form has been a struggle in the past. Earlier today, I spent entirely too long trying to find $z_x, z_t, z_{xx}, z_{tt}$ when $z =  f(x + t) + g(x-t) $ I had to first realize that the
coordinate" z was being used as a function $z(x,y)$ here. Then, taking the first partial derivatives are straight forward for me using the chain rule. However, the second derivatives make much, much less sense. I can see that $$z_{xx} = \frac{\partial}{\partial x} \left( \frac{\partial z}{\partial f} \frac{\partial f}{\partial x}+ \frac{\partial z}{\partial g} \frac{\partial g}{\partial x} \right) = \frac{\partial z}{\partial x}\left(z_f f_x + z_g g_x\right).$$ But, like the above problem, isn't $z_f$ ultimately a function of $x$ because $f$ is a function of $x$ as well? Would this require the use of the product rule too?
Is there something that I'm missing in my understanding of multivariable functions, the chain rule, and the product rule? This is all fairly muddy for me, concept-wise. Could I have some help understanding?
Thank you!
Answer: $$f=F(x^2+y^2)$$
$$f_x=\frac{\partial F(x^2+y^2)}{\partial x}=\frac{d F(s)}{d s}\frac{\partial s}{\partial x}$$
$$f_{xx}=\frac{\partial}{\partial x}\bigg(\frac{\partial F(x^2+y^2)}{\partial x}\bigg)=\frac{\partial}{\partial x}\bigg(\frac{d F(s)}{d s}\frac{\partial s}{\partial x}\bigg)=\frac{\partial}{\partial x}\bigg(\frac{d F(s)}{d s}\bigg)\frac{\partial s}{\partial x}+\frac{d F(s)}{d s}\frac{\partial}{\partial x}\bigg(\frac{\partial s}{\partial x}\bigg)$$
$$\Rightarrow f_{xx}=\frac{d^2 F(s)}{d s^2}\frac{\partial s}{\partial x}\frac{\partial s}{\partial x}+\frac{d F(s)}{d s}\frac{\partial^2 s}{\partial x^2}$$
$$\Rightarrow f_{xx}=\frac{d^2 F(s)}{d s^2}4x^2+\frac{d F(s)}{d s}2$$
Comment: In Short: $$\small\begin{align}f_{x} &= F_s\cdot s_x\\[1ex] f_{xx} &= [F_s]_x\cdot s_x+F_s\cdot s_{xx} \\[0ex] &= ~F_{ss}\cdot {s_x}^2+F_s\cdot s_{xx}\end{align}$$


How to change the background color of a JFrame dynamically?

Question: Hello i was wondering of how to change the background color of a JFrame dynamically as in this Website when you click on the button Ok, Let's Go and then select any option, the background change dynamically, i would like to do it, but using a JFrame. I was thinking on create a cicle to do it. If someone do knows how to do it, i'll be thankful
This is what i want:
Comment: Use a Swing Timer, and change r,g,b values in the timer will repainting every incremental change.
Comment: Could you please make an example?
Answer: YourJFrame.getContentPane().setBackground(Color.colorName);

Where "YourJFrame" is the name of your component and "colorName" is the name of one of the colors available in the Color class.
Comment: I know how to change the background color, what i don't know is how to change it dynamically, as in the gif example
Comment: I don't think that Java can do that alone. Check JavaFX or other libraries, maybe there's something there related to your problem.

Also, be sure to check:

http://stackoverflow.com/questions/21270610/java-smooth-color-transition and http://docs.oracle.com/javafx/2/api/javafx/animation/Transition.html
Answer:
Could you please make an example?

Below is an example switching from blue to green and green to blue. There's bug with the first click to green. And it's probably not the most robust code, but It's just an example that I'm too lazy to improve on right now. You can play with it
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.Timer;

public class ChangeColor {

    public ChangeColor() {
        JFrame frame = new JFrame();
        frame.add(new ColorPanel());
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }

    public class ColorPanel extends JPanel {

        private static final int DELAY = 30;
        private static final int INCREMENT = 5;
        private Color currentColor = Color.BLUE;
        boolean isBlue = true;
        boolean isGreen = false;
        private int r,g,b;

        private Timer timer = null;
        private JButton greenButton = null;
        private JButton blueButton = null;

        public ColorPanel() {
            r = 0; g = 0; b = 255;

            greenButton = createGreenButton();
            blueButton = createBlueButton();

            timer = new Timer(DELAY, new ActionListener() {
                public void actionPerformed(ActionEvent e) {

                    if (isBlue) {
                        if (b == 0) {
                            stopTimer();
                            enableButtons();
                        } else {
                            blueToGreen();
                            setColor(new Color(r, b, g));
                        }
                    }

                    if (isGreen) {
                        if (g == 0) {
                            stopTimer();
                            enableButtons();
                        } else {
                            greenToBlue();
                            setColor(new Color(r, b, g));
                        }
                    }

                    repaint();
                }
            });

            add(blueButton);
            add(greenButton);
        }

        public JButton createBlueButton() {
            JButton button = new JButton("BLUE");
            button.addActionListener(new ActionListener(){
                public void actionPerformed(ActionEvent e) {
                    if (currentColor != new Color(0, 255, 0)) {
                        System.out.println("turn blue");
                        isBlue = true;
                        isGreen = false;
                        diableButtons();
                        startTimer();
                    }
                }
            });
            return button;
        }

        public void diableButtons() {
            blueButton.setEnabled(false);
            greenButton.setEnabled(false);
        }

        public void enableButtons() {
            blueButton.setEnabled(true);
            greenButton.setEnabled(true);
        }

        public JButton createGreenButton() {
            JButton button = new JButton("GREEN");
            button.addActionListener(new ActionListener(){
                public void actionPerformed(ActionEvent e) {
                    if (currentColor != new Color(0, 0, 255)) {
                        System.out.println("turn green");
                        isGreen = true;
                        isBlue = false;
                        diableButtons();
                        startTimer();

                    }
                }
            });
            return button;
        }

        private void blueToGreen() {
            b -= INCREMENT;
            g += INCREMENT;
        }

        private void greenToBlue() {
            g -= INCREMENT;
            b += INCREMENT;
        }

        public void setColor(Color color) {
            this.currentColor = color;
        }

        public void startTimer() {
            timer.start();
        }

        public void stopTimer() {
            timer.stop();
        }

        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            g.setColor(currentColor);
            g.fillRect(0, 0, getWidth(), getHeight());
        }

        @Override
        public Dimension getPreferredSize() {
            return new Dimension(300, 300);
        }
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable(){
            public void run() {
                new ChangeColor();
            }
        });

    }
}

Comment: Hey, really thanks, but could you please explain me how to know what r,g,b int values should i use for other colours?
Comment: This is probably the simplest solution as the colors I chose are strictly 255. but with other colors, it gets more complicated. You're going to need to do some more logic. I don't really have the time to figure it out, but basically you have to figure out a stopping point based of the calculation. The way I'm doing it is probably not the best solution for it. The timer code will get very verbose. So you need to figure out the calculations and figure out how the increment each change while ensuring there is a stopping point for the change.
Answer: Add this to the actionListeners of your buttons
JFrame.getContentPane().setBackground(Color.colorName);
And change the colours at will.


Comando init e after_theme_support WordPress

Question: Alguém poderia me ajudar a entender a funcionalidade desses comandos no WordPress:
init

e
after_theme_support

Answer: Acredito que você quis dizer add_theme_support ou after_setup_theme ao invés de after_theme_support. Bom, lá vai:
O add_theme_support é uma função chamada geralmente no functions.php para adicionar componentes do tema.
add_theme_support('COMPONENTE_DO_TEMA', array('PARÂMETROS_DO_COMPONENTE','...','...'));
O after_setup_theme é um parâmetro usado na função add_action para que uma função execute assim que o tema termine de ser carregado, logo após a execução de functions.php. Geralmente usado para realizar configurações e mudar opções do tema.
add_action('after_setup_theme','SUA_FUNÇÃO_AQUI');

O init é um parâmetro também usado na função add_action, mas, diferente do after_setup_theme, ele executa uma função assim que o WordPress inicializa, mas antes dos headers serem enviados. Geralmente utilizado para inicialização de plugins.
add_action('init','SUA_FUNÇÃO_AQUI');

A grande diferença entre o after_setup_theme e o init é que na execução do init o usuário já estará devidamente autenticado.
Você pode procurar por mais detalhes na documentação do WordPress e exemplos de uso do init e do after_setup_theme no guia de referência de código do WordPress.


How to change color image to Black & White image in iOS 6.0?

Question: I am using the below code for convert black and white image. Its working fine. But I change the brightness and contrast of that image. App is crashed only on iOS 6.0. I am using any deprecated methods? Please help me. Change brightness and contrast using this link https://github.com/esilverberg/ios-image-filters
<code>- (UIImage *)convertImageToGrayScale:(UIImage *)image
{
    CGRect imageRect = CGRectMake(0, 0, image.size.width, image.size.height);
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceGray();
    CGContextRef context = CGBitmapContextCreate(nil, image.size.width, image.size.height, 8, 0, colorSpace, kCGImageAlphaNone);
    CGContextDrawImage(context, imageRect, [image CGImage]);
    CGImageRef imageRef = CGBitmapContextCreateImage(context);
    UIImage *newImage = [UIImage imageWithCGImage:imageRef];
    CGColorSpaceRelease(colorSpace);
    CGContextRelease(context);
    CFRelease(imageRef);
    return newImage;
}
</code>
Thanks in advance.
Answer: Check the following links for the list of deprecated methods
https://developer.apple.com/library/ios/#releasenotes/General/RN-iOSSDK-6_0/_index.html
http://www.bgr.com/2012/07/16/ios-6-download-beta-3-change-log/
https://developer.apple.com/library/mac/#releasenotes/DeveloperTools/RN-Xcode/_index.html


Installing java 1.7 runtime jre-7u4 in silent mode (with no user interaction)

Question: I would like to install jre-7u4-windows-i586.exe and jre-7u4-windows-x64.exe in "silent" mode (without any screens or prompts appearing).
With java 1.6, the command switches were
jre-6u21-windows-x64.exe  /passive "/qb ADDLOCAL=ALL"
which did a completely silent install ok.
With java 1.7,
jre-7u4-windows-x64.exe  /passive "/qb ADDLOCAL=ALL"
  does not work
jre-7u4-windows-x64.exe  /q   (or /qn)
  does not work
The installer runs, but prompts for confirmations.
Does anyone know if this feature is broken?  (by mistake or on purpose?)  Or if there are other switches to use with 1.7?
Answer: As I know in JRE7 /s means silent install mode, so you should try this:
jre-6u21-windows-x64.exe /s INSTALLDIR=DRIVE:\FOLDER...
Comment: The link is from the oracle site http://docs.oracle.com/javase/7/docs/webnotes/install/windows/jre-installer-options.html. But all other options after /s (silent) don't work as stated in their docs. So basically if you want to install silent in a non-default dir your out of luck.
Comment: That worked, woohoo, thanks!  The `INSTALLDIR=xxx` part is optional, it works with just `/s`.  If you have a web link where you got this info, please post it, in case others want to use additional options.


Inserting a string into another string

Question: I am working on iPhone app. I have the SQL query:
 NSString *myRed = [NSString stringWithFormat: @"%1.4f", slideR.value];

 [self insertData:@"INSERT INTO colour VALUES("+myRed+")"];

It produces syntax error. How to insert a string into string. That approach in Java would have worked.
Best regards
Answer: Try this :
NSString *myRed = [NSString stringWithFormat: @"%1.4f", slideR.value];

[self insertData:[NSString stringWithFormat:@"INSERT INTO colour VALUES(\"%@\")",myRed]];

If you don't want " then :-
[self insertData:[NSString stringWithFormat:@"INSERT INTO colour VALUES(%@)",myRed]];

Hope it helps you.
Answer: You could try writing your query and your string appended together before hand.
             NSString *str = @"Your values";
             NSString *query = [NSString stringWithFormat:@"INSERT INTO color VALUES(%@)", str];
             [self insertData:query];

Inserting a string into another string


Infinite Scroll com PHP array

Question: Tenho um array PHP com cerca de 10.000 chaves organizado assim:
Array
(
    [0] => Array
        (
            [id] => 13154
            [photo_file] => 013154.jpg
        )

    [1] => Array
        (
            [id] => 7885
            [photo_file] => 007885.jpg
        )
)

E no arquivo HTML tenho um loop que transforma o array em tags de imagens assim:
<?php
  foreach ($array as $key => $value) {
    $photo_file = $array[$key]["photo_file"];
    echo "";
?>

Eu queria criar um Infinite Scroll a partir deste array PHP para evitar carregar todas as imagens de uma só vez quando a página fosse acessada. Alguma idéia da melhor maneira de fazer isso?
Talvez eu pudesse converter o array PHP para JSON e depois para uma variável Javascript para usar JQuery?
Answer: Você pode carregar todo o array de uma só vez usando ajax (talvez com jQuery), o php (servidor) retornaria o array codificado em json, o javascript se encarregaria de ouvir o evento onscroll para exibir o conteudo no html.
Ou você pode usar outra abordagem, em que o php não retorna todo o array de uma vez só. Mas em vez disso retorna aos poucos, por exemplo, 10 indices por vez. Para isso, o cliente em javascript teria que mandar na requisição ajax o ultimo indice acessado e o servidor manipularia o restante.
Comment: Obrigado Juven, eu acabei adotando a segunda abordagem sua (LIMIT + AJAX + GET), mais clássica e com mais conteúdo. Para isso, adicionei uma condicional na query, pois antes estava usando PHP para filtrar os resultados e montar o array.

Infinite Scroll com PHP array


Clustering genes in a time course experiment

Question: I have seen a few queries on clustering in time series and specifically on clustering, but I don't think they answer my question.
Background: I want to cluster genes in a time course experiment in yeast. There are four time points say: t1 t2 t3  and  t4 and total number of genes G. I have the data in form a matrix M in which the columns represent the treatments (or time points)  t1 t2 t3  and  t4  and the rows represent the genes. Therefore, M is a Gx4 matrix.
Problem: I want to cluster the genes which behave the same across all time points t1 t2 t3  and  t4  as well as within a particular time point ti , where i is in {1, 2, 3, 4} (In case we cannot do both the clusterings together, the clustering within a time point is more important than clustering across time points). In addition to this, I also want to draw a heatmap.
My Solution:
I use the R code below to obtain a heatmap as well as the clusters using hclust function in R (performs hierarchical clustering with euclidean distance)
    row.scaled.expr <- (expr.diff - rowMeans(expr.diff)) / rowSds(expr.diff)

    breaks.expr <- c(quantile(row.scaled.expr[row.scaled.expr < 0],
                               seq(0,1,length=10)[-9]), 0,
                               quantile(row.scaled.expr[row.scaled.expr > 0],
                               seq(0,1,length=10))[-1] )

    blue.red.expr <- maPalette(low = "blue", high = "red", mid = "white",
                     k=length(breaks.expr) - 1)

    pdf("images/clust.pdf",
         height=30,width=20,pointsize=20)
    ht1 <- heatmap.2(row.scaled.expr, col = blue.red.expr, Colv = FALSE, key = FALSE,
      dendrogram = "row", scale = "none", trace = "none",
      cex=1.5, cexRow=1, cexCol=2,
      density.info = "none", breaks = breaks.expr,
      labCol = colnames(row.scaled.expr),
      labRow="",
      lmat=rbind( c(0, 3), c(2,1), c(0,4) ), lhei=c(0.25, 4, 0.25 ),
      main=expression("Heat Map"),
      ylab="Genes in the Microarray",
      xlab="Treatments"
      )
    dev.off()

I recently discovered hopach package in Bioconductor which can be used to estimate the number of clusters. Previously, I was randomly assigning the number of bins for the heatmap and cutting the tree at an appropriate height to get a pre-specified number of clusters.
Possible Problems in my solution:

I may be not clustering the genes within a particular treatment and clustering genes only across treatments or vice versa.
There may be better ways of obtaining a heatmap for the pattern I want to see (similar genes within a treatment and across treatments).
There may be better visualization methods which I am not aware of.

Note:

csgillespie (moderator) has a more general document on his website in which he discusses all the aspects of time course analysis (including heatmaps and clustering). I would appreciate if you can point me to an articles which describe heatmaps and clustering in detail.
I have tried the pvclust package, but it complains that M is singular and then it crashes.
Answer: In complement to @mbq's response (Mfuzz looks fine), I'll just put some references (PDFs) about clustering of time-course gene expression data:

Futschik, ME and Charlisle, B (2005). Noise robust clustering of gene expression time-course data. Journal of Bioinformatics and Computational Biology, 3(4), 965-988.
Luan, Y and Li, H (2003). Clustering of time-course gene expression data using a mixed-effects model with B-splines. Bioinformatics, 19(4), 474-482.
Tai YC and Speed, TP (2006). A multivariate empirical Bayes statistic for replicated microarray time course data. The Annals of Statistics, 34, 2387–2412.
Schliep, A, Steinhoff, C, and Schönhuth, A (2004). Robust inference of groups in gene expression time-courses using mixtures of HMMs. Bioinformatics, 20(1), i283-i228.
Costa, IG, de Carvalho, F, and de Souto, MCP (2004). Comparative analysis of clustering methods for gene expression time course data. Genetics and Molecular Biology, 27(4), 623-631.
Inoue, LYT, Neira, M, Nelson, C, Gleave, M, and Etzioni, R (2006). Cluster-based network model for time-course gene expression data. Biostatistics, 8(3), 507-525.
Phang, TL, Neville, MC, Rudolph, M, and Hunter, L (2003). Trajectory Clustering: A Non-Parametric Method for Grouping Gene Expression Time Courses with Applications to Mammary Development. Pacific Symposium on Biocomputing, 8, 351-362.

Did you try the timecourse package (as suggested by @csgillespie in his handout)?
Comment: The `timecourse` package isn't really for determining clusters, rather it's for calculating which genes are differentially expressed.
Comment: @csgillespie (+1) Thanks. I thought it might be used to isolate genes with varying temporal profiles across biological conditions, or as a first step before using a clustering procedure (in fact, I was thinking of `kml` but I'm not really an expert in that domain).
Comment: You are correct in that you would tend use to isolate interesting genes before any clustering - basically thin down your list of genes. I suppose it does perform clustering of a sort, i.e.differentially expressed vs non-differentially expressed.
Answer: It seems you just want to make a fair standard analysis, so I am not a best person to answer your question; yet I would suggest you to dive deeper into Bioconductor; it has a lot of useful stuff, nevertheless finding what you want is painful. For instance Mfuzz package looks promising.
Comment: There's also an example of using Mfuzz in my [tutorial paper](http://www.mas.ncl.ac.uk/~ncsg3/microarray/)
Answer: Just to add to the other answers (which look like they should solve your problem), did you try using standard clustering algorithms for you data when constructing your dendrogram? For example,
heatmap.2(dataset, <standard args>,
          hclustfun = function(c){hclust(c, method= 'average')}
          )

Instead of using the average distance for clustering, you can also use "ward", "single", "median", ... See ?hclust for a full list.
To extract clusters, use the hclust command directly and then use the cutree command. For example,
hc = hclust(dataset)
cutree(hc)

More details can be found at my webpage.
Comment: @suncoolsu: I've updated my answer. Does that help?
Comment: . Yes, but one of the difficulties I had was in extracting the clusters from the heatmap.2 object. Is there an easy way of extracting the clusters? I am aware of the `cutree` command which can be used to extract clusters from the heatmap.2 object.


Do the intervals in a chord determine its sound?

Question: For example, in a C Major chord of (C, E, G), I have the intervals of:

A Major Third (C, E)
A Perfect Fifth (C, G)
A Minor Third (E, G)

In a C Minor chord (C, Eb, G), I have intervals of:

A Minor Third (C, Eb)
A Perfect Fifth (C, G)
A Major Third (Eb, G)

So I have the exact same intervals, but it sounds very different. Is this because the intervals involving the root note carry more importance, or does it have nothing to do with the intervals?
Comment: I'm trying to find pretty well a duplicate of this that I posed some time ago. Bear in mind sad/happy is very subjective.
Comment: There is definitely a good dupe - I think that is your one @Tim. There are also a number of questions like this that are closed as opinion based (due to the whole sad/happy being entirely subjective). If you can find the good one, I'd rather close as dupe.
Comment: Yes, I was wondering about subjective happiness as well. Maybe they should sound as happy as each other theoretically, but because of the way music is usually composed, we think of it as sad. But that seems pretty unlikely.
Comment: @DoktorMayhem - 'Theory of major and minor chord sounds', I reckon.
Comment: Aaron's answer looks useful. If we close as a dupe can we merge his answer into another post?
Comment: The question was asked, was useful enough to be answered, and drew some good answers.  I say just leave it alone. :D  Also, @OctopuSS7, I recommend learning about the "overtone series."  That will explain a lot, I think.
Comment: What instrument and how is it tuned?  On a modern piano, the distance between notes is a constant and it shouldn't change the character of a chord all that much to transpose it up or down.  But on some instruments/older pianos (or those just using other temperaments), the further you get away from the key of C major, the more out of tune it will sound.  This is due to perfect octaves not quite lining up with perfect fifths mathematically.  Modern instruments tend to split the difference in favor of octaves, but this wasn't always the case.
Answer: Sounds are perceived according to their relationships with other sounds — so ... intervals. And intervals are perceived — and defined — according to the lower pitch.
Given the example of major and minor chords, while they contain the same (unordered) collection of intervals, the order is important, and it's clear that the defining relationship in terms of chord quality (major vs. minor) is between the third and the root — when the chord is in root position.
This is borne out by the fact that a common difficulty in ear training is distinguishing the quality of a first inversion chord. First inversion major chords are often misinterpreted as minor, and minor chords as major, because of the interval against the lowest pitch.
So, the root of the chord is critical in defining its sound, but experience suggests that the lowest pitch is even more important until one is trained to perceive the root regardless of its position in the chord.1

Historical aside
It's worth noting that there is significant historical precedent for defining harmony in terms of the lowest pitch. Prior to and concurrent with the development of Tonality, figured bass notation, for example, defined harmony in terms of intervals above the bass. Further, Rameau's theory of harmony based on thirds, which is now the predominant understanding of chords, stemmed from the idea of a "fundamental bass" -- an idea that became understood as the "tonic".

Note
1 As @piiperiReinstateMonica points out in the comments as well as an answer to the OP, the location of the root of the chord is most clearly signaled by the presence of the fifth (in root position) or fourth (in first or second inversion). In ear-training courses, learning to find this interval within the chord, and to identify whether the lower or upper note is the root (i.e., whether it's a fifth or fourth, respectively), is essential to overcoming the initial difficulty created by hearing, for example, a minor third at the bottom of a major triad (i.e., a first inversion triad).
Comment: So many of my students at some point in their development, said that while they used to just enjoy listening (ignorantly, if you like) to music, they then listened with very different ears. Far more technically. Which from certain aspects, is a shame. Someone once said 'ignorance is bliss' - too true...
Comment: Does this mean that a chord can sound very different to someone with good ear training, compared to a normal person? And would that mean that playing an intrument could change how you hear music?
Comment: @OctopuSS7 In short, yes. Ear training, even without playing an instrument, can greatly impact one's perception of music; playing an instrument can also advance that.
Comment: This being the accepted answer, one aspect about intervals in chords is worth adding, and this may not be obvious: the upper note of perfect fourths, and the lower note of perfect fifths gets extra weight as a root candidate. C - G is a fifth -> C is the root. Swap the notes the other way: G - C is a fourth -> C is still the root. This can be tried by playing G - C - E, which hopefully gets identified as a C major, and then G - B - E, which should identify as an E minor. In G - B - E, the B - E interval points at an E root, but in G - C - E, the G - C interval points at C being the root.
Comment: @piiperiReinstateMonica That's a good point. I've added a note and would appreciate your feedback on whether or not it works.
Comment: At least it's mentioned now, so if someone starts to look for theoretic patterns in chords, perfect fifths and fourths are among the patterns. The ear training aspect is completely foreign to me. I find it strange that ear training would change the behavior of basic phenomena such as perfect fourths/fifths, which I would intuitively assume as being related to the primitive perception of "are the sound waves coming from one or several sources", like harmonic partials. And I guess that even untrained people hear the Smoke on the Water riff as being in G, not in D, even before the bass comes in.
Answer: You don't have the exact same intervals... above the bass.
You don't want to just list the intervals and then mix up the order and say it's all the same.
Traditional harmony puts the intervals in relation to the bass (or you could say in relation to the chord root, it's not the same but we can skip over that.)
C major is a major third above the bass and a perfect fifth above the bass.
C minor is a minor third above the bass and a perfect fifth above the bass.
The interval qualities do determine the sound:

Because of the perfect fifths above the bass the chords are either major or minor triads, specifically they are not diminished or augmented triads where a diminished fifth or augmented fifth would define those chord types. You might categorize the major & minor triads as perfect triads, and the ones with diminished/augmented fifths as imperfect or altered triads, but while logical those aren't standard terms.
The quality of the third determines whether the "perfect" triad is major or minor.
Answer: The intervals in a chord do define what the chord sounds like and how it functions or operates, but the intervals are felt in relation to a root note. (And as explained later, in relation to a tonic) Where does the root come from? Perfect fifths and fourths have a special role in pointing to a possible root. In addition to that, whatever is the lowest note i.e. bass, is a dimension in the chord, but it's not the same thing as root. G - C - E does work as a C major chord, but if you're expecting C as the tonic, home note, then G - C - E doesn't feel as much like being home as C - E - G.
The C - G interval in both of your example chords is a perfect fifth (or fourth if it's G - C) point to C being a possible root, and the "third", E or Eb, is felt in relation to that. It doesn't matter which of the notes is higher, C or G, the interval points to C being a root. G - C - E is a C major chord, because G - C points to C being a root. But if we move C down a half step: G - B - E, then the root-defining fifth/fourth is B - E, which points to E being a root, and the G makes it an E minor.
If there are no fifths or fourths, then the bass note has more weight in defining the root. C - D - E would be some kind of a C major chord, but C - D - Eb is some kind of a C minor chord. But E - C - D? At least it's not E minor or E major.
One more thing that affects how notes in chords are perceived is the tonic, the expected home base note. For example if you heard your example chords after having established Bb as the tonic, it would make you feel different about them compared to if, say, C was the tonic.
It's possible to have several fourths or fifths in a chord, and then the effect or "meaning" of the chord comes even stronger from your expectations. What is a G - C - F chord, is it a Csus4 waiting for the F to resolve down to E, or G7sus4 without a fifth waiting for the C to resolve down to B? Or maybe "F sus2", not waiting for any resolution that much? What it feels like depends on what you expect. Even rhythmic placement in a phrase or other longer structure has a role in setting expectations. You can experiment with this by establishing a tonic by playing a cadence. For example, establish F major by playing the chords F, Bb, C7, F. What does a G - C - F chord feel like? Then establish C major: C, F, G7, C. What does the G - C - F chord feel like now?
To put it all together, the sound and function of a chord comes from: all its intervals, in relation to (1) a root note, (2) the bass note, and finally the/a (3) tonic note which gives an additional point of reference. You could even add other note-expectations as points of reference as well. Like for example if you expected C - Eb - G, but got C - E - G instead, then it feels a lot different than if you had expected the C - E - G.
There are non-functional (if that's a music term) aspects to the sound of chords as well, namely chord voicings, which means the spreading and/or doubling of notes in different octaves. A wider spacing gives a different sound than a narrow one. If you move your E or Eb up an octave, so it's C - G - E or C - G - Eb, it's a different sound even though the major/minor aspect doesn't change.

Edit. The OP asks:

Just to clarify, what's the difference between the tonic and the root?

A chord has a root note, but a tonic exists outside individual chords. There's no tonic in any single chord, but there can be a tonic in your mind. When people say that a song is "in C", it means that C is the tonic. It is a home note, center of balance to which your mind relates other notes and chords. When analyzing or listening to a single individual chord, naming a tonic would be conceptually incorrect, because tonic is not a property of a chord.
When exactly is a tonic set? It's a slightly fuzzy phenomenon that needs time to settle in, so it's not an immediate on/off switch. If you've spent awhile without hearing any music, then hearing even a single chord might set the tonic. But if you had been listening to a song that's in F, hearing one C major chord immediately after that most probably won't set the tonic to C. You will hear the C major in relation to the F and it won't feel like home. In this case, resetting the tonic somewhere else can require more powerful means. Keep a moment of silence and play a cadence.
If you play the chords C, F, G7, C, it will most probably cause C to be established as a tonic note in your mind, and C major will feel like the tonic chord. If not, play the cadence C, F, G7, C a few more times. Now, having C as an expected home, C major will feel a certain way, and F major will feel a certain different way, even though they are both simple major chords.
These feelings would be different, if you had a different tonic in mind. Try it. Establish G major as the tonic by playing G, C, D7, G a few times. How do the C major and F major feel now? C doesn't feel like a home anymore, and F feels quite different and special, doesn't it? Even a simple chord can sound unfamiliar and more complex, if it's played in an unexpected place.
Comment: @OctopuSS7 I added an explanation about root vs tonic.
Comment: Just to clarify, what's the difference between the tonic and the root?


$f(x) = x^3-x^2+3x-1$ and $f(1) = 2$, find $g'(2)$ if $g(x) = f^{-1} (x)$

Question: $f(x) = x^3-x^2+3x-1$ and $f(1) = 2$, find $g'(2)$ if $g(x) = f^{-1} (x)$.
I'm stuck.
Can I get hints only? No anwser please.
Comment: I can't understand why it is given $\;f(1)=2\;$ after we're given the function. Perhaps this is something else?
Answer: You can use this formula:
$$\frac{d}{dx}{f^{-1}(x)}=\frac{1}{f'(f^{-1}(x))}$$
Answer: Hint:

To find $f(1)$, plug $1$ into $f(x) = x^3-x^2+3x-1$.
To find $g'(2)$ Notice that by the chain rule $$(f(g(x)))' = 1 \Rightarrow f'(g(x))g'(x) = 1 \Rightarrow g'(x) = \frac{1}{f'(g(x))}$$
Answer: hint: compute $f^\prime(1)$  and then use the fact that the slopes of $f$  at $1$ and of $g$ at the corresponding point $2$ are reciprocals.


Windows share - wrong password

Question: Disclaimer: I'm completely new to this.
I'm trying to connect to a windows share folder in a different network. When I start remote desktop to the machine with the shared folder, the shared folder works (within the remote desktop: \\DOMAIN\\sharedfolder\ works as expected).
However, if I now try to connect from my own machine, neither the combination user / password, nor DOMAIN\user / password works, and all I get is "The specified network password is not correct".
Is there some magic trick to this? Do I have to type in DOMAIN\password or what?
Answer: First off, is the same DOMAIN\user account being used to log into the remote desktop session that you are trying to use locally?  You say "different network" so, that's why I ask.  Do you mean different domain entirely?  Or possibly they gave you a local server account to use?
Things to test:

From your machine can you ping the server that you are trying to reach?
If so, can you click start, run, then enter "\SERVERNAME" and hit enter and it then prompts for credentials?

If it does prompt, then you should be able to enter the same credentials you use to start the remote desktop session (paying special attention to the DOMAIN name if it is on a different domain or a local server account ID).
Bottom line:  if you can actually reach the remote server from your PC then whatever credentials you use to login to the remote desktop session should work to get you access to the remote share.
Comment: (How do I insert new lines here :( )
My computer is in the `MY-DESKTOP` domain, so it will choose the username `MY-DESKTOP\USER` if I don't specify the domain. \\
1. `ping server.com` works, `ping DOMAIN` works \\
2. run -> `\\DOMAIN` opens a promt, but there's instantly an error at the bottom: `Logon failure: unknown user name or bad password` (probably because my login name, domain and password differ from the  data for the server), and it resets me to the Domain `MY-DESKTOP` \\
run -> `\\server.com` -> `DOMAIN\user`/`password/` works :D thanks!
Answer: Where exactly does this shared folder reside? On the domain? If yes then the domain user account would need access associated with the appropriate ACL. Are you able to use network tools to test connectivity like tracert or ping? Because that would identify network issues and also assume access issues if not...
Answer: Humm check your network setting
update your group policies
flushdns
use domain\user
it should work
Comment: This is a terrible answer.
Comment: Welcome to Server Fault. This answer does not meet our quality standards - It is a ["button-pushing" answer](http://blog.serverfault.com/2011/06/09/press-the-green-button-twice/) which does nothing to help someone understand the cause of the problem, or how to address the root cause so it won't reoccur. Please consider updating your answer to explain ***why*** you think this is a good solution, and *what underlying cause(s) it is designed to address*.  Thanks!
Comment: done everything and still doesn't work :(

Windows share - wrong password


Eclipse won't detect my phone

Question: So I have been developing apps for android and I'm using my phone to run it.
I have been doing this for a while but when i plugged my phone into my laptop again it said that it started to install the driver again but now fails.
Now I can't use my phone to debug my apps.
Does anyone know how to fix this?
This occurred more than once.
Comment: you should download and install [Android ADB Driver](http://developer.android.com/sdk/win-usb.html) on your machine
Comment: @ABFORCE But it worked before, it happend when i plugged the device again
Comment: @user2982786 Reboot your Windows or phone or Eclipse may solve this problem
Answer: When this happens to me I just restart the adb server. Open a terminal and go to the directory where adb is located
<code>cd ...something.../android-sdk-macosx/platform-tools  (or something similar)
</code>
And then restart the server with this command series
<code>./adb kill-server; ./adb start-server; ./adb devices
</code>
Answer: It usually happen when Eclipse does not found Andriod Debug Bridge(adb) somehow.
So, in order to sort out this problem you can download "Universal adb".
Its a software which installs adb required for compatibility between your device and
Eclipse IDE.
First you just need to connect your device with your laptop and run the Universal adb software.
Hit the install button. And its all done.
I hope this works for you.

Eclipse won't detect my phone


Prove the inequality for $3$ numbers

Question: Given $x,y,z$ are reals such that $0<x<y<z<\frac{\pi}{2}$. Prove that $$\frac{\pi}{2}+2\sin x\cos y+2\sin y\cos z>\sin 2x+\sin 2y+\sin 2z$$ Since the inequality is not symmetric and equality too doesn't hold, I don't have many ideas. I tried using some rearrangement inequality, but it doesn't help. Thanks.
Comment: $0\lt x\lt y\lt z\lt \frac {\pi}2  \implies 0\lt \sin x\lt \sin y\lt \sin z\lt 1$. Does this helps a bit?
Comment: $\sin(2x) = 2\sin x \cos x$ seems like it could be of use.
Comment: And the most relevant fact about $\frac\pi2$ on the left-hand side is probably that it exceeds $\frac32$, which would be useful because $0\le p\le q\le\frac\pi2$ implies $\sin p\cos q\le \frac12$.
Comment: Hint:$0\lt x\lt y\lt z\lt \frac {\pi}2$, so, $\sin$ and $\cos$ are increasing and decreasing respectively of this order . Now, take the help of $Rearrangement$-$inequality$.
Comment: @SubhadeepDey are you sure rearrangement is enough? I think you get close with that but not to the finish line.
Comment: With an approch very similar to the proof of the Schur-Vornicu inequality it is possible to prove that the constant $\frac{\pi}{2}$ may be replaced with the smaller $\sqrt{2}$.
Comment: For the OP: as a math entusiast, it would be a good thing to give some credit to the people who answered your questions by accepting their answers.
Answer: Our inequality is equivalent to:
$$f(x,y,z)=\sin(x)(\cos(x)-\cos(y))+\sin(y)(\cos(y)-\cos(z))+\sin(z)\cos(z)<\frac{\pi}{4}\tag{1}$$
but due to the concavity of the sine function, if we set $g(t)=\sin(t)\cos(t)$ we have:
$$\begin{eqnarray*}2\cdot f(x,y,z)&=&g(x)+g(z)+g(y-x)+g(z-y)\\&\leq&g(x)+g(z)+2\cdot g\left(\frac{z-x}{2}\right)\tag{2}\end{eqnarray*}$$
so it is enough to prove that if $0\leq x\leq z\leq\frac{\pi}{2}$,
$$ h(x,z)=\sin(x)\cos(x)+\sin(z)\cos(z)+\sin(z-x)\leq\frac{\pi}{2}\tag{3}$$
holds. It is easy to check that $\frac{\partial h}{\partial x}$ and $\frac{\partial h}{\partial z}$ both vanish iff $\cos(x+z)\cos(x-z)=0$, i.e. $z=\frac{\pi}{2}-x$. So, in order to prove $(3)$ it is enough to check that if $0\leq x\leq\frac{\pi}{4}$,
$$ j(x) = \sin(2x)+\cos(2x)\leq\frac{\pi}{2}\tag{4} $$
holds. That is trivial by the Cauchy-Schwarz inequality: moreover, the RHS of $(4)$ can be replaced with the smaller constant $\sqrt{2}$. So we have:

If $0\leq x\leq y\leq z\leq\frac{\pi}{2}$,
  $$\color{red}{\sqrt{2}}+2\sin x\cos y+2\sin y\cos z \geq \sin(2x)+\sin(2y)+\sin(2z).\tag{5}$$

Prove the inequality for $3$ numbers


Looping forwarded and locally originating connections through port forwarding rules in firewalld

Question: I have a Debian box running firewalld set up a as gateway NAT/router. This device has two NICS; wan --- public interface, assigned to the external firewalld zone, dynamically assigned IP address using DHCP ---, and lan1 --- private interface, assigned to the trusted firewalld zone, statically assigned IP address of 192.168.0.1/16.
The system is also configured to do NAT and port forwarding using firewalld:
(router) $> sudo firewall-cmd --info-zone=external
external (active)
  target: DROP
  icmp-block-inversion: yes
  interfaces: wan
  sources:
  services: http https ssh
  ports: 8443/tcp
  protocols:
  forward: yes
  masquerade: yes
  forward-ports:
        port=8443:proto=tcp:toport=8443:toaddr=192.168.0.2
        port=443:proto=tcp:toport=443:toaddr=192.168.0.2
        port=80:proto=tcp:toport=80:toaddr=192.168.0.2
  source-ports:
  icmp-blocks: echo-reply echo-request fragmentation-needed neighbour-advertisement neighbour-solicitation packet-too-big port-unreachable router-advertisement router-solicitation time-exceeded
  rich rules:

(router) $> sudo firewall-cmd --info-zone=trusted
trusted (active)
  target: ACCEPT
  icmp-block-inversion: no
  interfaces: lan1 lo
  sources:
  services: ssh
  ports:
  protocols:
  forward: yes
  masquerade: no
  forward-ports:
  source-ports:
  icmp-blocks:
  rich rules:

(router) $> sudo sysctl -n net.ipv4.ip_forward
1

So far, so good. Devices within the internal 192.168.0.0/16 network can access the internet without any issues, and incoming connections on the wan interface to ports 80, 443, and 8443 are correctly forwarded to 192.168.0.2 where a reverse proxy instance is listening.
The problem arises when I want to use the public-facing IP address of the router from an internal device to access the reverse proxy on 192.168.0.2. To illustrate this, I have two public DNS records associated with the public address of wan; hq.mydomain.tld, which is proxied through Cloudflare, and gateway.mydomain.tld, which instead points directly to the public IP address of wan.
If I hit hq.mydomain.tld from an internal device, the request in properly routed to 192.168.0.2, as expected, as the request is first going to Cloudflare and then proxied back to my gateway:
$> curl -sS -D - https://hq.mydomain.tld -o /dev/null -L
HTTP/2 200
date: Sat, 16 Dec 2023 16:43:09 GMT
content-type: text/html; charset=utf-8
cache-control: public, max-age=600
...

However, if I instead hit gateway.mydomain.tld from an internal device, it seems as if no rules are applied and the request instead directly hits the router. Nothing is listening on the forwarded ports on the router, and so the request immediately fails.
$> curl -sS -D - https://gateway.mydomain.tld -o /dev/null -L
curl: (7) Failed to connect to gateway.mydomain.tld port 443 after 713 ms: Couldn't connect to server

The same thing happens if instead of the public hostname I use the public IP of the router.
$> curl -sS -D - https://a.b.c.d -o /dev/null -L
curl: (7) Failed to connect to a.b.c.d port 443 after 18 ms: Couldn't connect to server

This also happens if I curl from the router itself, either using it's own public IP address or localhost:
(router) $> curl -sS -D - https://a.b.c.d. -o /dev/null -L
curl: (7) Failed to connect to a.b.c.d port 443 after 0 ms: Couldn't connect to server

(router) $> curl -sS -D - https://localhost -o /dev/null -L
curl: (7) Failed to connect to localhost port 443 after 0 ms: Couldn't connect to server

My question is then: how do I configure firewalld (or its backend, nftables) to apply the public port forwarding rules to traffic originating from the internal network or from the router itself?
Note that I can't use rules which directly use the public IP of wan, as this is a DHCP-assigned IP address and could change at any moment, rendering the rules useless.
I have tried a bunch of different things without success:

Setting up identical port forwarding rules on the trusted zone.

Using direct firewalld port forwarding rules on the loopback interface.

Finally, I tried creating a firewalld policy using trusted (the internal zone) as a the ingress zone and HOST as the egress zone:
(router) $> sudo firewall-cmd --info-policy=internal_fwd
internal_fwd (active)
  priority: -1
  target: CONTINUE
  ingress-zones: trusted
  egress-zones: HOST
  services:
  ports:
  protocols:
  masquerade: no
  forward-ports:
  source-ports:
  icmp-blocks:
  rich rules:

I really thought this would work, as such a policy applies to any traffic coming from the internal network that terminates in the router. However, it seems you can't use a policy with an egress-zones: HOST to forward ports to another device:
(router) $> sudo firewall-cmd --permanent --policy=internal_fwd --add-forward-port=port=8443:proto=tcp:toport=8443:toaddr=192.168.0.2
Error: INVALID_FORWARD: Policy 'internal_fwd': A 'forward-port' with 'to-addr' is invalid for egress zone 'HOST'

Answer: The most common practice is to NAT from external to internal.
First enable enable masquerading for that zone (I use public in this example)
firewall-cmd --zone=public --add-masquerade

firewall-cmd --permanent --zone=public --add-forward-port=port=80:proto=tcp:toaddr=192.168.x.x:toport=80

Owh yeah you also need to enable net.ipv4.ip_forward = 1
Comment: I just figured out that what I want is called "hairpin NAT", and is actually a thing! https://serverfault.com/questions/55611/loopback-to-forwarded-public-ip-address-from-local-network-hairpin-nat
Comment: Thank you for your reply, but my question clearly explains that (1) masquerade is already enabled for my public-facing interface, (2) the `sysctl` parameter `net.ipv4.ip_forward` is already set to `1`, (3) traffic is already being NAT-ed and forwarded correctly, and (4) port forwarding is set up and working as expected. The problem is NOT forwarding from the external network to the internal one, but rather forwarding _within_ the internal network.
Comment: It's a bit weird and uncommon to forward ports from the internal network. I think you might better off with a VPN or proxy. Or can elaborate more in detail what exactly you want to forward from the internal network. You can have rules which filter the traffic from the internal network to public.
Comment: > It's a bit weird and uncommon to forward ports from the internal network.

I understand, but I'm really just trying to replicate behavior that I have seen enabled by default in cheap off-the-shelves routers. What I really want is consistent behavior when accessing my public IP/hostname from within and from outside my internal network. I would like to always be able to access "gateway.mydomain.tld" and reach my web services, no matter if I'm connected to my intranet or I'm somewhere else. Maybe I could solve this with my internal DNS server, but that has it's own limitations.
Comment: Yes, this brings me to split-dns. Where you have a dns server who a public zone and internal zone. The domain name can be the same, in the internal zone you have the internal ip with associated to a record. And the same for the external zone. The external zone responds only ti queries on the internet, and the internal zone is scoped to the local network. For NAT, if traffic stays internal there is nothing to be translated from external to internal
Answer: This is a case of NAT hairpinning: here the final target is in the same LAN as the original source, so it will attempt to reply directly to it, bypassing the NAT inverse transformations that has to be done for replies. As the source doesn't know of the final target address (it doesn't know about 192.168.0.2 and so TCP replies from this source will be discarded with a TCP RST).
To handle NAT hairpinning, the replies also have to go through the NAT router so they can undergo the inverse NAT transformation. One easy way to do this is to also perform NAT on the source address in addition to the destination address. Any address that would get the reverse proxy server to reply through the NAT router is acceptable: its LAN address, its public address or any other address, including a fictional address, that would have the NAT router as gateway for the reverse proxy server. Here, for simplicity, the LAN address will be used (through the selective use of masquerade).
With pure nftables this could have been handled with a rule such as below in nat/postrouting:
iif lan1 oif lan1 ct status dnat masquerade

But this can't be done within firewalld. Instead using source address along output interface in a rich rule can achieve the same. The rich rule will perform masquerade on the trusted zone when the source is within 192.168.0.0/16. This happens only when the packet has been routed back from 192.168.0.0/16 to 192.168.0.0/16 (ie to lan1, ie to trusted), meaning NAT was performed or this wouldn't have happened (except for the corner case of a misconfigured system in trusted zone that would use the gateway to reach other 192.168.0.0/16 addresses instead of directly):
firewall-cmd --zone=trusted --add-rich-rule='rule family="ipv4" source address="192.168.0.0/16" masquerade'

This results in this diff for the nftables backend ruleset:
--- /tmp/ruleset1   2023-12-20 10:22:31.937292389 +0000
+++ /tmp/ruleset2   2023-12-20 10:26:31.155214737 +0000
@@ -519,6 +519,7 @@
    }

    chain nat_POST_trusted_allow {
+       ip saddr 192.168.0.0/16 oifname != "lo" masquerade
    }

    chain nat_POST_trusted_post {

which is exactly what is intended.
Alas that's not enough. Because the port forwarding rules were added to the external zone, no DNAT actually happened, because the only zone having been traversed is the trusted zone (tied to the lan1 interface), but DNAT rules are performed only when the packet traverses the external zone (tied to the wan interface), and firewalld doesn't appear to have fallbacks (the relevant parts in the nftables backend use goto statements rather than jump statements, precluding the traversal of further chains). Port forwarding rules have to be duplicated in the trusted zone so they are also performed for this case:
firewall-cmd --zone=trusted --add-forward-port=port=8443:proto=tcp:toport=8443:toaddr=192.168.0.2
firewall-cmd --zone=trusted --add-forward-port=port=443:proto=tcp:toport=443:toaddr=192.168.0.2
firewall-cmd --zone=trusted --add-forward-port=port=80:proto=tcp:toport=80:toaddr=192.168.0.2

Use --permanent on all previous commands once correct behavior was verified.
Note: the reverse proxy's logs will all show the NAT router's 192.168.0.1 as source for all clients behind lan1. This appears unavoidable within the constraints of the rich rules language. Using directly nftables, one could have performed a prefix change in nat/postrouting like:
snat ip prefix to ip saddr map { 192.168.0.0/16 : 10.168.0.0/16 }

to still be able to distinguish individual clients from the trusted zone in proxy proxy's logs with the inverse mapping (eg: 10.168.1.2 means the client was actually 192.168.1.2). I don't know how to do this within firewalld.

UPDATE: the router NAT case from itself to itself can be handled using firewalld policies, but even here there are workarounds needed.

Active Policies
Policies only become active if all of the following are true.

The ingress zones list contain at least one regular zone or a single
symbolic zone.

The egress zones list contain at least one regular zone or a single
symbolic zone.

For non symbolic zones, the zone must be active. That is, it must have
interfaces or sources assigned to it.

If the policy is not active then the policy has no effect.

Symbolic zones:
HOST
This symbolic zone is for traffic flowing to or from the host running
firewalld. This corresponds to netfilter (iptables/nftables) chains
INPUT and OUTPUT.

If used in the egress zones list it will apply to traffic on the INPUT
chain.

If used in the ingress zones list it will apply to traffic on the
OUTPUT chain.

Workarounds are needed: both ingress and egress are needed, HOST can be used only once and has to be in ingress to have rules added to nat/output, and port-forwarding rules require that the egress zone has no interface added to it, else an error such as:
Error: INVALID_ZONE: Policy 'nat-hairpin-host': 'forward-port' cannot be used because egress zone 'trusted' has assigned interfaces

will happen.
So use HOST in ingress and recycle an unused zone: internal to be used as egress zone with instead of the lo interface bound to it, the host's address on the wan interface, to meet all prerequisites to have the policy activated (and then only when reaching the WAN address). One could use an other unused zone or even define an additional custom zone by adding an XML file (eg: by following this) instead of internal. There won't be much interaction with the extra zone chosen, especially considering that filter/input and output rules always explicitly grant access to the lo interface.
The documentation about using policies doesn't provide much examples from CLI and describes an XML file. Still RHEL's documentation provides examples (that are unrelated to this problem). Policies can only be used along --permanent (and thus requiring at the end --reload).
The instructions below will consider 192.0.2.2/24 is the address set on wan to access services. So in the end:
firewall-cmd --permanent --new-policy nat-hairpin-host
firewall-cmd --permanent --policy=nat-hairpin-host --add-ingress-zone=HOST
firewall-cmd --permanent --policy=nat-hairpin-host --add-egress-zone=internal
firewall-cmd --permanent --policy=nat-hairpin-host --add-forward-port=port=8443:proto=tcp:toport=8443:toaddr=192.168.0.2
firewall-cmd --permanent --policy=nat-hairpin-host --add-forward-port=port=443:proto=tcp:toport=443:toaddr=192.168.0.2
firewall-cmd --permanent --policy=nat-hairpin-host --add-forward-port=port=80:proto=tcp:toport=80:toaddr=192.168.0.2

firewall-cmd --permanent --zone=internal --add-source=192.0.2.2

firewall-cmd --reload

Which will in the end create along plumbing rules and equivalent filter rules, something similar to this:
[...]

        chain nat_OUTPUT_POLICIES_pre {
                ip daddr 192.0.2.2 jump nat_OUT_policy_nat-hairpin-host
        }

[...]

        chain nat_OUT_policy_nat-hairpin-host_allow {
                meta nfproto ipv4 tcp dport 443 dnat ip to 192.168.0.2:443
                meta nfproto ipv4 tcp dport 80 dnat ip to 192.168.0.2:80
                meta nfproto ipv4 tcp dport 8443 dnat ip to 192.168.0.2:8443
        }

The reverse proxy will see the source being the WAN address (the primary address for the WAN IP LAN if multiple addresses are set) since this source wasn't (and didn't have to be) changed, and that's the source the NAT router selected when reaching itself before DNAT rerouted it elsewhere.
# ip route get 192.0.2.2
local 192.0.2.2 dev lo src 192.0.2.2 uid 0
    cache <local>

Comment: Thank you for your highly detailed answer! This really seems to be a step in the right direction, however it still doesn't work. Setting `firewall-cmd --zone=trusted --add-rich-rule='rule family="ipv4" source address="192.168.0.0/16" masquerade'` and enabling port forwarding on the internal, trusted, zone does in fact redirect requests from internal clients to the internal web server (yay), but it does so for *all* requests to port 80 or 443, no matter the hostname or IP. In practice, this thus breaks internet access for all devices in the LAN...
Comment: I will keep trying different combinations based on what you have detailed here, and I'll come back if I figure it out. Thanks!


A definition of zeros of a complex function.

Question: I'm studying complex variables with a book written by Churchill.
In the textbook, he defines a point as a zero of a function only when it is zero and analytic at the point. But I don't understand why we need analyticity when we talk about zeros.
I suspect that people didn't want a point to be zeros and poles of a function at the same time. If we didn't require a function to be analytic, then, for example, we just can bring a function which has a pole at a point z and redefine the function at a point z by zero. Then z is a zero and a pole at the same time.
(* A pole of a function is an isolated singular point at which the principal part of its Laurent Series has at least one non-zero term and finitely many non-zero terms)
But I don't know why they shouldn't appear at the same point. Is there any reason for this?
Thanks in advance!
Comment: Poles and zeros are quite different, and a pole is *not* a zero. What *is* the case is that $f$ has a pole of order $m$ at a point $z$ if and only if its reciprocal, $1/f$, is analytic at $z$ and has a zero of order $m$ there. Being analytic is quite important here.
Comment: Can you specify the edition and page number for this definition, and perhaps quote it verbatim? I am looking at a second edition of Churchill (from 1960), and on page 52 it simply says "A value of $z$ for which $f(z)=0$ is called a *zero* of the function $f$."
Comment: @Barry Cipra, 8th edition and page 249 of section 75 zeros of analytic function.
Comment: Suppose that f is analytic at z. If f(z) = 0 and if there is a positive integer m such that m-th derivative at z is not zero and each derivative of lower order vanishes at z , then f is said to have a zero of order m at z.
Comment: Oh. It says about a zero of order... I'm sorry! But I believe I never seen a definition of zero in other pages.
Comment: The excerpt I cited was in a section on "Further Properties of Trigonometric Functions." It was immediately followed by the assertion that "*the real zeros of sin z and cos z are their only zeros.*" In the second edition, "Zeros of Analytic Functions" is section 65, on page 149. The book has clearly undergone some expansion!
Comment: Oh my book doesn't have a section called 'Further properties of Trigonometric functions'! Yes! It's undergone some expansions! Then my question is changed... Can I say that A pole of a function can be a zero, but not a zero of order m?
Comment: BTW, you can delete a question if it has not received any (upvoted) answers.
Comment: Thank you! I will delete it soon!
Comment: Is this incorrect that a function f such that $f(1)=0 and f(z)=1/(z-1)$ has a pole and a zero at $z=1$?
Comment: Ah, I see what you're asking now. That's actually an interesting question! To answer it requires looking at exactly how Churchill defines things.
Comment: Sorry.. My English isn't good enough to clarify my question. I will leave my post undeleted! Thank you :)
Answer: The condition of being analytic for $f(z)$ at its zero $z=a$(say) is inherent which can be verified by just looking at the definition of the order of a zero of $f(z)$ i.e.

"A function $f(z)$ has a zero of order $m$ at $z=a$ if $f(z)=(z-a)^mg(z)$, where $g(a)\ne 0$ and $g(z)$ is analytic at $z=a$ ".

Analyticity of $g$ at $z=a$ necessitates  analyticity of $f$ at $z=a$. In contrast, while displaying the functional value of a real function $f(x)$ at a point $x=a$ of its domain, it is not necessary that $f$ is continuous/differentiable there. For example, $f(x)=0$, if $x\le 0$ and $f(x)=1$ elsewhere on $\mathbb R$, you can see $f(0)=0$. Further, $x=a$ is not necessarily the limit point of the domain of $f$ for defining $f(a)$ e.g. if $A=${$0$}$\cup (1,\infty)$ and a function  $f:A\rightarrow \mathbb R$ defined as $f(x)=0$ if $x=0$ and $f(x)=x$ elsewhere is a continuous function on its domain. However, the domain of a complex continuous function can't have isolated points inside it.
Comment: Ah that makes sense. One more question! If we define a function f by &f(1)=0  and f(z)=1/(z-1)& Then z=1 is clearly a pole of order 1. Is it a zero?
Comment: Defining $f$ in such a way leads to a contradiction at $z=1$ actually. A point $z=a$ is either a singularity of $f$ or a point in domain of analyticity of $f$.
Answer: The function
$$f(z)=\begin{cases}{1\over z}&\text{if }z\not=0\\0&\text{if }z=0\end{cases}$$
(similar to what the OP asks about in comments) meets the definitions in (my edition, at least, of) Churchill for having both a zero at $z=0$ and a (simple) pole at $z=0$.  In particular, the definition of a zero does not mention anything about continuity (much less analyticity), while the definitions of (isolated) singularities and poles do not mention whether the function is or is not assigned a value at the singular point, only that it's analytic in a neighborhood around the point.
So technically yes, a function can have both a zero and a pole at the same point.  This is kind of a trick answer to a trick question: the assignment of the value $0$ to $f(0)$ is quite arbitrary, since no value makes the continuous at $z=0$. But kudos to the OP for wondering whether Churchill's definitions allow it.


Topological version of second isomorphism theorem

Question: Is there a version of the second isomorphism theorem for topological spaces? That is, given $X$ and $Y$ topological spaces, is there a condition such that $(X \cup Y)/Y$ is homeomorphic to $X/(X \cap Y)$? What about an isomorphism of homology/fundamental groups?
Answer: Let $Z$ be a topological space. Let $X$ and $Y$ be nonempty subspaces of $Z$.
Assumption:

The identity map from $X\cup Y$, as a subspace of $Z$, to the pushout $X\cup_{X\cap Y}Y$ in the sense of categorical notations, is a homeomorphism

This is true if, say, $X$ and $Y$ are both closed or both open in $X\cup  Y$, which is true if they are both closed or both open in $Z$. If you interpret $X\cup Y$ as the categorical union then this is always true. The idea is that this assumption says maps out of $X\cup Y$ (which are constant on $Y$) are the same thing as maps out of $X$ and $Y$ (which agree on $X\cap Y$ and which are constant on $Y$) which are the same thing as maps out of $X$ (which are constant on $X\cap Y$), thereby equating the universal properties of $(X\cup Y)/Y$ and $X/(X\cap Y)$.
On a similar note, we must interpret $X/(X\cap Y)$ as the categorical quotient in the instance that $X\cap Y$ is empty i.e. we must say it is $X\sqcup\{\ast\}$ for some adjoined point $\ast$.
Then there is a canonical homeomorphism $(X\cup Y)/Y\cong X/(X\cap Y)$.
The proof:

Define $F$ to be the composite $X\hookrightarrow X\cup Y\twoheadrightarrow(X\cup Y)/Y$. Observe that $F$ is constant on $X\cap Y$ so it induces a continuous $f:X/(X\cap Y)\to(X\cup Y)/Y$ (which takes the quotient point of the domain to the quotient point of the codomain, a necessary stipulation for the case $X\cap Y=\emptyset$).
Define $G_1$ to be the quotient $X\twoheadrightarrow X/(X\cap Y)$ and $G_2$ to be the composite $Y\to\ast\hookrightarrow X/(X\cap Y)$ where the point $\ast$ is included as the quotient point. Both are continuous and agree on their common domain $X\cap Y$ so by assumption there is a continuous extension of these to some $G:X\cup Y\to X/(X\cap Y)$. Obviously $G$ is constant on $Y$, hence we have an induced continuous $g:(X\cup Y)/Y\to X/(X\cap Y)$.

It's then not too hard to check $f$ and $g$ are mutually inverse. Note by the uniqueness of the maps induced from a quotient space that it suffices to show: $$\begin{align}(X\cup Y\twoheadrightarrow(X\cup Y)/Y\overset{fg}{\longrightarrow}(X\cup Y)/Y)&=(X\cup Y\twoheadrightarrow(X\cup Y)/Y)\\(X\twoheadrightarrow X/(X\cap Y)\overset{gf}{\longrightarrow}X/(X\cap Y))&=(X\twoheadrightarrow X/(X\cap Y))\end{align}$$Which is easy if you understand how $f$ and $g$ are defined.