Add restriction to content on the basis of various User

Question: I am new in drupal, So I want to know how can I restrict my content in content listing according to various users. e.g. I have four contents named A,B,C,D. Now I want Customer1 to see and edit only content A and B. While Customer2 can do the same with C and D only.
I've done my research and read about "form_node_admin_content_alter" but not sure how it works. So kindly provide me an efficient solution for this.
Thank you
Answer: Creat role and assign role to the different user. Based on role set permissions of view content under people permission page.
If A role user can see A type of content so you can allow permission to view that content type page.
Comment: Hi, Thank you for responding. Actually I can restrict content on role basis but it will do for the whole content not for particular ones. What I want is user can see the content list but should be able to only see particular content in the list.Please help me if there is a way to do so. thank you once again


Views: How can I show a list of users who have a taxonomy term attached via a term reference field?

Question: I'm using the views module's built-in "Taxonomy term" view which overrides the way Drupal displays taxonomy by default and makes it accessible to views.  However, this only works for content, not users.
I tried creating a new view that lists users but there is no contextual filter like "User: has taxonomy term", just "Content: has taxonomy term."  In my case, however, some of the fields I want to display are term references stored on the user profile; they don't exist on any content.
Ideally, this is what I want: if a user visits the page taxonomy/term/oranges, it will show all users who have "oranges" in a taxonomy reference field.  How can I do this?
Comment: There doesn't seem to be a direct way to do what you want, at my great surprise. [This](http://drupal.org/node/562270) thread, though, contains some snippets which should do the job.
Comment: This works a little better: http://drupal.stackexchange.com/questions/9332/drupal-7-views-contextual-filters-taxonomy-name.
Comment: I guess you'll have to use a Relationship in your View. If your user has the field, it will appear in the list.
Comment: I have already configured a relationship (Content: Author).  However, though this makes the taxonomy term available under Fields, I am trying to show the users that have been "tagged" with the taxonomy term based on the term ID (The "Taxonomy Term" view shows all content that has been tagged with a term; I want to do the same for users.)  Adding a relationship alone does not allow me to do this.
Answer: I ended up implementing this by overriding the taxonomy page with panels instead of views.  I then made the old view taxonomy term override into a content pane.  Then, to get the "User: has taxonomy term" effect, I made a view (content pane) for each vocabulary with a "Term ID" contextual filter (supplied as a panel argument) and a relationship of "Taxonomy term: User using MY TERM".  I then added these views as content panes to the taxonomy override in panels.
I had to do this for each vocabulary, but it works.
Answer: I found a different solution by using EVA.
In my case, I have a dentistry website that has a taxonomy vocabulary named as "Expertise" and terms named as "Endodontics, Pedodontology" etc.
Dentist members can choose their area of expertises from this vocabulary on their profile2 pages ("Field: Expertise" as a term referenced field, profile2 is not neccessary at all).
I was trying to show term related dentists on taxonomy term archive pages. So I did this:

I created a Profiles block View that displays fields (You can create Users block if you don't use Profile2)
Added a Relationship -> Profile:Expertise
Added a Contexual filter -> (term from field_expertise) Taxonomy term: Term ID
Added an EVA Field
Selected Entity Type: Taxonomy Term
Selected Budles: Expertise
Selected Arguments: id
Set up EVA field "Visible" from "Expertise" vocabulary display (admin/structure/taxonomy/EXPERTISE/display


Is it possible to get the controller, action and routeValues from a URL (based on the Global.asax routes)?

Question: I have a URL. Is it possible to somehow get the controller- and action-name and the routevalues? (which would normally be generated by the .NET MVC framework based on the definition in global.asax)
Answer: Where and when do you want to get the values?
From within your code you can call:
<code>HttpContextBase context = new HttpContextWrapper(HttpContext.Current);
RouteData rd = RouteTable.Routes.GetRouteData(context);

if (rd != null) {
    string controllerName = rd.GetRequiredString("controller");
    string actionName = rd.GetRequiredString("action");
}
</code>
Please note that this only works from within your application's code. There is definitely no way to get this information about other sites and applications.
Comment: Me neither, likely changed since 10 year old post.
Comment: As far as I know, this code should work just fine for System.Web.Mvc on ASP.NET 4.x on .NET Framework. But for ASP.NET Core, this answer doesn't apply.
Answer: It is possible, check Haacked routing debugger.
Comment: I suppose I had better ask - why do you want to know this? making decision based upon the names of controllers/actions/route-values is going to make you code less loosely coupled.
Answer: You can get current controller name and Action name by adding Application_BeginRequest method inside your Global.asaxcs file.
Here is an example:
<code>    protected void Application_BeginRequest(object sender, EventArgs args)
    {
        HttpContextBase currentContext = new HttpContextWrapper(HttpContext.Current);

        UrlHelper urlHelper = new UrlHelper(HttpContext.Current.Request.RequestContext);
        RouteData routeData = urlHelper.RouteCollection.GetRouteData(currentContext);

        string url = currentContext.Request.Url.AbsoluteUri;
        string httpMethod = currentContext.Request.HttpMethod;
        string action = routeData.Values["action"] as string;
        string controller = routeData.Values["controller"] as string;

        if (!string.IsNullOrEmpty(controller) && !string.IsNullOrEmpty(action))
        {
           Logger.Log( controller, action, url, httpMethod);
        }
    }
</code>


Como usar um svg (ou div) para clicar e selecionar o checkbox correspondente

Question: Tenho um formulário que é um filtro de busca de receitas. Nesse filtro tenho um grupo de checkbox referente à categoria:
<form method="get" action="/busca">

Categoria

  <input type="checkbox" name="categoria[]" value="entrada"> Entrada
  <input type="checkbox" name="categoria[]" value="principal"> Principal
  <button type="submit">Buscar Receitas</button>
</form>

Eu queria ao invés de aparecer os checkbox, aparecesse uma imagem (svg) para clicar, e ao clicar na imagem ele marca o checkbox correspondente. Estou usando biblioteca do fontawesome. Aí o DIV que queria que fosse clicavel, seria assim:

  Entrada

  Principal

Aí ao clicar nos divs, ele seleciona o checkbox correspondente.
E um item a mais, quando clicar no div, ele mudasse a classe do css, para ficar vermelho por exemplo. Poderia adicionar a classe ".clicado" e ao clicar novamente, remove essa classe.
Answer: Tem um jeito "meio gambiarra" de fazer, vou utilizar alguns conceitos que o @hugocsl utilizou.
Cada
 terá que ter seu id e onclick para chamar a função, que estará enviando um parâmetro, que é o id. Com a padronização dos id dos <button>, sempre começando com btn-, é só concatenar o id enviado com o btn e disparar o gatilho de marcação do checkbox e inserir um novo estilo:

function trocar(id){
   $('#btn-' + id).trigger('click');
   $("#" + id + " i").closest( ".categoria" ).toggleClass("clicado")
}
.clicado{
  color: #ff0000;
}
<!DOCTYPE html>

  <title></title>
  <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.3.1/css/all.css" integrity="sha384-mzrmE5qonljUremFsqc01SB46JvROS7bZs3IO2EmfFsd15uHvIt+Y8vEf7N7fWAU" crossorigin="anonymous">

<form method="get" action="/busca">

Categoria

  <input type="checkbox" name="categoria[]" value="entrada" id="btn-entrada"> Entrada
  <input type="checkbox" name="categoria[]" value="principal" id="btn-principal"> Principal
  <input type="checkbox" name="categoria[]" value="sobremesa" id="btn-sobremesa"> Sobremesa
  <button type="submit">Buscar Receitas</button>
</form>

  Entrada

  Principal

  Sobremesa

Comment: Legal, valeu.Tem alguma forma de fazer mais "dinâmico"? É que na verdade vão ser varias categorias, entrada, princpal, sobremesas, sopas, etc., aí acredito que exista alguma forma de fazer com que seja mais dinamico ne? Brigadão!
Comment: esse dinâmico, seria ter mais opções de escolha, deixar de uma forma mais visível?
Comment: seria para simplificar o codigo, por exemplo, se tiver 10 categorias, terei que criar 10 funções certo? não tem tipo como eu fazer uma função "genérica" que funciona para todos? (não sei se deu para entender minha duvida)
Comment: alterei minha resposta, utilizando a forma que o @hugocsl explicou.
Comment: show, funcionou, só tive que fazer uma alteração, aqui " $("#" + id + " i").toggleClass("clicado")" estava aplicando o css só no icone, alterei para  $("#" + id + " i").toggleClass("clicado") "$("#" + id + " i").closest( ".categoria" ).toggleClass("clicado")", alterei a resposta


Petest function in R

Question: How can I find the function 'petest' in R?
A little background, I want to compare two different #regressions,
y=x1+x2
logy=logx1+logx2
It is clear to me that I cannot use the BIC or AIC values, because the outcome variable is different. I searched in verbeek 2008 (A guide to modern Econometrics) and he suggests the PE test to compare linear and loglinear models.
I searched on this website http://artax.karlin.mff.cuni.cz/r-help/library/lmtest/html/petest.html and there I could find that the PE test exist in R, however, I cannot find it. I have the package lmtest, and 'petest' is supposed to be there, but when I try to use it, it says: Error: could not find function "petest".
Also, I have looked for more explanation, like examples, or videos that show how to apply this PE model, but I did not find any. Any help on this topic is highly appreciated!
Comment: If you could supply a reproducible example of the failure--specifically, the way in which you "try to use it,"--then this question could be migrated to [SO].
Answer: Your name tells me you might not be that familiar with R (correct me if I'm wrong). You will first need to install the needed package, see this link for how to: https://www.r-bloggers.com/installing-r-packages/
After installing, make sure you load the package by using
<code>library(lmtest)
</code>
After you've loaded the needed package, you can use
<code>?petest
</code>
to find the helpfile that corresponds to the function. Examples and applications of the function are found at the bottom of the helpfile.If after taking these steps you still can't open the helpfile, something has gone wrong with the loading of the library.

Petest function in R


Mudar URL de /controller?id=1 para /controller/1

Question: Na minha view tenho dois botões que passam parâmetros via GET para o index do meu controller, o problema é que a URL não fica com o tradicional ?id=1  e eu queria fazer com que ficasse assim:  /controller/1
View:
<code>@using (Html.BeginForm(FormMethod.Get))
        {
            <button type="submit" class="btn btn-primary" value="1" name="id">sites1</button>
            <button type="submit" class="btn btn-primary" value="2" name="id">sites2</button><br />

        }
</code>
Controller:
<code> public async Task<IActionResult> Index(int? id)
    {
        var listaDeSites = await _listaService.ListaDeSitesAsync(id);
        return View(listaDeSites);
    }
</code>
Comment: Poderia postar o código da sua classe RouteConfig? Obrigado.
Comment: Ta no padrão do asp.net core app.UseMvc(routes =>
            {

                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });
Comment: ps.: Você quer dizer `/Controller/1`, `/Controller/Action/1` ou `./Action/1` ?
Answer: Você poderia colocar o seguinte annotation:
<code>[HttpGet("{id}")]
</code>
ficando assim:
<code>[HttpGet("{id}")]
public async Task<IActionResult> Index(int? id)
{
    var listaDeSites = await _listaService.ListaDeSitesAsync(id);
    return View(listaDeSites);
}
</code>


Undefined Subintervals - Riemann Integrals

Question: I searched through stackexchange and multiple other PDFs but couldn't find an answer
I'm curious to know when talking about Riemann Integrals with respect to functions that are bounded on closed bounded intervals (which we've been studying).
If I take some arbitrary function $f$ which is bounded on the interval $[a,b]$ (where a and b are finite real numbers); what happens if the function $f$ is undefined on a sub interval of a particular partition in that closed bounded interval $[a,b]$? This sub interval can't have a lub or a glb since the sub interval doesn't contain any real numbers (in this example). Is it just completely ignored in the sum since there is no "area"? Please explain
Cheers
Answer: Maybe, i'm not understanding your question correctly, but are you essentially asking if you have some function that is discontinuous in a partition how would you perform the Riemann Integral?  I would imagine that the best approach would be to break up your function into however many discontinuities that may exist on the partition and perform the the Riemann Integral on those sub partitions that exist and then add them up.
Comment: Yep, discontinuous. So you're saying that you ignore the subintervals in [a,b] where the function is discontinuous, and only sum the continuous subintervals (given some partition)? I don't really believe your answer, since the Riemann Sum is defined such that you're finding the glb or lub of a particular subinterval of [a,b] (depending on whether you're talking about lower or upper sums) which doesn't exist if the function is discontinuous (undefined) on the entire subinterval
Comment: I don't really see the problem.  If a function isn't defined on a certain sub-interval then how can you possibly find a glb or lub?  It's the same idea of breaking up an integral of a discontinuous function on an interval.
Comment: Exactly, you can't have a glb or lub, that's the problem. So given a partition, where the function is discontinuous over a single subinterval (for a given partition) is the sum still defined even though one of the terms in the sum doesn't have a glb or a lub?
Comment: The Riemann sum is only defined on the intervals where it is not discontinuous.  Thus if you want to take a Riemann sum over an entire interval and there exist discontinuous subintervals you have to break up the sum to not include those intervals.
Comment: Perfect, cheers for the reply man
Answer: For Riemann integrability, you need the function to be bounded in the interval, and the set of discontinuities to have a Lebesgue measure of 0.
You can extend this to undefined points by saying that the undefined point could be any value without changing the value of the Riemann integral, so the value at that point doesn't matter.  This isn't the most rigorous thing you can say, but it can be said.
An entire sub-interval would have a Lebesgue measure greater than 0, because it would scale with the unit interval.
I wouldn't trust any definition of an integral that gives a value to a set with an undefined value.  I think it makes the most sense to say that an integral over an undefined interval is undefined.  Other than that, you might get away with calling it 0, or you might give it a value in a different unit that basically only gives you the measure of the undefined set under some obscure math.


How to call constructor inside the class?

Question: I want to call constructor inside the class  like:
    public class Myclass(){
   public MyClass(){
      //......
   }

   public MyClass(int id):this(){
      //......
   }

   private void Reset(){
      //.....
      this = new MyClass(id);    //here I want to call constructor
      //......
   }
}

but it is not working. Is it possible and how can I do it if Yes?
Comment: Why would you want to do that?  You can't alter the `this` pointer that way inside an instance method, nor should you want to.
Answer: Simple answer: You can't.
Slightly more complicated answer: Move your initialization logic into a separate method that can be called from the constructor and your Reset() method:
public class MyClass
{
    public int? Id { get; }

    public MyClass()
    {
        Initialize();
    }

    public MyClass(int id)
    {
        Initialize(id);
    }

    public Reset()
    {
        Initialize();
    }

    private Initialize(int? id = null)
    {
        // initialize values here instead of the constructor
        Id = id;
    }
}

Comment: This is perfectly succinct and clear and helped my own understanding immensely.
Answer: You can't. But what you could do is split the constructor logic into an Initialize method that then reset could call.
   public MyClass(){
   //......
   }

   public MyClass(int id):this(){
      Initialize(id);
   }

   private void Initialize(int id){
   //....
   }

   private void Reset(){
      //.....
      Initialize(id);
      //......
   }
}

