Clicar no botão e mostar só data e hora

Question: Tenho este botão para dar inicio da tarefa:

$('#IniciarTarefa').on('click', function () {
    $(this).closest('.form-group').data('inicio', new Date().getTime());
});

$('#mostrar').on('click', function () {
    var time = $('.form-group').data('inicio');
    alert(new Date(time));
});

        <button id="IniciarTarefa" name="IniciarTarefa" class="btn btn-info">Iniciar Tarefa</button>

<button id="mostrar">Mostrar quando tarefa foi iniciada</button>

Mas mostra a data desta forma:

E desta forma não consigo inserir na base de dados. Pretendia que mostrasse só a data desta forma:
2019-03-22 17:14:45
Comment: Possível duplicata de [Como formatar data no javascript?](https://pt.stackoverflow.com/questions/6526/como-formatar-data-no-javascript)
Answer: Utilizando função demonstrada em outra resposta em ingles (fonte aqui)

 function formatDate(date) {
  var monthNames = [
"Janeiro", "Fevereiro", "Março",
"Abril", "Maio", "Junho", "Julho",
"Agosto", "Setembro", "Outubro",
"Novembro", "Dezembro"
  ];

  var day = date.getDate();
  var monthIndex = date.getMonth();
  var year = date.getFullYear();
  var hours = date.getHours();
  var min = date.getMinutes();
  var sec = date.getSeconds();

  return year + '-' + (monthIndex+1) + '-' + day + ' ' + hours + ':' + min + ':' + sec;
}

var dtTime;
$('#IniciarTarefa').on('click', function () {
   $(this).closest('.form-group').data('inicio', formatDate( new Date() ) );
});

$('#mostrar').on('click', function () {
    var time = $('.form-group').data('inicio');
    alert('Data: '+ time );
});

        <button id="IniciarTarefa" name="IniciarTarefa" class="btn btn-info">Iniciar Tarefa</button>

<button id="mostrar">Mostrar quando tarefa foi iniciada</button>
Comment: mas pretendia que guardasse do value do botão além da data também a hora
Comment: Ok, adicionado.
Para mais opções, consultar documentação da classe Date: https://javascript.info/date
Comment: mas da forma que está só quando mostra é que a data é formatada, mas  o botão mostrar e a função do `click` do botão mostrar é para retirar. A ideia é guardar no `value` do botão com `id="IniciarTarefa"` a data e a hora formatada para depois inserir na tabela da base de dados.
Comment: Cara, você já tem a faca e o queijo na mão, pode manipular o codigo como quiser, de qualquer forma, script ajustado.
Answer: Boa tarde. Isto pode ajudar:

$('.jsData').on('click',()=>{
    obtainedData();
})

function obtainedData(){
  var fecha = new Date();
var options = { year: 'numeric', month: 'numeric', day: 'numeric',hour: 'numeric', minute: 'numeric', second:'numeric' };

alert(
  fecha.toLocaleDateString("pt-BR", options)
);
}

<button class="jsData">Obtained Date</button>

Clicar no botão e mostar só data e hora


how to get day of week from date in apache drill sql?

Question: I am using dbeaver connected to apache drill sql , trying to get day of week.
For example for '1/27/2019' the day of week is 1, considering sunday as the first day of week.
Example 2 : '1/28/2019', output : 2
Answer: In Apache Drill SQL, you should be able to use the TO_CHAR() data type conversion method. Format specifier 'e' should be what you need :
TO_CHAR(my_date_col, 'e')

If your dates are stored as string, you would need to convert them to date first, for example using TO_DATE :
TO_CHAR(TO_DATE(my_string_col, , 'MM/dd/yyyy'), 'e')

Comment: You would have to roll up your own logic, like, for example : `CASE WHEN TO_CHAR(my_date_col, 'e') = 1
    THEN '7'
    ELSE TO_CHAR( TO_NUMBER( TO_CHAR(my_date_col, 'e'), '#' ) + 1, '#' )
END`
Comment: Thank you ,its working , is there any way to mention start day of the week in TO_CHAR.     select to_char(current_timestamp,'e') its returning 7 as sunday is the last day of the week. how can we get the value as 1 stating that sunday is the start day of the week
Comment: @Surya I don't think there is a standard option for that, and I cannot find it in the documentation.
Answer: TO_CHAR(date_col, 'e') will return number. For example, if the weekday on Monday, it will return 1. and so on...
TO_CHAR(date_col, 'E') will return characters. For example, if the weekday on Monday, it will return Mon. and so on...
Make sure your date column is in date format, if not first convert it to date format using TO_DATE() and then perform the above step.


The integral of $ \sin(x^2) $

Question: The actual problem is: Find the first four nonzero terms and the general term of the Maclaurin series for $g(x) = \int\sin(x^2)dx $ with $g(0) = 1$.
How do you find the integral of $\sin(x^2)? $ I know that you are supposed to convert it into power series, but how do you actually take an integral there?
Any help would be appreciated.
Comment: it gives the so-called Fresnel-integral
Answer: You know that
$$ \sin x = \sum_{j=0}^\infty (-1)^j \frac{x^{2j+1}}{(2j+1)!},
\sin x^2 = \sum_{j=0}^\infty (-1)^j \frac{x^{4j+2}}{(2j+1)!}
$$
this series can be integrated termwise.
$$ g(x) = \int \sin x^2\,dx = \sum_{j=0}^\infty (-1)^j \int \frac{x^{4j+2}}{(2j+1)!} dx
= \sum_{j=0}^\infty (-1)^j \frac{x^{4j+3}}{(4j+3)(2j+1)!} + C
$$
Then substitute $x = 0$ to find $C$.
Comment: Well, looks like I need to go to E.SE to ask about the difference of "termwise" and "termwisely".
Comment: @G.Sassatelli Thanks. It is fixed.
Comment: Can I ask what happens to the constant (1?) when expanding the series? Will it simply not exist because of the (-1)^j? @Henry W.
Comment: @KER $\sin 0^2 = 0$ so the constant term is $0$.
Answer: Specifically: The primitives of $\sin(x^2)$ are not elementary, so you don't calculate them.
Hint for the problem: Recall that $g'(x)=\sin(x^2)$. And that the Maclaurin expansion of $g$ is $$g(0)+g'(0)x+\frac{g''(0)}{2}x^2+\cdots+\frac{g^{(n)}(0)}{n!}x^n+\cdots$$

The integral of $ \sin(x^2) $


What differences are between a NAS, a shared disk file system on a SAN, and a distributed filesystem?

Question: https://en.wikipedia.org/wiki/Clustered_file_system#Network-attached_storage says

Network-attached storage (NAS) provides both storage and a file
system, like a shared disk file system on top of a storage area
network (SAN). NAS typically uses file-based protocols (as opposed to
block-based protocols a SAN would use) such as NFS (popular on UNIX
systems), SMB/CIFS (Server Message Block/Common Internet File System)
(used with MS Windows systems), AFP (used with Apple Macintosh
computers), or NCP (used with OES and Novell NetWare).

https://en.wikipedia.org/wiki/Network-attached_storage

Network-attached storage (NAS) is a file-level (as opposed to block-level) computer data storage server connected to a computer network providing data access to a heterogeneous group of clients. NAS is specialized for serving files either by its hardware, software, or configuration. It is often manufactured as a computer appliance – a purpose-built specialized computer.[nb 1] NAS systems are networked appliances that contain one or more storage drives, often arranged into logical, redundant storage containers or RAID. Network-attached storage removes the responsibility of file serving from other servers on the network. They typically provide access to files using network file sharing protocols such as NFS, SMB, or AFP.
... A clustered NAS is a NAS that is using a distributed file system running simultaneously on multiple servers. The key difference between a clustered and traditional NAS is the ability to distribute[citation needed] (e.g. stripe) data and metadata across the cluster nodes or storage devices. Clustered NAS, like a traditional one, still provides unified access to the files from any of the cluster nodes, unrelated to the actual location of the data.

Does a NAS provide both block level and file level operations?
Does "Network-attached storage (NAS) provides both storage and a file system, like a shared disk file system on top of a storage area network (SAN)" mean that NAS and a shared disk file system on a SAN are the same?
Does "NAS typically uses file-based protocols (as opposed to block-based protocols a SAN would use) such as NFS (popular on UNIX systems), SMB/CIFS (Server Message Block/Common Internet File System) (used with MS Windows systems), AFP (used with Apple Macintosh computers), or NCP (used with OES and Novell NetWare)" mean that NAS and a distributed filesystem are the same?
Thanks.
Answer: Nowadays the border between NAS and SAN is unclear especially for SMB products.
Historically NAS devices consist of the bunch of disks arranged in some RAID to maximize the overall performance and achieve the required data redundancy. These devices have core operating systems aboard. Those OS do all low-level processing and file systems maintenance. File systems, in their turn, share disks content over the network on the file level. NAS present the storage over high-level protocols like SMB, NFS, AFP, etc. Modern NAS can also present block storage (iSCSI) and have basic SAN features like replication, snapshots, etc. If you need just "small" capacity (up to 100TB) and storage high availability is not required, modern NAS would be a best suitable option.
SAN is historically a block-level storage system that can be accessed via such fast protocols as FCoE, iSCSI, Fibre Channel, etc. Mostly SAN includes not only disk redundancy, but also controller redundancy and may allow active (or passive) replication between SAN boxes. SAN has flexible scalability option. And certainly, all enterprise level SAN know file protocols like CIFS and NFS.
Article regarding SAN and NAS - https://www.hyper-v.io/san-nas-public-cloud-lets-pick-secondary-storage/
Distributed filesystem is not a storage, but just a method how the storage access is organized and how the storage is presented. Actually, you can deploy distributed file system over (many) SAN/NAS devices. Here is an article with more explanations: https://www.quora.com/What-is-a-distributed-file-system-and-what-is-it-used-for
Answer: It varies, but a NAS typically exposes file level storage rather then block level storage.   Many NAS's are a variant of Linux or Another Unix variants running Windows file sharing (SMB) and Unix filesharing (NFS).   It may be possible to do block level sharing, but I don't believe its a particularly common use case.
A SAN typically provides block level storage rather then file level storage.
A distributed filesystem is where the files are spread over many computers but behave as file storage.
Comment: A NAS is a single computer (ie box with CPU, ram+disk).   A distributed filesystem is entirely different - the files are scattered over more then 1 computer/device even though they look, to the end user to all be at a single location...
Comment: Thanks.I am still wondering what difference are between a NAS and a distributed filessytem?  Could you elaborate more?
Comment: A NAS is a *single device* while a distributed filesystem looks like a single file system but the files are i*spread across multiple devices*
Comment: Thanks. NAS is Network-attached storage (NAS). In what sense do you mean by NAS is a "single device"? Isn't it the same as a distributed file system?
Comment: Distributed filesystems are not common as they are hard to build and maintain.  They have very specific use cases (generally storing more data then can be stored on a single device) and are seldom seen outside of "big data" companies, the military or institutions requiring massive storage.
Answer: SAN: filesystem - > network - > block device
NAS: network - > filesystem - > block device
IOW, SAN makes block devices accessible over the network. The storage server stores only blocks without any knowledge how they build a filesystem, if at all. In opposite, NAS makes filesystem accessible over the network. The NAS server exports it's local file system.
Often, NAS servers use SAN to store the data. For example, an NFS server can export local XFS file system wich is attached by iSCSI.
Comment: @BAKEZQ shared disk filesystem is a type of SAN, where multiple hosts can access the same block device. A NFS 4.1/pNFS with block layout driver over iSCSI it an example of it. The access to blocks coordinated by nfs server, however the clients directly talk to block devices.
Comment: waht is shared disk file system?


Comparing quasi-Poisson and negative binomial fit on panel data

Question: I am using the R package fixest to model over-dispersed count data with fixed effects.
While I have read that quasi-poisson and negative binomial regressions typically return similar results, this is not true in my case. When I use a quasi-poisson distribution with fixed effects, the model returns a statistically significant coefficient with a positive sign. But when I use a negative binomial distribution with fixed effects, the model does not produce a statistically significant result and the sign of the coefficient is negative (it reverses).
My first questions is, why do I get such different results?
    library(tidyverse)
    library(fixest)
    df_wall_deaths =
 read.csv('https://gist.githubusercontent.com/Alex-Devoid/ecf9a727dc885430737f40b38ceed95f/raw/2bec498a5b9ad1520a75f206cb612671639366a0/panel_data.csv')

    #The percent_unwalled_border variable is a percentage
    # expressed as a decimal
    #CORNO are corridors
    res_quasipoisson = feglm(death_counts ~
        percent_unwalled_border | CORNO, data =df_wall_deaths,
          family = "quasipoisson")
    esttable(res_quasipoisson,order = "Dist")

    res_negbin = femlm(death_counts ~ percent_unwalled_border |
      CORNO, df_wall_deaths,family = 'negbin')
      esttable(res_negbin,order = "Dist")
    # when I try to print res_negbin without esttable, it also
    # returns an error:
    # Error in coeftable[1, , FALSE] : incorrect number of
    # dimensions

My second question is, how can I compare the quasi-Poisson and negative binomial fit on this panel data?
Since I am working with panel data and using fixed effects, how can I compare the observed relationship between the mean and the variance in my dataset to the expected relationship from the models?
Below I have compared this relationship as if the models were not using fixed effects. But since fixed effects compare each corridor (CORNO) to itself, is it as simple as finding the mean and variance of arbitrary groups within each corridor? I have tried several things, including using a facet chart to run the comparison in each corodior, but I'm just not sure what the correct approach is.
    k <- res_negbin$theta

    THETA <- (sum(residuals(res_quasipoisson,
   type='pearson')^2)/degrees_freedom(res_quasipoisson_clustered,
   type = "resid"))

    #####
    #Arbitrarily divide data into 10 groups
    df_wall_deaths<-df_wall_deaths %>%
    mutate(groups=cut_number(percent_unwalled_border, n=10))
    #Calculate mean and variance for each group
    mean_variance <- df_wall_deaths %>%
      group_by(groups)%>%
      summarize(percenrt_unwalled_mean =
        mean(percent_unwalled_border),
                death_counts_mean = mean(death_counts),
                variance = var(death_counts))
    THETA <- (sum(residuals(res_quasipoisson,
   type='pearson')^2)/degrees_freedom(res_quasipoisson_clustered,
   type = "resid"))

    #plot the predicted mean-variance curves
    ggplot(mean_variance, aes(death_counts_mean,variance)) +
      geom_point() +
      #quasi-poisson
      geom_abline(slope=THETA) +
      #Negbin
      stat_function(fun=function(x)x+x^2/k,color="red")

EDIT:
I'm not sure if this is within the scope of this website, but I wanted to share a bit more:
Since I posted my questions, made a judgment call to use to the quasi-poisson distribution because it gives more weight to higher counts, while the negative binomial distribution weights counts more evenly, giving comparatively more weight to smaller counts within the dataset.
I think it's more appropriate to let the quasi-poisson distribution give more importance or weight to higher counts because we want to know more about the corridors where most migrant deaths are found. Do corridors with high counts also have a large share of Arizona's unwalled border in a given year, or not? I asked if this was an acceptable reason to choose the quasi-poisson distribution in this post: Comparing fixed effects quasi-Poisson and negative binomial fix
This data starts in 1990 when things were very different at the border. While I don't consider this dataset to be to be zero-inflated, for reasons I won't get into here, in the early 1990s more corridors had zero and low counts in these earlier years before it was Border Patrol's strategy to control urban areas and redirect traffic to more remote areas. I think a negative binomial model that weighs these low counts the same as higher counts in later years could skew the model.
Comment: it looks like your dataset is small, so bear in mind, it can be really tricky to model the variance - mean relationship. I would expect the significance of the coefficients to be different, but not the coefficient itself
Comment: from what you showed, it looks like coefficients are really different, which is weird.. might be good to check that the fit was done correctly
Comment: @StupidWolf Sorry for the dumb question, but how do I check that the fit was done correctly?
Comment: Could you check the package version? The error when printing the results does not pop for me.
Answer: On the first point: the assumption that the quasi-poisson leads to the same estimates as the negative binomial is wrong. They are two different models.
I guess what the OP has in mind is unbiasedness. The two estimators are indeed unbiased ($E[\hat{\beta}]=\beta$) but this does not mean that they lead to the same estimates. Especially that efficiency differ between the two methods.

On the second point: Even discounting for the FE structure, isn't your graph already sufficient to decide between the two methods? It really looks like the Poisson estimate is driven up by the large values (although, again, on expectation this estimator is unbiased -- but the estimate may be far off the true one for this particular sample).
Comment: Hi Laurent, I make an edit to my question explaining why I think it is appropriate for me to choose the quasi-poisson distribution. I'm happy to go into more detail in another medium, if you would like more to hear more about, for example, the limitations of the data and the model.


Need advice on a database structure

Question: A friend and I put together a MySQL php website where users can make predictions on sports events.
My question is regarding our "rankings" page which displays the list of members who have made the best predictions. The way we had it initially was each time a user loaded that page the server would calculate all the predictions from all the users, then displayed the top ones. Unfortunately, even with a small group alpha testing it, the loading of this page quickly became slower as the number of predictions grew.
Ideally speaking, we would like to have filters on this page, for each different sport, league and time frames, and create a dynamic rankings page, but we're stuck on finding an efficient way to structure our database that won't use up too much server resources.
Any ideas on what a better way could be is greatly appreciate. Thanks!
Comment: Please edit your question, showing the definition of the table in question and the query you are using.
Answer: You could use "materialized views" to calculate the score. A materialized view is a view (thus some query), but where the results are stored (in memory) and updated accordingly:
http://www.fromdual.com/mysql-materialized-views
One can expect that the difference (in the number of (correct) predictions) will not change dramatically between two page renderings. Thus that the number of calculations will be quite low.

Need advice on a database structure


Tic Tac Toe how to win based on image variable not string input

Question: I have some trouble running the checkForWinner function. I have set a document.turn to be an image variable, But After I changed what's inside the square.innerHTML to an image, the checkForWinner function cannot recognized my moves. How can I fix this? Do I need to set Global variable?
Thank you!

Javascript:
function choosebkgdX(){
      for (var i=1; i <= 9; i++) {
        clearBox(i);
    }
     document.turn ='';
}

function choosebkgdO(){
     for (var i=1; i <= 9; i++) {
        clearBox(i);
    }
    document.turn = '';
}

function nextMove(square) {
    if (document.turn==="X") {
    // if (document.turn===''){
        //  square.innerHTML = "X";
         square.innerHTML = '';
     } else {
        // square.innerHTML = "O";
        square.innerHTML = '';
     } switchTurn();
    }

function switchTurn(){
    if(checkForWinner(document.turn)) {
        alert("You Won!");
    } else if (document.turn == 'X') {
    // } else if (document.turn == '<images/boardx.png">') {
        // document.turn = 'O';
     document.turn = '';
    } else {
        document.turn = "X";
    //  document.turn = '<images/boardx.png">';
  }
}

function checkForWinner (move) {
    var result = false;
    if (checkRow(1, 2, 3, move)||
        checkRow(4, 5, 6, move)||
        checkRow(7, 8, 9, move)||
        checkRow(1, 4, 7, move)||
        checkRow(2, 5, 8, move)||
        checkRow(3, 6, 9, move)||
        checkRow(1, 5, 9, move)||
        checkRow(3, 5, 7, move)) {
        result = true;
    }
    return result;
}
function checkRow(a, b, c, move){
    var result = false;
    if (getBox(a) == move && getBox(b) == move && getBox(c) == move){
        result = true;
    }
    return result;
}

function getBox(number){
    return document.getElementById('s' + number).innerHTML;
}

function clearBox() {
    for (var i=1; i <= 9; i++) {
        document.getElementById('s' + i).innerHTML = "";
    }
}

Comment: You never declare `document.turn` and you really shouldn't be adding new properties to the document object in the first place. When `checkForWinner` runs, `document.turn` (which is supposedly passed to the function and received as `move`) is undefined.
Comment: Maybe this will help, [vue version](https://stackoverflow.com/a/52050802/661872)
Answer:

// Don't set up your events with HTML attributes.
// Do all JavaScript work separate from HTML and
// you see how much redudant code you can get rid of
document.querySelector("div.detailtoegrid").addEventListener("click", nextMove);

// You never declare document.turn and you really shouldn't
// be adding new properties to the document object in the first place.
// Instead create a variable and initialize it as the game starts.
let turn = "X";

function choosebkgdX(){
  for (var i=1; i <= 9; i++) {
    clearBox(i);
  }
  turn ='X';
}

function choosebkgdO(){
  for (var i=1; i <= 9; i++) {
   clearBox(i);
  }
  turn = 'O';
}

function nextMove(event) {
  if (turn==="X") {
    event.target.innerHTML = '';
  } else {
    event.target.innerHTML = '';
  }

  switchTurn();
}

function switchTurn(){
  if(checkForWinner(turn)) {
    alert("You Won!");
  } else if (turn == 'X') {
    turn = 'O';
  } else {
    turn = "X";
  }
}

function checkForWinner(move) {
console.log(move);
  var result = false;
  if (checkRow(1, 2, 3, move)|| checkRow(4, 5, 6, move)||
      checkRow(7, 8, 9, move)|| checkRow(1, 4, 7, move)||
      checkRow(2, 5, 8, move)|| checkRow(3, 6, 9, move)||
      checkRow(1, 5, 9, move)|| checkRow(3, 5, 7, move)) {
        result = true;
  }
  return result;
}

function checkRow(a, b, c, move){
  var result = false;
  if (getBox(a) == move && getBox(b) == move && getBox(c) == move){
   result = true;
  }
  return result;
}

function getBox(number){
  return document.getElementById('s' + number).innerHTML;
}

function clearBox() {
  for (var i=1; i <= 9; i++) {
    document.getElementById('s' + i).innerHTML = "";
  }
}
div.box {
  display:inline-block;
  margin:2px;
  height:40px;
  width: 40px;
  background-color:#e0e0e0;
}

img {
  width:30px;
  height:30px;
}

Comment: hi, this is is not working.... checkForWinner function is not being run. Should checkForWinner(move) be changed to checkForWinner(turn)?
Comment: @kimi315 Yes, `checkForWinner` is being run. You can see that by the `console.log()` that I've added. Now, the problem is that you are using HTML images in the boxes, but you are still checking for the number of the cell in `getBox()`.
Comment: Yes it is being run... but why is it not alerting you won?
function switchTurn(){
  if(checkForWinner(turn)) {
    console.log('running turn');
    alert("You Won!");


Sorting a list of objects with OrderByDescending

Question: I have an object (KS), which holds ID and Title (which has a number as part of the Title).
All I'm trying to do is sort it into descending order. The object has:
ID    Title
1     1 Outlook VPN
2     2 Outlook Access
3     4 Access VBA
4     3 Excel Automation

So when order by Title, it should read:
ID    Title
3     4 Access VBA
4     3 Excel Automation
2     2 Outlook Access
1     1 Outlook VPN

The code I'm using to sort it is:
IEnumerable<KS> query = results.OrderByDescending(x => x.Title);

However, query still has the objects in the original order!
Is there something to do with having numbers at the start of Title that I'm missing?
EDIT
I've added the code from the controller for clarity:
    [HttpPost]
    // [ValidateAntiForgeryToken]
    // id is a string of words eg: "outlook access vpn"
    // I split the words and want to check the Title to see how many words appear
    // Then sort by the most words found
    public JsonResult Lookup(string id)
    {
        List<string> listOfSearch = id.Split(' ').ToList();
        var results = db.KS.Where(x => listOfSearch.Any(item => x.Title.Contains(item)));

        // search each result, and count how many of the search words in id are found
        // then add the count to the start of Title
            foreach (KS result in results)
            {
                result.KSId = 0;
                foreach (string li in listOfSearch)
                {
                    if (result.Title.ToLower().Contains(li.ToLower()))
                    {
                        result.KSId += 1;
                    }
                }
                result.Title = result.KSId.ToString() + " " + result.Title;
            }
       // sort the results based on the Title - which has number of words at the start
       IEnumerable<KS> query = results.OrderByDescending(x => x.Title).ToList();
       return Json(query, JsonRequestBehavior.AllowGet);
    }

Here is a screenshot after query has been populated showing Titles in the order: 1, 2, 1, 1:

Model for the object if it helps is:
 public class KS
{
    public int KSId { get; set; }
    public string KSSol { get; set; }
    public string Title { get; set; }
    public string Fix { get; set; }
}

Comment: Are you sure you're using `query` rather than `results`? You haven't shown what you're doing with `query` after initializing the variable.
Comment: How are you accesing query?
Comment: We need more code. Show us how you use `query`, at the very least.
Comment: Hi - I've added all of the controller code above - this is a simple FAQ type system - all I want to do is pass a string of words, count how many of those are found in Title - add the count to the start of Title and then sort and return the data - thanks.
Comment: Were you using ToList() before?
Comment: No, I wasn't - but adding it didn't seem to make any difference.
Comment: Check Jamiec answer, that new code is different from the first one you gave us. There's your problem
Comment: Hi - KSId and Title should contain the same number to start with - I've changed my code back to Title anyway, and posted a screenshot above.
Comment: It might be more useful to put a `.ToList()` in the declaration of your `results` local variable, i.e. after the `.Where(...)`. Is the type of `KS` a struct?
Comment: Hi - Ks is just a model - this is an FAQ type system - there is a solution reference, KSSol, a Title, and a Fix (which contains the steps to answer the FAQ) - thanks, Mark
Comment: I don't know how your Json object is handling the `Enumerable`. Could you try to iterate it with a simple `foreach` loop, right before the `return` statements, and see if they show up in the right order?
Comment: Hi - the screenshot I've added shows what query looks like before the 'return' statement is executed - still in the wrong order though.
Answer: Old question, but maybe this will help someone using C#. I used the following expressions to sort a list of objects based on their quantity parameter in ascending or descending order. Can modify it to compare text as the original question was concerned with.
Ascending Order:
locationMaterials.Sort((x, y) => x.Quantity.CompareTo(y.Quantity));

Descending Order:
locationMaterials.Sort((x, y) => y.Quantity.CompareTo(x.Quantity));

Answer: As I said in a comment, put a .ToList() where you declare your results variable. That is:
var results = db.KS.Where(x => listOfSearch.Any(item => x.Title.Contains(item)))
    .ToList();

If you don't do that, the foreach loop will modify objects that might not be the same as the objects you sort later, because the database query is run again each time you enumerate your IQueryable<>.
Comment: This makes no difference as far as I can see.
Comment: @Jamiec Sure, see added sentence in my answer above.
Comment: Yup, totally right. I missed the fact it was a Database call!
Comment: Thank you - that sorted it for me.  And thank you to everyone else too.
Answer: You can always just ignore the strange behavior and go the safe way:
List<KS> query = results.ToList();
query.Sort((a, b) => a.Whatever.CompareTo(b.Whatever));

return Json(query, blah);

Answer: I simple did this and it worked for me :-
var sortedOrder = Query.OrderBy(b => b.Title.Substring(b.Title.IndexOf(" ")));

All I have done is SubString the Title at the index of of the blank space when ordering the objects in the sequence, that way, the OrderBy is looking at the first character in the title rather than the number at the beginning.
Answer: You are missing .ToList()
IEnumerable<KS> query = results.OrderByDescending(x => x.Title).ToList();

results.OrderByDescending(x => x.Title) is a query, and it has no data.
ToList() forces the query to be executed.
[EDIT]
My answer assumes that your results has acually not been materialized, and that that is the source of your problem.
Comment: @FranciscoAfonso he got wrong results, to get the results he had to enumarate the query before...
Comment: @FranciscoAfonso Why would he care about the collection that `query` encapsulates? When iterating over it, it should be in descending order as expected. Also note that you can edit a comment within 5 minutes since posting it to avoid spamming.
Comment: That's because OrderByDescending only stores info about how to order, it doesnt really order until the results are enumerated.
Comment: But `query` should already have the results in the right order... the OP claims it doesn't.
Comment: @FranciscoAfonso: Well if you iterate over `query`, you should get the right results. You *don't* need to call `ToList()`. It's evaluated lazily, but that's a different matter.
Comment: When you access query you should get results ordered... you don't need to call ToList
Comment: Agree with the above. The missing `.ToList()` or `.ToArray()` is a common mistake, but it has nothing to do with this case. We need more code to understand the source of the problem.
Comment: i believe hes talking about query object itself and not an enumeration of it so it's normal that they arent ordered yet.
Comment: Where are you seeing enumeration? I dont see any enumeration or iteration or even access to query. How can you tell so certain that he's doing that properly?
Comment: @FranciscoAfonso in debug mode the query need to be evaluated or enumerated to see the results... in fact you have to click the refresh button to get the items in the object inspector


Confusions about the negation of universal quantifier.

Question: For example, in FOL if we have $\neg \forall Cube(x)$, I know that this is equivalent to $\exists xCube(x)$.
My question is, if I translate the above into English sentence then:

$\neg \forall xCube(x)$ means "It's not the case that all objects x are Cubes"
$\exists xCube(x)$ means "There exists some object x such that x is a Cube"

Although by definition the above two sentences are equivalent. However, if we create a world where there are no Cubes at all, then the sentence "It's not the case that all objects x are Cubes" sounds reasonable, because if it's not that case all objects are cubes, then we probably could assume no objects are cubes,  on the other hand, "There exists some object x such that x is a Cube" tells us that there must exist at least one object x that must be a cube.
Also, consider the following(example taken from textbook):
$\forall xCube(x) \lor \lnot \forall xCube(x) $ is a tautology. If we interpret  this statement as "Either everything is cube or it's not the case that everything is cube", I can understand why it's a tautology based on the above argument. But, if we translate the sentence to:
$\forall xCube(x) \lor \exists xCube(x) $ Then it means either everything is cube or there exists some cube(s). But if we have a world that don't have any cubes at all, then this statement is false, thus, not a tautology.
I will appreciate it very much if anyone can point out the flaws in my reasoning.
Comment: I think you're missing a negation in your first sentence in "there is an $x$ that's NOT a cube".
Comment: I don't know where you got that equivalence from, but $\neg \forall x \ Cube(x) \Leftrightarrow \exists x \ \color{red}\neg Cube(x)$
Answer: Hint:
The correct negation is:
$\neg \forall x Cube(x)$  is equivalent to $\exists x(\neg Cube(x))$.
So the two sentences:
"It's not the case that all objects x are Cubes"
"There exists some object x such that x is a Cube"
are not equivalent.


Are these two statements regarding linear orders equivalent over ZF?

Question: I know that ZF set theory can't prove that every set can be linearly ordered. Now, consider the statement: "For every nonempty set $S$ and every element $s$ of $S$, $S$ can be linearly ordered with $s$ as the top element of that linear order". Is that statement equivalent, over ZF, to the statement that every set can be linearly ordered?
Answer: If you have a linear order $<$ on a set $S$ and if $s \in S$, you can perturb $<$ to make $s$ the top element. So the two statements are equivalent.


Word add-in, custom layout

Question: Is it possible to create a custom layout, existing ones are:

Print layout
Full Screen reading
Web layout
Outline
Draft

These can be found in the View Ribbon under the group Document Views.
My aim is to get my own layout button in either the existing View Ribbon (if it is possible to modify it) or add a new layout to my custom Ribbon.
Thanks in advance!
Comment: The answer is twofold: you could add button to Ribbon and associate some macro to it which will result with your 'private' settings of view. However, as a next step there could be some limitations of view settings- possibly you could not have your view up-side-down and others. But within common sense it's possible. Moreover, you could quite easily adjust behaviour of existing view-type-button and associate changes with some documents.
Comment: How do I go about changing the behaviour of existing view-type-buttons? I cannot find the code for it. Thanks
Comment: which word app version you are running?
Comment: I'm using Word 2010 add-in
Answer: This answer is going to provide information on how to change standard settings of any view type control and associate these changes with certain document. This will not work with all documents and will not change the control action for whole Word Application but for one document. Operation could be repeated for few document and almost all Word button.
Important! I'm not using English version of Office application therefore some description will not match exactly to what you have. Tried and tested for Word 2010.
There are following steps to go:

Open new document- one where control should work according to your private expectations.
Go to View >> Macros >> Show list of macros
In the combo-box below middle of the Macro window choose something like Word application commands (or Word macros or similar). As a result you get list of lots of macros names.
You need to guess which of the macro is associated with ribbon control you are going to change. Use common sense and logic to find it. Sometimes two or three seems to match and possibly you will need to make a try.
A) let's try to change behaviour of draft/pending/working view ribbon control. one rounded red below:

B) find macro ViewNormal (but not ViewDraft)
C) select this macro on the list
Change back on the combo-box list to your document (while keeping your chosen macro selected)
Press Create button on the right in the macro window. You will be moved to VBA Editor to the following code:
Sub ViewNormal()
'
' ViewNormal Makro
' Zmienia widok edycji na normalny
'
    If ActiveWindow.View.SplitSpecial = wdPaneNone Then
        ActiveWindow.ActivePane.View.Type = wdNormalView
    Else
        ActiveWindow.View.Type = wdNormalView
    End If

End Sub

This code is responsible for working of chosen ribbon control.
First, let's check if we can take control of ribbon button- add MsgBox "Control taken" at the end of the code, before End sub. Back to Word App and press button on the ribbon which result should be- setting of chosen view and our message box.
Now you need to change your code accordingly to set your view as you need. Use VBA for that.
Save document as .Docm and all the changes will be applied to the document each time you press chosen ribbon button.

Word add-in, custom layout


How Can I do a group by with the result of a case expression

Question: When I try to do a group by, using the result of a CASE expression named as Ticket, TOAD fails saying that Ticket it is not a valid item
SELECT
CASE WHEN ( amt_1 >= 10000000                             ) THEN  'R100000'
     WHEN ( amt_1 <   9000000 and amt_1 >=  8000000       ) THEN  'R090000'
     WHEN ( amt_1 <   8000000 and amt_1 >=  7000000       ) THEN  'R080000'
     WHEN ( amt_1 <   7000000 and amt_1 >=  6000000       ) THEN  'R070000'
     WHEN ( amt_1 <   6000000 and amt_1 >=  5000000       ) THEN  'R060000'
     WHEN ( amt_1 <   5000000 and amt_1 >=  4000000       ) THEN  'R050000'
     WHEN ( amt_1 <   4000000 and amt_1 >=  3000000       ) THEN  'R040000'
     WHEN ( amt_1 <   3000000 and amt_1 >=  2000000       ) THEN  'R030000'
     WHEN ( amt_1 <   2000000 and amt_1 >=  1000000       ) THEN  'R020000'
     WHEN ( amt_1 <   1000000 and amt_1 >=  500000        ) THEN  'R010000'
     WHEN ( amt_1 <    500000 and amt_1 >=  100000        ) THEN  'R005000'
     WHEN ( amt_1 <    100000                             ) THEN  'R001000'
END  as Ticket,
CAST ( SUM(AMT_1/100) AS DECIMAL(10,2) )
Count(*)
FROM BASE24.PTLF
GROUP BY  Ticket

Answer: In Oracle SQL (and in the SQL Standard - although apparently not in all SQL dialects), you can't group by a column name (alias) that is only defined in the SELECT clause. The name Ticket is only assigned to your expression when the SELECT clause is executed, and that is after GROUP BY is processed - despite what the order of the clauses in the syntax may suggest.
The simplest solution is to write a subquery where you define Ticket as that case expression, then select from the subquery and use the GROUP BY clause as you have it.
Uglier: you can copy the entire case expression from the SELECT clause and paste it in the GROUP BY clause (replacing the column name with this entire expression). You may think this uglier query will be more efficient, because it doesn't require a subquery and an outer query; but that is not the case. The optimizer will eliminate the subquery from the "good looking" query (with a subquery) and it will rewrite the query as the "ugly" one all on its own, without your help.
Best: The standard should (but DOES NOT) allow you / us to write the case expression in the GROUP BY clause and give it an alias there, and then let us use the alias in the SELECT clause. Alas that is not in the standard, nor implemented in any dialect I know of, although logically there should be no problem with it: we are allowed to "create column names" in a lot of other places, like in pivot operations, in match_recognize, in the model clause, etc. Why not in group by - only the standard writers know.
Answer: Use a common table expression:
WITH cteTicket_data
  AS (SELECT CASE
               WHEN ( amt_1 >= 10000000                      ) THEN 'R100000'
               WHEN ( amt_1 <   9000000 and amt_1 >=  8000000) THEN 'R090000'
               WHEN ( amt_1 <   8000000 and amt_1 >=  7000000) THEN 'R080000'
               WHEN ( amt_1 <   7000000 and amt_1 >=  6000000) THEN 'R070000'
               WHEN ( amt_1 <   6000000 and amt_1 >=  5000000) THEN 'R060000'
               WHEN ( amt_1 <   5000000 and amt_1 >=  4000000) THEN 'R050000'
               WHEN ( amt_1 <   4000000 and amt_1 >=  3000000) THEN 'R040000'
               WHEN ( amt_1 <   3000000 and amt_1 >=  2000000) THEN 'R030000'
               WHEN ( amt_1 <   2000000 and amt_1 >=  1000000) THEN 'R020000'
               WHEN ( amt_1 <   1000000 and amt_1 >=   500000) THEN 'R010000'
               WHEN ( amt_1 <    500000 and amt_1 >=   100000) THEN 'R005000'
               WHEN ( amt_1 <    100000                      ) THEN 'R001000'
             END as Ticket,
             CAST(AMT_1/100 AS DECIMAL(10,2) AS AMT
        FROM BASE24.PTLF)
SELECT TICKET,
       SUM(AMT),
       Count(*) AS TICKET_AMT_COUNT
  FROM cteTicket_data
  GROUP BY Ticket

Answer: You cannot use an alias defined in a SELECT clause of a query in the WHERE, GROUP BY or HAVING clauses at the same level as the SELECT clause is evaluated after those other clauses.
Use a sub-query to define the alias first and then use the alias in the outer query:
SELECT ticket,
       SUM(amt/100),
       COUNT(*)
FROM   (
  SELECT CASE
         WHEN amt_1 >= 10000000 THEN  'R100000'
         WHEN amt_1 >=  9000000 THEN  NULL
         WHEN amt_1 >=  8000000 THEN  'R090000'
         WHEN amt_1 >=  7000000 THEN  'R080000'
         WHEN amt_1 >=  6000000 THEN  'R070000'
         WHEN amt_1 >=  5000000 THEN  'R060000'
         WHEN amt_1 >=  4000000 THEN  'R050000'
         WHEN amt_1 >=  3000000 THEN  'R040000'
         WHEN amt_1 >=  2000000 THEN  'R030000'
         WHEN amt_1 >=  1000000 THEN  'R020000'
         WHEN amt_1 >=   500000 THEN  'R010000'
         WHEN amt_1 >=   100000 THEN  'R005000'
         WHEN amt_1 <    100000 THEN  'R001000'
         END  as Ticket,
         amt
  FROM   BASE24.PTLF
)
GROUP BY  Ticket;

Or, repeat the CASE expression so you don't refer to the alias:
SELECT CASE
       WHEN amt_1 >= 10000000 THEN  'R100000'
       WHEN amt_1 >=  9000000 THEN  NULL
       WHEN amt_1 >=  8000000 THEN  'R090000'
       WHEN amt_1 >=  7000000 THEN  'R080000'
       WHEN amt_1 >=  6000000 THEN  'R070000'
       WHEN amt_1 >=  5000000 THEN  'R060000'
       WHEN amt_1 >=  4000000 THEN  'R050000'
       WHEN amt_1 >=  3000000 THEN  'R040000'
       WHEN amt_1 >=  2000000 THEN  'R030000'
       WHEN amt_1 >=  1000000 THEN  'R020000'
       WHEN amt_1 >=   500000 THEN  'R010000'
       WHEN amt_1 >=   100000 THEN  'R005000'
       WHEN amt_1 <    100000 THEN  'R001000'
       END as Ticket,
       SUM(amt/100),
       COUNT(*)
FROM   BASE24.PTLF
)
GROUP BY
       CASE
       WHEN amt_1 >= 10000000 THEN  'R100000'
       WHEN amt_1 >=  9000000 THEN  NULL
       WHEN amt_1 >=  8000000 THEN  'R090000'
       WHEN amt_1 >=  7000000 THEN  'R080000'
       WHEN amt_1 >=  6000000 THEN  'R070000'
       WHEN amt_1 >=  5000000 THEN  'R060000'
       WHEN amt_1 >=  4000000 THEN  'R050000'
       WHEN amt_1 >=  3000000 THEN  'R040000'
       WHEN amt_1 >=  2000000 THEN  'R030000'
       WHEN amt_1 >=  1000000 THEN  'R020000'
       WHEN amt_1 >=   500000 THEN  'R010000'
       WHEN amt_1 >=   100000 THEN  'R005000'
       WHEN amt_1 <    100000 THEN  'R001000'
       END;


The Typewriter Sequence

Question: The typewriter sequence is an example of a sequence which converges to zero in measure but does not converge to zero a.e.
Could someone explain why it does not converge to zero a.e.?

$f_n(x) = \mathbb 1_{\left[\frac{n-2^k}{2^k}, \frac{n-2^k+1}{2^k}\right]} \text{, where } 2^k \leqslant n < 2^{k+1}.$

Note: the typewriter sequence (Example 7).
Answer: I drew the first 63 functions in the sequence to help me understand its convergences. It might help others as well to understand answers given above:

Unfortunately, here I can only attach the rasterized format. In case someone wants to reproduce it, here is the Latex code:
<code>\documentclass[9pt]{standalone}

\usepackage{bbm}
\usepackage{amsmath}
\usepackage{tikz,pgfplots}
\usetikzlibrary{arrows}

\newcommand{\nMAX}{63}
\newcommand{\xGrSamp}{8}

\begin{document}
\centering
\begin{tikzpicture}[font=\Large,shorten >=-2.5pt,shorten <=-2.5pt]
\begin{axis}[
    axis x line*=bottom,
    axis y line*=right,
    axis z line*=left,
    plot box ratio = 3 1000 2,
    view={.3}{.2},
    xmin=-0.2,    xmax=1.25,
    ymin=0.6,    ymax=\nMAX+0.3,
    zmin=0,    zmax=1.0,
    xtick={0,1/8,2/8,3/8,4/8,5/8,6/8,7/8,1},
    xticklabels={$0$,$\frac{1}{2^3}$,$\frac{2}{2^3}$,$\frac{3}{2^3}$,$\frac{4}{2^3}$,$\frac{5}{2^3}$,$\frac{6}{2^3}$,$\frac{7}{2^3}$,$1$},
    ytick={0,...,\nMAX},
    ztick={0,...,1.0},
    xlabel=$x$,
    ylabel=$n$,
    zlabel=$f_n(x)$,
    x label style={at={(axis description cs:0.067,-0.001)},anchor=north},
    y label style={at={(axis description cs:0.062,0.145)},anchor=south},
    z label style={at={(axis description cs:-0.002,0.035)},anchor=south},
    yscale=5,
    xscale=5,
    legend entries={$f_n(x)=1\,$,
                    $f_n(x)=0\,$},
    legend style={rounded corners=3pt,at={(0.023,0.14)}},
    legend style={nodes={scale=1.5, transform shape}},
    legend plot pos=right,
]
\foreach \n in {1, ..., \nMAX}
{
    \pgfmathsetmacro\k{floor(log2(\n+1e-1))}
    \pgfmathsetmacro{\xm}{-0.2}
    \pgfmathsetmacro\xM{1.2}
    \pgfmathsetmacro\xa{(\n-(2^(\k)))/(2^(\k))}
    \pgfmathsetmacro\xb{(\n-(2^(\k))+1)/(2^(\k))}
    \edef\temp
    {
        \noexpand\coordinate (d1) at (axis cs:\xm,\n,0);
        \noexpand\coordinate (d2) at (axis cs:\xa,\n,0);
        \noexpand\coordinate (d3) at (axis cs:\xa,\n,1);
        \noexpand\coordinate (d4) at (axis cs:\xb,\n,1);
        \noexpand\coordinate (d5) at (axis cs:\xb,\n,0);
        \noexpand\coordinate (d6) at (axis cs:\xM,\n,0);
        \noexpand\coordinate (g0) at (axis cs:\xm,\n,1);
        \noexpand\coordinate (g1) at (axis cs:\xM,\n,1);
    }
    \temp
    \draw[blue,<-o] (d1)--(d2);
    \draw[black,dashed,line width=0.04mm] (d2)--(d3);
    \draw[red,*-*]   (d3)--(d4);
    \draw[black,dashed,line width=0.04mm] (d4)--(d5);
    \draw[blue,o->] (d5)--(d6);
    \draw[black,dashed,line width=0.04mm] (g0)--(g1);
}
\pgfplotsinvokeforeach{0, ..., \xGrSamp}
{
    \draw[black,dashed,line width=0.06mm] (axis cs:#1/\xGrSamp,0,0)--(axis cs:#1/\xGrSamp,\nMAX,0);
}
\addlegendimage{no markers,red}
\addlegendimage{no markers,blue}
\end{axis}
 \node[rectangle,draw,rounded corners=3pt,text width=7.7cm] at (29.3,1.7)
 {\huge Typewriter Sequence: \\$f_n(x)={\mathbbm{1}}_{[\frac{n-2^k}{2^k},\frac{n-2^k+1}{2^k}]},$\\
    $\forall\, k\geq 0\,\, \&\,\, 2^k\leq n<2^{k+1} $};
\end{tikzpicture}

\end{document}
</code>
Answer: Animated visual demonstration

As the sequence progresses, the indicator functions move from left to right over $[0,1]$ and then half in width, when they reach the end, and then repeat this ad infinitem. But then, each left-to-right run of a particular width must, at some point, have a value of $1$ for every $x$ in the interval. Therefore, throughout the infinitely many left-to-right runs, every $x$ attains a value of $1$ infinitely many times. But since $x$ is usually $0$, it must have no pointwise limit.
On the other hand, the width of the interval over which each function is $1$ decreases to $0$, and the functions are eventually infinitesimally thin spikes. So their 'size' (both in terms of $L^1$ norm and measure) converges to zero.
This also explains the origin of the sequence's name, as it looks like the a typewriter's carriage return jumping it back to where it started.

I wrote the sequence in Desmos by using  $\frac{\operatorname{sign}\left(x-c\right)+1}{2}=\textbf{1}_{(c,\infty)}$, except at $x=c$, where it is $0.5$, and $1-\operatorname{sign}(x-c)^2=\begin{cases}1,&x=c\\0,&\text{else}\end{cases}$. This gives an expression for the functions in terms of the $\operatorname{sign}(\cdot)$ function, which can be interpreted by the program and can be simplified into the form in the animation above. A link to the project is available here.
Comment: Great animation! I will link to this page every time I mention the "typewriter sequence" again.
Comment: amazing work and comment thank @Jam !
Comment: @Jam Incredible work ! Thank a lot for your very clear answer.
Answer: Note that at any choice of $x$ and for any integer $N$, there is an $n>N$ with $f_n(x)=1$. So, the numerical sequence $f_n(x)$ cannot converge to $0$.
Note, however, that we can certainly select a subsequence of this sequence of functions that converges pointwise a.e.
Comment: What I show is that it does not converge to zero *anywhere* (at any particular point).  Certainly, then, it fails to "converge to $0$ a.e." (at almost every point).
Comment: So $f_n(x)$  converges to 0, except for uncountable set? Does this set have measure > zero? or it is not measurable?
Comment: @MATH I don't understand your question.  For any $c \in [0,1]$, $f_n(c)$ is a non-convergent sequence over $n$.  Does that make more sense?
Comment: I mean it is asked to prove that it does not converge to zero a.e. but what you show is that it does not converge to zero?
Answer: Draw a picture of the generic function $f_n$ in the typewriter sequence. It's a rectangle of height 1 over an interval of width $1/2^k$, with value zero elsewhere. As the sequence progresses, the rectangles slide across the unit interval, the way a typewriter moves across the page. At each 'carriage return' of the typewriter, a new row of rectangles starts, each rectangle having half the width as before. You can see that for every point $x$ in the unit interval, the sequence $f_n(x)$ takes values zero and one infinitely often, so $f_n(x)$ cannot converge to any number.
Answer: I wrote this sequence of functions as a counterexample for a question that was deleted.
$$
f_n(x)=\left[\frac km\le x\lt\frac{k+1}m\right]
$$
where $[\dots]$ are Iverson brackets, $m=\left\lfloor\frac{1+\sqrt{1+8n}}2\right\rfloor$ and $k=n-\frac{m(m-1)}2$.
The Typewriter Sequence is a subsequence of this sequence (when $m$ is a power of $2$). Like the Typewriter Sequence, this sequence does not tend to $0$ pointwise, but its $L^1$ norms vanish.
Answer: The set on which ${f_n}$ fails to converge to $0$ is exactly $[0, 1]$, which has full measure $1$. To see this, note that the interval $[0, 1]$ is repeatedly overwritten by indicator functions of intervals with decreasing length($1/2$, $1/4$, ... and so on). Since any point in $[0, 1] $is covered infinitely many times by such intervals, they oscillate between $0$ and $1$ infinitely often as $n \to \infty$.
The "overwriting" nature is what prevent the sequence from converging a.e, while the sequence ${{f_n := n 1_{[\frac{1}{n}, \frac{2}{n}]}}}$ does converge to $0$ a.e.(actually it converges almost uniformly.)

The Typewriter Sequence


What criteria does each batter in baseball's batting order have?

Question: I've heard analyst say that a player has been under performing as a batter in the heart of the order many times, or that a bottom of the line up batter has been doing well for its position as of recent.
This makes me believe that each batter in the line up has a specific role. Or at least there are certain league-wide expectations for each position. From what I have noticed, it seems that the heavy hitters are usually in the middle of the order. Also it's obvious that the lead off batter should have high on base percentage (OBP) to increase chances of scoring more runs.
Having said all of that, what are the general characteristics of each batter in the line up?
Comment: It can depend on who you ask.  Some teams are starting to go with a more "sabermetric" form of setting their lineup, and some teams stay with the "old" way.
Answer: Traditional
1 - High OBP/Speed

This guy should have a high chance of getting on base.  You want to get your guys on base so the later hitters have a chance to drive in runs.

2 - Contact/Bunt

This guy should have good contact numbers, or be able to bunt.  The point of this guy is to get your leadoff hitter into scoring position (2nd and 3rd base), whether it be by bunting him over or getting a base hit.

3 - All Around

This guy should posses power, or at least high contact rate.  This person should be the guy who gets your leadoff guy home.  Generally has some power, maybe 20-25 home run potential.

4 - Power

This guy is usually your big hitter.  They call this the "cleanup" hitter.  In a sense so he can "clean up" the bases.

5 - Power/OBP

This guy is generally your next biggest hitter, more power than the normal guys, set to protect the clean up hitter in the order.  He should also posses some kind of OBP as to get on base, kind of start the order over.

6 - RBI Guy

This guy, as with the 5th hitter, is there to protect the guys in front of him, and drive in runs.

7/8/9 - Fielders

In the AL, where you have the DH, these guys would be the guys who aren't really great at hitting, they're mostly in the lineup for their defensive prowess.  They can be good hitters, guys to get on base, or have some power, but generally teams keep their lesser hitters in the bottom.  In the NL, the 9th slot is generally used for the pitcher.

Sabermetrics
1 - High OBP

This guy needs to have high OBP, speed or not.  This guy is simply meant to get on base so there will be someone to drive in.

2 - Contact

One of your best hitters, usually high contact, and high OBP.  This guy is meant to drive in runs.  No more sacrificing, this guys intent is to score runs and limit outs.

3 - 5th Best Hitter

This guy would bat 5th in the traditional lineup, has some power, some contact, ability to drive in runs, and ability to help protect the #4.

4 - Power

This is your power hitter, as in the traditional lineup, you want this guy cleaning up the bases.  You want this guy to hit your home runs, and score.

5 - 4th Best

This is your cleanup guy in the traditional lineup.  This is the guy who also has power, also has the ability to drive in runs.

6/7 - 6th and 7th Best Hitters

These are the guys, as with the traditional lineup, who are usually only in the lineup for their defensive prowess.

8/9 - NL (Pitcher and 8th Best Hitter), AL (8th and 9th Best Hitter)

In the NL, with the new sabermetric lineup, the 8 slot is generally the pitcher and the 9 slot is for your worst hitter.  Basically hoping they get on base for the leadoff guy to start driving in runs again.

Basically the advantage to this lineup is to stop trading outs for runs.  This lineup is to maximize runs, and stop the thinking of "small ball", meaning bunting, getting base hits, etc.  This is usually called the "optimized" lineup.
Note:  This isn't meant to be a one size fits all lineup explanation.  Each team has their own idea as to what makes things work for them.  This is meant to simply be a general overview of how lineups are used in baseball.  Some teams may make slight changes to this theory.
Comment: Sabermetrics moved the best hitter into top 3 because those batters get many more ABs a year than the 4th thru 6th batters.  You want to maximize your best hitters plate appearances.
Comment: In the NL 8th spot is not always the pitcher, in fact pitchers are mostly 9th
slot. 8th slot pitcher is a strategy seen by very few managers. Other than that the answer is great. Fix that and I'll accept the answer.
Comment: This isn't meant to be a set ideology for every team.  8th slot pitcher is how it is done(a lot of the time) with the new sabermetric lineup.  Traditional lineup, the pitcher will bat 9th.  Every team has their own way of doing things, and not every single team will do it the same, but this is a general overview of each traditional and sabermetric lineups.
Comment: I see what you mean now, makes sense


Snippet to hide the editing of one vocab

Question: I need a snippet that hides/omits the editing of a certain vocab on the node/edit form of a certain content type if they are not in a certain role.  All the access modules are too heavy for just this small requirement.
Answer: You will need to create a custom module with:
Drupal 6:
<code>/**
 * implements hook_form_alter()
 */
MYMODULE_form_alter($form, $form_state, $form_id) {
  if ($form_id == 'type_node_form') {

    global $user;

    // Check to see if $user has does not have the administrator role.
    if (!in_array('administrator', array_values($user->roles))) {
      //to turn all vocabularies off
      $form['taxonomy']['#access'] = FALSE;

      //turn off a single vocabulary *BELOW*
      //if you select 'tags' from your vocabulary settings
      if(issset($form['taxonomy']['tags']) {
        $form['taxonomy']['tags']['vid'] = FALSE;
      }
      else {
        //if you do not selet 'tags' from your vocabulary settings
        $form['taxonomy']['vid'] = FALSE;
      }
    }
  }
}
</code>
So there is 3 options, depending how your vocabularies are setup.  You must subsitute 'vid' for the vocabulary id.
Drupal 7:
inside hook_form_alter() like
<code>if ($form_id == 'type_node_form') {

  global $user;

  // Check to see if $user has does not have the administrator role.
  if (!in_array('administrator', array_values($user->roles))) {
    $form['name_of_field']['#access'] = FALSE;
  }
}
</code>
Answer: drupal 6
in hook__form_alter if role and content-type i set
$form['taxonomy']['vid']['#access'] = FALSE;
this seems to hide without removing and validates.


BottomSheetDialogFragment behaviour disorder when added nested fragment in Android

Question: I've a BottomSheetDialogFragment inside a RecyclerView, when is clicked a button BottomSheet is showing. BottomSheetDialog expanding when scrolling down and collapsing when scroll finished on top normally.

But when I place the RecyclerView inside a fragment and lay the fragment to BottomSheetDialog; BottomSheet behaviours not working on the fragment, only works RecyclerView scrolling. On the other hand the behaviours work other places on BottomSheet. How to enable the behaviours as in the first?
Answer: You should check that your container layout has app:layout_behavior="@string/bottom_sheet_behavior"> and check that any listener/event you define extra, otherwise BottomSheetDialog normally behaive as you expect.
Comment: I've enabled nested scroll on recyclerview and solved, thanks.


Integration Testing In Visual Studio With Different Project Types

Question: We are in the middle of developing a new CRM, and it uses both WPF for local users, and a Windows Universal App (Store App) for the users in the field.  The basic flow is this

Customer calls in and gets scheduled on a field user in WPF app.
Field user goes on service call and updates on Surface through Universal App.
Customer gets billed from the WPF App.

All the modules are in place and working, but I do not seem to be able to integration test the entire project flow due to the different Project Types.
What I need to be able to do is add a reference to my Universal App in the unit test for my WPF app (or the other way around), so I can test the flow through both components.
I have been searching for a solution over the last few weeks, and have not been able to come up with any way to do this. If this is not directly possible (which I am guessing it is not), is there any way I can setup a test playlist so that the integration tests run in a particular order.
I am looking to avoid hard coding sample data into the db in order to test the Universal app, as this would not show the true flow of data from one app to another and back again.  Any help is appreciated.
UPDATE 8-21-2015:
We realize because of the Framework difference the best solution is going to be to run some type of ordered test.  We are using MSTest.  The problem with this is that Ordered Tests in Visual Studios are not solution wide, they are only allowed in a unit test project, which means it will be using the References from that project, and not allow both tests.
We don't care if we have to switch to a different testing framework, as having the proper tests is more important than using a specific framework.
Answer: You should use a Portable Class Library (PCL).  You can create a PCL in Visual Studio from the add new project screen.
When creating your PCL it will ask you what type of projects you want to target.  Since you stated WPF and Windows Store app you would .Net 4.5(or whatever version you are on) and WIndows 8.1 (or 8.0)
The PCL will allow you to write code in the Run Time with the lowest level of language features for the targeted projects.  In your case this would be the Window's Store app.
Now, instead of storing your logic inside your Window's store project, you will need to move your logic into the PCL.
Once you have compiled your PCL, you will need to add references to the Window's Store app so that you can use the logic within you Windows Store App (you will have to add the namespace for the PCL to make this work).  You will also add a reference to the PCL in your unit test project.  Because you targeted both Run times in your PCL, you will be able to call the code from your integration tests.
Since all your Logic is in the PCL, you should be able to test everything.  The only thing in your Window's Store app now should be the view specific data.
If you ever need to change the targets for your PCL (lets say want it to work with Windows Phone), you can edit the properties of the PCL project, and change the targets.  Be warned that if you add a target with a more constricted run time than one you currently selected, you will have to refactor your code to use only functions available in the lowest functional run time.


Tomcat not shutting down in Red Hat 5.5

Question: I'm running a Tomcat 6 server on a Red Hat 5.5 machine that I don't have root access for, although I do own all of the Tomcat files.  The server starts up fine when I run startup.sh, but for some reason shutdown.sh doesn't take down the server.  Do I need to be root to kill my server, or is there something else I'm missing?
Answer: Yes, you want to be root. You also want to see whats going on in catalina.out - the answer to your problem most likely is in that log file.
Comment: root or the same user than the one that is running tomcat...
Comment: Yep, a giant list of exceptions caused by lack of permissions.  I talked to the root user, and it's fixed.  Thanks though, guys.
Answer: This might help.

Tomcat not shutting down in Red Hat 5.5


Dúvidas para desenvolvimento de app com swift

Question: Estou trabalhando com um app para iOS e estou usando Swift. O meu cliente que é dono de um restaurante gostaria de usar um painel administrativo para adicionar novos pratos ao app.
Gostaria de saber se há um painel na net que já faça algo assim ou se terei de criá-lo. Se for criá-lo, qual linguagem usar que dê para depois integrar com o app iOS?
Answer:
Se for criá-lo, qual linguagem usar que dê para depois integrar com o
  app iOS?

Você precisa ter um fluxo de informações definido para o seu aplicativo mobile e para sua aplicação WEB.
Normalmente, é necessário um webservice responsável por encapsular sua regra de negócio e realizar as operações necessárias para o seu sistema. O aplicativo iOS e a aplicação web devem consumir os serviços deste webservice.
A linguagem de programação utilizada no aplicativo iOS, na página WEB e no webservice são independentes e não se relacionam. Você pode, por exemplo, criar um aplicativo iOS em SWIFT, um webservice em C# e uma aplicação web com angular js.

Gostaria de saber se há um painel na net que já faça algo assim ou se
  terei de criá-lo.

Você pode utilizar templates do bootstrap para a parte visual, existem muitos que simulam um painel administrativo, mas desconheço um aplicativo já implementado com as configurações necessárias para integrar com seu webservice. Neste caso, seria necessário realizar as operações de chamada ao webservice e tratar seu retorno na aplicação web.


"Page not found" on custom module

Question: I did a custom module, but i can't see the page with the URL : Page not found.
I can install the module and activiate, but i can't go on the page.
This is the code :
hello_world.hello_world:
  path: '/helloworld'
  defaults:
    _controller: 'Drupal\hello_world\Controller\HelloWorldController::helloWorld'
    _title: 'Hello World'
  requirements:
    _permission: 'access content'

name: Hello World
core: 8.x
type: module
package: Tutos
description: Mini module test Drupal 8

<?php
/**
 * @file
* Contains \Drupal\hello_world\Controller\HelloWorldController.
*/

namespace Drupal\hello_world\Controller;
use Drupal\Core\Controller\ControllerBase;

/**
 * Controller routines for hello_world module routes.
 */
class HelloWorldController extends ControllerBase {

  /**
   * Return the 'Hello World' page.
   *
   * @return string
   *   A render array containing our 'Hello World' page content.
   */
  public function helloWorld() {
    $output = array();

    $output['hello_world'] = array(
        '#markup' => $this->t('Hello World!'),
    );
    return $output;
  }
}

Comment: Looks all fine to me, is your controller class in the right place? You might want to share the whole folder somehow, e.g. as a github project.
Answer: You may need a leading \ for the controller definition.
Comment: Yes, according to current Drupal coding standards the line in the routing file should be `_controller: '\Drupal\hello_world\Controller\HelloWorldController::helloWorld'` HOWEVER it will work without the leading backslash - this is NOT an answer to why the code doesn't work.

"Page not found" on custom module


Remover um elemento específico com JAVASCRIPT de uma estrutura HTML

Question: Olá eu não tenho muita experiência com js e estou com um problema acredito que bobo mas que há dias tento resolver e não consigo.
Eu criei uma lista de elementos HTML com a seguinte estrutura:
HTML

Numero(s) inserido(s)

Função que adiciona os números
var listaNumeros = [];
function adicionaNumeros() {
    var i = listaNumeros.length;
    listaNumeros.push(i);
    $("#NumerosAdicionados").append("
" + i + "
");

}

Função que exclui os números
function excluiNumero(indice) {
    listaProcessos.splice(indice, 1);
}

Com esse código ele remove o elemento da lista, mas não remove do HTML, apenas quando seleciono o primeiro elemento para excluir ele exclui todos do HTML.
Comment: Possível duplicata de [Remover mais de um item de um array](http://pt.stackoverflow.com/questions/50520/remover-mais-de-um-item-de-um-array)
Comment: O que é `listaProcessos`?
Comment: @Randrade, o problema apresentado pela AP está relacionado a modificação dinâmica no HTML, e ela já consegue excluir o item array. Acho que essa questão, apesar de ser bem parecida, não menciona isso, mas posso estar errado.
Comment: @SamirBraga Se a dúvida do AP for essa mesmo, você tem razão. Eu havia entendido que era algo em relação ao `.splice()`.
Comment: A minha dúvida não era com relação ao splice não, era como exibir mesmo o html depois do item exluído.
Comment: E queres atribuir novos numeros ou pode ficar 1,2,5,6 no caso de teres excluído o 3 e 4?
Answer: Se listaProcessos for o mesmo que listaNumeros, você pode fazer assim:
Criei uma função renderList() que recria a lista baseada no array listaNumeros e em seus valores.
function renderList(){
    // Deixa dentro da ul só que tinha antes
    $("#NumerosAdicionados").html('
Numero(s) inserido(s)
');
    var html = ""; // var que receberá o html completo das li
    listaNumeros.forEach(function(el, i){
        // a cada item do array adicionar um novo li
        html += "
" + el + "
";
    })
    // faz apenas um append (melhor para o desempenho)
    $("#NumerosAdicionados").append(html);
}

Basta adicioná-la a função de excluir:
function excluiNumero(indice) {
    listaNumeros.splice(indice, 1);
    renderList();
}

Você vai ter um pouco de problemas ao adicionar número na sequência, já que sua função se baseia na quantidade de elementos e essa quantidade será mudada ao excluir. O que você pode fazer é somar ao último elemento, mas imagino que isso seja apenas um exemplo.
Resultado:

var listaNumeros = [];
function adicionaNumeros() {
    var i = listaNumeros.length == 0 ? listaNumeros.length : +listaNumeros[listaNumeros.length-1]+1;
    listaNumeros.push(i);
    $("#NumerosAdicionados").append("
" + i + "
");
}
$('.inserir').click(adicionaNumeros)

function excluiNumero(indice) {
    listaNumeros.splice(indice, 1);
   renderList();
}
function renderList(){
 $("#NumerosAdicionados").html('
Numero(s) inserido(s)
');
 var html = "";
 listaNumeros.forEach(function(el, i){
  html += "
" + el + "
";
 })
  $("#NumerosAdicionados").append(html);
}
$('.excluir').click(function(){
 excluiNumero(1);
})

Numero(s) inserido(s)

<button class="inserir">Inserir</button>

<button class="excluir">Excluir o 2°</button>
Comment: Muito obrigada, Samir Braga!!! Era exatamente isso que eu precisava mas não sabia como fazer.


Suggest a model from ACF and PACF values

Question: Considera sample of 50 observations from a stationary process with
$$\begin{array}{c|c|c|}
 \text{lag} & \text{acf} & \text{pacf}  \\ \hline
1 & 0.9 & 0.9 \\ \hline
2& 0.85 & 0.4\\ \hline
3&0.7&0.1\\ \hline
\end{array}$$
How do I suggest an appropriate model using the above information.
From my understanding, significance of ACF and PACF values were checked using:$ H_{0}: \rho=0$  rejected at 5% level of significance if $|\rho| >\frac{1.96}{\sqrt(50)}$. I found that only the last value of pacf is non significant.
(1)Can I say that the model is ARMA(2,3)?
(2) how to decide if it is AR, MA or ARMA?
NB: this was a question asked in an examination. To be worked out manually.
Answer: THE BIG PRINT:
Since the ACF is dominant i.e.has the most significant values the process is  autoregressive (AR) . The order of the AR model is determined by the # of significant values in the subordinate structure ... in this case the PACF .. thus 2.
The answer is (2,0,0)
THE LITTLE PRINT:
When does this simple strategy work ...
1) When there are no step/level shifts in the data
2) When there are no deterministic trends in the data
3) When there are no pulses in the data
4) When there are no seasonal pulses in the data
5) when the suggested model has constant parameters and constant error variance over time
Comment: Thank you. So if pacf had more number of significant values, would it be an MA process? When can one conclude that a process is ARMA?
Comment: Yes ... if PACF has more significant values than the ACF it would be an MA process of some order Q (GIVEN that you are not including possible seasonal structure) . An ARMA structure could be initially identified if there was no clear cut dominant structure i.e. a tie . More correctLy after estimating an AR MODEL the model residuals might suggest the need to add MA structure. Model identification is an iterative process NOT just a 1 step process.


Approximating the distribution of the product of iid beta variates

Question: Background
I am interested in the distribution of
$$\theta_0=1-\prod_{i=1}^n(1-\theta_i)$$
where the $\theta_{i>0}$ are iid beta random variates:
$$\theta_{i>0}\sim\text{Beta}(\alpha,\beta)$$
In my case $\beta\gg1\gg\alpha$ and $n\gg1$, so I used the following transformation:
$$\phi_i=-\ln(1-\theta_i)\\\theta_i=1-e^{-\phi_i}\\d\theta_i=e^{-\phi_i}\\p(\phi_i)\propto(1-e^{-\phi_{i}})^{\alpha-1}e^{-\phi_{i}\beta}\qquad\text{(1)}$$
With $\beta\gg\alpha$, $\theta_i$ and $\phi_i$ tend to be very small, so
$$1-e^{-\phi_i}\approx\phi_i$$
Substituting into (1) gives:
$$p(\phi_i)\hspace{1mm}\dot\propto\hspace{1mm}\phi_i^{\alpha-1}e^{-\phi_i\beta}$$
Or
$$\phi_i\hspace{1mm}\dot\sim\hspace{1mm}\text{Gamma}(\alpha,\beta)$$
Define $\phi_0$:
$$\phi_0\equiv\sum_{i=1}^n\phi_i$$
Using the properties of the gamma distribution:
$$\phi_0\hspace{1mm}\dot\sim\hspace{1mm}\text{Gamma}(n\alpha,\beta)$$
Finally,
$$\theta_0=1-e^{-\phi_0}$$
(I can further improve the approximation through moment matching to get slightly different values of $\alpha$ and $\beta$ to use in the gamma distribution, but this doesn't affect the question below.)
Question
What would be a good way to quantifiably demonstrate how well the above approximation works for varying values of $\alpha$, $\beta$, and $n$?
For a single set of values, I can use simulation, e.g.,
set.seed(214462480)
alpha <- 2e-3
beta <- 1001
n <- 1e3
theta0.sim1 <- -expm1(replicate(1e5, sum(log1p(-rbeta(n, alpha, beta)))))
theta0.sim2 <- -expm1(-rgamma(1e5, n*alpha, beta))
ks.test(theta0.sim1, theta0.sim2)$p.value
#> [1] 0.5396774

And the ecdf lines are right on top of each other.
However, simulation in this manner is slow and defeats the purpose of the approximation. $\alpha$ and $\beta$ are sampled from a joint posterior, so I require a large number of samples of $\theta_0$, each with varying $\alpha$ and $\beta$ parameters. Furthermore, this will be applied to a number of problems, so $n$ and the distributions of $\alpha$ and $\beta$ can also vary.
Comment: If you want to use a gamma distribution as an approximation, then note that $1-\theta_i\sim \text{Beta}(\beta, \alpha)$ and you can then use the method of moments to match the first two moments of a gamma distribution.
Comment: Yes, that is essentially what I do in the end, with $-\ln{(1-\theta_i)}$ being approximated as a gamma distribution. $\alpha$ and $\beta$ end up being really good initial estimates for the gamma parameters (so good that a *single* Newton-Raphson iteration does best for getting the final values using double precision).
Comment: Simulation is slow because your sample sizes are huge.  You can test the quality of the approximation with a relatively small number of replicates: often, even 50 will work fine.  Shortening the simulation makes it possible to create and inspect a large number of probability plots of your distributions so you can learn just how close they tend to be and how much they vary, as well as permitting you to explore a wide range of combinations of the parameters.
Comment: Thank you for taking the time to give me your thoughts. So far I'm getting that the best way to go about it is to manually characterize the 3-D $(\alpha,\beta,n)$ space by visually inspecting a large number of plots. If that's the case, I agree that P-P plots are probably the way to go. I was trying to come up with something that could be more easily automated and communicated to the users of the model. I'll keep thinking about it.
Answer: This is just an extended comment.  One can obtain the exact distribution (and mean and variance) of $\phi_{i>0}$ although for the values of $\alpha$ and $\beta$ you mention, the result differs little from your approximation.  (It can make a big difference for other values of $\alpha$ and $\beta$.)
Again, using Mathematica:
dist = TransformedDistribution[-Log[θ], θ \[Distributed] BetaDistribution[β, α]];

PDF[dist, ϕ]

μϕ = Mean[dist]
(* -PolyGamma[0, β] + PolyGamma[0, α + β] *)

σ2ϕ = Variance[dist]
(* PolyGamma[1, β] - PolyGamma[1, α + β] *)

sol = Solve[{μϕ == a b, σ2ϕ == a b^2}, {a, b}][[1]]

For your values of $\alpha=2/1000$ and $\beta=1001$ the values of $a$ and $b$ are
sol /. {β -> 1001, α -> 2/1000} // N
{a -> 0.002, b -> 0.000999499}

Comment: I instead equated the moments of $e^{-\dot\phi_0}$ with those of $1-\theta_0$, where $\dot\phi_0\sim\text{gamma}(a,b)$ in order to find $a$ and $b$. That way the approximating distribution matches the first two moments of the true distribution of the variable of interest ($\theta_0$).
Answer: Here is a "visual" approach (using Mathematica) to check on the gamma approximation for the distribution of $\theta_0$.
nsamples = 10000; (* Number of random samples *)
Manipulate[
 (* Random sample of θ0 values *)
 x = RandomVariate[BetaDistribution[β, α], {nsamples, n}];
 θ0 = 1 - Times @@ # & /@ x;

 (* Find gamma distribution parameters with same mean and variance *)
 (* θ0Var = E(θi^2)^n - E(θi)^(2n) *);
 θ0Var = (Variance[BetaDistribution[β, α]] + Mean[BetaDistribution[β, α]]^2 // Together)^n -
   Mean[BetaDistribution[β, α]]^(2 n);
 θ0Mean = 1 - Mean[BetaDistribution[β, α]]^n;
 {a, b} = {a0, b0} /. Solve[{θ0Mean == a0 b0, θ0Var == a0 b0^2}, {a0, b0}][[1]] // Quiet;

 (* Display histogram and approximating gamma density *)
 Show[Histogram[θ0, "FreedmanDiaconis", "PDF", PlotRange -> {{0, Automatic}, Automatic},
   Frame -> True, FrameLabel -> (Style[#, Bold, 18] &) /@ {"\!\(\*SubscriptBox[\(θ\), \(0\)]\)",  "Density"}],
  Plot[PDF[GammaDistribution[a, b], z], {z, 0, 1}, PlotRange -> All, PlotPoints -> 100]],
 {{n, 1001, Style["n", Italic, 14]}, 10, 2000, 1, Appearance -> "Labeled"},
 {{α, 1/1000, Style["α", 14]}, 1/1000, 1/10, Appearance -> "Labeled"},
 {{β, 1001, Style["β", 14]}, 50, 5000, Appearance -> "Labeled"}
 ]

Something similar could be done with a cdf.
The values of $a$ and $b$ for the approximating gamma distribution are
$$a=\frac{\left(\left(\frac{\beta }{\alpha +\beta }\right)^n-1\right)^2}{\left(\frac{\beta ^2+\beta }{(\alpha +\beta ) (\alpha +\beta +1)}\right)^n-\left(\frac{\beta }{\alpha +\beta }\right)^{2 n}}$$
$$b=\frac{\left(\frac{\beta }{\alpha +\beta }\right)^{2 n}-\left(\frac{\beta ^2+\beta }{(\alpha +\beta ) (\alpha +\beta +1)}\right)^n}{\left(\frac{\beta }{\alpha +\beta }\right)^n-1}$$
The above code can be modified to produce a P-P plot (as suggested by @whuber):
nsamples = 10000; (* Number of random samples *)
Manipulate[
 (* Random sample of θ0 values *)
 x = RandomVariate[BetaDistribution[β, α], {nsamples, n}];
 θ0 = 1 - Times @@ # & /@ x // Sort;

 (* Find gamma distribution parameters with same mean and variance *)
 (* θ0Var = E(θi^2)^n - E(θi)^(2n) *);
 θ0Var = (Variance[BetaDistribution[β, α]] + Mean[BetaDistribution[β, α]]^2 // Together)^n -
   Mean[BetaDistribution[β, α]]^(2 n);
 θ0Mean = 1 - Mean[BetaDistribution[β, α]]^n;
 {a, b} = {a0, b0} /. Solve[{θ0Mean == a0 b0, θ0Var == a0 b0^2}, {a0, b0}][[1]] // Quiet;

 (* Display histogram and approximating gamma density *)
 t = Table[{i/nsamples, CDF[GammaDistribution[a, b], θ0[[i]]],
    CDF[GammaDistribution[a, b], θ0[[i]]] - (i - 1/2)/nsamples},
   {i, nsamples}];
 GraphicsRow[{ListPlot[{{{0, 0}, {1, 1}}, t[[All, {1, 2}]]},
    Joined -> {True, False}, Frame -> True,
    PlotRange -> {{0, 1}, {0, 1}}, AspectRatio -> 1,
    PlotLabel -> Style["P-P Plot", Bold, 18],
    FrameLabel -> (Style[#, Bold, 14] &) /@ {"p", "CDF(Gamma(a,b))"}],
   ListPlot[{{{0, 0}, {1, 0}}, t[[All, {1, 3}]]},
    Joined -> {True, False}, Frame -> True, PlotRange -> {{0, 1}, Automatic},
    FrameLabel -> (Style[#, Bold, 14] &) /@ {"p", "CDF(Gamma(a,b)) - p"}]}],

 {{n, 1001, Style["n", Italic, 14]}, 10, 2000, 1, Appearance -> "Labeled"},
 {{α, 2/1000, Style["α", 14]}, 1/1000, 1/10, Appearance -> "Labeled"},
 {{β, 1001, Style["β", 14]}, 50, 5000, Appearance -> "Labeled"},
 TrackedSymbols :> {n, α, β}]

The plot on the right highlights the size of the departures for a particular random sample.
Comment: For this kind of study you will get much more out of P-P plots than by overplotting histograms, especially if you're interested in accuracy out in the tails.
Comment: @whuber Agreed.  I do think the use of the sliders helps one to check out a variety of combinations relatively quickly such that any combinations of parameters that result in gross departures can be spotted.
Comment: Thank you for the Mathematica script. I do like the sliders. If I were to take a manual approach, I would definitely want to (semi-) automate the plotting this way. However, note that I'm using $-\ln{(1-\theta_{i>0})}\dot\sim\text{Gamma}(a,b)$ rather than $\theta_0\dot\sim\text{Gamma}(a,b)$, although the latter seems to be working pretty well with the example values I gave.
Comment: +1 -- really nice solution.


if $w$ is a normal distribution where $n(0,1)$, then find the mgf of $w^2$.

Question: if $w$ is a normal distribution where $n(0,1)$, then find the mgf of $w^2$. I have looked it up and the answer is chi squared but i cannot seem to find a way to integrate this correctly.
I start the problem by generalizing it as
$e^{(tx)}* f(x^2)= e^{(tx)}*[1/\sqrt{2\pi } * e^{-(x^2/2)}]^2$
Am I starting this problem of incorrectly ?
Answer: Let  $Z$ be standard normal. Then the mgf (moment generating function) of $Z^2$ is $E(tZ^2)$, which is
$$\int_{-\infty}^\infty e^{tz^2} \frac{1}{\sqrt{2\pi}}e^{-z^2/2}\,dz,$$
which is
$$\int_{-\infty}^\infty \frac{1}{\sqrt{2\pi}}e^{-(z^2/2-tz^2)}\,dz.$$
To recognize the value of the integral, for suitable $t$ let $z\sqrt{1/2-t}=u/\sqrt{2}$.
Remark: Alternately, one can find the density function of $Z^2$, and then use this to find the mgf.


APC File Cache not working but user cache is fine

Question: I have just got a VPS (with cPanel/WHM) to test what gains i could get in my application with using apc file cache AND user cache.
So firstly I got the PHP 5.3 compiled in as a DSO (apache module).
Then installed APC via PECL through SSH. (First I tried with WHM Module installer, it also had the same problem, so I tried it via ssh)
All seemed fine and phpinfo showed apc loaded and enabled.
Then I checked with apc.php. All seemed OK
But as I started testing my php application, the stats in apc for File Cache Information state:
Cached Files    0 ( 0.0 Bytes)
Hits    1
Misses  0
Request Rate (hits, misses) 0.00 cache requests/second
Hit Rate    0.00 cache requests/second
Miss Rate   0.00 cache requests/second
Insert Rate 0.00 cache requests/second
Cache full count    0
Which meant no PHP files were being cached, even though I had browsed through over 10 PHP files having multiple includes. So there must have been some Cached Files.
But the user cache is functioning fine.
User Cache Information
Cached Variables    0 ( 0.0 Bytes)
Hits    1000
Misses  1000
Request Rate (hits, misses) 0.84 cache requests/second
Hit Rate    0.42 cache requests/second
Miss Rate   0.42 cache requests/second
Insert Rate 0.84 cache requests/second
Cache full count    0
Its actually from an APC caching test script which tries to retrieve and store 1000 entries and gives me the times. A sort of simple benchmark.
Can anyone help me here.
Even though apc.cache_by_default = 1, no php files are being cached.
This is my apc config
Runtime Settings
apc.cache_by_default    1
apc.canonicalize    1
apc.coredump_unmap  0
apc.enable_cli  0
apc.enabled 1
apc.file_md5    0
apc.file_update_protection  2
apc.filters
apc.gc_ttl  3600
apc.include_once_override   0
apc.lazy_classes    0
apc.lazy_functions  0
apc.max_file_size   1M
apc.mmap_file_mask
apc.num_files_hint  1000
apc.preload_path
apc.report_autofilter   0
apc.rfc1867 0
apc.rfc1867_freq    0
apc.rfc1867_name    APC_UPLOAD_PROGRESS
apc.rfc1867_prefix  upload_
apc.rfc1867_ttl 3600
apc.serializer  default
apc.shm_segments    1
apc.shm_size    32M
apc.slam_defense    1
apc.stat    1
apc.stat_ctime  0
apc.ttl 0
apc.use_request_time    1
apc.user_entries_hint   4096
apc.user_ttl    0
apc.write_lock  1
Also most php files are under 20KB, thus, apc.max_file_size = 1M is not the cause.
I have also tried using 'apc_compile_file ' to force some files into opcode cache with no luck. I have also re-installed APC with Debugging enabled, but nothing shows in the error_log
I have also tried setting mmap_file_mask to /dev/zero and /tmp/apc.xxxxxx, i have also set /tmp permissions to 777 to no avail
Any clue anyone.
Update: I have tried following things and none cause APC file cache to populate
1. set apc.enable_cli = 1 AND run a script from cli
2. Set apc.max_file_size = 5M (just in case)
3. switched php handler from dso to FastCGI in WHM (then switched it back to dso as it did not solve the problem)
4. Even tried restarting the container
Comment: apc.ttl 0
You try change this to other value. 0 means no cache
Example:
apc.ttl 21600
(for 6h)
Comment: If the APC test script is running via the command line, try setting apc.enable_cli 1
Comment: The test script is running from web. But I have also tried setting apc.enable_cli to 1 AND running a script from command line to no avail, still no file caching.
Comment: This is off-topic? Really??? This is a perfectly valid question pertinent to production systems that deal with an incompatibility between APC and SourceGuardian (as was identified after hours of diagnostics)
Answer: It seems the problem was with SourceGuardian.
File caching is now working fine after commenting out extension="ixed.5.3.lin" from php.ini.
It was found out by the Support at my hosting provider, so a thumbs up to such great support. I wouldn't have found the issue for days.
Thought should post the answer in case someone else stumbles over this problem.


Uploading images to CKeditor in a file field way?

Question: Background
I'm looking for one of the two possible solutions concerning image-uploading to Drupal, and especially to CKeditor image uploading and handling:
Possible solution 1
A module that creates an independent image-folder to every node, uploads images to this specific directory, and then let me choose only between these images directly from CKeditor. If the node is deleted, than this folder is deleted along with it.
Possible solution 2:
a module that uploads images into CKeditor text areas in an efficient, fast, Drupal-file-field-like way; It is important for me that this uploader will use the same rules like the Drupal file-field, the same mechanisms and SQL tables, so that when I delete the image I uploaded - it will be totally deleted from the site's home-folder.
So basically the uploader I'm looking for should do 2 things:

Upload files easy and fast, just like the Drupal file-field does.
Send some kind of signal when a file is deleted from that very CKeditor text area.

Please help me to find of these two possible solutions:
Answer: I'm not 100% sure but maybe insert module is a suitable solution for you.
INSERT:

Insert is a utility that makes inserting images and links to files into text areas or WYSIWYGs much easier. It adds a simple JavaScript-based button to FileField and ImageField widgets. When used with ImageField and ImageCache, images may be inserted into text areas with a specific ImageCache preset.
This module was previously known as FileField Insert.
Answer: Insert module is the standard way of doing this, it interfaces with ckeditor and allows you to insert images as an  tag but retain the file in the drupal file entity system.
INSERT:

Insert is a utility that makes inserting images and links to files into text areas or WYSIWYGs much easier. It adds a simple JavaScript-based button to FileField and ImageField widgets. When used with ImageField and ImageCache, images may be inserted into text areas with a specific ImageCache preset.
This module was previously known as FileField Insert.

An alternative way might be paragraphs module  which allows you to insert one or more images alongside text fields and theme them by layout (so text on left-image on right or vice versa) It's not ideal in all circumstances but works.
PARAGRAPHS:

Paragraphs is the new way of content creation!
  It allows you — Site Builders — to make things cleaner so that you can give more editing power to your end-users.
Instead of putting all their content in one WYSIWYG body field including images and videos, end-users can now choose on-the-fly between pre-defined Paragraph Types independent from one another. Paragraph Types can be anything you want from a simple text block or image to a complex and configurable slideshow.
Paragraphs module comes with a new "paragraphs" field type that works like Entity Reference's. Simply add a new paragraphs field on any Content Type you want and choose which Paragraph Types should be available to end-users. They can then add as many Paragraph items as you allowed them to and reorder them at will.


Global HTTP Header Manager with http script of uploading file

Question: Im writing script which have https request for uploading file. For this script I need to overwrite 'Content-Type' from global http header manager.
Is there any way to perform this in jmeter?
Answer:
As per HTTP Header Manager documentation:

JMeter now supports multiple Header Managers. The header entries are merged to form the list for the sampler. If an entry to be merged matches an existing header name, it replaces the previous entry. This allows one to set up a default set of headers, and apply adjustments to particular samplers.

HTTP Header Manager respects JMeter Scoping Rules so if you need to override a header - add another HTTP Header Manager as a child of the Sampler which header you need to "override"

Demo:
Comment: Thank you, but in this case I cant set 'Content-Type' header in inner 'HTTP Header Manager' because it needs be in next style:
multipart/form-data; boundary=someBoundary.
But when Im trying to use any value for boundary(even taken from successfull request) it give me response, saying about wrong format.

JMeter automatically set the right value in 'Content-Type' in case enabled 'Use multipart/formdata' checkbox in http request settings.

But If I have the global 'HTTP Header Manager', it overrides value generated by  'Use multipart/formdata' checkbox


Shouldn't dhclient confirm its lease after a carrier loss?

Question: I'm investigating an issue with a Ubuntu server acting as the Internet gateway for a branch office stopped working after being switched to a new Internet connection.
The IP address on the external interface is acquired from the ISP router via DHCP.
When the interface was disconnected from the old line and connected to the new one, there was no Internet connectivity. Checking the log, I found that the Ethernet link on the interface had come up but was still trying to use the IP address it had been using on the old line.
There weren't any dhclient log entries after the Link is Up message.
The way I understand DHCP, if the link on an Ethernet interface is going down and up again, the machine should assume that it might have been moved to a different network segment, and consequently try to reacquire its IP address before using it again.
Am I wrong?
Comment: I can confirm that dhclient **standalone** didn't appear to care about carrier loss when testing (on Debian). Now if it's itself managed by NetworkManager, then carrier loss + carrier up => DHCP Request. So it depends on your setup and the version of the various running utilities (maybe even including dhclient)
Comment: Interesting question, but I suppose that if the DHCP lease is not expired it will continue to keep the IP address? Does a laptop immediately try to acquire a new IP address if you unplug it temporarily from the network?

Since this is a server, why not write a simple script that verifies internet connectivity every X minutes and, if none is available, tries to renew the IP address?
Answer: you need to run sudo dhclient <ethernet interface id>
ex: sudo dhclient eth0
Also check this out!
Comment: Of course, but that doesn't answer the question. It's also difficult to implement because the administrative access to the machine in question is via VPN over the very internet connection that is affected by the problem. So I have a real interest in getting this to work without manual intervention as it should.


Load HTML String from AJAX Into Fancybox Programmatically

Question: I am trying to display an HTML string Programmatically in Fancybox 3, but I get the following error: 'Failed to execute 'getComputedStyle' on 'Window': parameter 1 is not of type 'Element'.

I did try to change the type to 'Inline' and using a href, but no luck.
I also tried to change Content to data without the extra GetHTML variable.
I looked at this post, but no luck:
JS: Failed to execute 'getComputedStyle' on 'Window': parameter is not of type 'Element'
I also had a look at this post:
Loading dynamic AJAX content into Fancybox
$('.LinkFancybox').on('click', function () {
  var CategoryID = $(this).attr("id");
  var UserID = "<%=CurrentUserId%>";
  var CompanyID = "<%=CompanyID%>";
  var CurrentCustomerCode = "<%=CurrentCustomerCode%>";

if (CurrentCustomerCode == "") {
  CurrentCustomerCode = "000-000";
}

var APIURL = $.fn.GetBaseURL() + 'DesktopModules/DNNCommon/API/Store/GetProductsForPubCat?CategoryId=' + CategoryID + '&UserID=' + UserID + '&CompanyID=' + CompanyID;

$.ajax({
  type: "GET",
  async: true,
  url: APIURL,
  datatype: "json",
  success: function (data) {
  var GetHTML = data;
  $.fancybox.open({
  type: 'ajax',
  width: 800,
  height: 800,
  autoSize: false,
  content: GetHTML
});
},
error: function (xhr, ajaxOptions, thrownError) {
console.log(xhr.responseText);
}
});
});

Answer: If you wish to display HTML content, then content type should be html, e.g., change to type: 'html'.


Inline script violates Content Security Policy

Question: I am loading an external script from chargebee.com and I am receiving this error message in console:

[Report Only] Refused to execute inline script because it violates the
  following Content Security Policy directive: "script-src
  'nonce-VVZ+V0c=' 'self' https://maps.googleapis.com
https://domain.chargebeestatic.com
http://dgkxwewtzsnml.cloudfront.net/static/app-static-assets/hp/hp-4.8.5/".
  Either the 'unsafe-inline' keyword, a hash ('sjZUY='), or a nonce
  ('nonce-...') is required to enable inline execution.

My content security policy defined in Nginx is:
add_header Content-Security-Policy "default-src 'self' https: data: 'unsafe-inline' 'unsafe-eval';" always;

Since I have specified 'unsafe-inline', I am not sure why this error pops up.
Update:
I can see when I click on iframe connector in Safari Console:
<!DOCTYPE>

  <title></title>

Comment: Check the actual headers of the response and check the document itself to see if it has an `` element. Because either some other part the backend is already setting a Content-Security-Policy header, or the document itself is — and the policy getting set includes `script-src 'nonce-VVZ+V0c=' 'self' https://maps.googleapis.com https://domain.chargebeestatic.com http://dgkxwewtzsnml.cloudfront.net/static/app-static-assets/hp/hp-4.8.5/"`.
Comment: Please see question update, are the cloudfront assets loaded without https? could  this be  the issue?
Answer: You may not use unsafe-inline and nonces at the same time. As soon as a nonce is added to your CSP, the unsafe-inline directive will be ignored by the browser.
If you're not adding the nonce yourself, then you're not in full control of your CSP because one of your dependencies is adding one which is either merged with yours or worse overwrites yours. Look at your headers with the browser dev tools to see if the headers actually sent correspond with your own CSP. You will find that they don't.
As a matter of fact, using unsafe-inline as a script source negates the whole point of having a CSP in the first place, so the best way to solve this would be to refactor your software to use nonces as well and then add your own nonce to your CSP.
Comment: Getting the same problem with onload event listioner, and tried many things, but i see no workaround or change of way to write it, to still perform event listioner like document.onload without it being blocked as "inline". any suggestions?


Is there a seq2seq model that can encode sentences that include numerical values?

Question: I am trying to build a seq2seq model that encodes sentences which include numerical values. For example,
Patient's systolic blood pressure was 128.

Conventional seq2seq models (e.g., RNN encoder/decoder) convert each word into an embedding and then model the sequence of embeddings into a vector (hidden state) that is fed to the decoder. However, this sentence includes a number that needs to be regenerated by the decoder and it does not make a lot of sense to treat '128' as a word and include it in the embedding because 1) you can have any number during test time while your corpora likely includes a subset of possible numbers, and 2) it is very inefficient to model 128 as a string as opposed to a number, and 3) if the decoder generates '127' instead of '128', it is still acceptable and this should lead to a small increase in the loss function, while the conventional seq2seq model would penalize an output of '20', '50' or '10000000' (or even a string like 'hello') the same as '127'.
Any ideas how to model numerical values in a more effective way?
Answer: You did not say what are you using the seq2seq model for, but if it is machine translation, you usually do not have to worry about the numbers. Long numbers get segmented into subwords and the model easily learns to copy the tokens.
Alternatively, you really want to make sure that the numbers in the input and the output are the same, you can replace the numbers in the source sentence with special tokens, something like NUM-1, NUM-2, etc. The seq2seq model will learn to copy the special tokens and you can then replace them with the original number.
My answer, however, only holds if you want to copy the numbers and not do any reasoning on top of them.
Answer: You could take the log of each number, then quantize by rounding so that you end up with a reasonable amount of distinct tokens. Using log ensures that the relative difference between any two numbers which get encoded to the same token is upper bounded.
Another approach is to have tokens 0 through 9 and encode large numbers as many tokens. Large language models have been able to learn basic arithmetic, even when they've not been trained to do so, which is encouraging evidence that this approach is ultimately more flexible and powerful.