Are all algorithms with a constant base to the n (e.g.: k^n) of the same time complexity?

Question: In this example: http://www.wolframalpha.com/input/?i=2%5E%281000000000%2F2%29+%3C+%283%2F2%29%5E1000000000
I noticed that those two equations are pretty similar no matter how high you go in n. Do all algorithms with a constant to the n fall in the same time complexity category? Such as 2^n, 3^n, 4^n, etc.
Comment: They are in the same category, This does not mean their complexity is the same. They are exponential running time algorithms. Obviously 2^n < 4^n
Comment: That example doesn't really show anything about algorithmic complexity. No, 2^n is not the same complexity as 3^n. Do you want a proof?
Comment: @elbek: You're right, I spoke carelessly; they are in the same category, but not equal.
Answer: They are in the same category, This does not mean their complexity is the same. They are exponential running time algorithms. Obviously 2^n < 4^n
We can see 4^n/2^n = 2^2n/2^n = 2^n
This means 4^n algorithm exponential slower(2^n times) than 2^n
The same thing happens with 3^n which is 1.5^n.
But this does not mean 2^n is something far less than 4^n, It is still exponential and will not be feasible when n>50.
Note this is happening due to n is not in the base. If they were in the base like this:
4n^k vs n^k then this 2 algorithms are asymptotically the same(as long as n is relatively small than actually data size). They would be different by linear time, just like O(n) vs c * O(n)
Answer: The time complexities O(an) and O(bn) are not the same if 1 < a < b.  As a quick proof, we can use the formal definition of big-O notation to show that bn ≠ O(an).
This works by contradiction.  Suppose that bn = O(an) and that 1 < a  a, it should start to become clear that this is impossible - as n grows larger, bn / an = (b / a)n will get larger and larger.  In particular, if we pick any n ≥ n0 such that n > logb / a c, then we will have that

(b / a)n > (b / a)log(b/a) c = c

So, if we pick n = max{n0, c + 1}, then it's not true that bn ≤ c · an, contradicting our assumption that bn = O(an).
This means, in particular, that O(2n) ≠ O(1.5n) and that O(3n) ≠ O(2n).  This is why when using big-O notation, it's still necessary to specify the base of any exponents that end up getting used.
One more thing to notice - although it looks like 21000000000/2 is approximately 1.41000000000/2, notice that these are totally different numbers.  The first is of the form 10108.1ish and the second of the form 10108.2ish.  That might not seem like a big difference, but it's absolutely colossal.  Take, for example, 10101 and 10102.  This first number is 1010, which is 10 billion and takes ten digits to write out.  The second is 10100, one googol, which takes 100 digits to write out.  There's a huge difference between them - the first of them is close to the world population, while the second is about the total number of atoms in the universe!
Hope this helps!


Passing an argument to an Oracle Stored Procedure

Question: This may have been asked before, so I'm sorry if this is repeated. If you can link to where I can find an answer, I would really appreciate it. I've looked around at other answers and on Google but nothing seems to have worked yet.
So...
I have a stored procedure in Oracle 11g (that I cannot change) and I have to use OCI (no choice here).
The stored procedure declaration is like:
PROCEDURE GetEmployee(EID IN NUMBER, rcursor IN OUT cursor_type);

How do I call this in C?
I tried to use the OCI example here as a basis, modifying it so:
char * query =  "DECLARE \
     EID NUMBER; \
     RCURSOR CORP.EMPASSIST.cursor_type; \
     BEGIN \
       EID:= NULL; \
       RCURSOR := NULL; \
       EMPASSIST.GetEmployee( EID=> EID, RCURSOR => RCURSOR ); \
       :RCURSOR := RCURSOR; --<-- Cursor \
     END;";

OCIError * db_error;
OCIStmt * statement;
OCIEnv * environment;
OCIServer * server;
OCISession * session;
OCISvcCtx * service;

OCIBind * cursor_bind;
OCIBind * eid_bind;
OCIStmt * cursor_stm;
OCIStmt * eid_stm;

retval += OCIStmtPrepare(statement, db_error, (OraText *) query, strlen(query), OCI_NTV_SYNTAX, OCI_DEFAULT);
retval += OCIHandleAlloc(environment, (void **) &eid_stm, OCI_HTYPE_STMT, 0, NULL);
retval += OCIHandleAlloc(environment, (void **) &cursor_stm, OCI_HTYPE_STMT, 0, NULL);
retval += OCIBindByPos(statement, &eid_bind, db_error, 1, &eid_stm, 0, SQLT_NUM, NULL, 0, NULL, 0, 0, OCI_DEFAULT);
retval += OCIBindByPos(statement, &cursor_bind, db_error, 2, &cursor_stm, 0, SQLT_RSET, NULL, 0, NULL, 0, 0, OCI_DEFAULT);

retval += OCIStmtExecute(service, statement, db_error, 1, 0, NULL, NULL, OCI_COMMIT_ON_SUCCESS);