Answer: No this is not possible. You cannot assign to this.
You could however let Reset() return a new instance of MyClass so the caller code could say:
public class MyClass
{
    public MyClass Reset()
    {
        return new MyClass();
    }
}

MyClass c = new MyClass();
c = c.Reset();

Or you could implement the Reset method in such a way that all fields are reinitialized to their default values.
Comment: If a new instance was returned, it's no longer Resetting anything. It's returning a freshly created instance of the class. Kind of misleading.
Comment: I like the idea of Reset() returning a new instance, in that case should probably be `static` though.
Comment: True, perhaps `Create()` would be a better method name.
Comment: @JamesMichaelHare - Unless you're creating an object factory, you should really just use new...which makes this suggestion a bit redundant.
Answer: You can call a constructor for your class inside your class (in fact this is often done with factory methods):
public class MyClass
{
    public static MyClass Create()
    {
        return new MyClass();
    }
}

But you can't change the value of the this reference inside the class.  You should instead have your "Reset()" method set the fields back to their default values.
Answer: Within a class you can't reassign this (although it's worth noting that within a struct it's perfectly legal). The question, though, is whether you should. I assume that your goal is to set all field values to a specific state, so as other people have already said you can either have your Reset method return a new instance or you can break out your logic into a Clear() method and call that instead.


Inclusion of a squared independent variable in a Distributed Lag model

Question: I am interested in regressing monthly temperature data on an individual's self-evaluated wellbeing in a panel survey, of the form:
lm(wellbeing ~ temperature + factor(month) + factor(individualID), df)
I know that the relationship is likely to be non-linear, so need to include a quadratic term:
lm(wellbeing ~ temperature + I(temperature factor^2) + (month) + factor(individualID), df)
However, I also know that an individual's wellbeing at any given moment is likely to reflect temperature during the observed month as well as months prior. Therefore I'd like to run a distributed lag model (say with one month's lag) to measure this cumulative effect. In theory, I would simply add last month's value into the regression, though I am unsure if it's feasible to do so if the independent variable is quadratic in nature? Would it simply be:
lm(wellbeing ~ temperature + I(temperature factor^2) + dplyr::lag(temperature) + (month) + factor(individualID), df)
I could also use dLagM to make life easier, though am mainly curious as to whether this type of setup is reasonable? Every reference guide that I've come across deals only with independent variables as non-quadratic terms.
Any help is much appreciated.
Answer: I don't think your line of reasoning justifies the inclusion of the lagged term. We don't actually require that $X_t \perp X_{t-1}$ to obtain unbiased and efficient estimates of the model effects. Rather, distributed lag models test a different hypothesis: to estimate the cumulative effect of a regressor on an outcome. That is not the hypothesis you stated at the top of the question.
Something to be cautious of, you need to exercise careful management to estimate lagged effects in panel data. Note, for instance, if you look at the lagged effects you would estimate in the 3rd model, you would get
id mon tmp lagtmp
1   ja   0     NA
1   fe   5      0
1   ma  10      5
2   ja   0  ***10***
2   fe   5      0
2   ma  10      5

where the *** shows an incorrect term. You need to use the tapply statement instead.
in general: there is nothing stopping you from having both linear and quadratic of the concurrent regressor and a linear term for the lagged regressor(s). If the model actually follows;
$$E[Y_t|X_t, X_{t-1}] = \alpha + \beta_1 X_t + \beta_2 X_t^2 + \beta_3 X_{t-1}$$
then the estimates will be efficient and unbiased. With such a peculiar setup, most reviewers will want to know that you used some sensitivity analysis to actually verify that this prespecified model has some objectively favorable fit conditions.
Comment: Thanks, this is really useful. And yes, you're right, as far as I understand the lagged term would instead be picking up on the cumulative effect of temperature (during the present month and one month prior) on wellbeing. Something that is indeed useful to know in this context. Thanks also for flagging the need to be careful when calculating the lagged term.


Probability: $N$ dependent Bernoulli trials?

Question: I understand the proof, but I don't see why Bernoulli trials are mutually independent [...] is not necessary.
Comment: This is a derivation of expected value of binomial distribution, i.e. distribution of sum of independent Bernoulli random variables. The highlighted comment seems to say that in some other part of the book they will show that the independence assumption is not needed. So it seems that you should rather quote the other part of the book is you don't understand it.
Answer: The expected value operator has a linearity property which means that the expected value of a sum is always equal to the sum of the individual expected values.  This property holds regardless of the dependence between the terms in the sum.  So if $X = B_1 + \cdots + B_n$ is a sum of Bernoulli trials $B_i \sim \text{Bern}(p)$ then, by the linearity property you have:
$$\mathbb{E}(X) = \mathbb{E}\Bigg( \sum_{i=1}^n B_i \Bigg) =  \sum_{i=1}^n \mathbb{E}(B_i) = \sum_{i=1}^n p = np.$$
The quoted section shown in your question obtains this result by a different method, using the fact that $X \sim \text{Bin}(n,p)$ in the case where the trials are independent.  However, as you can see, the result holds even in the case where independence does not hold.


How can I transform a code that split '|' into a function

Question: I have a column called brands. The rows look like this
 |Brands|

|Gucci|Prada|
|Versace|Levis|Adidas|
|Champion|Diesel|Nike|

I have a code to split the '|' from the column brands.
split_columns=['Brands']

for brand in split_brands:
    brands_data[brand]=brands_data[brand].apply(lambda x: x.split('|'))

That code work well and split the '|'.
My question is :
How I can transform that code into a function. I would like to learn to do that.
Answer: Do this
def func(split_brands):
    for brand in split_brands:
        brands_data[brand]=brands_data[brand].apply(lambda x: x.split('|'))

Answer: I will use Google Doc String Format and convert your code. The important thing is to name your function and arguments something intelligible so that they can be understood and interpreted easily

def split_columns(brands, brands_data):
    """Used to split column string on the `|` character

    Args:
        brands (str): String containing brand names separated
            by `|` character to be seperated
        brands_data (pandas df column): Dataframe column containing the information

    Returns:
        The updated dataframe column
    """

    for brand in brands:
        brands_data[brand]=brands_data[brand].apply(lambda x: x.split('|'))

    return brands_data

That being said I feel like something feels off here.
If you are simply passing in a column and all you want to do is get the column back out such that each entry is now a nested list...
'1|Versace|Levis|Adidas|' --> ['1','Versace','Levis','Adidas']
The easiest way would be to not use a function and simply call .apply() directly:

Assuming a dataframe named df and a dataframe row named Brands
>>>df
                    Brands
0           0|Gucci|Prada|
1  1|Versace|Levis|Adidas|
2  2|Champion|Diesel|Nike|

>>>df["Brands"] = df["Brands"].apply(lambda row: row.split('|'))
>>>df
                          Brands
0            [0, Gucci, Prada, ]
1  [1, Versace, Levis, Adidas, ]
2  [2, Champion, Diesel, Nike, ]

Hopefully this clarification may help you
Comment: I think the thing that I was missing is that i forgot to write an equal here : split columns=['Brands']
Comment: That makes sense. If my answer helped or you think it will help others please make sure to click the check. If not feel free to answer your question yourself and then select it so people know where to look for the answer. :)
Comment: I have a question, Im getting an Attribute Error. "float"object has no attribute "split".              Here:  brands_data[brand]=brands_data[brand].apply(lambda x: x.split('|')) . What could I do in this case?
Comment: This is because somewhere in brands_data there is a **`brads_data[brand]`** that is a float (number with decimals). Try printing out all your **`brands_data[brand]`** and look for something that isn't a string (doesn't look like "0|Gucci|Prada|" or something similar). As a quick workaround you could change your code to this... but again it feels weird... ---> **`brands_data[brand]=brands_data[brand].apply(lambda x: str(x).split('|'))`** This is simply forcing the type to string prior to running the split command. It's a bandaid but it should fix the error. Hope that helps!
Comment: Thank so much!! Your solution solved the problem. A gold medal for you!


