Definition of weak-$*$ topology

Question: Though I learned some basic theory about topological vector spaces, I always confused about the definition of weak-$*$ topology.
Given $x\in X$, let $\phi_x: X^*\to \Bbb R$ denote the evaluation map $u\to u(x)$ at $x$.
The weak-$*$ topology on $X^*$ is the initial topology associated with the family of all evaluation mpas $\phi_x: X^*\to \Bbb R$. Thus, the weak-$*$ topology is the smallest topology on $X^*$ for which all evaluation maps $\phi_x$ are continuous.

What is the definition of initial topology, how to understand the first statement?
Why the weak-$*$ topology is the smallest topology on $X^*$ for which all evaluation maps $\phi_x$ are continuous?

3.There is also a conclusion: every subset of $X^*$ which is open for the weak-$*$ topology is also open for the strong topology. (1)
I want to show that $(X^*,SOT)\rightarrow (X^*, \|\cdot \|)$
is continuous, but the book I refered mention that "since all evaluation maps are continuous for the strong topology", why can we prove (1) by the reason $"\cdots"$.
Comment: For question 1 you should just look up the definition on wikipedia e.g. For the second question, it's really just a matter of writing out the definition. By definition it is the universal topology such that the evaluation maps are continuous after all.
Answer: I explained the basic theory of initial topologies in this answer.
Given a family of functions defined on a set, where the codomain have topologies, we give the set the smallest topology that makes all these functions continuous wrt the already given topologies on the codomains. I prove existence and unicity in that answer.
In your case we have the set $X^\ast$ and all point-evaluation functions $\phi_x$, where $x$ ranges over $X$, and so the common codomain is the field $\Bbb R$ (or $\Bbb C$ in the case of complex vector spaces), which has its standard topology.
If we take all continuous linear maps from $X^\ast$ (in the norm topology) to $\Bbb R$) we get the weak topology (instead of the weak-star topology) on $X^\ast$; the evaluations are but a small subset of these. We then get a topology in general between (as subsets) the weak-star topology and the norm topology.
This is all general topology theory, but in the case where all $\phi_x$ are linear (as is the case here) and the domain is a vector space, we get a vector space topology on the domain, so that $+$ and scalar multiplication are still continuous on it.
So as to your question 2.: it's true by definition. And we choose it because it's useful, e.g. because the closed unit ball is compact in this topology (which can have useful consequences). And as the norm topology is one of the topologies that makes all $\phi_x$ continuous by minimality
$\mathcal{T}_{w\ast} \subseteq \mathcal{T}_{\textrm{strong}}$ and so the inclusion is continuous. QED.
From the general theory plus some reasoning it follows that the following sets form a base for the open sets of the weak-star topology:
$$B(f; \{x_1, x_2, \ldots,x _n\}, r):= \{g \in X^\ast \mid \forall 1 \le i \le n: |f(x_i) - g(x_i) | < r\}$$
where $f \in X^\ast$, $\{x_1, \ldots, x_n\}$ is a finite subset of $X$ and $r>0$.
This makes it quite concrete as a topology.
Comment: I don't understand why can we get a weak topology by taking all continuous linear maps from $X^*$ to $\Bbb R$. Should the topology be the collection of subsets of $X^*$?
Comment: @mathbeginner I mean the minimal topology that *those* maps are all continuous instead of just the evaluations. Another initial topology.
Answer: By initial topology the author means the weakest (coarsest) topology that makes your $\phi_x$ continuous.
To see its the weakest, you just have to write down a topology $\sigma$ that makes all the $\phi_x$ continuous, and realize that the weak topology is contained in this one as well. If you want to be a bit more set theoretical, you can show that the lattice of all topologies on a set $X$ is always complete (i.e all the subsets are bounded above and bellow) under the relation $\tau_2$ is finer (stronger) than $\tau_1$ if $\tau_1 \subset \tau_2$. Then, the set off all topologies that make a family $\{ f_\alpha :X\to Y \} $ continuous always has a weakest ( coarsest) topology associated with it.
For 3, consider that the norm topology makes all $\phi_x$ continuous. So the topology it induces is stronger (finer) than the weak* topology by definition of the later. Hence, if a set U is on the weak* topology, it must also be on the strong topology.
Showing the inclusion map is continuous is then just a consequence of the definitions.

Definition of weak-$*$ topology


=?UTF-8?B??= in Emails sent via php mail problem

Question: I have a website, and in the "Contact" section I have a form which users may fill in to contact me.
The form is a simple form which action is a php page.
The php code:
 $to = "firstname.lastname@example.com";

 $name=$_POST['name']; // sender name
 $email=$_POST['email']; // sender email
 $tel= $_POST['tel']; // sender tel
 $subject=$_POST['subject']; // subject CHOSEN FROM DROPLIST, ALL TESTED
 $text=$_POST['text']; // Message from sender
 $text.="\n\nTel:".$tel; // Added to message to show me the telephone nr to the sender at bottom of message

 $headers="MIME-Version: 1.0"."\n";
 $headers.="Content-type: text/plain; charset=UTF-8"."\n";
 $headers.="From: $name <$email>"."\n";

 mail($to, '=?UTF-8?B?'.base64_encode($subject).'?=', $text, $headers, '-firstname.lastname@example.com');

Could somebody please tell me why this works most of the time, but sometimes I receive email whith no text and the subject line showing
=?UTF-8?B??=
I use outlook express, and I have read this System.Net.Mail and =?utf-8?B?XXXXX.... Headers
but it didn't help.
The problem is not in Outlook, because when I log in to the actual mailprogram where I fetch the POP3 emails from, the email looks the same.
When I right click in Outlook and chose "message source" then there is no "From" information.
Ex, a good message should look like this:
Subject: =?UTF-8?B?w5Z2cmlndA==?=
MIME-Version: 1.0
Content-type: text/plain; charset=UTF-8
From: John Doe
However, the ones with problem looks like this:
Subject: =?UTF-8?B??=
MIME-Version: 1.0
Content-type: text/plain; charset=UTF-8
From:
As if the information has been lost somewhere.
You should know also that I have a VPS, which I manage myself.
I use postfix as an emailserver, if thats got anything to do with it.
But then again, why does it work sometimes?
Also another thing that I have noticed is that sometimes special characters are not shown correctly (by both Outlook and the webmail).
For instance, the name "Björkman" in swedish is shown like Björkman, but again, only sometimes.
I hope anybody knows something about this problem, because it is very hard to track down for me atleast.
If you need more input let me know.
Comment: possible duplicate of [=?UTF-8?B??= in Emails sent via php mail problem](http://stackoverflow.com/questions/4518316/utf-8b-in-emails-sent-via-php-mail-problem)
Answer: Looks like the form is posted with all fields left blank. There are bots crawling the net and submitting empty forms. Have you been able to reproduce this with actual form data?
Additional hint: your code is open to email header injection - I can post any headers I want, separated by line breaks, in $_POST['name'] and your code will put it into the email headers. At least remove any line breaks from user data that will go into the header section.
Comment: No I haven't been able to reproduce it. Maybe you are right... I will add mysql_real_escape_string to sanitize it, but the thing is, I use javascript to validate the form before submit, and no empty fields are allowed.
Comment: @Camran while it probably isn't responsible for this problem, *never* rely on client-side validation.


angularjs how to put array in my url

Question: im getting multiple month in my url here my problem i get of object instead of a name of the months that i choose

as you can see in my url i got object months=%5Bobject%20Object%5D
i want to see like this months = [mar, apr]
here my view in that particular combobox
md-input-container flex=""
      label Months
      md-select ng-model="params.months[month]" multiple="true"
        md-option ng-repeat="month in ctrl.months "  ng-value="month"
          | {{month}}

here my controller
#= require ./../../module

class IncomeStatementIndexCtrl
  constructor: ($scope, $route, $mdDialog, $filter, $routeParams, $location, Account, Branch)->
    @branches = Branch.query()
    @clear = ->
      $scope.params = {}
      $location.search($scope.params)

    $scope.params = $location.search()

    @months = [ 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug',
    'Sep', 'Oct', 'Nov', 'Dec']

   if $scope.params.as_of_date?
     $scope.params.as_of_date = new Date($scope.params.as_of_date)
     @incomes = Account::IncomeStatement.query ($scope.params), (data) =>

   @search = () =>
     $scope.params.date_to_compare =
     $filter('date'($scope.params.date_to_compare , "yyyy-MM-dd")
     $scope.params.as_of_date = $filter('date')
    ($scope.params.as_of_date , "yyyy-MM-dd")
     $location.search($scope.params)

IncomeStatementIndexCtrl.$inject = ["$scope", "$route", "$mdDialog", "$filter", "$routeParams", "$location", "Account", "Branch"]

angular
  .module "CaesApp"
  .controller "IncomeStatementIndexCtrl", IncomeStatementIndexCtrl

i need to achieve this so i can get correct the params in my controller in ruby on rails
Comment: to send params as array, what you need to do in cross browser way is.. `?month=mar&month=apr&mon=may`, you will need to write custom code or use some library to `convert array to urlEncode format`
Answer: I don't know much angular, but for send array on any request is :
request =  url?parameter[]=a&parameter[]=b&parameter[]=c

and on rails it is
"parameter":[
"a","b","c"
]

Comment: hi @Darlyncinho Bravo any plunker or jsfiddle so i can visualize thanks for the reply T_T

angularjs how to put array in my url


Access - conditional statement

Question: Coming from the excel world, how to I create a conditional statement to populate one field based on the value on the other, something that in excel would look like:
=if(A1="A","Yes","No")

Thank you
EDIT:
Ok, I've done the following:
=IIF([FundingStream]="A", "N/A", "Student Finance")

But I've got an error:
Invalid SQL syntax - cannot use multiple columns in a column-level CHECK constraint
I'm entering this expression in the Validation Rule of the properties of a Field that N/A or Student Finance should appear.
EDIT 2:
I've done as suggested below. When I type in the FundingStream, it does not change the LoanCRN field at all. See the screenshot below:
Comment: Is this supposed to be in VBA, a form, a query?  In VBA: "If xxx = "A" then yyy = "Yes" Else yyy = "No" End IF
Answer: Although they can serve some of the same purposes, relational databases system require a different paradigm.  The simple idea of setting one column value based on another is actually rather complex when compared to a spreadsheet.  You will only face continued frustration if you try to convert your spreadsheet literally.
The following statement in a Validation Rule is not an assignment, rather it is a Boolean comparison operation:  It returns true or false.  It constrains the values which can be saved to the database, but it does not change the column values.
[Field1] = Iif([FundingStream]="A", "N/A", "Student Finance")

As a further side note, some languages have two different symbols for assignment and comparison, for instance := for assignment and == for equality comparison.  But many languages, like VBA, interpret a single = based on context.  If you understand the difference, the context usually becomes apparent what the equal sign means in a particular case.
To change the values of one field based on another requires other techniques.  The flexibility of any code or macro driven environment, like Access, provide various ways of doing this that can't all be outlined here.  However, the two most obvious that come to mind are:
VBA code in a form module
Probably the most direct way of doing this is in the AfterUpdate event:
Private Sub FundingStream_AfterUpdate()
    If Me.FundingStream = "A" Then
        Me.LoanCRN = "N/A"
    Else
        Me.LoanCRN = "Student Finance"
    End If
End Sub

This assumes that you at least have two controls on your form:  FundingStream and LoanCRN.  This will do what you want... initially.  However, now you would need to consider whether the user can also update LoanCRN directly.  If they should never update LoanCRN directly, you could either 1) set the control property Locked = True, or 2) hide the control on the form so the user can't even see it, or 3) eliminate the actual control and just reference the record source column property directly, like Me![LoanCRN].  More details for any of those techniques is beyond this question.
But that's not all!  You need to consider appropriate default values.  What happens if the user never actually changes the FundingStream control?  Then your code would never run and so LoanCRN might not be set properly. In the end, it is likely that you will need further code elsewhere on the form, e.g. in Form_AfterUpdate(), Form_Current, etc.
The benefit to this approach is that you have all the flexibility of the data entry form to shape exactly how you want the data to flow.  The difficulty is in avoiding missing and conflicting behavior on the form.  This technique ultimately requires appropriate use of table and column constraints (i.e. Validation Rules and indexes) and familiarity with form and control events.
This also only works for the particular form.  If you have other forms or VBA code that change the FundingStream value, you would also need to add the same code in all those locations to ensure LoanCRN value is always valid.
Before Change Data Macro
Define a Before Change macro on the table to update values.  Use If and SetField macro actions to set LoanCRM based on FundingStream.
From a naive perspective, this is actually the most direct, easy way to do it.  The Data Macro is called automatically every time a record is saved, no matter if it is updated on a form or in VBA code.
This also has many restrictions and does not allow flexibility of adding many dynamic conditions, especially conditions present at data entry.  If your macro logic is not robust, it can cause unnecessary errors that prevent the entire set of data from being saved.
Comment: Thanks a lot - I'm probably missing some other obvious thing. Sorry. Am new to access. I have updated the questions. Please see above.
Comment: Thanks a lot. On a generic note, I need to switch from thinking in Excel terms about Access.