but this does not seem to work for me. All the handle allocation seems to work just fine. No errors.
However, it fails on the OCIStmtExecute step. I have to BindByPos after that, and they fail too, but I'm guessing that is because of the statement execution failure.
Please help!
==========================================================================
Fixed: Posting in answers in case it helps someone else
Comment: What exact failure are you seeing? Also I would think that since you are connecting to Oracle, `Pro*C` (pre-compiler) would be a better choice here. It would be n-times easier to do this in `Pro*C`. [Here](http://docs.oracle.com/cd/B10500_01/appdev.920/a97269/toc.htm) are some directions on `Pro*C`.
Comment: The statement executes fine. It is the result that is garbage. When I print out the defines variables, I get weird values. However, when I run the same thing in sqlplus, I get good results.
Answer: Changed:
char * query =  "DECLARE \
 EID NUMBER; \
 RCURSOR CORP.EMPASSIST.cursor_type; \
 BEGIN \
   EID:= NULL; \
   RCURSOR := NULL; \
   EMPASSIST.GetEmployee( EID=> EID, RCURSOR => RCURSOR ); \
   :RCURSOR := RCURSOR; --<-- Cursor \
 END;";

to
int eid = /* whatever value */;
char * query_template = "CALL EMPASSIST.GetEmployee(%d, :RCURSOR)";
char query[1023] =  {'\0'};
snprintf(query, sizeof(query) - 1, query_template, eid);

Changed the rest to:
OCIError * db_error;
OCIStmt * statement;
OCIEnv * environment;
OCISvcCtx * service;

OCIBind * cursor_bind;
OCIStmt * cursor_stm;

retval += OCIHandleAlloc(environment, (void **) &statement, OCI_HTYPE_STMT, 0, NULL);
retval += OCIStmtPrepare(statement, db_error, (OraText *) query, strlen(query), OCI_NTV_SYNTAX, OCI_DEFAULT);
retval += OCIHandleAlloc(environment, (void **) &cursor_stm, OCI_HTYPE_STMT, 0, NULL);
retval += OCIBindByName(statement, &cursorbind, db_error, (OraText *) ":RCURSOR", strlen(":RCURSOR"), &cursor, 0, SQLT_RSET, 0, 0, 0, 0, 0, OCI_DEFAULT);

retval += OCIStmtExecute(service, statement, db_error, 1, 0, NULL, NULL, OCI_COMMIT_ON_SUCCESS);

Answer: It would help if you post the actual error.
However as with named data types, binding REFs is a two-step process. First, call OCIBindByName() or OCIBindByPos(), and then call OCIBindObject().
REFs are bound using the SQLT_REF datatype. When SQLT_REF is used, then the program variable being bound must be of type OCIRef *.
With inheritance and REF substitutability, you can bind a REF value to a subtype instance where a REF to the supertype is expected.
Comment: The statement executes fine. It is the result that is garbage. When I print out the defines variables, I get weird values. However, when I run the same thing in sqlplus, I get good results.


How to add a tag on a deleted file in CVS?

Question: I need to create a branch from the state of the HEAD several days ago, for which I would like to add a tag on all files in a module. Trouble is that a few files were removed using cvs remove between that day and now. When I tried to do "cvs rtag" using -D option, I don't see the tag on the deleted files although the deleted files existed then in the cvs.
Is there a straightforward way to branch from a specific date with all the files that existed then?
Answer: Unfortunately cvs (r)tag does not allow mixing the -D and -r options. But cvs update does, so you can update your working copy to the date and branch you want and then cvs tag your working copy.


Convert single disk raid0 to raid1 on an LSI megaraid controller

Question: I have a server with an LSI Megaraid raid controller which has a single disk for the OS configured in raid0
What i want to do, is add a second brand new disk for redundancy and convert the raid0 to raid1 without losing the data on the first disk
Is it possible to do this with the Megaraid Controller ? If yes, is it maybe possible to do it without downtime as well ?
Could someone provide me with the megacli commands involved to achieve this?
Comment: Whether you can do it automatically via the controller or now I think everyone on this site would recommend backing up the server, rebuilding the array and restoring anyway - it's the only way to be sure it'll function as you wish.
Comment: @Chopper3 Why? The whole point with hardware RAID controllers is that they can do exactly these sorts of things. Yes, have a backup, but no need to rebuild and restore unless things go wrong.
Comment: @Colin'tHart - because after over thirty years of doing this kind of work I've seen many 'RAID conversions' go badly wrong, and the problem isn not always immediately apparent. The user needs to act professionally so needs to backup the system anyway before trying this conversion - at which point there's only two ways forward - try the conversion or create the new R1 and restore. The only way to be absolutely sure that the new array is in a known good state is the latter option as your conversion may have introduced lost data without you knowing.
Answer: To answer my own question, it is infact possible to migrate live from a single drive raid0 to raid1 (providing an extra disk) with Megaraid cards
The megacli command is as follows (it can also be done from within the WebBios configuration utility of the raid controller):
megacli -ldrecon -start -r1 -add -physdrv[e:s] -l0 -a0

where [e:s] is the enclosure:slot_number of the extra disk and -l0 is the logical disk ID of the raid0 disk.
Someone can monitor the progress of the reconstruction by issuing the command:
megacli -ldrecon -showprog -l0 -a0

Comment: I ended up with exactly same solution, but... Run "megacli -adpgetprop ReconRate -a0" and notice that you are doing a reshape at 30% speed. Sooo slooow. So I set the limit into 100% (the reshape was scheduled to a least-loaded time).
Comment: Surprisingly enough, after I set the newly added disk to offline, it did immediately start to rebuild the disk, which is about twice as fast as migration.


Como faço para não mapear uma Classe com o Entity Framework

Question: Estou fazendo meu primeiro sistema (C# ASP MVC 5) com o Entity Framework e Migrations.
Tenho minhas classes que foram mapeadas corretamente e migradas para o Banco de Dados que é SQL Server 2012.
Mas a questão é como eu posso criar uma classe que não seja mapeada pelo EF e Migrations?
Tenho uma classe de Certificados conforme abaixo:
Nesta classe que criar um campo StatusCertificado, para isso pensei em criar uma classe para que seja um tipo de dados enum, mas o EF insiste em criar essa classe/tabela no meu banco de dados. Este Enum apenas teria os valores (Ativo, Inativo, Vencido).
Penso então que eu não preciso criar uma tabela fisica no banco.
Qual a melhor forma de eu fazer isso? Agradeço antecipadamente.
using System;
using System.ComponentModel.DataAnnotations;

namespace ControleGCD.Models
{
    public class Certificado
    {

        [Key]
        public int CertificadoId { get; set; }

        public string CertificadoChave { get; set; }

        public string CertificadoDescricao { get; set; }

        public decimal CertificadoPreco { get; set; }

        public DateTime CertificadoDtCompra { get; set; }

        public DateTime CertificadoDtVencimento { get; set; }

        public DateTime CertificadoDtCadastro { get; set; }

       **public DateTime CertificadoStatus{ get; set; }**

    }
}

Comment: "seja um tipo de dados enum", porque não criar um enum?
Answer: Você pode usar a DataAnnotation [NotMapped]
namespace ControleGCD.Models
{
    public class Certificado
    {
        //...
        public DateTime CertificadoDtCadastro { get; set; }

        [NotMapped]
        public DateTime CertificadoStatus{ get; set; }
    }
}

Comment: Funcionou aqui perfeitamente, criei uma nova classe Enum (StatusCertificado )e na minha classe ja existente (certificados) criei uma propriedade do tipo StatusCertificado. Deu certinho. Obrigado pela ajuda.


High School Probability and Contradiction

Question: So I recently came across this question (2(a)) that my friend who teaches high school math posed to me. I thought the solution could be found by using the identities $P(B\,|\,A) = \dfrac{P(A\cap B)}{P(A)}$ and $P(A \cup B) = P(A) + P(B) - P(A \cap B)$. However it apparently leads to the conclusion that $P(A \cap B) > P(B)$. Does anyone have any suggestions why?
It seemed to work out to $\dfrac{2}{3}P(A) = P(A \cap B)$ and thus $\dfrac{16}{25} = P(A) + \dfrac{2}{5} - \dfrac{2}{3}P(A)$. So $P(A) = \dfrac{18}{25}$. But that means that $P(A \cap B) = \dfrac{12}{25}$.
Answer: Your approach is correct. The problem is with the question. The values are not consistent. It can be proved that given $P(B)$ and $P(B \mid A)$, the value of $P(A \cup B)'$ should be at least $\frac{7}{15}$.
Comment: I did the problem over and over again and couldn't figure out why my numbers didn't make sense (our numbers). I think this has to be a problem with the problem. Can you show how to prove that?
Comment: I was wondering if there was a theoretical explanation like it fails because of collinearity or whatever.


Formatting Date with month names in different languages using date pipe

Question: I am displaying date in html like this
{{ item.lastModified | date : 'MMM d, y' }}

So the date displays something like this Jul 20, 2021
Now when I change my browser language I need the month to change to that language the language should be picked up dynamically , but its displaying in English. How do I do this?
Answer: You need to set yours 'locale':

In your app.module.ts:

    // Import all the languages you need (you can add any language you want i.e: '../locales/en-GB', '/locales/en-US', ... ).
    // In this example, I will use 'es' for Spanish and 'fr' for French:
    import myLocaleEs from '@angular/common/locales/es'
    import myLocaleFr from '@angular/common/locales/fr'

    import {registerLocaleData} from '@angular/common';

    registerLocaleData(myLocaleEs);
    registerLocaleData(myLocaleFr);

In your HTML:

    // "en" is always by default, you don't need to register
    {{ fecha | date: "long":"":"en" }}

    {{ fecha | date: "long":"":"es" }}

    {{ fecha | date: "short":"":"fr" }}
or  {{ fecha | date: 'MMM d, y':"":"fr" }}

Set Globally
It is a way to set "globaly" your favorite locale (if it's different to "en", the default), so then you don't need to write it down in every pipe:
You need to add to app.module.ts, besides all the above code, this import and the PROVIDERS section:
...
import { LOCALE_ID} from '@angular/core';
...

...
providers: [
    {provide: LOCALE_ID, useValue: 'es'} // Same value you used above 'es' or 'fr' or whatever you had registered
  ],
...


In MVC5 template load properly on default link localhost:port/home but not in localhost:port/home/view

Question: I am new in MVC5. I am adding HTML template in MVC project. I create a default project of mvc5 in visual studio 2015 and then i create Master Layout and controller plus view. When i execute my project it loads my whole template properly with its css and js files. But whenever i shuffle my view, my page navigate to its view with proper styling but i dont know why my js didn't load properly. I got no errors in console.
Here is my code:
RouteConfig.cs
routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{id}",
                defaults: new { controller = "AdminDashboard", action = "Index", id = UrlParameter.Optional }
            );

AdminPanel.cshtml

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Limitless - Responsive Web Application Kit by Eugene Kopyov</title>

    <link href="https://fonts.googleapis.com/css?family=Roboto:400,300,100,500,700,900" rel="stylesheet" type="text/css">
    <link href="@Url.Content("~/assets/")css/icons/icomoon/styles.css" rel="stylesheet" type="text/css">
    <link href="@Url.Content("~/assets/")css/bootstrap.css" rel="stylesheet" type="text/css">
    <link href="@Url.Content("~/assets/")css/core.css" rel="stylesheet" type="text/css">
    <link href="@Url.Content("~/assets/")css/components.css" rel="stylesheet" type="text/css">
    <link href="@Url.Content("~/assets/")css/colors.css" rel="stylesheet" type="text/css">

    @*@Styles.Render("~/Assets/css")
        @Scripts.Render("~/Assets/js")*@

Navigation Code in AdminPanel.cshtml

Main

 Dashboard

 abc

                                     Page layouts

                                        @*
EmptyPage
*@

@Html.ActionLink("Department", "Department", "AdminDashboard")

AdminDashboardController.cs:
public ActionResult Department()
{
    return View();
}

ScreenShots:
enter image description here
enter image description here
Answer: I solved this issue by my self and I want to share my research, the error in this code was bad hierarchy.
Firstly i have to render my js files and the end of my _Layout and secondly I need to create @Section for my content scripts. This hierarchy resolve my problem.
_Layout.cs
at the end of my page:
    @Scripts.Render("~/Assets/js")

    @RenderSection("Script", required: false)

Dashboard.cs
Content View at the bottom of my dashboard.cs page:
  @section Script{

    }


Do not mutate vuex store state outside mutation handlers error for set state array

Question: After writing the data to vuex state I am getting error because I am using v-model. The instance has both object and array instances. There is no error in the object state but I am getting the following error in the array part. Has anyone encountered this situation? what could be the solution
Steps:

Write data to the form(firstName).
Click the Set State Array button
Change the data in the form(firstName).

Error: [vuex] do not mutate vuex store state outside mutation handlers.
export const state = () => ({
  formsArray: [],
  formObject: {}
});

const mutations = {
  SET_FORMSARRAY(state, payload) {
    console.log('formsArray', payload);
    state.formsArray = [...payload];
  },
  SET_FORMSOBJECT(state, payload) {
    console.log('formObject', payload);
    state.formObject = { ...payload };
  }
};

export default {
  namespaced: true,
  state,
  mutations
};

<template>

  {{forms}}

      {{index+1}}. firstName
      <v-text-field
        v-model="form.firstName"
        solo
      />

    <v-btn
      elevation="2"
      class="ma-2"
      @click="setStateArray"
    >SET STATE ARRAY</v-btn>

         firstName
      <v-text-field
        v-model="formsObject.firstName"
        solo
      />
     lastName
      <v-text-field
        v-model="formsObject.lastName"
        solo
      />
    <v-btn
      elevation="2"
        class="ma-2"
      @click="setStateObject"
    >SET STATE OBJECT</v-btn>

State Array:  {{formsArray}}

 State Object:  {{formObject}}

</template>

Example :https://stackblitz.com/edit/vuex-set-state-array-error
Comment: it inherits the binding, copy the object your passing in, I generally make a global util which is somewhat like a `$copy = v => JSON.parse(JSON.stringify(v))`, then use it throughout like `this.$copy(obj)` when passing things back to the store. Really you need to add your code here, else once you have removed the workspace, your link has rotted and your question is then lacking a verifiable example, be aware the title of your question will show up in any search engine search as this is a common gotcha
Comment: The error means what it says. The solution is to mutate the store only with actions/mutations. You shallowly copy the array so it becomes a part of the store, then you continue to mutate it.
Comment: Please make a search for this one. It was asked a lot of times already, with those exact keywords.
Comment: Does this answer your question? [Do not mutate Vuex store state outside mutation handlers (ERROR)](https://stackoverflow.com/questions/57699759/do-not-mutate-vuex-store-state-outside-mutation-handlers-error)
Comment: @kissu Unfortunately this is not the answer to my question. The solution must be in the right approach. I request you to answer after trying on stackblitz example. Of course, we do research before asking questions.
Answer: The difference between the test cases is that the array is actually an array of objects, while the object case is a flat object. When you're writing to the store with the spread syntax, this works fine for the object. When trying this with the array, only the array itself is being copied, but the reference to the objects inside still persists - therefor the error is being thrown. A possible solution would be to also use the spread syntax for the objects inside the array, or to use a deep-copy approach for writing into the store.
Comment: Thanks, deep copy was the solution for me
Comment: Glad that the correct answer was indeed a deep copy! @EnesGenc (this one: https://stackoverflow.com/a/57699922/8816585)
Comment: @EnesGenc you have some quirks with this solution tho: https://flaviocopes.com/how-to-clone-javascript-object/
Comment: @EnesGenc You're welcome! If you like, you can mark my answer as the accepted answer :)
Comment: @kissu code that works :)

`const temp = JSON.parse(JSON.stringify(payload))`


Apache Spark: Exponential Moving Average

Question: I am writing an application in Spark/Scala in which I need to calculate the exponential moving average of a column.
EMA_t = (price_t * 0.4) + (EMA_t-1 * 0.6)

The problem I am facing is that I need the previously calculated value (EMA_t-1) of the same column. Via mySQL this would be possible by using MODEL or by creating an EMA column which you can then update row per row, but I've tried this and neither work with the Spark SQL or Hive Context... Is there any way I can access this EMA_t-1?
My data looks like this :
timestamp price
15:31 132.3
15:32 132.48
15:33 132.76
15:34 132.66
15:35 132.71
15:36 132.52
15:37 132.63
15:38 132.575
15:39 132.57

So I would need to add a new column where my first value is just the price of the first row and then I would need to use the previous value: EMA_t = (price_t * 0.4) + (EMA_t-1 * 0.6) to calculate the following rows in that column.
My EMA column would have to be:
EMA
132.3
132.372
132.5272
132.58032
132.632192
132.5873152
132.6043891
132.5926335
132.5835801

I am currently trying to do it using Spark SQL and Hive but if it is possible to do it in another way, this would be just as welcome! I was also wondering how I could do this with Spark Streaming. My data is in a dataframe and I am using Spark 1.4.1.
Thanks a lot for any help provided!
Comment: I don't think your use case is well suited for a big data environment since its power is to process data in parallel and your use case doesn't allow this...how many records do you have?
Comment: @mark91 I have about 100 000 rows per dataset and about 100 datasets I need to analyze. The reason I need to calculate this is that I need this as input to calculate a feature. I would need to use these features to train a model with random forest. My model has to predict whether the price will go up or down based on the values of several features. I also would need to make this real-time in the future.
Comment: Then up to me the best option is to distribute the data such as each dataset is in a partition (and each partition contains a dataset) and then you process independently each partition..
Answer: To answer your question:

The problem I am facing is that I need the previously calculated value (EMA_t-1) of the same column

I think you need two functions: Window and Lag. (I also make null value to zero for convenience when calculating EMA)
my_window = Window.orderBy("timestamp")

df.withColumn("price_lag_1",when(lag(col("price"),1).over(my_window).isNull,lit(0)).otherwise(lag(col("price"),1).over(my_window)))

I am new to Spark Scala also, and am trying to see if I can define an UDF to do the exponential average. But for now an obvious walk around would be manually adding up all lag column ( 0.4 * lag0 + 0.4*0.6*lag1 + 0.4 * 0.6^2*lag2 ...) Something like this
df.withColumn("ema_price",
price * lit(0.4) * Math.pow(0.6,0) +
lag(col("price"),1).over(my_window) * 0.4 * Math.pow(0.6,1) +
lag(col("price"),2).over(my_window) * 0.4 * Math.pow(0.6,2)  + .... )

I ignored the when.otherwise to make it more clear. And this method works for me now..
----Update----
def emaFunc (y: org.apache.spark.sql.Column, group: org.apache.spark.sql.Column, order: org.apache.spark.sql.Column, beta: Double, lookBack: Int) : org.apache.spark.sql.Column = {
  val ema_window = Window.partitionBy(group).orderBy(order)
  var i = 1
  var result = y
  while (i < lookBack){
    result =  result + lit(1) * ( when(lag(y,i).over(ema_window).isNull,lit(0)).otherwise(lag(y,i).over(ema_window)) * beta * Math.pow((1-beta),i)
    - when(lag(y,i).over(ema_window).isNull,lit(0)).otherwise(y * beta * Math.pow((1-beta),i))   )
    i = i + 1
  }
  return result }

By using this fuction you should be able to get EMA of price like..
df.withColumn("one",lit(1))
  .withColumn("ema_price", emaFunc('price,'one,'timestamp,0.1,10)

This will look back 10 days and calculate estimate EMA with beta=0.1. Column "one" is just a place holder since you don't have grouping column.
Comment: can you let me know how the calculation of beta as 0.1 is been calculated. I am trying the above code and finding the value of EMA 10. I am not getting proper values so I think I need to change beta value so can you help me how beta 0.1 is calculated?
Comment: Beta is like a decay factor. It is the parameter. you set the beta depend on how much you care about today, vs. how much you care about the history. @M
Comment: What if I will not use  this beta parameter bcoz I am not getting exactly what I want ?
Comment: @MaheshGupta I guess this formula requires you set beta(https://en.wikipedia.org/wiki/Moving_average#Exponential_moving_average), or maybe you could talk more about what exactly you want?
Answer: You should be able to do this with Spark Window Functions, which were introduced in 1.4: https://databricks.com/blog/2015/07/15/introducing-window-functions-in-spark-sql.html
w = Window().partitionBy().orderBy(col("timestamp"))
df.select("*", lag("price").over(w).alias("ema"))
This would select the last price for you so you can do your calculations on it


Unable to use any class,interface or fun created in jetbrains.compose module into non jetbrains.compose module

Question: In Kotlin multiplatform when i try to use compose module interface or class in non-compose module getting this error when i do maven-publish in windows and ios.
For example i created a project and added PR with error message
https://github.com/yuvaraj119/Expressus-temp/pull/1

In windows when i run the app it works perfectly no crash

but when i do maven-publish it throws error.

unable to publish only the non-compose module which is consuming
compose module.

where all other modules which are not consuming compose module
gets published.

even the compose module gets published.

In mac maven-publish get failed and non of the module gets
published below mac error

Could not resolve all task dependencies for configuration ':shared:iosArm64CompileKlibraries'.
Could not resolve project :shared-ui-compose.
Required by:
project :shared
> No matching variant of project :shared-ui-compose was found. The consumer was configured to find a usage of 'kotlin-api' of a library, preferably optimized for non-jvm, as well as attribute 'org.jetbrains.kotlin.platform.type' with value 'native', attribute 'org.jetbrains.kotlin.native.target' with value 'ios_arm64' but:
- Variant 'debugApiElements' capability Expressus:shared-ui-compose:unspecified declares an API of a library, preferably optimized for Android:
- Incompatible because this component declares a component, as well as attribute 'org.jetbrains.kotlin.platform.type' with value 'androidJvm' and the consumer needed a component, as well as attribute 'org.jetbrains.kotlin.platform.type' with value 'native'
- Other compatible attribute:
- Doesn't say anything about org.jetbrains.kotlin.native.target (required 'ios_arm64')
- Variant 'debugRuntimeElements' capability Expressus:shared-ui-compose:unspecified declares a runtime of a library, preferably optimized for Android:
- Incompatible because this component declares a component, as well as attribute 'org.jetbrains.kotlin.platform.type' with value 'androidJvm' and the consumer needed a component, as well as attribute 'org.jetbrains.kotlin.platform.type' with value 'native'
- Other compatible attribute:
- Doesn't say anything about org.jetbrains.kotlin.native.target (required 'ios_arm64')
- Variant 'jvmApiElements' capability Expressus:shared-ui-compose:unspecified declares an API of a library, preferably optimized for standard JVMs:
- Incompatible because this component declares a component, as well as attribute 'org.jetbrains.kotlin.platform.type' with value 'jvm' and the consumer needed a component, as well as attribute 'org.jetbrains.kotlin.platform.type' with value 'native'
- Other compatible attribute:
- Doesn't say anything about org.jetbrains.kotlin.native.target (required 'ios_arm64')
- Variant 'jvmRuntimeElements' capability Expressus:shared-ui-compose:unspecified declares a runtime of a library, preferably optimized for standard JVMs:
- Incompatible because this component declares a component, as well as attribute 'org.jetbrains.kotlin.platform.type' with value 'jvm' and the consumer needed a component, as well as attribute 'org.jetbrains.kotlin.platform.type' with value 'native'
- Other compatible attribute:
- Doesn't say anything about org.jetbrains.kotlin.native.target (required 'ios_arm64')
- Variant 'metadataApiElements' capability Expressus:shared-ui-compose:unspecified declares a library, preferably optimized for non-jvm:
- Incompatible because this component declares a usage of 'kotlin-metadata' of a component, as well as attribute 'org.jetbrains.kotlin.platform.type' with value 'common' and the consumer needed a usage of 'kotlin-api' of a component, as well as attribute 'org.jetbrains.kotlin.platform.type' with value 'native'
- Other compatible attribute:
- Doesn't say anything about org.jetbrains.kotlin.native.target (required 'ios_arm64')
- Variant 'releaseApiElements' capability Expressus:shared-ui-compose:unspecified declares an API of a library, preferably optimized for Android:
- Incompatible because this component declares a component, as well as attribute 'org.jetbrains.kotlin.platform.type' with value 'androidJvm' and the consumer needed a component, as well as attribute 'org.jetbrains.kotlin.platform.type' with value 'native'
- Other compatible attribute:
- Doesn't say anything about org.jetbrains.kotlin.native.target (required 'ios_arm64')
- Variant 'releaseRuntimeElements' capability Expressus:shared-ui-compose:unspecified declares a runtime of a library, preferably optimized for Android:
- Incompatible because this component declares a component, as well as attribute 'org.jetbrains.kotlin.platform.type' with value 'androidJvm' and the consumer needed a component, as well as attribute 'org.jetbrains.kotlin.platform.type' with value 'native'
- Other compatible attribute:
- Doesn't say anything about org.jetbrains.kotlin.native.target (required 'ios_arm64')```

Answer: This is because your shared declares iOS-targets in addition to jvm and android. This is equivalent of saying "I will compile my code to JVM, Android and iOS".
Therefore, all the dependencies you use in :shared:commonMain should also be compatible at least with those targets. However, shared-ui-compose project declares only jvm and android targets, essentially saying "I know how to compile only for JVM and Android, but not for iOS". The mismatch results in failure.
The general rule is that your dependency should support at least as many targets as you declare.
Unfortunately, in your case, you can't just declare iOS targets in shared-ui-compose, as it will start failing with a similar error because Compose doesn't provide support for iOS targets.
You can remove iOS targets in the consumer project (i.e. in shared). Obviously, you will lose the ability to compile to iOS, but frankly, I don't understand why shared had those targets to begin with, as the project overall doesn't support iOS.
P.S. The reason why you see a different behavior on Windows and MacOS is because the compilation of iOS-targets on Windows-hosts is not supported, and all tasks/build actions connected with iOS targets are just disabled in the build.
Answer: It usually depends on the kotlin library version you're using for multiplatform, because the distributor will have built klibs with a different version from the one in your build. I recommend version 1.8 since it has native target fallback and most maven kmm libraries use it or a bit lower


Why is statistics useful when many things that matter are one shot things?

Question: I don't know if it's just me, but I am very skeptical of statistics in general.  I can understand it in dice games, poker games, etc.  Very small, simple, mostly self-contained repeated games are fine.  For example, a coin landing on its edge is small enough to accept the probability that landing heads or tails is ~50%.
Playing a $10 game of poker aiming for a 95% win is fine.  But what if your entire life savings + more is dependent on you hitting a win or not?  How would knowing that you'd win in 95% of the time in that situation will help me at all?  Expected value doesn't help much there.
Other examples include a life-threatening surgery.  How does that help knowing that it is 51% survival rate versus 99% survival rate given existing data?  In both cases, I don't think it will matter to me what the doctor tells me, and I would go for it.  If actual data is 75%, he might as well tell me (barring ethics and law), that there is a 99.99999% chance of survival so I'd feel better.  In other words, existing data doesn't matter except binomially.  Even then, it doesn't matter if there is a 99.99999% survival rate, if I end up dying from it.
Also, earthquake probability.  It doesn't matter if a strong earthquake happened every x (where x > 100) years on average.  I have no idea if an earthquake will happen ever in my lifetime.  So why is it even useful information?
A less serious example, say, 100% of the places I've been to that I love are in the Americas, indifferent to 100% of the places I've been to in Europe, and hate 100% of the places that I have been to in Asia.  Now, that by no means mean that I wouldn't find a place that I love in Asia on my next trip or hate in Europe or indifferent in America, just by the very nature that the statistics doesn't capture all of the information I need, and I probably can never capture all of the information I need, even if I have traveled to over x% of all of those continents.  Just because there are unknowns in the 1-x% of those continents that I haven't been to.  (Feel free to replace the 100% with any other percentage).
I understand that there is no way to brute force everything and that you have to rely on statistics in many situations, but how can we believe that statistics are helpful in our one shot situation, especially when statistics basically do not extrapolate to outlier events?
Any insights to get over my skepticism of statistics?
Comment: (+1) Welcome to our site!  It isn't just you: this is a deep question that goes to the foundations of statistics.
Comment: The "life savings" example mixes separate issues. In economics, a common model for rational risk aversion is to maximize expected utility, not expected money, where utility is typically a concave (sublinear) function like log(money). This means losses cost more than gains of the same size, and this effect is larger for larger changes. This is very different from not believing there is any difference between $50\%$ and $99\%$, which leads to inconsistent and irrational behavior.
Comment: This strikes me as an important topic & discussion that could stay open. (I would understand if people wanted to make it CW, though.)
Comment: @DouglasZare this sounds like a very interesting area. Can you provide an introductory article to the topic of individual risk aversion regarding live savings ?
Comment: @steffen: This material is covered in many basic economics texts. The theory of expected utility maximization is viewed by many as too simple, and insufficient to explain many phenomena, but it is an important starting point to understand before moving on to ideas such as prospect theory. Something which is easily explained by expected utility maximization instead of expected money maximization should not be viewed as a failure of probability theory. http://en.wikipedia.org/wiki/Expected_utility_hypothesis
Comment: *I have no idea if an earthquake will happen ever in my lifetime*. I'm staying at the moment in Arica, Chile. We have quakes about once a week, although I lost count. But they are seldom stronger than about 5.  More frequent than rain, though. A useful site to look for quakes is https://earthquake.usgs.gov/earthquakes/map/
Answer: First I think that you may be confusing "statistics" meaning a collection of numbers or other facts describing a group or situation, and "statistics" meaning the science of using data and information to understand the world in the face of variation (others may be able to improve on my definitions).  Statisticians use both senses of the word, so it is not surprising when people mix them up.
Statistics (the science) is a lot about choosing strategies and choosing the best strategy even if we only get to apply it once.  Some times when I (and others) teach probability we use the classic Monty Hall problem (3 doors, 2 goats, 1 car) to motivate it and we show how we can estimate probabilities by playing the game a bunch of times (not for prizes) and we can see that the "switch" strategy wins 2/3 of the time and the "stay" strategy only wins 1/3 of the time.  Now if we had the opportunity to play the game a single time we would know some things about which strategy gives a better chance of winning.
The surgery example is similar, you will only have the surgery (or not have the surgery) once, but don't you want to know which strategy benifits more people?  If your choices are surgery with some chance greater than 0% of survival or no surgery and 0% of survival, then yes there is little difference between the surgery having 51% survival and 99.9% survival.  But what if there are other options as well, you can choose between surgery, doing nothing (which has 25% survival) or a change of diet and exercise which has 75% survival (but requires effort on your part), now wouldn't you care about if the surgery option has 51% vs. 99% survival?
Also consider the doctor, he will be doing more than just your surgery.  If surgery has 99.9% survival then he has no reason to consider alternatives, but if it only has 51% survival then while it may be the best choice today, he should be looking for other alternatives that increase that survival.  Yes even with 90% survival he will loose some patients, but which strategy gives him the best chance of saving the most patients?
This morning I wore my seat belt while driving (my usual strategy), but did not get in any accidents, so was my strategy a waste of time?  If I knew when I would get in an accident then I could save time by only putting on the seat belt on those occasions and not on others.  But I don't know when I will be in an accident so I will stick with my wear the seat belt strategy because I believe it will give me the best chance if I ever am in an accident even if that means wasting a bit of time and effort in the high percentage (hopefully 100%) of times that there is no accident.
Comment: +1 Greg Good post! I was writing mine at the same time as you. We may overlap a little but I think we both had things to say that were right on the mark and did not overlap. I am not sure what the OP thinks statistics is. It is nice that you gave him the benefit of the doubt. I took a more angry approach to it.
Comment: Hi Greg, I liked your answer, but can I reason it like this: statistics (the science) is itself a statistic, it works for x% of the time, (possibly high x), but there are the 1-x% unknown/random factors that we always need to be aware of. Given that we can model the unknown in any # (possibly infinite) of ways, we will never know x. Hopefully these outliers will never happen, but we should always be mindful and err on the conservative, especially if the event is catastrophic (ie. asteroids, financial products, nuclear accidents for society and car accidents for personal). Does this make sense?
Comment: @statskeptic, what you say applies to all areas, not just statistics.  In fact is applies less to true statistics than other fields because when statistics is done right the assumptions are clear.  Most times that statistics has failed it has not been the techniques, but that they were applied incorrectly.  In any field that involves uncertainty (which is pretty much anything other than religion or pure math, and even they have some) you can have an answer that is either wrong, useless, or uses statistics.
Comment: (+1) for statistics being "the science of using data and information to understand the world in the face of variation"
Answer: Just because you don't use statistics in your daily life does not mean that the field does not directly affect you. When you are at the doctor and they recommend one treatment over the other, you can bet that behind that recommendation was many clinical trials that used statistics to interpret the results of their experiments.
It turns out that the concept of expected value is also very useful even if you do not personally use the concept. Your example of betting your life savings fails to take into account how risk adverse you are. Other situations might find yourself less risk adverse, or where there are not catastrophic outcomes. Business, finance, actuarial contexts and others are examples of this. Perhaps you are issuing home insurance policy - then all of the sudden knowing the probability of an earthquake occurring within some specified period of time matters a great deal.
In the end statistics is a great way to deal with uncertainty. Your last example you made up some data about places you like to travel and claimed that statistics will say that you will never find a place in Asia that you like. This is just wrong. Of course this data will make you believe that Asia is less likely to have a place you like, but you can set your prior belief to be whatever you like, and statistics will tell you how to update your belief given the new data. Furthermore, it allows you to do modify your belief in a principled way that will allow you to act rationally in the presence of uncertainty.
Comment: +1 @jjund3 for addressing the OPs specific questions and for intermingling Bayesian and frequentist staistics without any conflict.
Comment: @statskeptic Your argument is very similar to Taleb's skepticism/ bashing of statistics in his book the Black Swan.  I think many statisticians myself included have shot holes in his argument which basially says that statistics is useless because it cannot predict that rare and unthinkable event (9/11 in your example,the stock market crash in his).
Comment: The traveling example was just a made up one, but the idea is that statistics does not capture the unknown. Your example of business contexts made me thought of the example of insurance companies of WTC probably estimated the cost/benefit of insuring the building without taking into account of planes destroying the building, but yet it is the one that mattered most.
Comment: @statskeptic Your point that statistics cannot account for all possible uncertainties is a good one. But it doesn't have to be complete and perfect to be useful.  We do have knowledge about terrorists.  Prior to 9/11 we did have examples of terrorists going on suicide missions and we had experience with highjacking of planes.  The information could have been pieced together to determine that crashing aplane into the World Trade Center was a possibility although we would probably have assessed it as a remote possibility.
Comment: We knew the World Trade Center was a favorite terrist target.  It had been attacked once before with a bomb set off in the basement.  The fact that the bomb was not strong enough to do the desired damage was at least a hint that the next time some very different method would be used.  Of course as often said hind sight is 20-20.  There are many examples where the unexpected or improbable happens.  But not in the case of the Challanger disaster.  There the Thiokol engineers even with limited data knew that there was some riks of a catastrophic failure due to O-rings failure at low temperature.
Comment: They tried to convince management to avoid the risk by just not lauching in cold weather.  But management failed to properly understand the engineers argument.  they didn't understand  or appreciate the risk and the desire to put the first teacher into space to please President Reagan was what was most on their mind.
Comment: Although it is true that these events may be so rare that statistics has difficulty predicting it is not true as he claimed in the first edition (second edition he toned down a little) that statistician rely on a false model involving the normal distribution which clearly does not apply to very rare events. it is true that the normal model does not apply to very rare events but it is not true that statisticians rely on the normal distribution to model rare or extreme event.  There is a well developed theory of extremes that we use which is appropriate.
Comment: @statskeptic: The WTC example is way off. Tom Clancy wrote a book (Debt of Honor, 1994) involving a suicide attack using a passenger plane on the Capitol. Insurance policies specify which "Acts of God" and war or terrorism are covered and which are not.
Comment: On this kind of questions (possibility of terrorist attacks, ...) the main problem with probability models for uncertailty is that we NEED TO ASSUME the sample space is known! A possibility we never happened to think abut, necessarily gets zero probability. "ludic fallacy"! But the principled way of thinking still helps.
Comment: @Michael Chernick: I think you are misreading Taleb.
Answer: I myself have the same doubts about the usefulness of probability, and statistics, when it comes to taking decision about a single event. In my opinion, knowing the probability, real or estimated, is extremely important when the objective is estimating outcomes of samples, be they a single event repeated a number of times or a sample drown from a certain population. In short, knowing the probability makes more sense for the casino who, based on probability calculations can put the rules that guarantee he would win in the long run (after many plays) and not for a gambler who pretends to play one time, so he would won or loose (these are the outcomes when the experiment is run a single time). It's also important for the generals who contemplate sending their solders to a battle with the risk (probability) of losing 10% of them, but not for a certain solder (say, John) who is only going to die or survive.  There are so many examples like these in real life.
The point I want to make is that, Probability and Statistics, not only are useful in real life but, more precisely, they are a tool for all modern scientific researches and decision making rules. However, it's not correct to say that rationality implies relying on the probability of a single event, without the intention or the possibility of repeating it, for estimating the outcome. The tendency of the probability to influence a certain individual's decision, based on her or his degree of risk aversion, is obviously subjective.  Risk avert and risk lover have different attitudes (decisions) toward the same lottery (the same expected value).
Comment: 1- I didn't say that risk averse persons never gamble.
2-What I meant by "subjective" is that knowing the expected value of a lottery does not determine a person's attitude toward it. All other things equal, this attitude is a function of a personal characteristic which is the degree of risk aversion which determines the expected utility of the gamble.
3-Rationality in economic theory depends upon hypotheses and hence is relative. That's why two individuals showing different attitudes toward the same expected value could be both called "rational".
Comment: I wish we don't miss the central point of this discussion, which is dealing with the fact that events with very low probability can take place in any trail. and vise versa.
Comment: The point about risk aversion is an interesting one, in terms of how people react to an uncertain event. But note that when economists consider choice under uncertainty (e.g. commodities contingent upon the state of the world), the true probability comes into play via the *fair odds line* (a budget constraint reflecting the possible bundles under an actuarially fair gamble). Agents behave not just according to their preferences (e.g. risk aversion) alone, but also according to the interplay of their budget constraint (the available gamble) and their assessment of the fair odds line.
Comment: Briefly, it's not true that all risk-averse people "never gamble" (in the broadest sense of the word), just that they can't be tempted to gamble by actuarially fair odds. A sufficient risk premium (dependent on their degree of risk aversion) can alter that decision, however. Since this analysis depends on the agent's perception of the fair odds, even on a "one-off shot" a rational agent will weigh up the probabilities.
Answer: The world is stochastic not deterministic.  If it were deterministic the physicists would be ruling the world and statisticians would be out of a job.  But the reality is that statisticians are in high demand in almost every discipline.  That is not to say that there isn't a place for physics and other sciences but statistics works hand in hand with science and is the basis for many scientific discoveries.
Enough chatter and down to specifics.  I have worked the last 17 years in the medical industry, first in medical devices, then pharmaceuticals, and now general medical research. Drugs and medical devices that improve quality of life and often save or extend life are developed and approved in this country and around the world on a regular basis. In the US approval requires evidence of safety and efficacy before the FDA will allow a drug or medical device to be marketed.  Evidence to the FDA comes from clinical trials in phases.  All the clinical trials require valid statistical design and analysis methods.  Nothing is perfect.  Drugs work well for some people while others may not respond or will have adverse events (bad reactions that can cause illness or death).  The trials separate out the ineffective drugs from the effective.  Most drugs fail and there is often a ten year cycle from early stage development to end of phase III with approval and marketing at the end of the trial.  Postmarket surveillance which also requires statistics is then applied to make sure that the drug works well enough for the general population.  Sometimes the general population that the drug is approved for is a less restrictive group than the patients that were eligible for the clinical trials.  So sometimes drugs do turn out to be dangerous and get pulled from the market.  Statistics helps in all aspects of drug safety.
Statistics is not perfect.  We live with some mistakes due to randomness and uncertainty.  But it is controlled and our lives are better and errors are reduced from what they would be had statistical science not been involved.
Comment: Okay statskeptic so you are not confused. But why is it so hard to see how statistics improves your chance for success.  Probability theory tells you the odds of winning games of chance.  If you could use Thorpe's Beat the Dealer strategy in blackjack and you have a large bank of funds you can make a fortune in the long run.  The MIT students proved it in Las Vegas even though the advantage in counting has been reduced by the use of mixing multiple decks. It is true.  The casino knows that card counters are a threat.
Comment: Don't get me wrong. I understand there is statistics in everything, even physics with quantum mechanics is all about probability, and there isn't enough atoms to do computation without statistics. I just want to find out how to deal with the randomness and uncertainty which can influence my (or other people's) life more than any actual statistic or distribution.
Comment: They search for them and when they think they find one they throw him or her out of the casino no questions asked.
Comment: Also, please don't think that I'm trying to flame your profession. There are computers that are doing computation statistically to save power, and I respect that. I'm just trying to learn how people with much more knowledge than me in statistics deal with these questions.
Comment: @statskeptic I fyou saw my original post I apologize for my inital comments.  They were rightfully edited out by a moderator.  I think I misunderstood what you were trying to say.  I hope we answered your question well and relieved some of your skepticism.
Answer: I skeptical of statistics for the following reasons.

I am convinced anybody without a graduate degree in statistics has no clue what they are doing. Unf. there are millions of people across the world doing research without a graduate degree in statistics. I was an undergraduate math major at the Univeristy of Maryland College, Park. I took 4 400 level math classes. All teachers did was teach you how to calculate stuff. Nobody taught me how to make sense of anything or do any statistical analysis except for hypothesis testing, which makes no sense for 2 reasons.
    1. For every hypothesis test I was taught, I had to make assumptions beforehand. Nobody taught me which assumption(s) I had to start with.
    2. P values make no sense logically. A graduate degree in statistics might teach you what a p value actually is. However, I am convinced  no undergraduate knows how to use it. The undergraduate definition assumes a probability of something that depends on the hypothesis being correct. Logically, the definition makes no sense at all. Even worse, NOBODY has ever told me where the probability comes from. I have actually emailed almost my whole math department(more than 200 people) if somebody could give me an answer. The most popular and only responses were "one would have to ASSUME the error rates for the probability" (When I asked people how this was done, they all answered me "from previous experiments", I could not get anything more specific from anybody), "It's just the way it is", and "it is completely random".
The same thing happened when I googled what the signifigance of a p value is.
It leads me to the conclusion...
Even a sig. number of math and statistics professors have no clue what the logic behind statistics is. I don't expect people to have in depth knowledge. However, I have a feeling that even a sig. % of researches and professors do not understand any of the underlying logic behind statistics.
Statistical error is not the same thing as actual error. Because people like to use statistics to derive estimates for things that are humongous, people like to use statistical error to "mask" the fact that they have no clue what the actual error.
People use small samples for big populations because statistical theory tells them they can. I learned from one of my college courses, that people like to use data that is an estimate from about 30 schools in the country to show that there are few violent incidents in schools in the whole country. There are about 100,000 schools. That sounds insane. A whole popular movement is based off of about 30 schools in the whole country.
People like to make the burden of proof statistical. The Higgs Bossom was never discovered. It was discovered statistically, but that doesn't mean anything. Something being discovered purely statistically is useless because nobody knows the accuracy of statistics.
People like to use statistics to make important desicions. Statistics can be used as a guide, but nobody knows how accurate it really is. Just because a problem seems impossible to solve does not mean that statistics is the next best thing. The fact that DNA testing is based off of statistic gives me the chills. Can I be given the death penalty soley because of statistics? Could a murderer be released from jail soley because of statistics?

I believe statistics can be useful, but only if it is not used as the conclusion. I believe statistics can tell us what some of the possibilities are. Then logic, not statistical logic should be used to prove which possibility(s) is correct.
Comment: "professors do not understand any of the underlying logic behind statistics" - there are some radically different philosophies of statistics (see e.g. the Bayesian-Frequentist debate) but most people are pragmatic about the techniques they apply to a particular problem. This may not feature highly, if at all, on an undergrad course, but the philosophy of statistics certainly wasn't drawn up at random on the back of an envelope one day. As for p-values, "Logically, the definition makes no sense at all": perhaps you should consult [this question on CV](http://stats.stackexchange.com/q/31/22228).
Comment: "...useless because nobody knows the accuracy of statistics", & your complaints about drawing conclusions from statistical evidence like a sample of schools or DNA, suggests you don't trust *statistical inference*. Yet often a limited sample is all the evidence available, or all the data you can afford to capture. How to weigh up such evidence? We face uncertainty, as our sample won't exactly reflect the wider population. Inference deals with that uncertainty, eg confidence intervals measure uncertainty in sample statistics like the sample mean (roughly, the "accuracy" of statistics is known).
Comment: Speculative rants are not considered appropriate answers on SE sites. They may be amusing--and may contain some truths, as I believe this one does--but in the end they die sad deaths, as in the bleak assessment of man's life in [Macbeth, Act V, scene 5, lines 26-28.](http://nfs.sparknotes.com/macbeth/page_202.html)
Answer: The long and the short of it is that probability is the unique generalization of ordinary true/false logic to degrees of belief between 0 and 1. This is the so-called logical Bayesian interpretation of probability, originated by R.T. Cox and later championed by E.T. Jaynes.
Furthermore under weak assumptions it can be shown that the right way to order uncertain outcomes by preference is to order them by expected utility, with the expected taken with respect to the probability distribution over outcomes.
See Robert Clemen, "Making Hard Decisions", for an introduction and exposition on applied decision analysis which is based on Bayesian probability and expected utility.
You are absolutely right to be skeptical about conventional frequentist statistics; by the design of its inventors (R.A. Fisher, J. Neyman, E. Pearson) it is limited to repetitive events. But many everyday problems don't involve repetitive events. What to do? The typical approach is some combination of forcing square pegs into round holes, and moving the goalposts. Shameful, really.
Comment: There is more about the scientific method to unite us and say resoundingly that STAISTICS IS IMPORTANT when facing a skeptic. Instead you agree with the skeptic in order to take a cheap shot at frequentist methods!  That is what is shameful.
Comment: -1 In my opinion a very poor and unfair portrayal of frequentist statistics.  I would not take such a negative view of the Bayesian approach.  But the Bayesians (any camp) are not free from criticism.  Is degree of belief to be the staple of inference?  Is degree of belief subjective and personal, so that two people can give two different answers?  What about the need for a prior distribution?  How should it be picked?  Lots of questions for any paradigm for inference.  But aren't we past the stage of hostle bickering over the foundations?
Comment: Hug it out guys.
Comment: I don't mind getting into a discussion about the foundations.  This is not the appropriate place and my only point to you was that I think you took a cheap shot and that your answer was inappropriate. That doesn't require a discussion of the foundations of statistics.
Comment: @MichaelChernick: (1) to simply shout STATISTICS IS IMPORTANT is hardly an argument which will win over a skeptic. (2) Bayesian inference has the same relation to problem data as ordinary logic. That is, given some premises, you crank out a solution by applying laws of probability. The data (e.g. any prior distribution) are neither right nor wrong; they just are. Reasonable people disagree about prior distributions just as they might about any other problem data.
Comment: (ahem ... continuing) (3) If you cannot state all the data needed to reach a conclusion, then you can't apply Bayesian inference. If for some reason you really can't state a prior distribution, then you simply have to admit the problem isn't solvable by Bayesian inference. (4) If you think I've made some inaccurate statements about frequentist statistics, by all means, please give your best rebuttal.
Comment: I don't need to defend the frequentist approach. As you probably know there are many long and complex arguments that can be made on both sides. I took Bayesian statistics from Dennis Lindley who taught me that frequentist theory is incoherent. I also know about the marginalization paradox and problems with improper priors and the difficulty associated with the concept of noninformative priors. I realize that some of the Bayesian problems I mentioned only apply to the objective Bayesians and not the subjective school. I was not knocking the Bayesian paradigm.
Comment: Rather I was objecting to taking cheap shots at the frequentist approach.  I was merely pointing out that it goes both ways.  The Bayesian approach can be criticized in many ways just as the frequentist approach can. You didn't really say much that was critical of the frequentist approach but you did bash it.  Your only basis was to say putting it in my own words, that probability needs to be more general than talking about frequency of events from repeated observations of a random variable.
Comment: @MichaelChernick: You don't need to do anything, but I think you have to admit it's not a very interesting discussion if one side refuses to field an argument. I actually don't care if you "knock" Bayesianism, as long as you have some rationale.
Comment: "Don't start 'Holy Wars.'  Statistics is a science in evolution and there is room for diverging opinions on many issues."  Raynald Levesque, http://www.spsstools.net/es/notes/3/


How can I add a landing page before GitLab's login page?

Question: Running a GitLab deployed on AMI/AWS. Currently my domain leads straight to the login. How do I add a page such that www.example.com is a custom page, then www.example.com/GitLab is Gitlab's login page?
Comment: How did you deploy Gitlab? Omnibus package?
Answer: If you deployed Gitlab using omnibus package the procedure is pretty simple :
Set the external_url in /etc/gitlab/gitlab.rb:
external_url "https://example.com/gitlab"
Reconfigure GitLab for the changes to take effect:
sudo gitlab-ctl reconfigure
Restart the services so that Unicorn and Sidekiq picks up the changes
sudo gitlab-ctl restart
From https://docs.gitlab.com/omnibus/settings/configuration.html#configuring-a-relative-url-for-gitlab
However, if you deployed from the sources then the procedure is described here https://docs.gitlab.com/ce/install/relative_url.html


How to use ajax to display database records using a select list?

Question: I have used a select list in my custom form to select a product code and display data corresponding to that code. I am using AJAX for this task but it does not display any record.
function webform_module_menu() {
  $items = array();

  // Change the description of a form element.
  $items['examples/webform_module/report'] = array(
    'title' => 'Report',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('webform_module_report'),
    'access callback' => TRUE,
    'weight' => 0,
  );
   return $items;
}

function webform_module_report($form, &$form_state) {
  $result = db_query("SELECT o.nid, o.sku FROM {formmodule_order} o ");
  $options = array();

  foreach($result as $row) {
    $options[$row->nid] = $row->sku;
  }

  $form['select'] = array(
    '#title' => 'Option',
    '#type' => 'select',
    '#options' => $options,
    '#ajax' => array(
      'wrapper' => 'some-form-results-wrapper',
      'callback' => 'webform_module_display'
    )
  );

  $form['results'] = array(
    '#prefix' => '
',
    '#suffix' => '
'
  );

  // If the form has been submitted, build up your results and display them
  if (isset($form_state['values']['select'])) {
    $rows = db_select('formmodule_order', 't')
      ->fields('t')
      ->condition('t.sku', $form_state['values']['select'])
      ->execute()
      ->fetchAll();

    $header =  array(t('Product ID'), t('Product Code'), t('Product Stock'), t('Product Purchased'), t('Created'));

    $form['results']['#markup'] = theme('table', array('header' => $header, 'rows' => $rows));
  }
  else {
    $form['results']['#markup'] = '
The results will appear here when you change the dropdown option.
';
  }

  return $form;
}

function webform_module_display($form, $form_state) {
  return $form['results'];
}

Update: after debugging the query under if statement $rows = db_select('formmodule_order', 't') ->fields('t') ->condition('t.sku', $form_state['values']['select']) ->execute() ->fetchAll(); does not print any result. It just says array(). What does that mean?
Comment: After lot of hair pulling i edited my code to this level that its flow is all correct in the sense i want to do but it does not displaying any output
Comment: Debug Advice:

add 'type' => 'item' and '#markup' => '' to your element early state of results element.

$form_state has to be by reference in ajax callback (&$form_state)
dpm($form_state) inside your callback

try to return 'test';
in your callback
Comment: after debugging the query under if statement - $rows = db_select('formmodule_order', 't')
      ->fields('t')
      ->condition('t.sku', $form_state['values']['select'])
      ->execute()
      ->fetchAll(); does not print any result. It just say array(). what does that mean
Comment: print_r($rows)?
Comment: @Pan Chrono yes it prints the array as required but does not display it below the header line
Answer: Display recrd from database when selected from select list Using AJAX
yourmodule.module file
<?php

hook_menu implementation
function webform_module_menu() {
  $items = array();

  // Change the description of a form element.
  $items['examples/webform_module/report'] = array(
    'title' => 'Report',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('webform_module_report'),
    'access callback' => TRUE,
    'weight' => 0,
  );
   return $items;
}

function webform_module_report($form, &$form_state) {
**query to fetch data in a select list**
$result = db_query("SELECT o.nid, o.sku FROM {formmodule_order} o ");

    $options = array();
   foreach($result as $row) {
      $options[$row->nid] = $row->sku;

    }

 //drupal_set_message('
' . print_r($options, true) . '
');
 $form['select'] = array(
    '#title' => 'Option',
    '#type' => 'select',
    '#options' => $options,    **//option will be displayed here**
    '#ajax' => array(
      'wrapper' => 'some-form-results-wrapper',
      'callback' => 'webform_module_display'
    )
  );

This will form the header of the table below which the data will be displayed
  $form['results'] = array(
    '#prefix' => '
',
    '#suffix' => '
',
    '#tree' => TRUE,
    '#theme' => 'table',
    '#header' => array(t('Product ID'), t('Product Code'), t('Product Stock'), t('Product Purchased'), t('Created')),
    '#rows' => array(),

  );
  // drupal_set_message('
header:' . print_r($form['results'], true) . '
');

  **// If the form has been submitted, build up your results and display them**
  if (isset($form_state['values']['select'])) {

    drupal_set_message('
select_option:' . print_r($form_state['values']['select'], true) . '
');

  $query = db_select('formmodule_order', 't')
      ->fields('t')
      ->condition('nid', $form_state['values']['select']);

     $result = $query->execute();
     // drupal_set_message('
option1:' . print_r($result, true) . '
');
    **// loop through to display result**
   while($row = $result->fetchAssoc()) {

    //$debug .= '
Header Record #'.'
' . print_r($row, true) . '
';
  $nid = array('#id' => 'id',
                 '#type' => 'markup',
                 '#markup' => '' . $row['nid']. '',
                 );
    //drupal_set_message('
' . print_r($nid, true) . '
');
    $sku = array('#id' => 'sku',
                     '#type' => 'markup',
                    '#markup' => '' . $row['sku'] . '',
                 );
    //drupal_set_message('
' . print_r($sku, true) . '
');
   $orderin = array('#id' => 'orderin',
                 '#type' => 'markup',
                 '#markup' => '' . $row['orderin']. '',
                 );
            //   print_r($orderin);
    //drupal_set_message('
' . print_r($nid, true) . '
');
    $orderout = array('#id' => 'orderout',
                     '#type' => 'markup',
                    '#markup' => '' . $row['orderout'] . '',
                 );
    //drupal_set_message('
' . print_r($orderOut, true) . '
');
    $created = array('#id' => 'created',
                     '#type' => 'markup',
                    '#markup' => '' . $row['created'] . '',
                 );

    $form['results'][] = array('nid' => &$nid,
                                'sku' => &$sku,
                                'orderIn' => &$orderin,
                                'orderOut' => &$orderout,
                                'created' => &$created,
                                );
    $form['results']['#rows'][] = array(array('data' => &$nid),
                                         array('data' => &$sku),
                                         array('data' => &$orderin),
                                        array('data' => &$orderout),
                                         array('data' => &$created),
                                         );
    unset($nid);
    unset($sku);
    unset($orderin);
    unset($orderout);
     unset($created);

    }

  }

 else {
   $form['results']['#rows'] = '
The results will appear here when you change the dropdown option.
';
    }

      return $form;
    }

**callback function**
   function webform_module_display($form, $form_state) {

      return $form['results'];

    }


Can one use python 3.5 in a docker container based out of the TensorFlow docker image?

Question: I was trying to use python 3.5 with my docker container. I tried:
gcr.io/tensorflow/tensorflow:latest-devel

and
gcr.io/tensorflow/tensorflow:latest-devel-py3

but it seems that both images only have python version up to 3.4. Is it possible to have as base image the docker container but also have python 3.5? Or even better, is it possible to have the base image from the official tensorflow image have python 3.5 itself?
I know its possible to pip install it in the Dockerfile as in (as shown in the tf download page):
RUN export TF_BINARY_URL=https://storage.googleapis.com/tensorflow/linux/cpu/tensorflow-0.12.1-cp35-cp35m-linux_x86_64.whl
pip3 install --upgrade $TF_BINARY_URL

however that seems that would not get me the latest tensorflow version. If one can pip install the most recent TensorFlow version why does the latest base image not a way to get the most recent TensorFlow build and have it in python3.5?

I have definitively tried installing python 3.5 as suggested by here however, even though the installation of python 3.5 is successful, it breaks numpy in a way I can't fix (as explained here). Honestly, the best solution would be to just have python 3.5 automatically available on the image but for some reason its not there. I have done some research on this and it seems to install python 3.5 its a little difficult. Why is that? Is the reason python 3.5 is missing is because of tensorflow or because of ubuntu? My ideal solution would be to not have me install python 3.5 and that it comes, but it seems there might be a fundamental issue with this. What is it? Is it just because it has not been installed for tensorflow docker image and ubuntu, or am I over complicated a simple problem?

as another solution, I was thinking maybe to install anaconda or something and then do that, but I wanted to have tensorflow as my base image and it seems anaconda suggests to have their image as base. Since there isn't an easy way to install anaconda with apt-install I am still working to see how I can programatically install anaconda so that there can be a tensorflow image as base and then install as instructed in a Dockerfile, some version of anaconda.

There is now a git issue ine official tensorflow for this:
https://github.com/tensorflow/tensorflow/issues/7368

I mentioned that one can just install TensorFlow in the DockerFile directly so here is an example docker file that worked for me:
RUN apt-get update && apt-get install -y build-essential git libjpeg-dev
RUN apt-get install -y vim

# get wget
RUN apt-get install wget

# install python 3.5
RUN add-apt-repository -y ppa:fkrull/deadsnakes
RUN apt-get -y update
RUN apt-get -y install python3.5

RUN wget https://bootstrap.pypa.io/get-pip.py
RUN python3.5 get-pip.py
RUN python3.5 -m pip install -U numpy

#Install some stuff my lib needs
RUN python3.5 -m pip install -U numpy
RUN python3.5 -m pip install -U namespaces
RUN python3.5 -m pip install -U scikit-learn
RUN python3.5 -m pip install -U scipy
RUN python3.5 -m pip install -U pdb
RUN python3.5 -m pip install -U keras

#
#export TF_BINARY_URL=https://storage.googleapis.com/tensorflow/linux/cpu/tensorflow-0.12.1-cp35-cp35m-linux_x86_64.whl
RUN python3.5 -m pip install https://storage.googleapis.com/tensorflow/linux/cpu/tensorflow-0.12.1-cp35-cp35m-linux_x86_64.whl

I think the only interesting thing to note is that I installed pip directly because that package/intallation of python3.5 doesn't come with pip for it for some reason. That lead to me to install python packages to use:
python3.5 -m pip install

instead of
pip3

you can see more of those details here: How does one install/fix a failed numpy installation that works on python 3.4 but not in 3.5?
Also note that I had issues installing python the "official way" (i.e. with apt-get or something like that) so I resorted to what the following question/answer suggested: https://askubuntu.com/questions/682869/how-do-i-install-newer-python-versions-using-apt-get
Comment: Have you considered just starting with a base ubuntu image and then installing python3.5 and tensorflow?
Comment: @pvg yes. I suggested that at the beginning of my question. I will provide the code/Dockerfile for that in a bit at the end of my question. The issue is that that doesn't pull the most latest TensorFlow build. But it can be a short term fix.
Comment: Well, I just tried it for kicks and it took less than a minute without complaining. I think it's also not obvious (to me, at least, maybe you've figured it out) exactly what the versions in the images are. The ones you refer to are a month old. There are some there that are from half an hour ago.
Comment: Ah here. https://console.cloud.google.com/kubernetes/images/tags/tensorflow?location=GLOBAL&project=tensorflow

You can see that 'latest' is basically the same as the latest release you get from pip. You can get even more latest which may include a python interpreter more to your liking.
Comment: @pvg interesting. It definitively did not take me under a minute to install python 3.5 on my Docker image and also successfully use it with tensorflow. Mine broke numpy for some reason. I detailed in my question how I fixed it. I would be interested in seeing how you did it. Feel free to provide it as an answer, it can still be helpful as a partial solution.
Comment: @pvg not sure I understand what your last comment means. I thought that pip got a specific version since the it clearly linked to the specific version of TensorFlow. Does the base image not get the latest working version of tensorflow? The link I provided is at least the one they recommend on the official tensorflow website it seems https://www.tensorflow.org/get_started/os_setup#docker_installation
Answer: With a plain 'ubuntu' docker image from DockerHub and relying on pip to do its own dependency resolution (I wonder if not doing that is what causes your numpy problems) I ran:
apt-get install python3
apt-get install python3-pip
pip install tensorflow

As far as I can tell, this gave me python3.5 with the latest tensorflow - like their docker image but with python3.5.
To me, the provided docker image is something that's intended to work 'as is' and presumably the bits and pieces provided are intended to convey the developer's higher confidence that they all work correctly together. If you need to make substantial changes it seems easier and simpler to just start from scratch.
Comment: @CharlieParker Yes, I did, I updated the text to reflect that.
Comment: The middle approach - start with the pre-made docker image and then try to replace one component or another with a version you want - this is perfectly reasonable in theory but in practice turns out to be a painful and unpleasant mess. So I don't think you misunderstood or were misguided by anything, you just accidentally picked the path of maximum hassle.
Comment: did you do this in a Docker image? i.e. what is your base image?
Comment: thanks so much pvg! This is so valuable for me. I have no idea why I didn't try that. Maybe it was because my tensorflow base image only had python 3.4 or maybe I was misguided by this question: http://askubuntu.com/questions/682869/how-do-i-install-newer-python-versions-using-apt-get/881697#881697, whatever it was thanks (if you know you can tell me though). Also, what is the difference with doing your suggestion and installing tensorflow directly with a pip command `pip3 install tensorflow` and having an official tensorflow base image? I'm trying to understand which one I should be using.
Comment: As far as I can tell, there is no difference as they seem to keep the tf versions in pypi  (and their published wheel file) and on the image in sync. I'm guessing the docker image is the thing most closely represents the devs own environment. So if you want maximum convenience, compatibility etc, use their image. If you have other specific needs (say, you really want python3.5, etc), install tf with pip. Your tool for sorting out compatibility with your other python deps, existing code, etc is then pyenv, rather than docker . You can go on to make your own docker image with the final result.
Answer: Yes. Python 3 docker images are available on dockerhub nightly builds.
CPU only
docker pull tensorflow/tensorflow:nightly-py3
with GPU support
docker pull tensorflow/tensorflow:nightly-gpu-py3

https://hub.docker.com/r/tensorflow/tensorflow/tags/
https://github.com/tensorflow/tensorflow/issues/3467
Answer: I have tried to pull in a python:3.5 image and install tensorflow basing on this image, which works.
what I have in the dockerfile:
FROM python:3.5
RUN pip install tensorflow


Moonlight sonata, note lengths inside triplets

Question:
The first triplet is very uneven. Its total length is 1/4.
Triplet 1:
A (1/8), D#(1/4), F#(1/4 divided by 3 = 1/12)
For how long should I hold A and D#? Should I hold D# with 1st finger until C# from the 2nd triplet is pressed with the 2nd finger?

Or just together with F#:

Triplet 2:
C# (1/4), F#(1/12), A(1/12)
Here I keep pressing C# with 2nd finger while playing F# (4th), A (5th)
Triplet 3 (simple):
I hold B# till the end of this triplet and the next one.
Please, explain, how to play the 1st triplet?
Comment: Up - and down- stems **always** indicate different voices.  Each voice here is clearly marked as to note lengths, as Lawrence "KIng of" Payne answered.
Answer: You can see WHEN the D# and C# are played.  There are no rests in the lower voice, and no overlaps.  All you're really being asked to do is 'bring out' the melody A, D#, C#.    Maybe easier to see if I write it separately, with the triplet indications that Beethoven has tired of writing by this point.
Answer: Technically, it doesn't matter how long you hold those notes, because Beethoven tells you to keep the damper pedal held down for the entire first movement.  Even though a modern Steinway sustains longer than his piano, some respected pianists still perform it like this.


Azure Industrial IoT Platform web app needs permission to access resources in your organization that only an admin can grant

Question: I'm trying to deploy the platform using deploy.ps1 and it seems to work, but I cannot login to the engineering tool web app. I get the following message:

my-test-iiot needs permission to access resources in your organization
that only an admin can grant. Please ask an admin to grant permission
to this app before you can use it.

What should I do?
Answer: The issue is related to the application registrations in Azure Active Directory that are needed to authenticate. Basically we recommend three different options:

Contact your IT- or AAD-Admin and ask for the process to get admin consent for your application. This would allow your app to use the corporate AAD for authentication.
We provide a script called aad-register.ps1 that the AAD-Admin can execute to create the necessary application registrations and grant consent automatically.
Create your own AAD or AAD B2C, this would give you the necessary rights and is the quickest solution for a PoC or test environment.

See Deploying Azure Industrial IoT Platform and dependencies for more information.


On the usage of words instead of numbers to denote numbers

Question: [To the best of my knowledge, I did not find any previous question that deals with this issue. I hope it is not a duplicate.]
I have a problem with the way in which mathematicians sometime use words instead of numbers to actually denote numbers. To me it seems that numbers should always be used whenever we are actually talking about numbers, however it is not really the case.
EXAMPLES:
1) "Probability one" or "Probability 1"?
2) "Measure zero" or "Measure 0"?
3) "Solution larger than one" or "Solution larger than 1"?
4) "The value is one" or "the value is 1"?
In all these cases, I think the proper way of writing is the second one, however I often find the first way.
To me this looks particularly incoherent, because the same authors shamelessly move to the second style whenever the number is slightly awkward (i.e. it is not an integer). Indeed, it is quite easy to find somebody who writes down "probability one", and then later on writes "the value is $1/2$". [Please, note that I am not referring to a sentence like "the value of $\alpha$ is $1/2$", that can be easily rephrased in a more readable expression such as "where $\alpha = 1/2$".]
Here there are my questions.
1) Is there a general rule to write down numbers?
2) Is my intuition correct about the way in which things are usually written?
3) Is my intuition correct about the way in which things should be (on logical and grammatical grounds) written?
Thank you in advance for any feedback!
PS: True enough, the first and the second examples can be considered slightly different from the third and the fourth, because - even if it actually applies what I claim (i.e. writers use words to denote numbers) - those could be considered expressions that have developed historically an inner meaning that goes beyond the fact that they indirectly refer to numbers.
Comment: @Hayden (and flawr): Yes, non-mathematical writing has general rules like this.  Kolmin says it is illogical for mathematical writing.  I say to Kolmin: go ahead and to it your way, but don't complain when others do it in other ways,
Comment: I think this has less to do about mathematics and more to do about writing style.  When I was going through elementary and secondary school, the rule of thumb was to use words for numerals less than 10, and to use the numerals for 10 and up.
Comment: Be glad we are not required to say "unity", as mathematicians used to do when writing the number $1$ as a word.
Comment: In german I learned that only the integers $0,...,12$ should be written out as words, everything else should be written as number. But this is rather a general rule, an does even in german not necessarly apply to mathematical texts.
Comment: @GEdgar: I see what you meant. Thus my question is, which one of the two forms I presented do you consider good mathematical writing? (More or less in the same way in which there is *bad* mathematical writing for Serre).
Answer: I found a guide on writing mathematical papers here (about in the middle of the text) that has following guidlines:

(...) In addition, avoid numerals because they slow down the reading. Write
  numbers out if they can be expressed in one or two words and are used
  as adjectives, unless they are accompanied by units, a percentage
  sign, or a monetary sign. For instance, write, "The equation has two
  roots," and "One root is 2." Don't begin a sentence with a numeral
  or a symbol; reformulate the sentence if necessary.
Comment: The remark that "numerals slow down reading" is ridiculous. Generally, using appropriate *mathematical* notation (vs. natural language) *speeds-up* reading and comprehension (assuming a mathematically competent reader). I'd dread reading a paper in number theory written that way.
Comment: Thus, the second way should be the *best* one, in terms of mathematical style as well, shouldn't be? Actually, it is a bit ambiguous, because in one line it says that the have to (note the imperative) be written out if they can be expressed in one or two words, but then we find "One root is 2". Now, this looks good to me, but it is slightly incoherent, isn't it?
Comment: I do not fully agree with @BillDubuque's comment. @ Kolmin: Yes it is coherent, since the author said you should write it out when the number if used as an *adjective*. The way I understand it is that they can *only* be written out when used as adjective. But I agree, I prefer numerals when refering to a value. (But not as adjective)
Comment: @Kolmin Further, natural language may inhibit intrinsic mathematical pattern matching. For a simple example, compare: "in a domain, $\, x^{\color{#c00}{\large 5}}-a\,$ has at most $\,\color{#c00}5\,$ roots", vs. "five roots". Using *precisely* the same symbol $\,\color{#c00}5\,$ in both places helps the reader to see the relationship between the degree and the number of roots. In less trivial examples, such pattern-matching can be greatly obfuscated by the use of natural language.
Comment: IMO, both yours and the site statement are debatable. It is true that mathematical writing is more about conventions than logical soundness, but still using numbers does not interfere with the quality of the reading and it is generally sounder (at least in the examples I wrote down).
Comment: @flawr: It is interesting. I think we read the conjunction "and" in two different ways. I read it as the author was enumerating the cases in which you can use a numeral, that is: (1) when the number can be expressed in one or two words; (2) when it is used as an adjective. Thus, while I was reading the "and" as a logical "or", you were actually reading it as a logical "and".
Comment: Using natural language (e.g. English) instead of highly-optimized mathematical language is akin to riding a bike with training wheels. If you wish to excel at mathematics it is essential to train your mind to think in *mathematical* language, not natural language. With enough practice, one can *mentally* visualize an entire blackboard worth of grossly inefficient natural-language-presented mathematics.
Comment: @BillDubuque That's an excellent point about pattern-matching. And, sometimes, I try to make the text more structured/readable by, for example, using numerals for values and words for counts, for example: There are four cars A,B,C and D, with respective speeds (in hm/h) $50,60,70$ and $80.\quad$ I'm okay with this Answer's excerpt,  but its opening sentence indeed makes no sense unless changed to something like "In addition, avoid **a jumble of** numerals because they *slow down reading (and inhibit pattern-matching)*."
Comment: @Kolmin Both instances of "and" in the excerpt are meant as conjunctions; otherwise, the author's 2nd example ("write 'One root is 2'") would be contradicting their own advice to use spell out numbers in words whenever they can be expressed in up to two words.


Why is it so hard for a horse to win the triple crown?

Question: Why is it tough for a horse to run three ~1 mile races within 5 weeks to win the triple crown (Kentucky Derby, Preakness, Belmont)?
Perhaps I don't understand horse physiology verse human physiology but why is this the case?  Humans can run many miles per day while training and/or can run a 1-2 mile race once or twice a week (well, my friends did in HS for track and field).
EDIT: Here's an article that shows the owner complaining the field was stacked with fresh horses against his "tired" horse but again, for a horse to run three 1 mile races in 5 weeks, fatigue shouldn't be an issue unless I'm totally off regarding horse vs. human physiology.
http://www.usatoday.com/story/sports/horseracing/2014/06/08/california-chrome-belmont-stakes-triple-crown-steve-coburn-angy/10196373/
Answer: The 3 races in 6 weeks isn't the issue.  While some horses will race only in one race - particularly the Derby - most of them are racing all three unless they get hurt.
Instead, there are several contributing factors making it harder to win the triple crown.

The three races are of different lengths, meaning different horses will run them differently.  The Belmont is 1.5 miles, while the Kentucky Derby is about 1.25 miles, and the Preakness is in between (1 3/16ths mile). That seems like a small difference, but it does matter - and human racers definitely see differences between a 50 meter dash and a 100 meter dash, at least, if not quite that small of differences.
Even if the races were identical, each race has a different number of horses, horses start out at a different spot in each race, and weather conditions may vary how a horse performs at each race.
Finally, you have the problem of repeatedly winning a race.  Unless a horse is far superior to all of the other horses out there, it's very hard to win 3 consecutive races, beating the same field (roughly) three times.  It's the same reason why golfers rarely win the single-year grand slam - you have to be perfect four times, and it's very hard to do that.  Even a horse who (by himself) had a 75% chance to win each race, which is far more than nearly any horse is considered to have in any given year, that's 3/4*3/4*3/4 or 27/64ths to win all three - under 50%.
Comment: thx for your answer and bringing up other reasons/pts. I guess I sitll think 3 races in 6 wks for a horse that has won the 1st 2 legs is a big issue to consider b/c I think it was last yr when the owner of CAChrome complained that there were horses in the Belmont that didn't run the 1st two races and he made it seem like there were 10 fresh horses gunning against his "tired" horse for that race. If I remember correctly, I think I heard there were only 4 horses that ran both the Derby and Preakness that were in last year's Belmont (haven't looked up yet, just relying on memory).
Comment: I should have posted this first before opening my mouth

http://www.usatoday.com/story/sports/horseracing/2014/06/08/california-chrome-belmont-stakes-triple-crown-steve-coburn-angy/10196373/

"California Chrome ran his third Triple Crown race in five weeks. Only two other horses in the 11-horse Belmont field also ran in all three. Ride On Curlin was last and General a Rod was seventh."


Dias da semana dinamicamente

Question: Quero mostrar os dias da semana (Terça 2 dezembro) numa tabela por semana a partir da função date. Ou seja a tabela tem 7 colunas e começa no domingo até sabado. Por exemplo:
Dia da semana

Answer: Você pode fazer uso da função date() do PHP para obter o dia da semana.
echo date("l"); //exibe o nome do dia da semana, em inglês
echo date("N"); //exibe a representação numérica do dia da semana

echo date("d")." "; //exibe o dia
echo date("m")." "; //exibe o mês
echo date("Y")." "; //exibe o ano

Como parâmetro você passa o formato de saída desejado ("N" retorna a representação numérica ISO-8601 do dia da semana)
Usando date("N") é possível construir uma função simples que retorne o dia da semana em português.
echo dayOfWeek(date("N")); //exibe o dia da semana em portugues

function dayOfWeek($day){
    switch ($day) {
        case 1:
            return "Segunda";
        case 2:
            return "Terça";
        case 3:
            return "Quarta";
        case 4:
            return "Quinta";
        case 5:
            return "Sexta";
        case 6:
            return "Sábado";
        case 7:
            return "Domingo";
    }
}

Sobre a questão de gerar uma tabela com dos dias da semana...
echo "
";
echo "
";
for ($i=1; $i <= 7 ; $i++) {
    echo "";
    echo dayOfWeek($i);
    echo "	";
}
echo "
";
echo "
";

Comment: mesmo esquema, só procurar na documentação qual parâmetro te retorna o número do mês
Comment: Certo e quero escrever o dia e o mes junto ao dia de semana.

Dias da semana dinamicamente


How to safely update an existing Kubernetes server without original configurations

Question: I was handed a Kubernetes cluster with no config files, and was not setup with helm. The author said they just created everything from the cmd line. It is a small/new cluster for a single API server with an nginx ingress controller. I know enough of Kubernetes to get around and was able to add a new web server, but now I need to get in deeper and update existing configs. Specifically, I want to enable prometheus metrics on the nginx controller, but I don't want to break anything.
Is there a standard way to retrieve the existing configurations (deployments, services, etc) from the cluster, make modifications, and apply them? Or is there a way to patch in updates to individual parts of the existing configuration without having to create a new yaml file?
I understand I can get the current config with something like this:
kubectl get services -n nginx -o yaml

That output has additional fields like creationTimestamp, uid, etc, that I suppose I need to remove. Or can I just save the output exactly as is to a yaml file, make my modifications to enable prometheus, and then apply the config back to the controller?  Will it ignore the kube-created fields? Is there a different approach I should be considering?
Secondly, should I store these configurations in a repository, or is this just how things are done?
Answer: Seems like you have almost anything you need; there are only some minor considerations:

kubectl -n <ns> get <CRD> -o yaml will give you the output with some read-only identificators, which you cannot redefine even if they will keep theis values, so these aren't suited to keep them as plain files.
use kubectl edit instead
as about should you keep these in any VCS you want, or should you just make modifications on the fly - it's entirely up to you to decide; any attempt to discuss this will probably start a flame.
Comment: Thank you very much, exactly what I was missing.  I'm okay with taking an approach that 50% consider valid.  I'm sure I will come to a conclusion on that myself as I get more insight and experience with Kube.


finding fixed field of automorphism

Question: Let $F$ be a field and let $g:F(x) \to F(x)$ be the automorphism which maps $x$ to $x+1$.
I need to find the fixed field of this automorphism.
So far I know $g$ fixes $F$. I want to use Galois applications but the group generated by $g$ is infinite.
Can I have a hint how to start?
Thanks.
Comment: OK, sorry, I misread the question.
Answer: Hint: a standard way to show that a rational function over a field is constant is to show it has either has infinitely many zeroes (in its algebraic closure), or that it has no zeroes and no poles (in its algebraic closure).
I'm assuming you're in a field of characteristic zero? Otherwise, your automorphism group is finite.
Comment: there is no information about the characteristic but I will check the different cases

finding fixed field of automorphism


Move uploaded content automatically from one node to another

Question: Is it possible post images/text on a different page other than the one being uploaded?
I have an insert page where users can add images/text but I want whatever they post to go on another page automatically ('things' page) sorted by the most recent first. I only want to keep the 'insert' page as an 'insert' and without content!
Answer: Content in Drupal is organized in "nodes":

A node is any piece of individual content, such as a page, poll, article, forum topic, or a blog entry. Comments are not stored as nodes but are always connected to one.

So you'll always have a "page" or whatever your content type is named, to store and edit the content. But you don't need to show these pages necessarily to the visitors or users of that site.
You should take a look into Views module, which will enable you to create (another sort of) "pages" that automatically collect content from "nodes" according to the rules and filters that you have definded for it.