Edited: Choice between forecasting models

Question: Narrowed question below
I'm researching forecasting models for my job. I need a forecasting model for which I made the following assumpions:

I need a Time series model
My data is influenced by "seasons" (There are four months in which the data is higher, the months are spread throughout the year, it's month 4, 6, 9 and 10)
I need an accurate forecast between 1 and 6 months.
I guess it's stationary but I'm not sure
I have accurate data of the last 3 years

I found the models below, the problem is, I can't seem to find literature that lets me choose between the models. My boss wants me to have chosen a model before I'm going to test it on my data. With every bit of literature I seek and find, all the models are getting more unclear and I'm stuck at this point for a while now.
The models I found:

Seasonal ARIMA
Unobserved Component Model
Seasonal Naïve Method
Method of Holt-Winters
Box-Jenkins (Is this the same as seasonal ARIMA?)
STL Decomposition

I'm hoping you're able to help me clear up which models are used for what, how to make a choice between the models, if some models aren't to be used for my data and if I forgot a model that could be the solution for me.
Edit, narrowing down my question:
I have got monthly data, there's 'spreaded seasonality', how I like to call it, four months in the year with higher numbers. Except for Seasonal Naïve Method I can't seem to find a forecasting model which is applicable to this kind of seasonality. I've looked at lots of different models and literature but this doesn't get me much further. The data itself is almost constant throughout the year, except for those four months. I need to forecast up to 6 months from when the model is used.
Is there a forecasting model that can be used for accurately forecasting data with this 'spreaded seasonality'?
Comment: I don't think you can expect anybody to tell you what model is "right" for your data, particularly knowing so little about it, but to compare and contrast so many different types of model does make this question rather broad in my opinion. It would benefit from some narrowing down.
Comment: By looking at the data visually, I can relate to it as i have worked on this kind of data in the past. My approach is outlined in my answer.
Comment: "I have accurate data of the last 3 years" - is this daily data? Weekly? Monthly?
Comment: @Silverfish I tried narrowing my question down and making it more specific.
Answer: Your question has 2 parts.
1) To test if data is stationary or not. to answer that here  is an useful example with R code.
2) How to choose a technique for forecasting:
a) take a data-set and divide it into train and holdout sample.
b) create forecasting model by using each of the forecasting technique separately.
c) use the created model to forecast for holdout sample.
d) compare predicted values against actual values in the holdout sample and calculate model accuracy.
e) choose the technique which gives the most accurate results.
this gives a hint about how to test model accuracy.
Interpreting accuracy results for an ARIMA model fit


JavaFX not accepting the correct URL for Image object

Question: While attempting to mess around with JavaFX and its basic functions on java 1.8 I kept running into the issue that my Image objects would not accept the URL for a png file contained within my src folder. The icon image object gave me trouble at first but when I copied the file name via the "Copy Path/Reference..." option it worked. This was not the case for the coinImage object where no matter how I format the image URL it will not accept it. To clarify, my files are named "icon.png" and "coin.png" and they are placed in the src folder. I have tried the following formats:
Image coinImage = new Image("coin.png");
Image coinImage = new Image("/coin.png");
Image coinImage = new Image("file:coin.png");
Image coinImage = new Image("file:/coin.png");

Below is the code which most relates to the problem to reduce on the size of this question:
public class MainStage extends Application {
    public void start(Stage stage) throws Exception{
        Group root = new Group();
        Scene scene = new Scene(root,1000,1000,Color.LIGHTSKYBLUE);
        Image icon = new Image("icon.png");

        Image coinImage = new Image("coin.png");
        ImageView imageView = new ImageView(coinImage);
        imageView.setX(400);
        imageView.setY(500);

        root.getChildren().add(imageView);
        stage.getIcons().add(icon);
        stage.setTitle("Test");
        stage.setScene(scene);
        stage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }
}

Here are all of my imports as well but I do not think they are the issue here:
import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.paint.Color;
import javafx.scene.shape.Circle;
import javafx.scene.shape.Line;
import javafx.scene.shape.Polygon;
import javafx.scene.shape.Rectangle;
import javafx.scene.text.Font;
import javafx.scene.text.Text;
import javafx.stage.Stage;

If any additional information is needed I should be able to provide it. Thanks.
Comment: don't _mess around_ with random parameters, instead work through a decent tutorial on the basics (at the very least study the api doc of related classes throroughly - they might be a bit on the dense side, but digging into every single word/class you don't know yet will help :)
Comment: Refer to the [Eden resource guide](https://edencoding.com/where-to-put-resource-files-in-javafx/).  Check the binary output of your build and ensure that the resource is actually in the location you are looking for it.  Also see: [How do I determine the correct path for FXML files, CSS files, Images, and other resources needed by my JavaFX Application?](https://stackoverflow.com/questions/61531317/how-do-i-determine-the-correct-path-for-fxml-files-css-files-images-and-other), examples are in the [Image javadoc](https://openjfx.io/javadoc/17/javafx.graphics/javafx/scene/image/Image.html).
Answer: It is recommended to keep images and resources in a dedicated assets folder.
You need to have the assets folder in your classpath.
Set the assets directory as a resource directory and then create a javafx Image from location: "/coinImage.png":
If you are using IntelliJ To set folder as resource directory follow this guide
Answer: This issue is coming from the fact that Java will search for your image file in the bin directory. You should put your image in the bin directory.
I added a small print in your code that can help for debugging
System.out.println("GET  PATH"+this.getClass().getClassLoader().getResource("").getPath());

The output that i got
GET PATH /D:/Nabil-local/eclipse-workspace/Stackoverflow/bin/

I think there is another way to specify a folder


How is Simplex related to statistics at all?

Question: I was reading here about change point detection using STAN(bayesian modeling language).
In section Discrete sampling gmodena uses simplex as a data type to store probabilities of a model parameter.
From my research I understand that simplex is a type of geometrical structure, but I don't follow as to why are statisticians looking at it?
Can someone explain to me in relatively simple english why do statisticians look at this shape? What does it represent in statistics?
Answer: If you have a disjoint set of possible events (say three of them) that exhaust all possiblites, the probabilities of each of these events must sum to one:
$$p_1 + p_2 + p_3 = 1$$
Being probabilities, each of these is also bounded between zero and one:
$$ 0 \leq p_i \leq 1 $$
If consider the three probabilities as a point in euclidean space $(p_1, p_2, p_3)$, then this equation and the probability constraints define a triangle resting snugly in the positive quadrant.

(Image credit Wikipedia)
In general, when there are more than three probabilities involved
$$p_1 + p_2 + \cdots + p_k = 1$$
then the vectors of possible probabilities will trace out a simplex (a high dimensional triangle) in the corresponding euclidean space.

Simplex is used here because modeler is assuming that there is specifically one change point in the times series, modeler wants to make sure that probabilities of change point occurring on a given day add up to 1?

Given this quote from the document

The softmax transform maps log_p to a K-simplex...

I think that is correct.
Comment: A completely non-maths person here. Can you please explain how this property(probability vectors tracing out a simplex) might be important or useful ?
Comment: Thanks for quick repsonse, so to put it back in terms of change point detection. Simplex is used here becasuse modeler is assuming that there is specifically one change point in the times series, modeler wants to make sure that probabilities of change point occuring on a given day add up to 1.
Comment: @sgp667 Edited into answer.


Retornar objetos somados de um array em um só

Question: Seguinte, sou designer e estou aprendendo javascript aos poucos.
Uma das coisas que tenho mais dificuldades, são objetos e arrays, por isso to focando mais nisso agora. Tenho um array com 4 objetos como o código a seguir.
var players = [{
  name: "Batman",
  id: "1",
  points: 10
},
{
  name: "Superman",
  id: "2",
  points: 10
},
{
  name: "Batman",
  id: "1",
  points: 10
},
{
  name: "Superman",
  id: "2",
  points: 5
}
];

O que eu preciso: retornar os objetos com as mesmas ids's e os points somados, resultando em 2 objetos.
Qual a lógica que eu uso pra resolver esse problema? Como juntar os objetos com a mesma id e somar os points de cada um? Já consegui fazer só com 1 objeto, mas estava comparando com a id. Se eu tivesse um array bem maior, seria quase inviável ficar comparando um por um. Quero entender a lógica aplicada nesse contexto.
Answer: Tens várias maneiras, sugestões:
Cria um novo objeto com um for:

var players = [{
    name: "Batman",
    id: "1",
    points: 10
  },
  {
    name: "Superman",
    id: "2",
    points: 10
  },
  {
    name: "Batman",
    id: "1",
    points: 10
  },
  {
    name: "Superman",
    id: "2",
    points: 5
  }
];

var obj = {};
for (var i = 0; i < players.length; i++) {
  var id = players[i].id;
  if (!obj[id]) obj[id] = players[i]; // caso ainda não haja um objeto com essa ID
  else obj[id].points += players[i].points;
}

console.log(obj);

Usa o .reduce():

var players = [{
    name: "Batman",
    id: "1",
    points: 10
  },
  {
    name: "Superman",
    id: "2",
    points: 10
  },
  {
    name: "Batman",
    id: "1",
    points: 10
  },
  {
    name: "Superman",
    id: "2",
    points: 5
  }
];
var obj = players.reduce(function(obj, player) {
  if (!obj[player.id]) obj[player.id] = player; // caso ainda não haja um objeto com essa ID
  else obj[player.id].points += player.points;
  return obj;
}, {});

console.log(obj);
Comment: Eu segui esses dois exemplos seu porém o array ao invés de retornar com index, ta retornando com o ID de cada objeto.


Way to differentiate table and other text in xsl-fo

Question: I am setting a column-count to 2 in my simple-page-master.
I am using xsl-fo to generate the pdf, the text now splits into two columns perfectly.
However, I am now with a new issue caused by this, it also splits the tables into two columns, which I don't want to, I want to leave the table as it is and only split the text.
Here is the complete fo file:
http://pastebin.com/Z7Nkm279
The column count is set to "2" in layout-master-set.
Could any experts offer some suggestions? Thanks!
Comment: **Please** provide a COMPLETE FO document (NOT just a skeleton) that demonstrates the problem. You can paste it at http://pastebin.com or a similar service.
Comment: Yeah, I have uploaded it to pastebin.com, let me know if that works.
Comment: this is the version in which I already took out the @span="all". I did put it there before, but no effect, thus I took it out.
Comment: When running your FO file through XEP, there are several warnings like this one: **[warning] 'span' attribute on block ignored because the element is not a direct child of a flow**. You have to fix those if you want the spanning of tables to work. I did mention this requirement in my answer.
Answer: You can let your XSLT stylesheet wrap tables in <fo:block> elements that have span="all" set:
<fo:block span="all">
  <fo:table width="100%" ...>
  ...
  </fo:table>
<fo:block>

This will make the table span all the columns of a multi-column region (provided that the <fo:block> is a direct child of <fo:flow>). Reference: http://www.w3.org/TR/2001/REC-xsl-20011015/slice7.html#span.
Comment: @mzin, this is not working. The table is still splits into two columns.
Comment: yes, please see the updated question with the fo. I have taken out the @span attribute. Let me know if more info is needed. Thx


How can I re-arrange my multi-plot to reverse alphabetical order?

Question: Fig1
I've made my figure(Fig1 above) and annotated it to my liking, but I want the assorted figures to be displayed in reverse alphabetical order according to the top label names. I can reverse the values of the x-axis, but "order()" and "title()" don't seem to produce the effect I'm aiming for here. Is there any way to tell R I want the multi plot ordered differently? Or, is this just something I'll have to edit myself in another program like Adobe?
Code might be sloppy, but I'm just starting to work in R.
library(tidypaleo)
data<-read.table('multiplot_r.txt',sep="\t",header=TRUE)
as_tibble(data)
zone_data <- tibble(ymin = 0, ymax = 9649, xmin = -Inf, xmax = Inf)
multi_plot +
geom_rect(mapping = aes(ymin = ymin, ymax = ymax, xmin = xmin, xmax =
xmax), data = zone_data, alpha = 0.2, inherit.aes = FALSE)
multi_plot <- ggplot(data, aes(x = value, y = Age)) +
geom_lineh() +
scale_y_reverse() +
facet_geochem_gridh(vars(param)) +
geom_hline(yintercept = c(2200,2800,5000,5500), linetype = "dashed",
colour = "red")+
labs(x = "d18O", y = "Years BP")
multi_plot

Comment: Try with converting your `param` variable to a factor and setting the order of the levels in your desired order.
Answer: Set param as a factor and reverse the order.
library (tidyverse)
data <- data %>% mutate(param = fct_rev(param))


Which part of calculating the T statistic relies on assumption of normal distribution?

Question: Recently, I got into an argument with a professor at my University. As part of a discussion, I made a statement that the calculation of the T statistics (independent sample T test: (mu1 - mu2)/PooledSD) does not by itself have any assumptions about the distribution of the data. My point was that the statistic itself is a simple signal to noise ratio kind of measure and it is the calculation of the p value which relies on the normal distribution. I went on to say that the p value could alternatively be calculated without making any assumptions by using permutation testing to build a distribution and find the p value. The professor on the other hand argued that my understanding was totally incorrect and that the calculation of the T statistic assumes a normal distribution.
My question is: which part of the independent sample t test makes the assumption of the normal distribution?
On a related note: is the normal distribution assumption about the data or the residuals of the data?
Comment: You are correct that one can compute a t statistic even for data not sampled from a normal population. The standard (1 and 2-sample) t tests require (nearly) normal data in order for the t-stat to have (nearly) a Student's t dist'n. Also, the form of the t-stat is _motivated_ by normal data. // But, when you're doing a permutation test you have a choice of 'metrics' for comparing one sample with a standard or two samples against each other. You can use as metric: a diff involving mean(s),  trimmed means, medians, t-stat, etc. Then it's the _permutation_ dist'n of the metric that matters.
Comment: Would it be fair to say your professor is not primarily a statistician? ;-)
Comment: Related to your related note: what do mean by residuals of the data?
Answer: Let $Z \sim \mathcal{N}(0,1)$ and $U \sim \chi^2_n$, and further assume $Z$ is independent of $U$. Then, the random variable
$$X = \frac{Z}{\sqrt{U/n}} \sim t_{n}.$$
In other words, $X$ is distributed according to a $t$ distribution with $n$ degrees of freedom if it is the ratio of a standard normal and the square root of a chi-squared random variable over its degrees of freedom. This is a definition we'll appeal to later.
Specifically, consider two independent samples from two normal populations $\mathcal{N}(\mu_X, \sigma^2)$, and $\mathcal{N}(\mu_Y, \sigma^2)$. Denote the first sample as I.I.D normal random variables $X_1, X_2, ..., X_n$, and the second sample as $Y_1, Y_2, ..., Y_m$.
The test statistic that we use (as I'm sure you're familiar with) is
$$T = \frac{\bar{X} - \bar{Y} - (\mu_X - \mu_Y)}{s_p\sqrt{\frac{1}{n} + \frac{1}{m}}}$$
where $s_p = \sqrt{\frac{(n-1)s_X^2 + (m-1)s_Y^2}{m + n - 2}}$, and $s_X^2$ and $s_Y^2$ are the sample (unbiased) standard deviations of each of our samples. We multiply $\sigma\sqrt{(1/n) + (1/m)}$ in the numerator and denominator of $T$ and simplify to get
$$T = \frac{\frac{\bar{X} - \bar{Y} - (\mu_X - \mu_Y)}{\sigma\sqrt{\frac{1}{n} + \frac{1}{m}}}}{\sqrt{\frac{\frac{(n-1)s_X^2}{\sigma^2} + \frac{(m-1)s_Y^2}{\sigma^2}}{m+n-2}}}$$.
It is standard fare in many statistics textbooks that (under the specific conditions we lay out here, but not generally)
$$\frac{(n-1)s_X^2}{\sigma^2} + \frac{(m-1)s_Y^2}{\sigma^2} \sim \chi_{m+ n-2}^2.$$
Further, by properties of the normal distribution,
$$\frac{\bar{X} - \bar{Y} - (\mu_X - \mu_Y)}{\sigma\sqrt{\frac{1}{n} + \frac{1}{m}}} \sim \mathcal{N}(0,1).$$
So, indeed, by our definition at the very beginning, $T \sim t_{m+n-2}$.