Access - conditional statement


Find $\frac{x^2}{y} + \frac{y^2}{z} + \frac{z^2}{x} \to \min$

Question: I'm trying to solve
\begin{align*}
&\frac{x^2}{y} + \frac{y^2}{z} + \frac{z^2}{x} \to \min \\
&x + y + z = 1 \\
&x, y, z > 0,
\end{align*}
using only inequalities.
How can i solve it? I used am-gm, tried to "break" terms, but got only after all $(xy + yz + xz) = \frac{1}{2}$
Comment: @AlexeyBurdin this famous named result is called is the Rearrangement Inequality.  I didn't read your comment but had posted as much.
Comment: Suppose wlog $x\le y\le z\Rightarrow \frac1x\ge \frac1y\ge \frac1z$. If $a_1b_{\sigma(2)}>b_{\sigma(3)}$ it's a famous named result but I've forgotten the name... so $\frac{x^2}{y}+\frac{y^2}{z}+\frac{z^2}{x}\ge\frac{x^2}{x}+\frac{y^2}{y}+\frac{z^2}{z}=x+y+z=1$
Comment: Just think a little bit before posting
Comment: @SohamChatterjee well, if you insist on...
Answer: You can use Cauchy-Schwarz:
$$\sum\dfrac{x^2}{y}\sum y\geq(x+y+z)^2$$
or an even simpler one is:
$$\sum\dfrac{x^2}{y}-\sum y = \sum\left(\dfrac{x^2}{y} - 2x+y\right)=\sum\dfrac{(x-y)^2}{y}\geq 0.$$
Answer: By Cauchy-Schwarz we get$$\frac{x^2}{y} + \frac{y^2}{z} + \frac{z^2}{x} \geq \frac{(x+y+z)^2}{x+y+z}=1$$
Comment: why have you posted the answer, if we already have one? Note that it's using Cauchy-Schwarz also
Comment: I am using cauchy scwarz but with a different apporach
Comment: But why? Nevermind, then, please, make your 'different approach' obvious.


check if the column is having a valid data or not in spark

Question: I have a date column which has date in YYYYMM format when i take the data from a file but after i convert that to a dataframe i have to to check if the data is valid or not, which means i have to check whether it is in YYYYMMDD or not. Otherwise i have to replace it default date 9999-12-31. here is an example This is how my case statement has to look like--
case when is_valid_date(date) is not null then date else 9999-12-31.

I need to create a simple function called is_valid_data to check if the date value is valid or not
 input table
 ID  date
 1  12345

 o/p expected
 ID  date
 1  9999-12-31

Comment: you question is bit confusing.  is your input data is in YYYYMM or YYYYMMDD?
Comment: input data is in YYYYMM
Comment: in tat case, you can change the dateformat in my solution.. let me know if the solution worked
Answer: If I understood your question properly, below is my approach.You need not required to build a function rather you can build an expression with in-build functions and pass the expression.
val df = Seq("12345", "20190312", "3", "4", "5").toDF("col1")
import org.apache.spark.sql.functions._

/*
* checks the given raw data is in expected date format or not.
* if not in the expected format, values are replaced with default value.
*
* Note: You need to change the dateformat according to your requirement
*/

val condExp = when(to_date(col("col1"), "yyyymmdd") isNull, lit("9999-12-31")).otherwise(col("col1"))
df.withColumn("col2", condExp).show()

Result
+--------+----------+
|    col1|      col2|
+--------+----------+
|   12345|9999-12-31|
|20190312|  20190312|
|       3|9999-12-31|
|       4|9999-12-31|
|       5|9999-12-31|
+--------+----------+


What neural learning algorithm could work better than backpropagation for the dataset?

Question: I'm writing a thesis where I developed a script that generates NN and precalculates weights and biases to reduce a required number of epochs. I am using feedforward and recurrent NN, applying backpropagation and stochastic gradient descent optimization, tahn activation function
These my input and target datasets.
<code>      Input          Target
Dec Inc > 0 > 1 |  0  >0    >1
 1  -1  -1  -1  | -1  -1    -1
 1  -1   1  -1  |  1  -1    -1
 1  -1   1   1  |  1   1    -1
-1   1  -1  -1  | -1   1    -1
</code>
Is there any other algorithm that could work better than backprop?
I just want to enrich my thesis, if you can share a reference I would really appreciate it
Many thanks
Answer: I am not sure it will work better but you could try optimization methods based on second-order derivatives: L-BFGS or Newton's method.

It depends on the model structure and dataset, but I think back propagation will work better in most cases. But it could be worth trying!
If you want a reference regarding optimization methods for neural networks, refer to here.


ProgressDialog in android app

Question: I have a problem with my app. The progressDialog shows perfectly but after that the aplication doesn't work. The app have to show a message after the progressDialog and complete some editText. Here is the code of the MyActivity:
public class MyActivity extends ActionBarActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_my);
    Button button = (Button) findViewById(R.id.searchBtn);
    button.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
        final ProgressDialog progress = ProgressDialog.show(MyActivity.this,

          "Buscando...",
                    "Espere mientras se busca la información...", true);

            new Thread(new Runnable() {
                @Override
                public void run()
                {
                    // Código principal de la aplicación

                    EditText text = (EditText) findViewById(R.id.nameTxt);
                    //comprobar si existe nombre
                    if ("".equals(text.getText().toString().trim())) {
                        Toast.makeText(getApplicationContext(), getResources().getString(R.string.noNameMsg), Toast.LENGTH_SHORT).show();
                        return;
                    }
                    String enteredName = text.getText().toString();
                    String finalName = enteredName.toLowerCase();
                    //String salutation = getResources().getString(R.string.hello)
                    // + " " + enteredName;
                    int codeASCII = 0;
                    for (int x = 0; x < finalName.length(); x++) {
                        codeASCII += (int) finalName.charAt(x);
                    }

                    EditText day = (EditText) findViewById(R.id.day);
                    //comprobar si se ha introducido día
                    if ("".equals(day.getText().toString().trim())) {
                        Toast.makeText(getApplicationContext(), getResources().getString(R.string.noDayMsg), Toast.LENGTH_SHORT).show();
                        return;
                    }
                    EditText month = (EditText) findViewById(R.id.month);
                    //comprobar si se ha introducido mes
                    if ("".equals(month.getText().toString().trim())) {
                        Toast.makeText(getApplicationContext(), getResources().getString(R.string.noMonthMsg), Toast.LENGTH_SHORT).show();
                        return;
                    }
                    EditText year = (EditText) findViewById(R.id.year);
                    //comprobar si se ha introducido año
                    if ("".equals(year.getText().toString().trim())) {
                        Toast.makeText(getApplicationContext(), getResources().getString(R.string.noYearMsg), Toast.LENGTH_SHORT).show();
                        return;
                    }

                    int dia = Integer.valueOf(day.getText().toString());
                    int año = Integer.valueOf(year.getText().toString());
                    int mes = Integer.valueOf(month.getText().toString());
                    int nacimiento = dia + mes + año;
                    int nTotal = 17;
                    int x = (codeASCII + nacimiento) % nTotal;

                    String[] insultos = new String[nTotal];

                    insultos[0] = "No te preocupes, hay más virtudes que la inteligencia";
                    insultos[1] = "Tienes futuro como plantador de nabos";
                    insultos[2] = "Ha llegado la hora de pensar en ir saliendo del armario";
                    insultos[3] = "Se puede vivir con dignidad a pesar de tan elevado grado de alopecia";
                    insultos[4] = "Tú tambien podrás triunfar, recuerda a Forrest Gump";
                    insultos[5] = "Ni Newton ni Einsten, sabemos que lo tuyo es Bob Esponja";
                    insultos[6] = "A no todo el mundo le sale bien una O cuando usa un canuto. No te preocupes, ya aprenderás";
                    insultos[7] = "Tu atractivo será evidente para muchos, puede incluso que para alguna persona";
                    insultos[8] = "No es un error que te creas tan atractivo, tu error es que no estás bien informado";
                    insultos[9] = "Te espera un brillante fututro en el mundo del porno, siempre hace falta gente que lleve las toallas";
                    insultos[10] = "Tu cociente intelectual es, bueno, el suficiente para que te hayas descargado esta aplicación absolutamente inútil";
                    insultos[11] = "Muéstrate siempre tal y como eres, salvo cuando intentes gustar a alguien";
                    insultos[12] = "Si le caes bien a mucha gente deberías recordar que el perro es el mejor amigo del hombre ";
                    insultos[13] = "Tienes una mente de altos vuelos, o lo que es lo mismo, un cerebro de pájaro";
                    insultos[14] = "La mediocridad es lo que más abunda, puede que eso te dé consuelo";
                    insultos[15] = "Totorota es una palabra canaria. Aún así, cualquier peninsular que te vea sabrá lo que significa";
                    insultos[16] = "Por fin podrás vivir como siempre habías soñado... en casa de tu madre";

                    TextView out = (TextView) findViewById(R.id.out);
                    out.setText(insultos[x]);

                    runOnUiThread(new Runnable() {
                        @Override
                        public void run()
                        {
                            progress.dismiss();
                        }
                    });
                }
            }).start();
        }

    });
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.my, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();
    if (id == R.id.action_settings) {
        return true;
    }
    return super.onOptionsItemSelected(item);
}

}
Comment: So your app crashes after the ProgressDialog appears is it? What does your logcat show?
Comment: "but after that the aplication doesn't work" - what does this mean? app crashes?
Answer: you can use AsyncTask class to do something like this:
after onCreate() method define inner class like below code:
private class Async extends AsyncTask<String, Integer, String> {