Now, to address your question (if it's not obvious already!) We assume that our samples are normal because it allows us to say
$$\frac{\bar{X} - \bar{Y} - (\mu_X - \mu_Y)}{\sigma\sqrt{\frac{1}{n} + \frac{1}{m}}} \sim \mathcal{N}(0,1)$$
and
$$\frac{(n-1)s_X^2}{\sigma^2} + \frac{(m-1)s_Y^2}{\sigma^2} \sim \chi_{m+ n-2}^2$$
exactly. There are no approximations here. This is because each sample is normally distributed and independent of each other, so their sums, averages, differences are normally distributed too! Therefore, our statistic $T$ is distributed exactly $t_{m+n-2}$, by our definition at the beginning. This is the detail which your teacher is referencing.
Clearly, though, if your sample size is large enough, we can appeal to the central limit theorem and say that the distribution of the sample means of each of your samples are approximately normal. Therefore, $T$ is approximately $t_{m+n-2}$. For many applications, this is good enough!


Rotation of a Plane in 3d about a line

Question: I have a set of points in the XY planes, I want to translate them all to the YZ plane by rotating about a line. Basically,
Here, in this cube
Imagine I have a list of points on 2376 plane, I want to translate those points in such a way that the points on plane 2367 land on the same location on the plane 2341. Is there a possible rotation matrix for this?
Comment: Welcome to MSE! Please see [how-to-ask-a-good-question](https://math.meta.stackexchange.com/questions/9959/how-to-ask-a-good-question) and edit your post accordingly
Comment: A few things to be aware of: (1) Every rotation in 3D space is a rotation around a line, but there are a lot of different lines to choose from. (2) There are eight different rotations that take the square $2367$ to the square $2341.$ (3) If you just want to move the square $2367$ and everything in its plane into the plane where $2341$ was, there are a lot more choices. (4) Rotation matrices only work for rotations around lines that pass through the point $(0,0,0).$ A rotation around the $y$ axis is one such rotation.
Comment: It's a little hard to relate the rotation described in terms of the cube's faces to the rotation described in terms of coordinate planes, because there are no coordinate axes marked in the picture. To reconcile the two descriptions we would have to make the axes cross at point $2,$ so point $2$ has coordinates $(0,0,0),$ while point $6$ has coordinates $(1,0,0)$ ($x$ axis points down), point $3$ has coordinates $(0,1,0)$ ($y$ axis points right), and point $1$ has coordinates $(0,0,1).$ That's an unusual point of view to use when looking at $x,y,z$ axes, so it may confuse people.
Answer: Sure.  I'm not going to tell you the answer, because I want to show you how to find the answer yourself.  Teach a person to fish, and they will be happy fishing for the rest of their life, and so on :).
First, consider counterclockwise rotation on a 2D plane:
$$\left[ \begin{matrix} x_1 \\ y_1 \end{matrix} \right] =
\left[ \begin{matrix} 0 & -1 \\ 1 & 0 \end{matrix} \right]
\left[ \begin{matrix} x_0 \\ y_0 \end{matrix} \right] \tag{1}\label{AC1}$$
Essentially, $\eqref{AC1}$ is just
$$\left\lbrace\begin{aligned} x_1 &= -y_0 \\ y_1 &= x_0 \end{aligned}\right.$$
Feel free to try some coordinate pairs to see how this works.  As an example, $(1,0) \to (0,1) \to (-1,0) \to (0,-1) \to (1,0)$.  Drawing the points on a paper, or say at Desmos, can be very useful here.
Second, consider the identity transformation in 3D:
$$\left[ \begin{matrix} x_1 \\ y_1 \\ z_1 \end{matrix} \right] =
\left[ \begin{matrix} 1 & 0 & 0 \\ 0 & 1 & 0 \\ 0 & 0 & 1 \end{matrix} \right]
\left[ \begin{matrix} x_0 \\ y_0 \\ z_0 \end{matrix} \right] \tag{2}\label{AC2}$$
Essentially, the rows corresponding to the coordinate axis that stays put, are all zeros except $1$ on the diagonal.  If you play with this for a second, you'll realize why that is.
We can combine the two, by ignoring the row and column that corresponds to the coordinate axis that stays unchanged.  This gives us three rotation matrices:
$\mathbf{R}_{xy}$ rotates the $xy$ plane by ninety degrees, leaving $z$ coordinates intact:
$$\mathbf{R}_{xy} = \left[ \begin{matrix} 0 & -1 & 0 \\ 1 & 0 & 0 \\ 0 & 0 & 1 \end{matrix} \right ] \tag{XY}\label{ACXY}$$
$\mathbf{R}_{xz}$ rotates the $xz$ plane by ninety degrees, leaving $y$ coordinates intact:
$$\mathbf{R}_{xz} = \left[ \begin{matrix} 0 & 0 & -1 \\ 0 & 1 & 0 \\ 1 & 0 & 0 \end{matrix} \right ] \tag{XZ}\label{ACXZ}$$
$\mathbf{R}_{yz}$ rotates the $yz$ plane by ninety degrees, leaving $x$ coordinates intact:
$$\mathbf{R}_{yz} = \left[ \begin{matrix} 1 & 0 & 0 \\ 0 & 0 & -1 \\ 0 & 1 & 0 \end{matrix} \right ] \tag{YZ}\label{ACYZ}$$
(Yes, one of those is the matrix OP is looking for, I believe.)
Pure rotation and mirroring matrices that do not scale or skew are orthonormal.  Their inverse is their transpose,
$$\mathbf{R}^{-1} = \mathbf{R}^{T}$$
which means that if you want to rotate in the other direction, just transpose the matrix.  (Rotation in the opposite direction is obviously the inverse rotation, right?)

Rotation of a Plane in 3d about a line


Commerce Product generate Preview on Add Product page

Question: I want to add a Preview button in Commerce Product Add form. Before adding product, user can see Preview of Product same as Product Display/Detail page.
I am using Rules to create Product Display after saving Product.
I have added below code in form_alter hook but  :
//Add Preview
<code>function mymodule_form_alter(&$form, &$form_state, $form_id) {
 if ($form_id == 'commerce_product_ui_product_form') {
       $form['actions']['preview'] = array(
          '#type' => 'submit',
          '#value' => t('Preview'),
          '#weight' => 10,
          '#submit' => array('product_preview'),
        );

        // Some special stuff when previewing a node.
        if (isset($form_state['node_preview'])) {
          $form['#prefix'] = $form_state['node_preview'];
          $node->in_preview = TRUE;
        }
        else {
          unset($node->in_preview);
        }
  }
}

function product_preview($form, &$form_state, $node) {
  module_load_include('inc', 'node', 'node.pages');
  $node = new stdClass();
  $node->field_product['und'][0]['product_id'] = $productId;
  $node->title = 'test';
  $node->uid = 2;
  $node->type = 'commerceproduct';
  $node->in_preview = TRUE;
  $form_state['node'] = $node;

  node_form_build_preview($form, $form_state);
}
</code>
Above code displays preview for edit but problem is in node object i am getting $node->field_product['und'][0]['product_id'] value not whole Product object. So any updated value of product form fields won't be reflected in preview.
I am not sure how to build whole product object within node object.
Can anyone tell me what is missing here ?
Answer: You can try rendering the product entity and attaching it to the form.
To render the product entity (see entity_view):
<code>// Extract the referenced product from the node.
$node_wrapper = entity_metadata_wrapper('node', $node);
$product = $node_wrapper->field_product->value();

$product_view_mode = 'full'; // Set the view mode you want to use to display this product.

// This will return a render array.
$rendered_product = entity_view('commerce_product', array($product->product_id => $product), $product_view_mode);
</code>
Finally, alter the form so that it also contains the rendered product.
<code>// Now add the markup to the form.
$form['product_preview'] = array(
  '#markup' => render($rendered_product);
);
</code>
Comment: I have created node-type.tpl.php which is not rendering using above code. It is loading default node.tpl.php.


Router calling with template URI parameters

Question: I am using the useRouter hook.
I have templated pages in my application.
I have a useEffect hook responding to router and making an API call.
I am trying to forward the entire URL to /api/${path}.json${query}
const u = new URL(`https://example.com${router.asPath}`)
const path = `/api${u.pathname}.json${u.search}`

However the router seems to fire twice, once as the template, and again as filled with parameters for instance:

/[design]/[product]
/blue/shirt

This is consequentially firing the call to the API twice.
Here's my hook:
export const usePage = () => {
    const router = useRouter();
    const [page, setPage] = useState()
    useEffect(() => {
        (async () => {
            // the next.js query is littered with the params, so we can get
            // just the query with this:
            const u = new URL(`https://example.com${router.asPath}`)
            const path = `/api${u.pathname}.json${u.search}`
            console.log({ path })
            const results = await fetch(path, { method: 'GET' });
            const json = await results.json();
            setPage(json)
        })();
    }, [router]);
    return page;
}

I can wrap the call in a conditional check to see if there's [|] in the url, and don't run the api call. Wondering if there's a better way.
Comment: What's setting the `router.asPath` to `/[design]/[product]`? Unless you're changing the routing externally to `usePage`, that `useEffect` should only fire once.
Answer: Band-aid solution:
export const usePage = () => {
    const router = useRouter();
    const [page, setPage] = useState()
    useEffect(() => {
        (async () => {
            // the next.js query is littered with the params, so we can get
            // just the query with this:
            const u = new URL(`https://example.com${router.asPath}`)
            if (u.pathname.match(/\[/)) return;
            const path = `/api${u.pathname}.json${u.search}`
            const results = await fetch(path, { method: 'GET' });
            const json = await results.json();
            setPage(json)
        })();
    }, [router]);
    return page;
}


Aproveitar API Android em aplicações Desktop

Question: Posso aproveitar os códigos de uma API feita para Android e usar numa aplicação java desktop ?
PS.: Não manjo nada de Java, estou disposto a aprender. Sei apenas Delphi e C++...
No delphi por exemplo, posso aproveitar o código mobile e utilizar no desktop e vice versa.
Comment: Corrigindo as definições: uma biblioteca fornece uma API (_Application Programming Interface_), isto é, um conjunto de classes, interfaces e métodos públicos que você pode usar para desenvolver um aplicativo. Um SDK pode incluir uma biblioteca, entre outras ferramentas (_debuggers_, ambiente de desenvolvimento ou IDE), e você ainda pode usar no seu código bibliotecas que não pertencem ao SDK (essas bibliotecas externas podem servir para vários ambientes, incluindo mobile e desktop). O aplicativo que você desenvolve usando SDK e bibliotecas se chama aplicativo final mesmo.
Comment: a API foi feita por você? Ela é genérica ou utiliza recursos do SDK de android? Se sua API não utiliza nenhum recurso do SDK **é possível** que ela possa ser aproveitada em ambas plataformas
Comment: Entendi @Piovezan, só me tire essa dúvida... vou tentar ser um pouco mais objetivo. A sony tem API de suas câmeras em android, poderia utilizar essa API em alguma aplicação desktop?
Comment: No meu entendimento, a API de câmeras em Android da Sony é específica para Android (isso se não for específica para plataformas da Sony, isto é, combinações de hardware e versão de Android da Sony). Ela espera que o sistema operacional forneça recursos como intents, etc. específicos do Android, que a plataforma desktop não pode fornecer. Fosse porém um Android para PC (arquitetura x86), daí poderia funcionar.
Comment: @Piovezan obrigado pelo comentário, agregou bastante
Comment: @WilliamBarreto Se a resposta foi útil siga [essas orientações](http://pt.stackoverflow.com/help/someone-answers). Sugiro também aguardar por comentários de outros usuários que possam agregar mais à resposta, inclusive fornecendo alternativas para seu problema.
Answer: No meu entendimento, a API de câmeras em Android da Sony é específica para Android (isso se não for específica para plataformas da Sony, isto é, combinações de hardware e versão de Android da Sony). Ela espera que o sistema operacional forneça recursos como intents, etc. específicos do Android, que a plataforma desktop não pode fornecer. Fosse porém um Android para PC (arquitetura x86), daí poderia funcionar, mas aí estamos falando em não rodar Windows nem Linux.


In R, how can specific columns be transposed to rows, aligning with the original values?

Question: When I organize data sheet, I made this way.
A <- data.frame(
  Season = rep(2023, 5),
  crop = rep("Soybean", 5),
  treatment = rep("Inside panel", 5),
  plot = rep(6, 5),
  row = 1:5,
  rep1 = c(24.30, 30.30, 21.80, 22.90, 20.60),
  rep2 = c(10.30, 0.00, 29.30, 0.00, 30.80),
  rep3 = c(30.70, 28.40, 15.50, 22.30, 17.40),
  SS1 = c("tr1", "tr1", "tr1", "tr3", "tr1"),
  SS2 = c("tr3", "tr2", "tr2", "tr2", "tr3"),
  SS3 = c("tr2", "tr3", "tr3", "tr1", "tr2")
)

  Season    crop    treatment plot row rep1 rep2 rep3 SS1 SS2 SS3
1   2023 Soybean Inside panel    6   1 24.3 10.3 30.7 tr1 tr3 tr2
2   2023 Soybean Inside panel    6   2 30.3  0.0 28.4 tr1 tr2 tr3
3   2023 Soybean Inside panel    6   3 21.8 29.3 15.5 tr1 tr2 tr3
4   2023 Soybean Inside panel    6   4 22.9  0.0 22.3 tr3 tr2 tr1
5   2023 Soybean Inside panel    6   5 20.6 30.8 17.4 tr1 tr3 tr2

SS1 align with rep1, and SS2 align with rep2, and SS3 align with rep3. For example, in the first row, 24.3 is for tr1, and 10.3 is for tr3, and 30.7 is for tr2.
What I want is to transpose SS columns into rows.
B=data.frame(
  Season = rep(2023, 15),
  crop = rep("Soybean", 15),
  treatment = rep("Inside panel", 15),
  plot = rep(6, 15),
  row = rep(1:5, each = 3),
  rep = rep(1:3, times = 5),
  SS = c("tr1", "tr3", "tr2", "tr1", "tr2", "tr3", "tr1", "tr2", "tr3", "tr3", "tr2", "tr1", "tr1", "tr3", "tr2"),
  yield = c(24.30, 10.30, 30.70, 30.30, 0.00, 28.40, 21.80, 29.30, 15.50, 22.90, 0.00, 22.30, 20.60, 30.80, 17.40))

   Season    crop    treatment plot row rep  SS yield
1    2023 Soybean Inside panel    6   1   1 tr1  24.3
2    2023 Soybean Inside panel    6   1   2 tr3  10.3
3    2023 Soybean Inside panel    6   1   3 tr2  30.7
4    2023 Soybean Inside panel    6   2   1 tr1  30.3
5    2023 Soybean Inside panel    6   2   2 tr2   0.0
6    2023 Soybean Inside panel    6   2   3 tr3  28.4
7    2023 Soybean Inside panel    6   3   1 tr1  21.8
8    2023 Soybean Inside panel    6   3   2 tr2  29.3
9    2023 Soybean Inside panel    6   3   3 tr3  15.5
10   2023 Soybean Inside panel    6   4   1 tr3  22.9
11   2023 Soybean Inside panel    6   4   2 tr2   0.0
12   2023 Soybean Inside panel    6   4   3 tr1  22.3
13   2023 Soybean Inside panel    6   5   1 tr1  20.6
14   2023 Soybean Inside panel    6   5   2 tr3  30.8
15   2023 Soybean Inside panel    6   5   3 tr2  17.4

Could you let me know how to convert transpose columns to rows, aligning with the original values?
Answer: Update: see input of @Onyambu:
library(dplyr)
library(tidyr)

A %>%
  pivot_longer(
    cols = c(starts_with("rep"), starts_with("SS")),
    names_to = c(".value", NA),
    names_pattern = "(rep|SS)(\\d+)"
  )

First answer:
We could do it this way: It is the compact mode of using pivot_longer twice:
We use names_to = c(".value", "set") and names_pattern = "(rep|SS)(\\d+)" to separate the column names into two parts. .value keeps the common part of the column names (rep and SS), and set keeps the numeric suffix (and is removed afterwords).
library(dplyr)
library(tidyr)

A %>%
  pivot_longer(
    cols = c(starts_with("rep"), starts_with("SS")),
    names_to = c(".value", "set"),
    names_pattern = "(rep|SS)(\\d+)"
  ) %>%
  select(-set)

  Season crop    treatment     plot   row   rep SS
    <dbl> <chr>   <chr>        <dbl> <int> <dbl> <chr>
 1   2023 Soybean Inside panel     6     1  24.3 tr1
 2   2023 Soybean Inside panel     6     1  10.3 tr3
 3   2023 Soybean Inside panel     6     1  30.7 tr2
 4   2023 Soybean Inside panel     6     2  30.3 tr1
 5   2023 Soybean Inside panel     6     2   0   tr2
 6   2023 Soybean Inside panel     6     2  28.4 tr3
 7   2023 Soybean Inside panel     6     3  21.8 tr1
 8   2023 Soybean Inside panel     6     3  29.3 tr2
 9   2023 Soybean Inside panel     6     3  15.5 tr3
10   2023 Soybean Inside panel     6     4  22.9 tr3
11   2023 Soybean Inside panel     6     4   0   tr2
12   2023 Soybean Inside panel     6     4  22.3 tr1
13   2023 Soybean Inside panel     6     5  20.6 tr1
14   2023 Soybean Inside panel     6     5  30.8 tr3
15   2023 Soybean Inside panel     6     5  17.4 tr2

Comment: instead of `select(-set)` use `names_to = c('.value', NA)` or use `names_to = '.value'` with a pattern capturing only the first part ie, `names_pattern = "(rep|SS)\\d+"`
Comment: Thank you so much!! You saved my time a lot!! Many thanks!!!
Comment: This is very useful. Thanks @Onyambu!
Answer: The pivot_longer() function in tidyr can do the trick.  Use "name_pattern" to separate the front part(rep or SS) from the test/trial number.
library(tidyr)
pivot_longer(A, cols= -c("Season", "crop", "treatment", "plot", "row"),
             names_pattern="(\\D+)(\\d)", names_to = c(".value", "test"))
#or
#pivot_longer(A, cols= matches("\\d$"), names_pattern="(\\D+)(\\d)",
         names_to = c(".value", "test"))

# A tibble: 15 × 8
Season crop    treatment     plot   row test    rep SS
<dbl> <chr>   <chr>        <dbl> <int> <chr> <dbl> <chr>
1   2023 Soybean Inside panel     6     1 1      24.3 tr1
2   2023 Soybean Inside panel     6     1 2      10.3 tr3
3   2023 Soybean Inside panel     6     1 3      30.7 tr2
4   2023 Soybean Inside panel     6     2 1      30.3 tr1
5   2023 Soybean Inside panel     6     2 2       0   tr2
6   2023 Soybean Inside panel     6     2 3      28.4 tr3
...

You will need to rename the columns to your final desired results.
Comment: Thank you so much!!! I solved my problem!!
Answer: Basically what you want is
> reshape(A, var=list(6:8, 9:11), sep='', dir='l')

To get desired column names we can refine
> reshape(A, var=list(6:8, 9:11), sep='', dir='l', v.names=c('yield', 'SS'),
+         timevar='rep')

And finally to resemble sorting of the shown desired output
> reshape(A, var=list(6:8, 9:11), sep='', dir='l', v.names=c('yield', 'SS'),
+         timevar='rep') |>
+   {\(.) .[with(., order(row, rep)), setdiff(names(.), 'id')]}()
    Season    crop    treatment plot row rep yield  SS
1.1   2023 Soybean Inside panel    6   1   1  24.3 tr1
1.2   2023 Soybean Inside panel    6   1   2  10.3 tr3
1.3   2023 Soybean Inside panel    6   1   3  30.7 tr2
2.1   2023 Soybean Inside panel    6   2   1  30.3 tr1
2.2   2023 Soybean Inside panel    6   2   2   0.0 tr2
2.3   2023 Soybean Inside panel    6   2   3  28.4 tr3
3.1   2023 Soybean Inside panel    6   3   1  21.8 tr1
3.2   2023 Soybean Inside panel    6   3   2  29.3 tr2
3.3   2023 Soybean Inside panel    6   3   3  15.5 tr3
4.1   2023 Soybean Inside panel    6   4   1  22.9 tr3
4.2   2023 Soybean Inside panel    6   4   2   0.0 tr2
4.3   2023 Soybean Inside panel    6   4   3  22.3 tr1
5.1   2023 Soybean Inside panel    6   5   1  20.6 tr1
5.2   2023 Soybean Inside panel    6   5   2  30.8 tr3
5.3   2023 Soybean Inside panel    6   5   3  17.4 tr2

Data:
> dput(A)
structure(list(Season = c(2023, 2023, 2023, 2023, 2023), crop = c("Soybean",
"Soybean", "Soybean", "Soybean", "Soybean"), treatment = c("Inside panel",
"Inside panel", "Inside panel", "Inside panel", "Inside panel"
), plot = c(6, 6, 6, 6, 6), row = 1:5, rep1 = c(24.3, 30.3, 21.8,
22.9, 20.6), rep2 = c(10.3, 0, 29.3, 0, 30.8), rep3 = c(30.7,
28.4, 15.5, 22.3, 17.4), SS1 = c("tr1", "tr1", "tr1", "tr3",
"tr1"), SS2 = c("tr3", "tr2", "tr2", "tr2", "tr3"), SS3 = c("tr2",
"tr3", "tr3", "tr1", "tr2")), class = "data.frame", row.names = c(NA,
-5L))


Pointer to structure NOT changing at all when passed to function

Question:  stack.h
 #define MAX_STACK 10
 typedef int STACK_ITEM;
 typedef struct Stack *STACK ;

stack.c
 #include"stack.h"

struct Stack{
    STACK_ITEM contents[MAX_STACK];
    int tos;
};

_Bool create_stack(STACK s){
    s = malloc(sizeof(struct Stack));
    if(s == NULL )
        return 0;
    s->tos = 0;
    return 1;
}

When calling the create_stack function, it doesn't affect s (pointer to structure) at all. So, my question is: why is s not changing, even though it is a pointer, not a value, passed?
Comment: Because the function overwrites the *copy* of the value passed, which is forgotten when the function ends.
Answer: Function parameters are its local variables. That is the parameters hold copies of the passed arguments. To change an original argument in a function you have to pass it by reference through pointer.
So change the function like
_Bool create_stack(STACK *s){
    *s = malloc(sizeof(struct Stack));
    if(*s == NULL )
        return 0;
    ( *s )->tos = 0;
    return 1;
}

Answer: In order for a C function to modify an argument, the argument must be given as a pointer to the value to be changed. Thus, for a simple integer argument:
void Inc(int *value) {
    ++(*value);
}

will do the trick, but:
void Inc(int value) {
    ++value;
}

will do absolutely nothing to any argument given in a call to Inc, as the function just gets a copy of the 'value' given.
The same goes for a pointer! Your function just changes a copy of the pointer it is passed. So, you should change your function to take a pointer to the pointer:
_Bool create_stack(STACK *s){ // Pointer to a pointer to Stack
    *s = malloc(sizeof(struct Stack)); // Change the value of the STACK object pointed to
    if (*s == NULL )
        return 0;
    (*s)->tos = 0; // And, again, we need to (singly) dereference to 'double' pointer
    return 1;
}

Then, in your calling code, where you originally have something like:
_Bool answer = create_stack(myStackPointer);

you would need to add the address of your pointer:
_Bool answer = create_stack(&myStackPointer);

Feel free to ask for further clarification and/or explanation.
Answer: Remember, all parameters are passed by value in C.
When you pass a pointer as a function parameter, you can access the object (or array of objects) pointed to by that pointer.
Your create_stack() is passed a pointer to a struct Stack, that is the s parameter.  It then ignores the original value of s and reassigns it. That is allowed, but note that it does not change the original pointer in the caller of create_stack() because function parameters are passed by value.
There are two ways to do what you want.
The first way is to pass a pointer to a pointer:
_Bool create_stack(STACK *s){
    *s = malloc(sizeof(struct Stack));
    if(*s == NULL )
        return 0;
    (*s)->tos = 0;
    return 1;
}

Call it e.g.:
STACK mystack;
_Bool ret;

ret = create_stack(&mystack);
if (!ret) {
    /* error */
}

The second way is to not pass anything and return a pointer to the allocated stack:
STACK create_stack(void){
    STACK s = malloc(sizeof(struct Stack));
    if(s != NULL ) {
        s->tos = 0;
    }
    return s;
}

Call it e.g.:
STACK s;

s = create_stack();
if (s == NULL) {
    /* error */
}

Finally, as a point of programming style, do not typedef pointers in the way you have done. It is clearer if the pointer is explicit, for example, use typedef struct Stack STACK; instead of typedef struct Stack *STACK; and adjust the usage accordingly, for example, replacing STACK s with STACK *s and replacing STACK *s with STACK **s.


Replacing alpha characters and spaces in string with jQuery

Question: I have a string that allows only numbers
$(this).val($(this).val().replace(/([a-zA-Z])/g, ""));

How can I add a space, so this will get replaced with "" same way in one string?
Comment: try this... http://stackoverflow.com/questions/181356/regex-to-match-alphanumeric-and-spaces
Comment: where do you want to add space exactly?
Comment: possible duplicate of [How to allow only numeric (0-9) in HTML  inputbox using jQuery?](http://stackoverflow.com/questions/995183/how-to-allow-only-numeric-0-9-in-html-inputbox-using-jquery)
Answer: To match only non-numerics, you would do [^0-9] instead of [a-zA-Z] (this is called a negated character class).
If you want an input to allow only numbers, with HTML5 you can simply do <input type="number">. For wider support, there are plenty of JavaScript solutions, have a look at How to allow only numeric (0-9) in HTML  inputbox using jQuery? as suggested in the comments.
Comment: @schlingel There are plenty of different solutions at that link, but it does indeed seem like they are all using different key-events instead of the `input` event. I edited your fiddle: http://jsfiddle.net/7rSVb/3/
Comment: Your link works fine if the user types the text but it fails if the user pastes the text.
Answer: Just add the space to your Regex:
  "asfasd asdf asdf".replace(/([a-zA-Z ])/g, "");

Yields:
  ""

Edit:
I misunderstood your question. If you want to prevent every input but numbers use this regex:
function removeNotAllowedChars($input) {
   $input.val($input.val().replace(/[^0-9]/g, ''));
}

$('#myText')
   .keyup(function() {
     var $input = $(this);
     removeNotAllowedChars($input);
   })
   .change(function() {
     var $input = $(this);
     removeNotAllowedChars($input);
   });

Using these script removes the input instantly if the user types the character and if he pastes the input after the focus changes. Try it here: JSFiddle
Comment: That's great, thank you,  but just thinking that would be easier to prevent the space key in general. This is my function $('*[data-type-validation="numeric"]).each(function (index, value) {
            $(this).change(function () {
                $(this).val($(this).val().replace(/([a-zA-Z ])/g, ""));

            })
        }); any idea please?
Answer: use \s - Matches a single white space character, including space, tab, form feed, line feed. Equivalent to
Regex Guide


If some sequence $(x_{n})$ is convergent in $X$ show that $(x_{n})$ is stationary (eventually constant).

Question: Let $X$ be non-empty set and
$ T = \{ V \subseteq X : card ( X \backslash V) \leq \aleph_{0} \} \cup \{\emptyset\}$ topology on $X$. If some sequence $(x_{n})$ is convergent in $X$ show that $(x_{n})$ is stationary ( sequence that eventually becomes constant sequence //after some $n \in \mathbb{N} $ all members of sequence are equal).
I tried to prove it by contradiction but I got stuck.
Comment: What do you mean by $card(X\setminus V)\leq \aleph_0$ ? Also explain what a "stationary sequence mean"
Comment: as what I know, **stationary** is when the sequence becomes constant after some $N >> 0$.
Comment: @freehumorist: It's anyway good to precise this point when you ask the question. By the way, I don't really understand all these upvotes... No real definition, no real try from the OP...
Comment: @user657324 forgot to write down that $T$  is topology, sorry
Comment: @user560461 Can you explain where you got stuck? Write down your attempted proof by contradiction.
Answer: Hint: Suppose $x_n\rightarrow x$ but there are $x_n\neq x$ with $n$ arbitrarily large.  Consider the neighborhood of $x$ defined by $V:=X - \{x_n | x_n\neq x\}$.  Does the sequence $(x_n)$ eventually lie in this neighborhood?


How to mock JavaFX controls with mockito?

Question: I am currently working on a simple JavaFX MVC/MVP to test if I could get any unit tests for JavaFX working. My goal is to test a JavaFX dialog or control in a unit test. To make my unit tests as independent as possible from any JavaFX calls I want to try to mock any JavaFX calls. But unfortunately I am struggling to get it working properly. I also don't want to work with TestFX because of the lack of proper documentation.
Until now I am still a bit new to unit testing in Java, but I do have experience in writing unit tests in c++ (google test/mock)
Specs:

JDK 8
Mockito 3.5.13
JUnit 4.12
Hamcrest 1.3

What do I have until now?
I have created a View class which is responsible for updating the dialog, for registering the actions for a button and for showing the dialog.
public class View {

    private Stage stage;
    private Label label;
    private Button button;

    public View(Stage stage, Label label, Button button) {
        this.stage = stage;
        this.label = label;
        this.button = button;
    }

    public void updateLabel(int count) {
        label.setText("Countdown: " + count);
    }

    public void ShowStage() {
        //button.setText("Count");
        //stage.setScene(new Scene(new VBox(label, button)));
        stage.show();
    }

    public void RegisterButtonAction(EventHandler<ActionEvent> value) {
        button.setOnAction(value);
    }

}

Additionally I also have a Unit test for the view, in which I have three tests:

for the constructor
for updating a label
for showing the dialog
For this unit test I already have a JavaFX threading rule (see How do you mock a JavaFX toolkit initialization?), which is responsible for starting a JavaFX thread. For the button, the label and the stage I created mocks with mockito, they are injected via the constructor (fast hack for testing).
As I created mocks, I expected that the calls to JavaFX are mocked, but it seems that there is still something missing.

public class ViewTest {

    @org.junit.Rule
    public JavaFXThreadingRule rule = new JavaFXThreadingRule();

    private Stage m_stageMock;
    private Label m_labelMock;
    private Button m_buttonMock;

    private View m_testee;

    @Before
    public void SetUp() throws InterruptedException {
        m_stageMock = mock(Stage.class);
        m_labelMock = mock(Label.class);
        m_buttonMock = mock(Button.class);
        m_testee = new View(m_stageMock, m_labelMock, m_buttonMock);
    }

    @After
    public void TearDown(){
        m_testee = null;
        m_stageMock = null;
        m_labelMock = null;
        m_buttonMock = null;
    }

    @Test
    public void Constructor_HappyPath_NoCrash() {

    }

    @Test
    public void UpdateLabel_IntegerGiven_PrintNumber() {
        int count = 8;
        doNothing().when(m_labelMock).setText("Countdown: " + count);
        m_testee.updateLabel(count);
    }

    @Test
    public void ShowStage_HappyPath_ShowsWindowWithButtonAndLabel() {
        VBox vbox = new VBox();
        Scene scene = new Scene(vbox);
        //doNothing().when(m_buttonMock).setText("Count");
        //doNothing().when(m_stageMock).setScene(any(Scene.class));
        doNothing().when(m_stageMock).show();
        m_testee.ShowStage();
    }

}

What additional things have I tried so far?

I tried to set mockito in such a way that it is capable to mock final function/classes.
I tried to implement a custom mock maker based on How do you mock a JavaFX toolkit initialization?.

Maybe someone has a solution or an example for me, or I am just missing something small.
I would be very grateful if I could get any help.
All the best
Fossa
Answer: I hope my answer helps after it's been a long time since you asked this question but it can help someone out there.
It would have helped if you shared the output from your tests, error or not, but I was in your shoes a while ago. First, you need to understand how the platforms JavaFX, Mockito, and JUnit work. They are frameworks and unique in how they execute within the Java virtual machine. Any artifact that belongs to the domain of JavaFX will require JavaFX's runtime before they work the way you intend them to. This is why the main class (the class where the main method is contained) must subclass JavaFX's Application class and override its "start" method. When your application runs java knows to look for this method and your application runs within the domain of JavaFX, allowing all JavaFX's artifacts to execute as implemented in your code. In other words, a thread specific to JavaFX will be started and this is where your application will be executed, away from the main thread.
Second, when you run your tests with Junit you are not required to create a main class and its main method. Junit's framework does this for you behind the scenes and executes your tests. Junit is not aware of JavaFX so your tests should fail, and throw IllegalStateException because the JavaFX thread hasn't been started. Junit does not do that automatically. JavaFX's main thread needs to be started and all JavaFX code needs to run on that thread.
In my situation, I needed to test some business logic in my JavaFX application and these are the parts of the application that don't require JavaFX artifacts.  I had one of them like so
@Override
    public void onVendRequest(VendRequestVendronEvent event) {
        // The paying amount entered by the customer on Vendron's sale UI is passed over to the application's GUI
        CardPaymentController.setPayingAmount(event.getRequiredPrice());

        // Show the GUI (there's a lag of about two to three seconds)
        Platform.runLater(() -> super.stage.show());
        this.socketPayLogger.info("Showing GUI");

        // More code below
    }

Well, you see the part that calls the GUI to be displayed, that's JavaFX code. This method runs on a separate thread because I employed concurrency in my application, and when I needed to call JavaFX code (like updating GUI components) from a thread that is not the main JavaFX thread I had to wrap my statements in a Runnable, hand it over to the "runLater" method and it safely executes them on the JavaFX's thread. Read about it here. Testing this method as said earlier will throw an IllegalStateException when JavaFx's thread is not running. So to bring JavaFX framework into my test I had to add the line below in my tests.
Platform.startup(runnable);

You just have to simply place your tests in the runnable object and call that line in your test method. This brings over the JavaFX framework into your tests and its artifacts are executed as they should all the while Junit is not compromised in any way. You can read up about the class in the JavaFX 17 docs here.
Here's the test that worked for me
@Test
void testOnVendRequest(){
    Runnable runnable = () -> {
        try {
            n6DeviceConnection.createSerialConnection();
            assertTrue(n6DeviceConnection.isConnected());
             Optional<VendronSocketMessage> optional = controller.create("External PC Plugin;Vend Request;add_on_variable=&required_price=200#");

            if (optional.isPresent()){
                VendronEvent vendronEvent = vendronEventFactory.createVendronEvent(optional.get(), new Object());
                posPay.onVendRequest((VendRequestVendronEvent) vendronEvent);
            }
        } catch (SerialPortException e) {
            throw new RuntimeException(e);
        }
    };

    Platform.startup(runnable);
    while (true){
        if (posPay.isPaymentTransactionComplete()){
            String string = posPay.getFinishedTransactionReport();
            assertInstanceOf(String.class, string);
            break;
        }
    }
}

JUnit will call the JavaFX framework allowing smooth execution of your tests. So, always remember that all JavaFx artifacts should be executed or called on the JavaFX's thread and not any other thread. Calling Platform.startup(runnable); will ensure JavaFX's main thread is started or make your main class the subclass of Application and if you must execute any JavaFX from a thread that's not the JavaFX thread use Platform.runLater(Runnable runnable)
Comment: `Platform.startup(() -> {})` was all that was needed in my case. For multiple test cases only requiring this setup, it is not possible to place it in `@BeforeEach`, due to `IllegalStateException: Toolkit already initialized`. Instead, place the setup in a `@BeforeAll`.
Comment: Turns out that this will fail in environments where a display is not available (such as CI/CD pipeline), encountering: `java.lang.UnsupportedOperationException: Unable to open DISPLAY`.


Editable webform submissions

Question: Requirements for user submissions are:

anonymous user is able to submit form data
admin can delete any submission
admin can edit any field of any submission
form can contains fields which are not displayed to user, but admin can edit them
admin can sort and filter the submissions according to one field (date type)

There is webform module, but I do not know if it can solve all those requirements (the first one is OK, ofc ;)
Comment: everything can be done
Answer: I would recommend using the Webform module and the Webform Report module.
So

webform module
webform module
webform module
when adding a field to your form there are two checkboxes at the bottom (Disabled and Private) which will do what you need it to do.
webform report module
Answer: Webform is not necessary for the tasks you've outlined.
Simply create a content type, and grant the Anonymous user role access to create content of that type.
To have 'hidden' fields which the admin can still edit, you can either hide those fields with CSS, deny access to them via the #access property through a hook_form_alter(), or use the Field Permissions module to restrict access to those specific fields. Note that the Field Permissions module has some performance implications.

Editable webform submissions


Redundant values in dataframe to be used as a key and another column as a value

Question: I got a dataframe like
name  count  title
a       1      c1
a       2      c2
a       3      b1
b       4      f1
b       5      f2
c       6      g1

I want to transfer it to a dict with name as key and title as value.
I expect the output to be like
{a: [c1, c2, b1], b: [f1, f2], c: [g1]}

I tried this:
sites = {}
features = []
for index,row in df.iterrows():
    sites[row["name"]] = features.append(row["title"])

and got a dictionary with None values as
{a: None, b: None, c: None}

Why do I get None and how can I do this correctly?

I also tried this:
your_dict = df.groupby(["Name"])["title"].apply(list).to_dict().get("Name")

and also got None value.
Comment: Did you try iterating over the rows in the dataframe and appending the value of the "title" column to a list in the dictionary using the value of the "Name" column as key?
Comment: yes and it gives me a dict with none value
Answer: your_dict = df.groupby(["name"])["title"].apply(list).to_dict()

Comment: it gives me None
Comment: @AshrafKhaled adjusted my answer, try this one
Comment: if i want to check in this dict if any key contains those 3 things [ c1 , c2 , b1] print it , what can I do ?
Comment: ['c1', 'c2', 'b1'] in your_dict.values()
Comment: even if the list conatins others ? , I need it as a must
Comment: as an example :

if key1 : [ a , b ,c ,d ,e ]
and key 2 : [ a , b ,e]

i need to print key 1 as it contains all of [ a, b ,c] together  and not key 2
Answer: The append method appends a value to a list by modifying it. It does not return anything (more specifically, it returns None).
Therefore, by writing

sites[row["name"]] = features.append(row["title"])

you insert None values into the dictionary.
Instead, you need to use
sites[row["name"]].append(row["title"])

For this to work you need to ensure that the list exists when you try to append to it for the first time. An easy way to do this is to use a defaultdict.
from collections import defaultdict

sites = defaultdict(list)

for index, row in df.iterrows():
    sites[row["name"]].append(row["title"])


Repeated measures bootstrap: resample per ID per condition

Question: Having a hard time here... I'm trying to create 1000 bootstrapped data sets for each subject in a repeated measures design with three independent variables: DepthValidity (2 levels), SideValidity (2 levels), and TargetDepth (2 levels). An additional goal is calculating a bootstrapped reaction time mean, median, and sd for each subject, for each possible condition (there are eight conditions in total).
I tried using and manipulating the code as found here: repeated measures bootstrap stats, grouped by multiple factors
df <- mydata %>%
  group_by(ID, Depth, TarDepth, Side) %>%
  summarise(measure=list(ReactionTime)) %>%
  ungroup()

myfunc <- function(data, indices) {
  data <- data[indices,]
  return(c(mean=mean(unlist(data$measure)),
           median=median(unlist(data$measure)),
           sd = sd(unlist(data$measure))))
}
set.seed(333)
bootresults <- df %>%
  group_by(ID, Depth, TarDepth, Side) %>%
  do(tidy(boot(data = ., statistic = myfunc, R = 1000)))

My original data frame (i.e., mydata) is in long format, where each row corresponds to a single data point for an individual under one of the eight conditions. Each individual has approximately 90 data points per condition.
Using the code above, I get data with repeating values as seen highlighted here:

Are the identical values occurring because I need to execute the above code in a for loop  (i.e., for each unique ID)? I tried that and it didn't seem to work, but I may very well be doing something wrong there, too. Perhaps it's because I have to have a single column with all of the different combinations of conditions, rather than three separate columns? How do I prevent repetition?
EDIT: Included dput
dput(droplevels(head(individ, 20)))

structure(list(ID = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L), .Label = "s109", class = "factor"),
    TarDepth = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
    1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L), .Label = "Mid", class = "factor"),
    Side = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
    1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L), .Label = "DIFF", class = "factor"),
    PRTS = c(0.834416149, 0.716587752, 0.716472204, 0.69970636,
    0.699617629, 0.682915685, 0.666703417, 0.616733331, 0.599953582,
    0.597570097, 0.595346526, 0.592605137, 0.588598339, 0.583834349,
    0.58285897, 0.568965957, 0.567117837, 0.566593729, 0.566063329,
    0.550269553), Depth = structure(c(1L, 1L, 1L, 1L, 1L, 1L,
    1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L), .Label = "DIFF", class = "factor")), row.names = c(NA,
20L), class = "data.frame")