    ProgressDialog progressDialog ;

    protected String doInBackground(String... urls) {

                String enteredName = text.getText().toString();
                String finalName = enteredName.toLowerCase();
                //String salutation = getResources().getString(R.string.hello)
                // + " " + enteredName;
                int codeASCII = 0;
                for (int x = 0; x < finalName.length(); x++) {
                    codeASCII += (int) finalName.charAt(x);
                }

                int dia = Integer.valueOf(day.getText().toString());
                int año = Integer.valueOf(year.getText().toString());
                int mes = Integer.valueOf(month.getText().toString());
                int nacimiento = dia + mes + año;
                int nTotal = 17;
                int x = (codeASCII + nacimiento) % nTotal;

                String[] insultos = new String[nTotal];

                insultos[0] = "No te preocupes, hay más virtudes que la inteligencia";
                insultos[1] = "Tienes futuro como plantador de nabos";
                insultos[2] = "Ha llegado la hora de pensar en ir saliendo del armario";
                insultos[3] = "Se puede vivir con dignidad a pesar de tan elevado grado de alopecia";
                insultos[4] = "Tú tambien podrás triunfar, recuerda a Forrest Gump";
                insultos[5] = "Ni Newton ni Einsten, sabemos que lo tuyo es Bob Esponja";
                insultos[6] = "A no todo el mundo le sale bien una O cuando usa un canuto. No te preocupes, ya aprenderás";
                insultos[7] = "Tu atractivo será evidente para muchos, puede incluso que para alguna persona";
                insultos[8] = "No es un error que te creas tan atractivo, tu error es que no estás bien informado";
                insultos[9] = "Te espera un brillante fututro en el mundo del porno, siempre hace falta gente que lleve las toallas";
                insultos[10] = "Tu cociente intelectual es, bueno, el suficiente para que te hayas descargado esta aplicación absolutamente inútil";
                insultos[11] = "Muéstrate siempre tal y como eres, salvo cuando intentes gustar a alguien";
                insultos[12] = "Si le caes bien a mucha gente deberías recordar que el perro es el mejor amigo del hombre ";
                insultos[13] = "Tienes una mente de altos vuelos, o lo que es lo mismo, un cerebro de pájaro";
                insultos[14] = "La mediocridad es lo que más abunda, puede que eso te dé consuelo";
                insultos[15] = "Totorota es una palabra canaria. Aún así, cualquier peninsular que te vea sabrá lo que significa";
                insultos[16] = "Por fin podrás vivir como siempre habías soñado... en casa de tu madre";

          return insultos[x];

    }

    @Override
    protected void onPreExecute() {

        progressDialog = new ProgressDialog(yourActivity.this);
        progressDialog.setMessage("yourMessage");
        progressDialog.setCancelable(false);
        progressDialog.show();
    }

    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);
        progressDialog .dismiss();
        outt.setText(result);
    }
}

define this variable as global variable:
    EditText text
    EditText day;
    EditText month;
    EditText year;
    TextView outt;

in onCreate() :
 text = (EditText) findViewById(R.id.nameTxt);
 day = (EditText) findViewById(R.id.day);
 month = (EditText) findViewById(R.id.month);
 year = (EditText) findViewById(R.id.year);
 outt = (TextView) findViewById(R.id.out);
 if ("".equals(text.getText().toString().trim())) {
                    Toast.makeText(getApplicationContext(), getResources().getString(R.string.noNameMsg), Toast.LENGTH_SHORT).show();
}else if ("".equals(day.getText().toString().trim())) {
                    Toast.makeText(getApplicationContext(), getResources().getString(R.string.noDayMsg), Toast.LENGTH_SHORT).show();
}else if ("".equals(month.getText().toString().trim())) {
                    Toast.makeText(getApplicationContext(), getResources().getString(R.string.noMonthMsg), Toast.LENGTH_SHORT).show();
} else  if ("".equals(year.getText().toString().trim())) {
                    Toast.makeText(getApplicationContext(), getResources().getString(R.string.noYearMsg), Toast.LENGTH_SHORT).show();
}else{
        new Async.execute();
}

ProgressDialog in android app


Append icon next to the link

Question: I have two links i-e Previous and Next I want to show back icon for previous button and next icon for next button.
I am using Font Awasome's cdn to place the icons.
 My code is as follows:
$('span.CustomerDataPagerClass').find('a').each(function () {
            if ($(this).is('[disabled != disabled]')) {
                var str = $(this).text();
                if (str == "Previous") {
                    $(this).append("").addClass('fa fa-chevron-circle-left');
                }
                if (str == "Next") {
                    $(this).after("").addClass('fa fa-chevron-circle-right');
                }
            }
        });

Here my icons are getting addded but for both time its first adding icon and then link the but i want first icon then Previous link for previous button and for next button first link and the icon
Please help me to achieve this.
Comment: Your using chaining incorrectly or unknowingly, check @void's answer, should fix your issue
Answer: Try
$(this).append("");

and
$(this).after("");

Your code is adding the classes 'fa fa-chevron-circle-left' to $(this) and not to the appended element.
Answer: Try this simple method:
$('span.CustomerDataPagerClass a:contains("Previous")').append("");
$('span.CustomerDataPagerClass a:contains("Next")').after("");

Append icon next to the link


If $f: \mathbb{R}^2 \to \mathbb{R}$ is a $C^1$ function, then $f$ is not bijective

Question: If $f: \mathbb{R}^2 \to \mathbb{R}$ is a $C^1$ function, then $f$ is not bijective.
Can someone explain why this is true or give me some hint? I don't realize how is bijection related with being a $C^1$ function, is it somehow related with the inverse function theorem?
Comment: Actually, continuity is enough. Try to use the fact that $\Bbb{R}^2$ is connected, and that continuous maps send connected sets into connected sets.
Comment: @Crostul : may be that is too advanced?
Comment: @cello May be, I still don't get it. I guess the problem should be with injectivity since $\mathbb{R}$ and $\mathbb{R}^2$ have the same cardinality so surjectivity should not be a problem, right?
Comment: @Eliana Find a partition of $\mathbb{R}^2$ into uncountably many connected subsets. Then think why this makes contradiction.
Answer: Here is a solution requiring nothing more than basic calculus showing that continuity is enough.
Suppose $f: \Bbb{R}^2 \to \Bbb{R}$ is continuous. I show you by contradiction that $f$ is not injective. Suppose by contradiction that $f$ is injective.
Consider the three maps $g_1, g_2, g_3 : [0,1] \to \Bbb{R}^2$ defined by
$$g_1(t) = (0,t)$$
$$g_2(t) = (t,0)$$
$$g_3(t) = (t,t)$$
It is obvious that these are continuous and injective. Consider the three (continuous and injective) compositions $f \circ g_1, f \circ g_2, f \circ g_3$ defined over $[0,1]$ with values in $\Bbb{R}$.
Then
$$f(g_1([0,1])), f(g_2([0,1])), f(g_3([0,1]))$$
are three bounded closed intervals containing the number $z= f(0,0)$. Note that:

Since $f \circ g_i$ is injective, $f(g_i([0,1]))$ does not consist of a single point. So $f(g_i([0,1])) = [a_i, b_i]$ with $a_i < b_i$.
But $\{ z \}= [a_1, b_1] \cap [ a_2, b_2] = [a_1, b_1] \cap [ a_3, b_3] =[a_2, b_2] \cap [ a_3, b_3]$ by injectivity. And this is impossible.
Answer: Another proof for $f$ merely continuous: Because $\mathbb R^2$ is connected, so is $f(\mathbb R^2)$ by the continuity of $f.$ Thus $f(\mathbb R^2)$ is an interval.  Choose a point $a$ in the interior of this interval. Then there is a unique $(b,c)\in \mathbb R^2$ such that $f(b,c)=a.$ But $\mathbb R^2 \setminus \{(b,c)\}$ is connected (because it's path connected), while $f(\mathbb R^2)\setminus \{a\}$ is not. Since $f$ preserves connectness, we have a contradiction.
Answer: As you can see in the other answers, continuity is already enough to derive a contradiction. In addition, here is a proof that uses that $f$ is continously differentiable:
Assume that $f$ is bijective and of class $C^1$. Write $f: \mathbb{R} \times \mathbb{R} \rightarrow \mathbb{R}$, and consider its differential $d_{(x,y)}f = (f_x, f_y)$. Because $f$ is bijective, there is some point $(x_0, y_0)$ such that $d_{(x_0,y_0)}f \neq (a,0)$, where $a \in \mathbb{R}$  is arbitrary. Let $f(x_0,y_0) = z_0$ and consider
$F(x,y) = f(x_0,y_0) - z_0$
Then we can apply the implicit function theorem (since the second component of the differential at $(x_0,y_0)$ is not zero and thus invertible), getting open neighbourhoods $U,V \subseteq \mathbb{R}$ with $x_0 \in U, y_0 \in V$ and a function $g: U \rightarrow V$ with $g(x_0) = y_0$, such that
$F(x,y) = 0\, \Leftrightarrow\, y = g(x)$
on $U \times V$ or, in other words,
$f(x,g(x)) - z_0 \equiv 0\, \Leftrightarrow\, f(x,g(x)) \equiv z_0$
on $U \times V$, which is a contradiction to the bijectivity of $f$.
For your interest: there are (non-continuous) bijective maps from $\mathbb{R^2}$ to $\mathbb{R}$ (look for example here: Examples of bijective map from $\mathbb{R}^3\rightarrow \mathbb{R}$)


How to create a button on top of ImageView and align it to the bottom of the screen?

Question: I want to have a button on top of ImageView using my xml file. When I run this code, the button appears to the left hand side of the screen on top of other buttons.
Does anyone have any idea on what to do to have a button on TOP of ImageView but at the bottom of the screen.
So far I have the following:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
   ......

    <ImageView
        android:id="@+id/filter_image_view"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_toRightOf="@id/filter_linear_layout" />

//this is the button I want to have on top of the ImageView
    <Button
        android:id="@+id/display_RGB"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:background="@drawable/button_blue_red_transluscent"
        android:text="@string/display_RGB"
        android:textColor="@android:color/white" />

</RelativeLayout>

Not too fussy as long as its somewhere at the bottom of the screen but in the center.
Comment: Try with ImageButton http://developer.android.com/reference/android/widget/ImageButton.html
Answer: You can put them in their own RelativeLayout, then you can manipulate the location of the button relative to the ImageView quite easily.
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:layout_toRightOf="@id/filter_linear_layout" >

    <ImageView
        android:id="@+id/filter_image_view"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        />

    <Button
        android:id="@+id/display_RGB"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@drawable/button_blue_red_transluscent"
        android:text="@string/display_RGB"
        android:textColor="@android:color/white"
        android:layout_centerHorizontal="true"
        android:layout_below="@id/filter_image_view"
         />
</RelativeLayout>

If this is not what you are looking, you'll need to post a sample image of how it currently looks and how you wants it to look.
[Edit]
Edited the XML layout. If you want the ImageView to center horizontally, add this to ImageView:
    android:layout_centerHorizontal="true"

And you'll probably want to add some spacing between ImageView and Button by adding this to Button:
    android:layout_marginTop="8dp"

Comment: +1 - this is the stuff, just need to put a picture to show you where on the imageview I mean. hold on please
Comment: There you go. Image is up
Answer: Try this.
<Button
        android:id="@+id/imageButton1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@color/white"
        android:padding="16dip"
        android:text="hi"
        android:textColor="@color/black"
         />


Existence Universal goto-programm (turing machine)

Question: May you can help me out with my problems with source codes. Well first of all we proved that for recursive functions $N:\mathbb N^2\rightarrow \mathbb N$ and $A^k: \mathbb N^k\rightarrow \mathbb N$ and for every goto programm (I am not 100% sure, but I think this is identical to a turing machine) there exist a source code $\mathcal{P}=<p_0,...,p_{L-1}>$ where $L$ is the number of lines of the program and $p_i$ is the code of the i-th line.
Question: How to construct a simple universal program $U$? I.e a program which delivers the ouput for the input $(\mathcal{P},n)$, this is what the program $P$ would give for the input $n$
This is nothing more than a goto-interpreter, similar to a java-interpreter, but what about a formal argument, why this program exist?
EDIT: Next to my original question (the construction of $U$), two other questions arises:Let $f(n)$ is the output of the universal program $U$ on the input $(n,n)$. Is $f$ recursiv? Same with $g(n)=f(n)+1$. Is it recursiv?
Comment: If you are not sure if goto programms are the same as Turing machines, can you at least give a *precise* definition of goto program?
Comment: If you are interested in the source (it is in german), you find the document here: http://www.logic.univie.ac.at/~adler/docs/gml.pdf on page 30.  In general we defined a goto program as a loop program (see here http://en.wikipedia.org/wiki/LOOP_%28programming_language%29) but instead using loops we use goto statements (=jump instructions). We replaced loops by "if x goto 42", which means the program jumps to line 42 if x holds.
Answer: You have to be a bit careful with asking "is $f(n)$" recursive, where $f(n) = U(n,n)$ and $U$ is a universal GOTO program (or recursive function or turing machine or whatever).
$f$ isn't total, so if you distinguish between recursive and partially recursive functions, it's obviously not recursive. It's partially recursive though, since every GOTO program (or turing machine or recursive function or whatever) is.
Comment: How do you know that f is not total?
Comment: @Babla Let $n$ be the code of the program "1: IF TRUE GOTO 1". THen $U(n,x) = \bot$ ($\bot$ means undefined) for every $x$, thus $U(n,n) = \bot$ and so $f(n)=\bot$
Comment: Thank you. But this would mean that the function $g(n)=f(n)+1$ is indeed recursiv because it always goes one step further, right?
Comment: No, because $\bot+1=\bot$ in a way. If you try to evaluate $g$ at $n$, you first have to evalutate $f(n)$. But you never *finish* doing that, you just keep on going. So the "+1" part never actually takes place, $g$ never finishes either, no result is produced, hence the value is $\bot$.
Comment: Ok, that makes sense, so we know it is not recursiv, but is there a goto program for $g(n)$, or differently formulated: Let A be the source code, what U(A,A) mean?
Comment: I've invited you to a chat room on chat.stackexchange.com, let's continue this there.
Comment: let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/8790/discussion-between-babla-and-fgp)
Answer: Quote from Wikipedia: "To show that something is Turing complete, it is enough to show that it can be used to simulate some Turing complete system. For example, an imperative language is Turing complete if it has conditional branching (e.g., "if" and "goto" statements, or a "branch if zero" instruction. See OISC) and the ability to change arbitrary memory locations (e.g., the ability to maintain an arbitrary number of variables). Since this is almost always the case, most if not all imperative languages are Turing complete if we ignore any limitations of finite memory"
Comment: I still do not see how we can construct an universal goto program now, may you can show me how to do that formally?
Comment: I don't think that is trivial (I mean simple), but I might be wrong. I don't know how to do it. Actually, it is not that difficult: you can use the definition of any known universal Turing machine (many examples on the web) and make a Java program that simulates it!
Comment: Even if counter intuitive (at least at the beginning), the rule 110 cellular automata is universal.
Comment: Thanks, but still, the proof of universality of rule 110 is not so easy, I guess there must be a much simpler goto interpreter $U$ that delivers an output for an input $(\mathcal{P},n)$
Comment: I agree. Actually, I am not sure how complex is the translation of a simple simulated universal TM (easy to implement) to the code that maps it to an arbitrary machine (P,n). I guess you'll have to wait until somebody with more knowledge writes an answer. If you don't get an answer in a couple of days, perhaps you could try to ask the question in a more specific way, such as: How to...?
Comment: But I guess you at least understood (at least intuitively) the WHY, which was your original question?
Comment: Yes, I edited my original post. Two more questioned arised, if you have any ideas I would be very thankful.


Finding the probability of destroying the target

Question: Hi I am trying to do the following problem.
Consider a guidance system which is designed to deliver a bomb to a target site, which we denote $(x_0,y_0)$. As with all things, the guidance system that we consider is imperfect and will deliver the bomb to a point (x,y), where the joint PDF  of this random vector, given the point of target, is $$f_{X,Y}(x,y|x_0,y_0)=\frac{1}{2\pi}exp\Big\{-\frac{(x-x_0)^2}{2}-\frac{(y-y_0)^2}{2}\Big\}$$ where both X and Y are measured in feet. If a particular target, located at the point (3,2), will be destroyed if a bomb is delivered within r=2 feet of it, what is the probability that the target will be destroyed if 10 bombs are fired at it?
Now so far my thinking is that taking $(x_0,y_0)=(3,2)$ I can write the PDF as $$f_{X,Y}(x,y|x_0,y_0)=\frac{1}{2\pi}exp\Big\{-\frac{(x-3)^2}{2}-\frac{(y-2)^2}{2}\Big\}$$ which can also be written as $$f(r)=\frac{1}{2\pi}exp\Big\{-\frac{1}{2}r^2\Big\}$$
Now if I integrate the above function from 0 to 2 I would have the required probability. I am confused with the number 10, what should I do with it. Also I am not sure whether I am at all in the right path or not?
I would highly appreciate that if you could help me. Thanks in advance.
Answer: If you just integrate the function from 0 to 2, you are just computing the probability of hitting it with a single shot. We know that if you make more attempts, the probability should increase.
Let's assume that each shot is indeed independent. Of course in practice, you are going to adjust your aim based on previous attempts.
$Pr(\text{ destroying a target in 10 shots})\\
=1-Pr(\text{ not destroying the target in any of the 10 shots})\\
=1-Pr(\text{ not destroying the target in a single shot})^{10} \\
=1-(1-Pr(\text{ destroying the target in a single shot}))^{10}$


print a struct within a struct golang

Question: I want to print a certain item within a struct, that is within a struct. Example:
Pretend I have made up a blueprint struct, and are making an new one
Pretend I have a myshapes struct, that contains a title, # of circles, and squares
car := blueprints{
dots: 5,
lines: 25,
shapes: []myshapes{
    myshapes{
        title:"car #1",
        circles:5,
        squares:7,
    },
    myshapes{
        title:"car #2",
        circles:2,
        squares:14,
    },
}

How do I print:
title:"car #1"
circles:5
squares:7
title:"car #2"
circles:2
squares:14

Comment: Let's not pretend or guess what types`blueprint` and `myshapes` are: [How to create a Minimal, Complete, and Verifiable example.](http://stackoverflow.com/help/mcve)
Answer: The example below shows how you'd print a particular field value of a struct:
type child struct {
    name string
    age int
}

type parent struct {
    name string
    age int
    children child
}

func main() {
    family := parent{
        name: "John",
        age: 40,
        children: child{
            name: "Johnny",
            age: 10,
        },
    }

    fmt.Println(family.children.name); // Prints "Johnny"
}

The code above would print "Johnny", which is a value of a struct within the parent struct. The code doesn't make much sense, however, because the field is children, yet there is only ever able to be one child as its value.
Let's leverage slices. Now that we know how to print a particular value, all we would need for your case is to loop over a slice and print the same way we did above.
We can do that like this:
type child struct {
    name string
    age int
}

type parent struct {
    name string
    age int
    children []child
}

func main() {
    family := parent{
        name: "John",
        age: 40,
        children: []child{
            child{
                name: "Johnny",
                age: 10,
            },
            child{
                name: "Jenna",
                age: 7,
            },
        },
    }

    for _, child := range family.children {
        fmt.Println(child.name);
    }
}

The above example will pront "Johnny" and "Jenna".
You can use a similar pattern to what I showed above in your own code to loop through your structs and print whatever value your heart desires :)

Keep in mind, there are many ways to loop through things. For example, all the following loops would print "Johnny" and "Jenna" from the examples above.
for _, child:= range family.children{ // Prints "Jonny" and "Jenna"
    fmt.Println(child.name);
}

for i, _ := range family.children{ // Prints "Jonny" and "Jenna"
    fmt.Println(family.children[i].name);
}

for i := 0; i < len(family.children); i++ { // Prints "Jonny" and "Jenna"
    fmt.Println(family.children[i].name);
}

print a struct within a struct golang


Standard Deviation of Cauchy distribution on a given interval

Question: In general Cauchy distribution doesn't have standard deviation defined, though it should be possible to calculate it for a given interval.
This is the formula that I'm trying to use:

PDF for Cauchy is

The mean for Cauchy is 0, so taking 0.4 as a scale and [-3;3] as interval we get an integral