EDIT:
Included dput for two subject IDs, since I'm getting a bias and std.error of 0 according to commenter's most recent solution:
dput(droplevels(head(individ, 32)))

structure(list(ID = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L), .Label = c("s97", "s98"), class = "factor"),
    TarDepth = structure(c(1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 1L,
    1L, 1L, 1L, 2L, 2L, 2L, 2L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L,
    1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L), .Label = c("Mid", "Near"
    ), class = "factor"), Side = structure(c(1L, 1L, 2L, 2L,
    1L, 1L, 2L, 2L, 1L, 1L, 2L, 2L, 1L, 1L, 2L, 2L, 1L, 1L, 2L,
    2L, 1L, 1L, 2L, 2L, 1L, 1L, 2L, 2L, 1L, 1L, 2L, 2L), .Label = c("DIFF",
    "SAME"), class = "factor"), PRTS = c(0.851425991, 0.84961243,
    0.840487545, 0.839716775, 0.820657432, 0.815991426, 0.807378203,
    0.800551856, 0.799805387, 0.787336857, 0.77253443, 0.765844159,
    0.751196415, 0.749769895, 0.749374114, 0.649443255, 0.184844206,
    0.608819523, 0.117052886, 0.082718123, 0.762629011, 0.050756321,
    0.074764508, 0.147296557, 0.428583992, 0.432677868, 0.378136045,
    0.135034201, 0.367393051, 0.593182243, 0.723897573, 0.533599005
    ), Depth = structure(c(2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L,
    1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L,
    2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L), .Label = c("DIFF", "SAME"
    ), class = "factor")), row.names = c(NA, 32L), class = "data.frame")

Comment: @akrun I realized my mistake. I accidentally added an extra step... THANK YOU for your AMAZING guidance! Answer selected/upvoted
Comment: Your data is showed in an image, which I cannot copy and test it.  I would recommend `dput` i.e. usage is `dput(droplevels(head(iris, 20)))` returns the structure of 20 rows
Comment: Thank you for your patience and continued help, @akrun. I edited my original question to include the `dput`
Comment: Please check my updated post.  It is just that your func didn't change the 'measure' to 'PRTS'
Comment: `nest_by` is from `dplyr`.   I am using `packageVersion('dplyr')#
[1] '1.0.6'`.  Please check your packageVersion of dplyr and if it is old, update it. thanks
>
Comment: Can you show `packageVersion('dplyr')`
Comment: Hi @akrun. So, I updated all of my R packages and `nest_by()` works fine now. I am not getting repeating numbers anymore under the "statistic" column, but I am not getting a bias and std.error of 0. I wonder if I should give you a `dput` with more than one subject ID... I will add a second edit.
Comment: Typo: I am getting a bias and std. error of 0.
Comment: Sorry, I am not understanding why you should 0 values.  The example works fine for me
Answer: We can split the data with group_split and loop over the list
library(dplyr)
library(purrr)
library(broom)
set.seed(333)
bootresults <-  df %>%
  group_split(ID, Depth, TarDepth, Side)  %>%
  map_dfr(~ tidy(boot(data = .x, statistic = myfunc, R = 1000)))