Which gives a value of 0.6174 = (0.7858)^2
But when I generate any number of Cauchy values with scale 0.4 (I was trying to generate 10,000 and 10,000,000 numbers - it didn't matter) and filter-out all the numbers which absolute value is greater than 3 it always gives me SD = 0.8198 which is completely different.
Any ideas on what am I doing wrong? Sorry to ask such a silly question.
Comment: You are looking at a *truncated* Cauchy distribution. That means you need to recalculate the normalizing constant for the PDF. That is, you need to divide the untruncated pdf by  $P( -3 < T < 3)$. Once you use this new normalizing constant, your formula for the standard deviation should work out.
Comment: A constant that you multiple the PDF by to insure that it integrates to 1. See [here](https://en.wikipedia.org/wiki/Normalizing_constant).
Comment: Could you please clarify what you mean by "normalizing constant"?
Comment: Unless you normalize to make the distribution a true truncated Cauchy it is not appropriate to call the integral a variance.
Comment: Actually by "truncated Cauchy distribution" I've found a paper which gives another PDF (even without PI in it) and by integrating this I've managed to get the required number. Thanks a lot! https://projecteuclid.org/download/pdfview_1/euclid.bjps/1291387776
Answer: Cliff helped me a lot and I've found a nice paper about truncated Cauchy distribution https://projecteuclid.org/download/pdfview_1/euclid.bjps/1291387776
Solving the integral for symmetrical interval [-A; A] we get:
$$\delta = -\frac{\gamma (arctan(\frac{A}{\gamma})*\gamma-A)}{arctan(\frac{A}{\gamma})} $$
$$MAD = \frac{\gamma*ln(\frac{\gamma^2+A^2}{\gamma^2})}{2*arctan(\frac{A}{\gamma})}$$


call react component in loop based on onclick button function which sets the state to true once button is clicked

Question: I am new in react, i am trying to get component based on if button is clicked and once the component is returned to Ui, i want to change button state back to original(false),so if i click on that button again i should get again new component below to the previous one,and this should just go on..,
in below code i am able to get this just one time.
const Command = () => {
  const [buttonState, setButtonState] = useState(false);

  const AndOrHandler = () => {
    if (buttonState) {
      return (

          <Grid container>
            <SomeComponent />
          </Grid>

      );
    }
    return null;
  };

  return (
    <Fragment>
      <FormControl>
        <SomeComponent />
        <AndOrHandler />
        <Button onClick={() => setButtonState(true)} variant="contained" color="primary">Add Condition</Button>
      </FormControl>
    </Fragment>
  );
};

export default Command;

Comment: Are you simply wanting to toggle the `buttonState` state value to toggle the rendering of `AndOrHandler`? Or are you trying to add new elements to the UI upon each button click? The description of issue is a little vague in this regard. What is your expected behavior and try to be as clear and concise as possible.
Comment: yes, I am trying to add new elements to the UI upon each button click
Comment: Can you please update your code with the looping logic? Or is that what you want us to write for you? What have you tried?
Comment: That is the part which i am not able to figure out, how to add loop here and render component on that... i was trying with, do while, but did not got satisfactory results..
Comment: Yeah, the switching of your mindset from imperative to declarative coding is a bit of a stumbling block for many, myself included. Go with Viet's solution but I do strongly suggest using functional state updates when the next state *depends* on the current state. If you get into that habit now when you're learning you can more easily avoid an entire class of react state bugs. Good luck, mate.
Answer: You want continue adding component, i suggest have state components:
const Command = () => {
    const component =

        <Grid container>
            <SomeComponent />
        </Grid>

;

    const [components, setComponents] = useState([]);

    return (
        <Fragment>
            <FormControl>
                <SomeComponent />
                {components.map(component => component)}
                <Button onClick={() => setComponents([...components, component])} variant="contained" color="primary">Add Condition</Button>
            </FormControl>
        </Fragment>
    );
};

export default Command;

Comment: Again, the idiomatic way to enqueue state updates that *depend* on existing state is to use a functional state update, `setComponents(components => [...components, component])`.
Comment: not really, I want loop like functionality, on button click i should get new new component below to previous component, your suggestion will just hide and show my current component.
Comment: The idiomatic way to toggle a boolean react state value is to use a functional update, i.e. `setButtonState(state => !state)`, BTW.


Verificar se um processo não está rodando para então executá-lo no Windows

Question: gostaria de verificar se um processo está ativo no windows e caso não executá-lo automaticamente, pois é um servidor dedicado e cai as vezes.
Pensei em rodar o script de tempo em tempo no agendador.
o nome do processo é servertet.exe
Agradeço desde já a ajuda!
Answer: Pensando na solução do seu problema, recomendo executar o aplicativo como serviço do windows, dessa forma você pode configurar para iniciar automaticamente, e se caso sua aplicação venha a cair mesmo com o servidor ligado, o serviço do windows cuida para reinicialo.
Assim, o uma das opções é o NSSM http://nssm.cc/usage.
Baixe o aplicativo do site acima (é Free) e coloque na mesma pasta do seu exe.
Em seguida entre no console do windows (cmd), vá até a pasta que baixou o arquivo e digite:
<code>nssm install servertet
</code>
Será aberta uma janela para informar os parâmetros do serviço, informe os dados:
No campo Path, localize o arquivo servertet.exe
No campo StartupDirectory deixe do jeito que ele preencheu, caso queira (e saiba), pode preencher os demais campos das outras abas.
Clique em InstallService e o serviço será instalado.
A partir deste momento servertet passa ser controlada como um serviço do windows normalmente.
OBS.: Lembre-se de fechar o servertet.exe e iniciar como serviço do windows, e teste antes de colocar em produção.
Comment: Obrigado pela resposta rápida amigo!
Vou tentar esse método, até pq o server roda através de um arquivo bat.
Comment: Deu certo? Se sim, poderia marcar a pergunta como respondida? Na dúvida, visite o [tour] para saber como fazer isso. Obrigado.


how to avoid if/else loops in JQuery

Question: The below code works perfectly but the if/else statements look so long and ugly. Is there a way I can avoid these statements?
CommissionTypeFilterVm is a list that contains 6 properties shown below whose values are either 1 or 0. I wanted to enable and disable the checkbox's based on the values of these properties:
CommissionType
CommissionTrials
OverrideType
OverrideTrials
BonusType
AdjustmentType

Here is the code:
   if (view != null)
        {
            if (view.CommissionTypeFilterVm !=null && view.CommissionTypeFilterVm.length>0)
            {
                if (view.CommissionTypeFilterVm[0].CommissionType != 1) {
                    this.$commissionType.prop("checked", false).prop("disabled", true);
                } else {
                    this.$commissionType.prop("disabled", false).prop("checked", true);
                }
                if (view.CommissionTypeFilterVm[0].CommissionTrials != 1) {
                    this.$commissionTrails.prop("checked", false).prop("disabled", true);
                } else {
                    this.$commissionTrails.prop("disabled", false).prop("checked", true);
                }
                if (view.CommissionTypeFilterVm[0].OverrideType != 1) {
                    this.$overrideType.prop("checked", false).prop("disabled", true);
                } else {
                    this.$overrideType.prop("disabled", false).prop("checked", true);
                }
                if (view.CommissionTypeFilterVm[0].OverrideTrials != 1) {
                    this.$overrideTrails.prop("checked", false).prop("disabled", true);
                } else {
                    this.$overrideTrails.prop("disabled", false).prop("checked", true);
                }
                if (view.CommissionTypeFilterVm[0].BonusType != 1) {
                    this.$bonusType.prop("checked", false).prop("disabled", true);
                } else {
                    this.$bonusType.prop("disabled", false).prop("checked", true);
                }
                if (view.CommissionTypeFilterVm[0].AdjustmentType != 1) {
                    this.$adjustmentType.prop("checked", false).prop("disabled", true);
                } else {
                    this.$adjustmentType.prop("disabled", false).prop("checked", true);
                }
            }
        }

Comment: This would be better suited for http://codereview.stackexchange.com
Comment: Depending on what else is contained in `view`, you could use a for in loop to loop through all properties of view and update the corresponding field based on it's value.
Answer: It may depend on your exact view.CommissionTypeFilterVm[0] object (what other properties does it have) but it looks like you try to do this :
var com = view.CommissionTypeFilterVm[0];
for (var key in com) { // if necessary check ownProperty
   this['$'+key.charAt(0).toLowerCase()+key.slice(1)]
      .prop({checked: com[key]==1, disabled: com[key]!=1});
}

Comment: `this['$'+key.lowerCaseFirst()].prop({checked: com[key]==1, disabled: com[key]!=1})`, but +1
Comment: @KevinB: It's not official. You could add it to the String.prototye, but it was enough to be descriptive :-)
Comment: @dystroy: It seems to me that OP is setting both the `checked` and `disabled` properties whether the condition passes or fails. Am I reading it wrong?
Comment: @Bergi I've never heard of lowerCaseFirst, and can't find it in the MDN. doesn't seem to work in chrome either. Am i just looking in the wrong place?
Comment: +1 Bergi, I hadn't see the first char case. I edited with a fix.
Comment: You need to set both the `checked` and `disabled` for each property. Right now you're just setting one or the other.
Comment: I am getting the following error when tried ur code: Microsoft JScript runtime error: Unable to get value of the property 'prop': object is null or undefined
Comment: Check the spelling of your trial(s).
Answer: if (view && view.CommissionTypeFilterVm && view.CommissionTypeFilterVm.length) {
    var vm = view.CommissionTypeFilterVm[0],
        props = ["CommissionType", "CommissionTrials", "OverrideType", "OverrideTrials", "BonusType", "AdjustmentType"];
    for (var i=0; i<props.length; i++) {
        var prop = props[i],
            bool = vm[prop] != 1,
            key = "$"+prop.charAt(0).toLowerCase()+prop.slice(1);
        this[key].prop({checked: !bool, disabled: bool});
    }
}

You could work around the ugly key manipulation if you'd named your properties respectively. You need to do so anyway as you have a typo in the trails/trials.
Comment: +1 for your remarks on my answer (I hadn't see until now you had made an answer too). For the typo, I guess it had to be fixed anyway, not reproduced.
Answer: You can just create a static map and loop over it:
    if (view != null && view.CommissionTypeFilterVm != null && view.CommissionTypeFilterVm.length > 0)
{
    var mapping = [
        { type: 'CommisionType', ele: '$commisionType' },
        { type: 'CommissionTrials', ele: '$commissionTrails' },
        { type: 'OverrideType', ele: '$overrideType' },
        { type: 'BonusType', ele: '$BonusType' }
    ];
    var self = this;

    $.each(mapping, function() {
        if (view.CommissionTypeFilterVm[0][this.type] !==1) {
            self[this.ele].prop("checked", false).prop("disabled", true);
        } else {
            self[this.ele].prop("disabled", false).prop("checked", true);
        }
    });
}

Hope that helps.
Comment: Could be further optimised, see @Sushanth--'s answer
Answer: Maybe not efficient .. Try this
if (view != null)
{
    if (view.CommissionTypeFilterVm !=null
                    && view.CommissionTypeFilterVm.length>0)
    {
        var typeFilter = view.CommissionTypeFilterVm[0];
        var check = typeFilter.CommissionType === 0 ? true : false;
        this.$commissionType.prop({ 'checked' : !check , 'disabled' : check });
        check = typeFilter.CommissionTrials === 0 ? true : false;
        this.$commissionTrails.prop({ 'checked' : !check , 'disabled' : check });
        check = typeFilter.OverrideType === 0 ? true : false;
        this.$overrideType.prop({ 'checked' : !check , 'disabled' : check });
        check = typeFilter.OverrideTrials === 0 ? true : false;
        this.$commissionType.prop({ 'checked' : !check , 'disabled' : check });
        check = typeFilter.BonusType === 0 ? true : false;
        this.$bonusType.prop({ 'checked' : !check , 'disabled' : check });
        check = typeFilter.AdjustmentType === 0 ? true : false;
        this.$adjustmentType.prop({ 'checked' : !check , 'disabled' : check });
    }
}

Comment: Could be further optimised, see @syazdani's answer

how to avoid if/else loops in JQuery


What is the difference between Translation language, Translation source, and Original language?

Question: Would anyone be able to explain to me what the difference is between "Original language", "Translation language", and "Translation source"? I think I have a pretty good idea, but for example I've added all of the above to my content overview admin view, and I translated one entity from English to German. The row for that translation in the overview table has:

original language -> German
translation language -> German
translation source -> English

Translation language and Translation source I assume is the language content was translated to, and Translation source was what content the translation was derived from. So, is Original language just the language that the specific content was created in? If so, how does Original language differ from Translation language? Thanks for helping me understand.
Answer: There's an open issue about "Original language" and "Translation language" at https://www.drupal.org/project/drupal/issues/2450195. Its current issue summary includes an explanation of how they're supposed to work:

All translatable entities have a field called Original Language, which is [base table].langcode (e.g., node.langcode for Node entities). They also have a field called Translation Language, which is [field data table].langcode (e.g., node_field_data.langcode for Node entities). Also keep in mind that in translatable entity Views currently, each row of the view output is one translation of the entity.

So, taking nodes as the easiest example, "Original language" is supposed to be the language the node was created in (node.langcode), "Translation language" is supposed to be the language of whatever translation the view has pulled in (node_field_data.langcode), and "Translation source" is whatever language was used as the source for the translation (node_field_data.content_translation_source).
As of right now, that issue is seven years old and still unresolved. Until it's fixed, when you use the "Original language" field, what you'll actually get is node_field_data.langcode, which is the same as "Translation language". ("Original language" when used as a filter or sort does give you node.langcode, which is what it's supposed to do.)
Comment: Thanks for the answer!


Which event should I use in Landing Page (Home) so that it won't show up when navigating to other VC?

Question: I have a view controller named HomeVC which acts as a center page to navigate to targeted view controllers based on conditions.
HomeVC is the Landing Page or main page.
In HomeVC, I have some UIControls like calendars and others.
Problem: The HomeVC shows up a brief second before navigating to VC2 when the condition is met.
Requirements:
How not to show HomeVC when condition is met when navigating to another UIViewController?
Update: Requirements
- not showing the UiControls on HomeVC
Here is the code for HomeVC:
override func viewDidAppear(_ animated: Bool) {

  super.viewWillAppear(animated)

 let defaults = UserDefaults.standard

 if defaults.object(forKey: "SessionToken") == nil {

  let VC = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentitfier: "VC2") as! VC2

 self.dismiss(animated: true, completion: nil)

 self.navigationController?.present(VC, animated: true)

 } else {

       //-- code for other task--

 }

}

Your help is appreciated. Thanks
Answer: Just turn off the dismissing and presenting animation to achieve that.
self.navigationController?.present(VC, animated: false)

self.dismiss(animated: false)

Comment: I used your suggestion in my code, it wont navigate and the homeVC is showed up when I used navigationController instead of present. Did I miss anything?
Comment: using above statements not working. I have to use self.dismiss(animated:false) and  self.present(VC, animated: false). Even this is OK BUT still see the homeVC in a fraction of a second. How to achieve a very smooth transition so that homeVC wont show up AT ALL? Why NavigationController can not be used in this condition?
Comment: For this to work, I would create a screen that looks just like the launch screen and use that to navigate to other view controllers.
Comment: as my in update requirement above. I think the HomeVC will show anyway. my solution is just make the uicontrol isHidden = true will show nothing on the homeVC so this will look nice.


Vmware host Insufficient Diskspcace

Question: We have two data stores each having vms. The second data store is now giving the insufficient disk erro. I have to put off some of the VMs in order to allow the critical vms for domain and email running. When I log onto the VMs, there is still available space however, on the storage configuration part, there much less space. The spaces are being used and we have to free the disk on the Vms although on the VMs there is space and then scan the data store to free space.
Please can someone tell me what should be done.
Comment: There are a number of ways to do it depending on what version/edition of vSphere you're running and what licensed features you have (storage vMotion, etc.). Assuming vSphere 5.x and no license you can simply shut down the VM, remove the VM from your inventory, move it from one datastore to the other using the datastore browser and then re-add the VM to your inventory.
Comment: Are your VMs thin provisioned or thick provisioned ? If you're running out of space and the VMs are thin provisioned then you're going to have issues...you'll have to migrate some of the vms to the first datastore.
Comment: Move some VM's from the almost full datastore to the not almost full datastore. You might be able to extend the datastore but without knowing anything about your server hardware there's no way to know if that's possible.
Comment: Thanks Lawrence and Joewerty, The VMs are thin provisioned. I am running my ESXi on Hp Proliant ML380 G7. The first data store is 130GB has 1VM and the second data store which has about 7 VM has 1TB. Currently the first data store has 110GB free space and the second data store has 5GB Free space. The VMs OS ranges from XP, 7, 2003 and 2012.
Comment: I am quit new here so can you tell me how I can migrate the VMs between the data store. I am already in the process of converting VM between the data store..much appreciated
Comment: I'm not a fan of using the VMware Converter to convert a VM for the purpose of moving it from one datastore to another. You can use this method (and in some cases it may be the only option, such as when moving vCenter server from one vSphere host to another) but it just seems like the wrong tool for the job to me.
Comment: Thanks Joeqwerty, I managed to move couple of VMs and free space for data store 2....
Comment: In doing so I managed to free 30GB yesterday on data store 2, and this morning I realized that this free space has been consumed fully. VMs cannot boot up. I had to shut down non crital VMs to have the critial one running. I now have 3GB free on data store 2. Free space data store 1 has not changed
Answer: Double-check that your VM's are thin-provisioned.  If not you can convert them, but you'll need to migrate them to the other datastore in order to complete the conversion.
If they are thin-provisioned, then its worth going through the VM's to look for any space you can reclaim.  old installers, log files etc.  Another tactic can be to reduce the page file size of any Windows VMs (you need to restart the VM to apply).
Make sure none of your VM's have snapshots running.  If so you'll need to delete/merge them.  However be aware that this can require more disk space to complete if the VM is powered on when snapshot is deleted.
Check the VMTools of your VM's, depending on their config you may be able to shrink the VM's disk usage (though usually not by much).
Lastly, check your datastores for wasted space, old VM's that haven't been deleted properly, and ISO's are common culprits.

Vmware host Insufficient Diskspcace


How to calculate percentages using z scores?

Question: sample distribution of 10
(20,12,8,10,7,11,13,6,4,16) miles
What percent of the commuters travel more than 8 miles to class?
Comment: Hint: Why do you need z-scores to calculate a percent here? If one person is male and one is female how would you calculate percent male?
Comment: @zbicyclist Not so, in the sense that if you knew you had say a uniform distribution and you knew a z score you could do calculations using the density function. It would be perhaps unusual to be in that situation, but it would be feasible. Any distribution for which mean and SD can be related to density, distribution, or quantile function would work.
Comment: @NickCox, thanks for the correction -- as you note, this would be unusual.  I commonly see analysts calculating z scores, and then over-assuming normality.
Comment: Not only do you not need them, you shouldn't use them unless you can assume the data are normal. With a normal distribution, z scores can be used to determine percentages, but this won't work with other distributions (e.g. a uniform distribution).
Answer: Using the Stabilized Normal Probability Plot technique, the data tests as normal:
   Obs    Xprime    Yprime      AbsDif alpha=.10 alpha=.05 alpha=.01
1    4 0.1435663 0.1728315 0.029265254 0.1324046 0.1453979 0.1724372
2    6 0.2531833 0.2554858 0.002302456 0.1324046 0.1453979 0.1724372
3    7 0.3333333 0.3028740 0.030459327 0.1324046 0.1453979 0.1724372
4    8 0.4030133 0.3534983 0.049515038 0.1324046 0.1453979 0.1724372
5   10 0.4681157 0.4612687 0.006847004 0.1324046 0.1453979 0.1724372
6   11 0.5318843 0.5166183 0.015266013 0.1324046 0.1453979 0.1724372
7   12 0.5969867 0.5716814 0.025305320 0.1324046 0.1453979 0.1724372
8   13 0.6666667 0.6255154 0.041151249 0.1324046 0.1453979 0.1724372
9   16 0.7468167 0.7711199 0.024303246 0.1324046 0.1453979 0.1724372
10  20 0.8564337 0.9069053 0.050471623 0.1324046 0.1453979 0.1724372

(JQT v21 i3 Technical Aids; Jul 1989.  Lloyd S. Nelson.  The power of this test was shown to compare favorably with the Shapiro-Wilk test and the Anderson-Darling test.)
Accepting the null hypothesis of normality, percentages can be calculated based on z-scores in the following manner:
Using R:
commute <- c(20,12,8,10,7,11,13,6,4,16)
pnorm((mean(commute)-8)/sd(commute))

Using Excel:
=NORM.S.DIST((AVERAGE(A1:A10)-8)/STDEV.S(A1:A10),TRUE)

where your sample is in the range A1:A10.


sufficient condition for equivalent norms

Question: I am writing this question with respect to the following answered question Two (equivalent ?) norms on Hilbert space that I feel a little uncertain of.
Then, I know that under the standard euclidean norm, $\langle f,g\rangle = \int_{\mathbb{R}} f(x)g(x)dx$, which induces the standard euclidean metric, $\|f\| = \langle f,f\rangle^{1/2}$, the space $L_2(\mathbb{R},\langle\cdot,\cdot\rangle) = \{ f | \|f\|_2<\infty\}$ is a Hilbert space.
Further define a strictly positive weight function $w:\mathbb{R}\mapsto\mathbb{R}$ such that $\int_{\mathbb{R}}w(x)dx = 1$, $w(x)> 0$ for all $w\in \mathbb{R}$ and $\|w\|_\infty <\infty$. Then I can define the weighted inner product by $\langle f,g\rangle_w = \int f(x)g(x)w(x)dx$, with induced norm $\|f\|_w = \langle f,f,\rangle_w^{1/2}$. Then, $L_2(\mathbb{R},\langle\cdot,\cdot\rangle_2) = \{f | \|f\|_w<\infty\}$, the space of all functions that are square integrable with respect to the weight $w$, is also a Hilbert space.
We also have the following inequality:
$$
\|f\|_w^2 = \int f(x)^2w(x)dx \leq \|w\|_\infty\int f(x)^2dx = \|w\|_\infty \|f\|_2
$$
which implies that $L_2(\mathbb{R},\langle\cdot,\cdot\rangle_2) \subset L_2(\mathbb{R},\langle\cdot,\cdot\rangle_w)$.
Question: Are these two norms equivalent?
Based off the question on stackexchange that I have referenced above, this is the following line of thought that I am going with.
Define a linear operator $T: L_2(\mathbb{R},\langle\cdot,\cdot\rangle_w) \mapsto L_2(\mathbb{R},\langle \cdot,\cdot\rangle)$ by the following mapping $T(f)= f$. Given the definition of T we have that $T$ is injective.
Furthermore, by our inequality, since $L_2(\mathbb{R},\langle\cdot,\cdot\rangle_2) \subset L_2(\mathbb{R},\langle\cdot,\cdot\rangle_w)$ we must also have that $T$ is surjective.
Under this construction, I believe that $T$ is a bijection and by the open mapping theorem, if $T$ is bounded, then $T^{-1}$ is also bounded. All that remains is to show that $T$ is bounded. By the closed graph theorem, we just need to show that if for any sequence $\|f_n-f\|_w \rightarrow 0$ and $\|Tf_n-g\|_2 = \|f_n-g\|_2\rightarrow 0$ then $f=g$ implies that $T$ is bounded.
Indeed, this is true since $\|f_n-g\|_w \leq \|f_n-g\|_2 \rightarrow 0$ and so we have that
$$
\|g-f\|_w \leq \|g-f_n\|_w + \|f_n-f\|_w \rightarrow 0\,,
$$
and since $w(x)>0$ for all $x\in\mathbb{R}$, we must have that $g=f$ almost everywhere. Hence $T$ is bounded.
Since both $T$ and $T^{-1}$ are bounded, it is an immediate consequence that both $\|\cdot\|_2$ and $\|\cdot\|_w$ are equivalent.
I feel like I've done something `handwavey' somewhere but I can't seem to pinpoint it.. Is this just a dream come true of a result or am I missing something fundamental?
BONUS QUESTION What are sufficient conditions on the weight function $w$ necessary to ensure that $\|\cdot\|_2$ and $\|\cdot\|_w$ are equivalent norms?
Comment: Yes that is my exact point. Really what you're assuming in your argument is that $\| f\|_w < +\infty$ implies that $\|f\|_2 < +\infty$, which is a pretty strong assumption.
Comment: I think I may have found a counterexample. Take $w(x) = \frac{1}{2} e^{-\lvert x \rvert}$ for all $x \in \mathbb{R}$. Now if we take $f(x) = e^{\lvert x\rvert /2}$, this function would be in $L_2(\mathbb{R},\langle \cdot, \cdot \rangle_w )$ but clearly this function can't be in the usual $L_2$. I'll try to find the error in the reasoning and write out an answer, but it may take a while.
Comment: My thoughts on that are the fact that the linear operator isn't defined for such a function $f(x)$.. maybe that's where it is, I'm not sure. Or the fact that my linear operator $T$ is only well defined on the co-domain $L_2(\mathbb{R},\langle\cdot,\cdot\rangle_2)\cap L_2(\mathbb{R},\langle\cdot,\cdot\rangle_w) = L_2(\mathbb{R},\langle\cdot,\cdot\rangle_2)$ which is not closed under $\|\cdot\|_w$.... hrmm.....
Comment: Yes that's exactly what I thought, really if you want $T(f) = f$ be well defined you already have to require that $T(f) = f \in L_2(\mathbb{R}, \langle \cdot, \cdot \rangle)$ for all $f \in L_2(\mathbb{R}, \langle \cdot, \cdot \rangle_w)$. So in order for $T$ to be well defined, you already have to assume $L_2(\mathbb{R}, \langle \cdot, \cdot \rangle_w)$ and $L_2(\mathbb{R}, \langle \cdot, \cdot \rangle)$ are the same.
Comment: well the thing is, in my mind the underlying vector space for both hilbert spaces is simply the space of all functions, which when induced by the different inner products leads to two differnt hilbert spaces. Going to the referred question on stackexchange, it almost looks like the two norms should be equivalent then, or is my interpretation of that wrong as well
Comment: maybe that's not necessarily true, because I restrict $L_2(\mathbb{R},\langle\cdot,\cdot\rangle_2)$ to the vector space of functions such that $\|f\|_2 <\infty$, and therefore the underlying vector space for both $L_2(\mathbb{R},\langle\cdot,\cdot\rangle)$ and $L_2(\mathbb{\mathbb{R}},\langle\cdot,\cdot\rangle_w)$ are different.
Comment: Ok I agree with that. I wonder what are some sufficient conditions on $w$ to ensure that they are equivalent..
Answer: As pointed out in the comments, your operator $T : L^2_w \to L^2$ is not well-defined, since there are $f \in L^2_w$ which do not belong to $L^2$.
In fact, under your assumptions, the norms are never equivalent. Let $\varepsilon > 0$. From $\int w = 1$ and $w > 0$, we find a measurable set $A \subset \mathbb R$ with positive Lebesgue measure and $w \le \varepsilon$ a.e. on $A$. Now, we define the function
$$f_\varepsilon = \chi_A,$$
where $\chi_A$ is the characteristic function of $A$ (it is $1$ on $A$ and $0$ outside of $A$).
Now, an easy calculation shows
$$\|f_\varepsilon\|_2 = \sqrt{\mu(A)},
\qquad \| f _\varepsilon \|_w \le \varepsilon \, \sqrt{\mu(A)},$$
where $\mu(A)> 0$ is the measure of $A$. Since $\varepsilon > 0$ was arbitrary, your norms cannot be equivalent.
Comment: that's a nice counterexample


Fingering first measure Funeral March

Question: Is the 5 5 fingering for the left hand, first measure, correct?
I ask it because it is for me as a beginner difficult to reposition my left pink quickly on the right place. Is there a good alternative?
Answer: There's rarely any 'correct' fingering! There's suggested fingering (bit like guitar tab!) but it's been done usually by someone who it works for. And if that's not you, you don't have to use it!
It does seem a bit jumpy, playing with pinky then playing another, higher note with pinky again. Certainly the F notes need pinky, then a sort of hand roll through index, up to A with thumb, and back to C again with index, making the stretch down to F not-too-bad using pinky again. As always, try out as many different fingerings as you can with any piece - I'm still doing that after 60+ yrs playing! But I reckon most will bottom out at 5-2-1-2.
Answer: The 5-5 is a viable option, particularly since the pedal is there to help cover the gap.
My preferred fingering would be 5-2-1, because the 5-2 is fairly comfortable, and I have a wide span between 2 and 1.
Some people prefer 5-3-1.

Fingering first measure Funeral March


App to web video calling using Sinch

Question: I am working on a project which is created as an application and as a website. This application includes app to app video calling as well as app to web video calling also. I have successfully implemented app to app calling, but how can i implement app to web calling.
My project includes user1 and user2. User1 calls user2 on app. App to app calling is successful,but user2 can be logged in from website also, then in this case i have to accomplish a video call from app to web. Please help me by some code for how can  i achieve this using Sinch library. Thank you.
Comment: @ShivamOberoi Please check this post  https://stackoverflow.com/questions/31278922/why-is-the-sinch-call-quality-from-mobile-app-to-browser-very-poor    This says that it is possible
Comment: Yes its possible...you can talk to Sinch support regarding this..
Answer: Yes it is possible to set a video call from phone to web using Sinch lib.
Code for this is same as for phone to phone calling. There is no change in the code in android.

App to web video calling using Sinch


How to resolve hostnames from a intranet interface?

Question: I have a public IP and some hostnames pointing to it, on this public IP server I have others intranet interfaces running apache virtual hosts servers, my question is how can I forward external requests to this interfaces?
On a simple apache virtual hosts running in the public IP machine I can easy do that editing /etc/hosts this way
127.0.0.1 mysite.com
127.0.0.1 blog.mysite.com

But by some motive it not work with intranet interfaces
172.17.0.1 mysite.com
172.17.0.2 blog.mysite.com
172.17.0.2 news.mysite.com

ps: A apache server is running on each IP
I simple get ERR_CONNECTION_REFUSED, if a ping it I get the server IP, so the public DNS are working
Can you help me?
Comment: The problem it self is that
Answer: The solution
Ok hours later I found the answer, is very simple:
You need to have another apache instance or whatever like it running on port 80 for this case and create virtual hosts to resolve the hostnames to the intranet ips.
More explanation
If I have apache running in others intranet IPs they are not visible on public IP, if someone access myhost.com he will be pointed to 0.0.0.0:80 (public ip), so in this port you need to have some service that understand the request and forward it to the respective internal host, apache do that.


Uploading Android aar library to bintray from TravisCI

Question: This is my first time trying to publish something to maven but I have an Android library that I am trying to integrate with TravisCI to build it when anything gets pushed to master Looking at the Bintray gradle documentation along with some articles I found about integration between the two and I came up with this for my build.gradle file
apply plugin: 'com.android.library'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'
apply plugin: 'com.jfrog.bintray'
apply plugin: 'maven-publish'

    publishing {
        publications {
            Production(MavenPublication) {
                artifact("$buildDir/outputs/aar/mlcamera-release.aar")
                groupId 'com.tycz'
                artifactId 'mlcamera'
                version '0.1.0'

                //The publication doesn't know about our dependencies, so we have to manually add them to the pom
                pom.withXml {
                    //def dependenciesNode = asNode().appendNode('dependencies')
                    //Iterate over the compile dependencies (we don't want the test ones), adding a <dependency> node for each
                    configurations.compile.allDependencies.each {
                        if (it.name != 'unspecified') {
                            def dependencyNode = dependenciesNode.appendNode('dependency')
                            dependencyNode.appendNode('groupId', it.group)
                            dependencyNode.appendNode('artifactId', it.name)
                            dependencyNode.appendNode('version', it.version)
                        }
                    }
                }
            }
        }
    }

    bintray {
        // Get Bintray credential from environment variable
        user = System.getenv('BINTRAY_USER')
        key = System.getenv('BINTRAY_API_KEY')
        dryRun = false
        override = false
        publish = true
        pkg {
            repo = 'MLCamera'
            name = project.name
            userOrg = 'tyczj359'
            desc = 'A wrapper library for the new CameraX API and Firebase MLKit to create easier setup for MLKit usage'
            vcsUrl = 'https://github.com/tyczj/MLCamera.git'

            version {
                name = '0.1.0'
                released = new Date()
            }
        }
        publications = ['Production']
    }

android {
    compileSdkVersion 29
    buildToolsVersion "29.0.3"

    defaultConfig {
        minSdkVersion 21
        targetSdkVersion 29
        versionCode 1
        versionName "0.1.0"

        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
        consumerProguardFiles 'consumer-rules.pro'
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }

    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }

    kotlinOptions {
        jvmTarget = JavaVersion.VERSION_1_8.toString()
    }

}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
    implementation 'androidx.appcompat:appcompat:1.1.0'
    implementation 'androidx.core:core-ktx:1.2.0'
    implementation 'com.google.firebase:firebase-ml-vision:24.0.1'
    implementation 'com.google.firebase:firebase-ml-vision-barcode-model:16.0.2'
    implementation 'com.google.firebase:firebase-ml-vision-object-detection-model:19.0.3'
    implementation 'androidx.core:core-ktx:1.2.0'
    implementation "androidx.camera:camera-core:1.0.0-beta01"
    implementation "androidx.camera:camera-camera2:1.0.0-beta01"
    implementation "androidx.camera:camera-view:1.0.0-alpha08"
    implementation "androidx.camera:camera-lifecycle:1.0.0-beta01"
    implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.3.0'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'androidx.test.ext:junit:1.1.1'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'

}

The library itself seems to build fine in travis but when I look in my bintray repo I see that there is nothing there.
This is my yml file for building on travis
language: android
jdk: oraclejdk8
dist: trusty

android:
  components:
    - build-tools-29.0.3
    - android-29
    - extra-google-m2repository
    - extra-android-m2repository
    - extra-google-google_play_services
script:
  - ./gradlew build
before_cache:
  - rm -f  $HOME/.gradle/caches/modules-2/modules-2.lock
  - rm -fr $HOME/.gradle/caches/*/plugin-resolution/
cache:
  directories:
    - $HOME/.gradle/caches/
    - $HOME/.gradle/wrapper/
    - $HOME/.android/build-cache

Can anyone help me out here to get it published to bintray?
This is the full repo anyone needs something else
Answer: The Travis yml file is only building the aar but not publishing as per the script command ./gradlew build. Changing it to ./gradlew build bintrayUpload should do the trick as in step 8 here.
Comment: When I add that I get an error saying `Execution failed for task ':mlcamera:publishProductionPublicationToMavenLocal'.

> Failed to publish publication 'Production' to repository 'mavenLocal'

   > Invalid publication 'Production': multiple artifacts with the identical extension and classifier ('aar', 'null').`


Fetch images across the internet with File API

Question: How can I use the FileAPI to fetch an image from another website via URL, and bring it into Drupal? Here is what I tried:
<code>foreach ($data['photos'] as $item) {
            $photo = file_get_contents($item['url']);

            $filename = $entity->field_id['und'][0]['value'] . '-' . $x . '.jpg';

            $file = file_save_data($photo, 'public://' . $filename, FILE_EXISTS_REPLACE);

            if (is_object($file) && file_exists($file->uri)) {
                $file->status = 1;
                $file = file_save($file);
                drupal_write_record('file_usage', $file);
                $entity->field_entity_image['und'][] = (array) $file;
                $x++;
            } else {
                // error
            }
        }
</code>
It doesn't quite work. The first time around it grabs some of the photos, then the second time around, it should remove any photos in the system and resave them (even if none changed), I have no way to tell if the remote file is new or not.
Answer: You might want to try just leaving the remote files as remote and have something like http://drupal.org/project/remote_stream_wrapper? There's an open issue in the module to add a field widget for image and file fields to support just a simple URL entry for a file.
Comment: How is that implemented? I see what it does, but not how to utilize it.
Answer: Not quite what you are looking for, but I have used Imagecache External with decent results.  Derivatives definitely gets saved locally.  I don't 100% recall whether a copy of the original gets saved locally.  This may or may not fit your needs.
The D7 version is in git, and not on the module page.
Comment: I suspect so.  Once in your templates, the images behave just like any other image field w/ an image style.  If you need it, you may need to make a no-scale image style so that a derivative gets saved locally, which isn't always a bad thing (allows you to set JPEG quality and ensure decent filesizes).
Comment: Interesting... so I would be able to use this with say Lightbox or jquery Cycle style display?
Comment: very interesting option. So the image styles get generated when you save your image node?
Comment: Derivative image URLs are built when the theme('image_style') gets invoked, and the img element via theme('image').  The actual derivative is generated on the fly when the URL is requested (see image_menu and image_style_deliver).  From the theme's and user's perspective, the external images are indistinguishable from other images using the same style when you use this module.


How to normalize mutual information between to real-valued random variables?

Question: How can I normalize mutual information between to real-valued random variables using Python or R? sklearn.metrics.normalized_mutual_info_score seems to work for only nominal data. Or how to interpret the unnormalized scores?
Answer: Strictly speaking you cannot just do that as-is.
Mutual information requires knowledge of your data generating probability density function. Nominal data naturally defines such pdf with counts. Continuous data doesn't.
There are two ways to handle that: either assume some pdf, like something parametric (or obtained with kernel smoothing), or convert your data to nominal data (this can be done for example using bucketing).


name of element mouse is hovering

Question: I'm using a global variable that toggles between true and false on mouse enter of a div and then I'm using the value of this variable elsewhere to show / hide another element depending on the value.
Actually, another way to do what I want would be to know if the mouse is hovering a div called MyDiv. I'm looking to remove the use of the global variable that toggles with the mouseenter/mouseleave events.
I tried this:
 var test = $('#MyDiv').mouseover() ? 1 : 0;

but it's not working.
Let me know if you have a 1-liner suggestion for returning the name of the div that's being hovered.
Thanks.
PS: I already know it can be done with more than 1 line
Comment: You want to know which element the mouse is currently over without having to add a hover handler to every element?
Answer: You should store your flag in jQuery's data storage:
$(this).data("mouseover", true);
if ($(this).data("mouseover"))

Comment: This still stores some value; I was looking to see if jquery enabled you to determine the name of the div being hovered. Looks like it's not possible.
Answer: You can do this:
$('#MyDiv').mouseover(function(){
    //show/hide other div or any other code
}) ;

OR
you can set another global variable that tells you whether mouse is hovering on MyDiv like this:
$('#MyDiv').mouseover(function(){
    myDivHovering = true;
}).mouseout(function() {
    myDivHovering = false;
}) ;

Comment: The show/hide works within a SetTimeout; hence I need to know where the mouse is when the time comes, not when the mouse enters or leaves.
Comment: Right but I'm looking to make it work without a global variable (the functionality currently already works with a global variable). Any way to determine the name of the div being hovered?
Comment: You want to know when the SetTimeout fires, which element the mouse is hovering on? And you don't want a global variable? And what if  the mouse not hovering on a div at that point?
Comment: Yes, all that ! If the mouse isn't hovering the div then don't hide another div
Answer: jQuery uses a callback style to handle events. The functionality you're describing can be implemented like so:
var mouse_on_mydiv = false;
$('#MyDiv').hover(function onMouseIn() {
    mouse_on_mydiv = true;
    alert(this.id); // => 'MyDiv'
}, function onMouseOut() {
    mouse_on_mydiv = false;
});

Comment: yes, this is already what I have, using a global variable. I'm looking to remove the global variable.
Comment: I don't know the context here. What is stopping you from removing it? Is it being used in some other part of your code that you want to refactor?
Comment: The global variable is not being used anywhere else and everything works. It's just that I'm looking to remove the variable.
Comment: Sure, take it out then :) I'm not sure what you mean. Is it that you want to have a method like $('#MyDiv').isMouseOver() that you can call from elsewhere? In that case SLaks' answer would fit your requirements.

name of element mouse is hovering


GPS location in my app

Question: Im having trouble passing the current location to my LatLng variable to show on my google map. Im not sure how to pass the value from my override statement in my location listener method. Im trying to implement an application that simply gets the GPS coordinates and places a marker on the map.
    @Override
       protected void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       setContentView(R.layout.activity_maps);

    locationManager = (LocationManager)getSystemService(LOCATION_SERVICE);

    //obtain location
    listener = new LocationListener() {
        @Override
        public void onLocationChanged(Location location) {
            double lat = location.getLatitude();
            double lng = location.getLongitude();
            LatLng appoint = new LatLng(lat,lng);
            return appoint;
        }

        @Override
        public void onStatusChanged(String s, int i, Bundle bundle) {

        }

        @Override
        public void onProviderEnabled(String s) {
        }

        @Override
        public void onProviderDisabled(String s) {
        }
    };

    // Obtain the SupportMapFragment and get notified when the map is ready to be used.
    SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
            .findFragmentById(R.id.map);
    mapFragment.getMapAsync(this);

}

@Override
public void onMapReady(GoogleMap googleMap) {
    mMap = googleMap;

    double lat = 34.014783;
    double lng = -84.571381;

    // Add a marker in Appoint from database and move the camera
    LatLng appoint = new LatLng(lat,lng);
    mMap.addMarker(new MarkerOptions().position(appoint).title("Where the wild gays are"));
    mMap.moveCamera(CameraUpdateFactory.newLatLng(appoint));`

Comment: try to create method  and pass lat and long to that method from your onlocationchanged method
Answer: Well, onLocationChanged doesn't return anything void so you cannot return the LatLng object, but you can add the marker to the mMap object (as long as it is not null).
E.g.
public void onLocationChanged(Location location) {
        double lat = location.getLatitude();
        double lng = location.getLongitude();
        LatLng appoint = new LatLng(lat,lng);
        if(mMap != null) {
            mMap.addMarker(new MarkerOptions().position(appoint).title("Where the wild gays are"));
            mMap.moveCamera(CameraUpdateFactory.newLatLng(appoint));
        }
    }

GPS location in my app


How to set directory in antcallbacktask?

Question: In ant task in ant, we have a property named 'Dir' where i can specify the base directory to be used in the called target. I am looking for something similar in 'ant callback' task. How can i set the directory in ant callback
Comment: Let know the specific thing you want to achieve along with the code that you have already tried.
Answer: <antcall> and <antcallback> are tasks which can be used to call other targets within the same file. <antcallback> has all attributes of <antcall> except that antcallback allows the properties of the called target to be accessed back in calling target. For more details, refer AntCall and AntCallback
However, <ant> task is generally used to call a target in another Ant file. Hence, the dir attribute comes into significance.


how i can read file with byte inside

Question: I have some file with bytes inside:
b'<meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">'

And i try to read this file inside unit tetst in 'rb' mode:
def test_04_foo(self):
    with open('test_data.txt', 'rb') as reader:
        print(reader.read())

    #some code here

And i have b'' in stdout.
How i can get bytes from file?
Comment: This looks like someone put a *string representation* of a bytes object into a text file. Don't do that.
Answer: The file contains a string representation of a bytes object, so you could solve this by following these questions: "safe" eval, Convert bytes to a string - something like this:
import ast

def test_04_foo(self):
    with open('test_data.txt', 'r') as reader:
        b = ast.literal_eval(reader.read())
    s = b.decode('utf-8')
    print(s)

how i can read file with byte inside


MissingPlginException sqflite flutter

Question: there is no problem when I run it on my own phone, but when I ctrl f5 with windows and emulator, I got such an error. It worked when I uninstalled the app from the emulator and ran it again. Why did this happen and how do I solve it in windows?
Comment: If I understand correctly, you use this https://pub.dev/packages/sqflite package that doesn't support Windows application.
Comment: Do you run your application on the web or on the emulator of phone?
Comment: I had no problems when I ran it on my own phone. When I ran it with the emulator, it gave an error at first, but when I uninstalled the application from the emulator and ran it again, the problem in the emulator was resolved. But when I run it on windows the problem still persists.
Answer: You use this package pub.dev/packages/sqflite that doesn't support Windows application right now.
Comment: Try to check this package: https://pub.dev/packages/moor

MissingPlginException sqflite flutter