Or another option is nest_by
set.seed(333)
bootresults <- df %>%
    nest_by(ID, Depth, TarDepth, Side) %>%
    mutate(new = list(tidy(boot(data = data, statistic = myfunc, R = 1000))))

Update
Using a reproducible example
df <- data.frame(id=c(1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2),
                  cond=c('A', 'A', 'B', 'B', 'A', 'A', 'B', 'B', 'A', 'A', 'B', 'B', 'A', 'A', 'B', 'B'),
                  comm=c('X', 'Y', 'X', 'Y', 'X', 'Y', 'X', 'Y','X', 'Y', 'X', 'Y', 'X', 'Y', 'X', 'Y'),
                  measure=c(0.8, 1.1, 0.7, 1.2, 0.9, 2.3, 0.6, 1.1, 0.7, 1.3, 0.6, 1.5, 1.0, 2.1, 0.7, 1.2))
myfunc <- function(data, indices) {
    data <- data[indices,]
    return(c(mean=mean(unlist(data$measure)),
             median=median(unlist(data$measure)),
             sd = sd(unlist(data$measure))))
}
df1 <- df %>%
   nest_by(cond, comm) %>%
   mutate(out = list(tidy(boot(data = data, statistic = myfunc, R = 1000))))
df1
# A tibble: 4 x 4
# Rowwise:  cond, comm
  cond  comm                data out
  <chr> <chr> <list<tibble[,2]>> <list>
1 A     X                [4 × 2] <tibble [3 × 4]>
2 A     Y                [4 × 2] <tibble [3 × 4]>
3 B     X                [4 × 2] <tibble [3 × 4]>
4 B     Y                [4 × 2] <tibble [3 × 4]>

Then, we unnest
library(tidyr)
df1 %>%
      ungroup %>%
      select(-data) %>%
      unnest(out)
# A tibble: 12 x 6
   cond  comm  term   statistic      bias std.error
   <chr> <chr> <chr>      <dbl>     <dbl>     <dbl>
 1 A     X     mean      0.85   -0.000250    0.0555
 2 A     X     median    0.85    0.000900    0.0734
 3 A     X     sd        0.129  -0.0246      0.0362
 4 A     Y     mean      1.7    -0.00575     0.253
 5 A     Y     median    1.7    -0.00650     0.374
 6 A     Y     sd        0.589  -0.103       0.162
 7 B     X     mean      0.65    0.000200    0.0258
 8 B     X     median    0.65    0.000550    0.0402
 9 B     X     sd        0.0577 -0.0120      0.0189
10 B     Y     mean      1.25    0.00260     0.0767
11 B     Y     median    1.2     0.0337      0.0995
12 B     Y     sd        0.173  -0.0372      0.0661

Update2
Based on the OP's input data, change the function 'myfunc' by changing the 'measure' with 'PRTS'
myfunc <- function(data, indices) {
  data <- data[indices,]
  return(c(mean=mean(unlist(data$PRTS)),
           median=median(unlist(data$PRTS)),
           sd = sd(unlist(data$PRTS))))
}
individ %>%
   nest_by(ID, Depth, TarDepth, Side) %>%
   mutate(out = list(tidy(boot(data = data, statistic = myfunc, R = 1000)))) %>%
   ungroup %>%
   select(-data) %>%
   unnest(out)
# A tibble: 3 x 8
  ID    Depth TarDepth Side  term   statistic      bias std.error
  <fct> <fct> <fct>    <fct> <chr>      <dbl>     <dbl>     <dbl>
1 s109  DIFF  Mid      DIFF  mean      0.630   0.000108    0.0166
2 s109  DIFF  Mid      DIFF  median    0.596   0.00756     0.0229
3 s109  DIFF  Mid      DIFF  sd        0.0738 -0.00361     0.0139

Comment: Hello akrun - thank you for taking the time to help me with this. I attempted your group_split and map_dfr method, and the data (mean, median, and mode) still repeats and now shows no bias/std.error from the boot, and the variable names (Depth, Side, TarDepth) and groupingID names are also missing.

I tried your nest_by, and keep getting errors as well. Also, did you mean nest_join or nest? Neither of those work as well.
Comment: @HannaHaponenko Can you post a dput of small example so that I can test it. thanks
Comment: So I ended up running map_dfr for every value in the list, and I ended up getting an error message

OUTPUT: Error in as_mapper(.f, ...) : argument ".f" is missing, with no default
Comment: @HannaHaponenko I requested `dput` so that I can test it and check where the error is. I meant the data and not the code.
Comment: @HannaHaponenko I added the reproducible example from the data in the linked post.  It is working fine for me
Comment: @HannaHaponenko i hope you have tested the updated solution.


Finding the next rational number

Question: A rational number is one that can be written as $a/b$ where $a$ and $b$ are integers, $b\gt0$ ($a$ can take care of negative rationals), and I suppose $\gcd(a,b) = 1$.
Given some $n\in\mathbb{Q}$ where $n=a/b$, what is the next rational number?
At first, I naively thought that it was $(a+1)/b$ but of course that is absurd. Consider $n=1/2$. The next rational number is obviously not $1$.
I decided that one must make the "granularity" finer. For instance $n=1/2=2/4$, so by the above idea, the next one is $3/4$, which is better.
Extending that, is it correct that the next rational number is:
$$
\frac{1+\prod_{n\in\mathbb{Z^+},n\neq b}n}{\prod_{n\in\mathbb{Z^+}}n}
$$
(We can factor in the sign of $a$ if we wanted to make this more correct)
Comment: Do you mean the next where they are linearly ordered? In that case there is no next because if $n_i$ and $n_{i+1}$ existed you could take the average which would contradict that $n_{i+1}$ was the next. If you mean the next as an enumeration you can get that from the Cantor diagonal enumeration.
Comment: I meant the next where they are linearly ordered.
Comment: I see, it wouldn't be enough to just multiply all integers together. You could multiply the denominator by another $2$ to get a rational in between the two supposedly sequential rationals.
Answer: The point of this exercise is to make you realize that there is no such thing as "the next rational number". You did well to realize $\frac{a+1}b$ does not work. But the problem is more general: suppose you do decide that some number $\frac c d$ is the "next" one after $\frac a b$. But ask yourself: what is the average of $\frac a b$ and $\frac c d$? And where is it located?

Finding the next rational number