Mutual dependence of replacement and power set axioms

Question: I read in Gittman, Hamkins, et al, that ZFC without the power set causes the axiom of replacement to fail. Yet I also read (generally, throughout the literature, but mostly in connection with Cantor's theorem) that the power set is generated by replacing one set with another. Is the term replacement in the context of the power set informally used? Or does this apparent circularity simply explain why power set and replacement are axiomatic?
Comment: "causes the axiom of replacement to fail" is a gross misunderstanding of the text.
Comment: Thanks. How is it to be understood then?
Comment: Maybe "fail" is too final a word! I see that ZFC without the power set has weaknesses that are repaired by using collection rather than replacement. So does collection work for generating a power set?
Comment: @asaf - I think you scared everyone away!
Comment: As I understand it, one gets a power set by starting with N and applying the function 2^N. Does the use of this function assume the viability of the axiom of replacement? Can anyone clarify this for me? I made a point of posting with the tag "elementary set theory" because I am novice with a sincere question.
Comment: Could you give a reference for where you read "that the power set is generated by replacing one set with another"? The only sensible meaning I can imagine for this statement is that, if we consider some set, then its power set is another set.  That has nothing to do with replacement axioms.
Answer: First of all, Victoria Gitman's last name has only one "t", and Thomas A. Johnstone is a co-author. Our paper is:

V. Gitman, J. D. Hamkins, and T. A. Johnstone, What is the theory ZFC without power set?, under review.

But you haven't described the result correctly. The main result is that many things go completely wrong, if one axiomatizes ZFC without power set using the replacement axiom, instead of the collection axiom plus separation. Although replacement is equivalent to collection plus separation over the usual version of ZFC without those axioms, when one omits the power set axiom this equivalence is no longer true, and there are a number of surprising issues that arise, as we explain in our paper. For example, one cannot prove that $\omega_1$ is regular in the version of ZFC-powerset where one has only replacement and not collection, even though the well-order principle is there, and similarly the Los theorem fails and there are many other problems.
The final conclusion is that the right way to axiomatize ZFC without power set is to use the collection and separation axioms, rather than merely replacement.
Comment: Apologies for misspelling Ms. Gitman's name and for reducing Mr. Johnstone to a figure in the crowd. Thanks too for clarifying the import of this paper. I do think I came closer in my own restatement of it, but as a novice I'm not one to judge. I see that my Ipad is posting when I try to start a new paragraph, so I will have to continue my reply from another computer tomorrow.
Comment: Unfortunately, I can no longer locate the sources where the power set is described in terms of replacing an original set. But let the intuition be wholly my own, my problem is the same. It really is a beginner's question, I think. Why is the power set P(N) considered not to be a mapping -- not to be a specific case of replacement, and therefore deserving of an axiom of its own?
Answer: Just to answer the title of the question: The axiom of power set and the axiom schema of replacement are independent of each other. Neither is deducible from the other plus the remaining axioms of ZFC.


Joomla url redirect to another domain

Question: I have created 5 menu items with a menu from Joomla admin panel. Out of 5, 4 menu item should be redirected to the same domain and the 5th one should redirect to another domain url.
How to do that in Joomla admin panel? I am totally new to Joomla. The correct guidance is appreciable.
Answer: You can use External Link while Menu creation. So you need to follow below steps.

Go to Menu Manager.
Select New Menu.
Now you will see the Menu Item Type field , Click on Select Button.
Here You need to choose Click on System Link.
Now it will open this options, i.e Menu Heading, Menu Item Alias, Separator, URL.
Choose URL option.
Now you need to give external link in the field Link textbox.

Hope it will solve your problem :)
Comment: I did it but it redirects to mycurrrentdomain/#undefined
Comment: What URL you entered there ?

Joomla url redirect to another domain


access controls in Form1 from another class

Question: I have one control textBox1 that sits in my main form Form1. I want to be able to change the textBox1 text from another class another_class, but I can't do it. My another_class has a event teacher that I handle from Form1 by doing the following
private void button1_Click(object sender, EventArgs e)
{
    another_class myNew_another_class = new another_class();
    myNew_another_class.teacher(sender, e);
}

So I can't create the following in another_class because it will mess with my handler above and red tag it
public another_class (Form1 anytext_Form)
{
    this.anytext_Form = anytext_Form;
}

Comment: Sorry I don't get what your problem is, what is messing with your handler and why?
Answer: Correct the syntax by:
partial class Form1 {
    private void button1_Click(object sender, EventArgs e) {
        another_class myNew_another_class=new another_class(this);
        myNew_another_class.teacher(sender, e);
    }
}

public partial class another_class {
    Form anytext_Form;

    public void teacher(object sender, EventArgs e) {
        // do something
    }

    public another_class(Form anytext_Form) {
        this.anytext_Form=anytext_Form;
    }
}

Comment: Thanks a lot that really helped, I spent 6 hours on that shit.

Thanks again,
Answer: I think you should explain what you actually what to do, because your event management doesn't look good IMO. Maybe the event isn't useful, or maybe you could refactor it if you tell us what you want to achieve actually.
To answer the question in your title, controls in another form are private members, so you can't access them outside the scope of the parent form. What you can do is expose public method that'll do the job:
public class Form1 : Form
{
    public void SetMyText(string text)
    {
        this.myTextbox.Text = text;
    }
}

public class Form2 : Form
{
    public void Foo()
    {
        var frm1 = new Form1();
        frm1.SetMyText("test");
    }
}

Answer: change this:
another_class myNew_another_class = new another_class();

to this:
another_class myNew_another_class = new another_class(this);

Answer: Change to this:
private void button1_Click(object sender, EventArgs e)
{
     another_class myNew_another_class = new another_class(this); //where this is Form1
     myNew_another_class.teacher(sender, e);
}

This then is the constructor for your "another_class" as you had it.
public another_class (Form1 anytext_Form)
{
         this.anytext_Form = anytext_Form;
}

Answer: I don't think you state your question clearly. What is teacher method doing?
However, as mentioned by others, all control access modifier is Private, so you cannot just directly access it. You can try to change the access modifier in the property of the object, or create a property:
public class Form1 : Form {
    public String TextboxText {
        set { this.myTextbox.Text = value; }
        get { return this.myTextbox.Text; }
    }
}


Jest await not working/returning anything test is frozen

Question: I am trying to use await in my test and when I run the test runner the test becomes stuck and no test result is returned. Here is my code
describe("retrieveCandidate", () => {
  describe("when settings are found", () => {
    beforeEach(() => {
      configurationApi = new ConfigurationApi(BaseUrl);
    });

    afterEach(() => {
      configurationApi = undefined;
    });
    it("should return set of configuration values", () => {
       const configurationValueSet: IConfigurationValueSet | undefined =
         await configurationApi?.retrieveCandidate(controlConfigurationValueSet.specializationKey);
      expect(true).toEqual(true);
    });
  });

Answer: So in my testsetup file I had
jest.useFakeTimers();

This caused my async functions to never return anything and caused my test to be in a frozen state


Is there a way to display some content fields in a separate block?

Question: I would like to display some content fields in a separate block so that I can manage the position of these like other blocks and also put them near to other blocks such as the search widget.
I am using display suite for laying out the content but don't think that this will serve my requirement to position some content fields further away from the the main content. One specific example I have is displaying the content's taxonomy fields below the search widget (which is in a block).
Comment: Block reference
and
node reference might be options to consider.
Answer: You could create a view which selects the field you want from a node. Use contextual filters to get the Node Id in your view.
Comment: +1 thanks @Lance. I think Field as Block in another answer is what I will go for at the moment but thanks for your answer as it may be useful for other scenario and if I have needs beyond what Field as Block provides.
Answer: Field as Block is a really simple module that lets you display fields in blocks.
Beyond that, you may want to investigate Panels (and related modules) which is a much more powerful but also much more complicated solution.
Comment: I enabled the module but can't see the 'display as block' option in the managedisplay. Please advise.
Comment: Sorry @pjcdawkins I had to move from your accepted answer to yannickoo as display suite module does what I am looking for and more. Display suite apparently includes the same kind of fuctionality as field as block Also, I am already using display suite and this appears to be incompatible with field as block and given that display suite does this functionality anyway I have chosen that. See issue here: https://drupal.org/node/2032195#comment-7604303 However in consolation I have upvoted some of your other posts.
Answer: Oh no! Please no Field Blocks or CCK Blocks or Views. Just use Display Suite and enable the "Display Suite Extras" module so that you can create DS Regions. With DS Regions it's possible to create a new region which is exposed as a block.
Comment: This screencast is from the maintainer of Display Suite (swentel) – http://www.youtube.com/watch?v=y4wyjxyhbNA
Comment: I will give a +1 (and maybe change accepted answer to yours), if you have a link to a guide or point me to where I would turn this on - e.g. in the 'manage display' section for the content type? (I already have display suite extras enabled but can not see how I can use it to make some fields appear in a separate block so that I can control this separate block in admin/structure/blocks )
Comment: Found the answer - to turn on "region to block"  go to yoursite.com/admin/structure/ds/list/extras Then click the bottom tab 'other disabled' and check the 'region to block' check box and go from there. (where yoursite.com is your site - replace this with that)


Displaying image on point hover in Plotly

Question: Plotly allows you to display text fields when hovering over a point on a scatterplot. Is it possible to instead display an image associated with each point when the user hovers over or clicks on it? I am mostly just using the web interface, but I could instead push my ggplot from R.
Comment: Have you tried `ggiraph` package?
Comment: [Here](https://stackoverflow.com/questions/58897330/hover-image-in-plotly-r-chart-in-shiny-app/59032642#59032642) you can find an example using `shiny`.
Answer: Unfortunately, there is no easy way to display images on hover on plotly graphs at the moment.
If you are willing to learn some javascript, plotly's embed API allows you to customize hover (as well as click) interactivity.
Here is an example of a custom hover interaction showing images on top of a plotly graph. The javascript source code can be found here.
Answer: Images on hover is now available by Plotly lib. Here is a sample:

from dash import Dash, dcc, html, Input, Output, no_update
import plotly.graph_objects as go
import pandas as pd

# Small molcule drugbank dataset
# Source: https://raw.githubusercontent.com/plotly/dash-sample-apps/main/apps/dash-drug-discovery/data/small_molecule_drugbank.csv'
data_path = 'datasets/small_molecule_drugbank.csv'

df = pd.read_csv(data_path, header=0, index_col=0)

fig = go.Figure(data=[
    go.Scatter(
        x=df["LOGP"],
        y=df["PKA"],
        mode="markers",
        marker=dict(
            colorscale='viridis',
            color=df["MW"],
            size=df["MW"],
            colorbar={"title": "Molecular
Weight"},
            line={"color": "#444"},
            reversescale=True,
            sizeref=45,
            sizemode="diameter",
            opacity=0.8,
        )
    )
])

# turn off native plotly.js hover effects - make sure to use
# hoverinfo="none" rather than "skip" which also halts events.
fig.update_traces(hoverinfo="none", hovertemplate=None)

fig.update_layout(
    xaxis=dict(title='Log P'),
    yaxis=dict(title='pkA'),
    plot_bgcolor='rgba(255,255,255,0.1)'
)

app = Dash(__name__)

app.layout = html.Div([
    dcc.Graph(id="graph-basic-2", figure=fig, clear_on_unhover=True),
    dcc.Tooltip(id="graph-tooltip"),
])

@app.callback(
    Output("graph-tooltip", "show"),
    Output("graph-tooltip", "bbox"),
    Output("graph-tooltip", "children"),
    Input("graph-basic-2", "hoverData"),
)
def display_hover(hoverData):
    if hoverData is None:
        return False, no_update, no_update

    # demo only shows the first point, but other points may also be available
    pt = hoverData["points"][0]
    bbox = pt["bbox"]
    num = pt["pointNumber"]

    df_row = df.iloc[num]
    img_src = df_row['IMG_URL']
    name = df_row['NAME']
    form = df_row['FORM']
    desc = df_row['DESC']
    if len(desc) > 300:
        desc = desc[:100] + '...'

    children = [
        html.Div([
            html.Img(src=img_src, style={"width": "100%"}),
            html.H2(f"{name}", style={"color": "darkblue"}),
            html.P(f"{form}"),
            html.P(f"{desc}"),
        ], style={'width': '200px', 'white-space': 'normal'})
    ]

    return True, bbox, children

if __name__ == "__main__":
    app.run_server(debug=True)

More info: https://dash.plotly.com/dash-core-components/tooltip
Comment: Link massively helps!
Comment: Is it safe to say the that your approach only loads and shows the images on the `on hover` event, while using purely a [Adavance Hover Template](https://plotly.com/python/hover-text-and-formatting/#advanced-hover-template) would load all images to then show `on hover`?
Comment: @EduardoReis using the customs callbacks to display images will only get the REST image when the mouse is over the graphic node. I will suggest you to test advance hover template in debug mode to check if it will load all the images.  It don't seems to be a good approach to get all the images, I never put it to prove. When you get this answer may you could share the results with community


Access JSON data inside brackets - home({"a": { "prop1": "data", "prop2": "data"});

Question: I'm getting some result when calling to some service as below.
Call:

Response:
home({
      "a": {
       "prop1": "data",
        "prop2": "data"
      },
      "b": {
        "prop1": "data",
        "prop2": "data"
      }
});

How to access data of this result using JavaScript ?
Comment: What is the result of your service? This is just the call.
Comment: `home` function is defined?
Comment: reference: https://en.wikipedia.org/wiki/JSONP
Answer: This looks a lot like a JSONP response!
Have a read on what is JSONP (http://en.wikipedia.org/wiki/JSONP)

Answer: Solution:
Thank you for all your valuable answers. It happened to be a JSONP response.

References :
https://learn.jquery.com/ajax/working-with-jsonp/
http://www.sitepoint.com/jsonp-examples/
Answer: if it is a JSONP you have to define home function, for example:
var result;

window.home = function(data) {
  result = data;
}

then you can get props
result.a.prop1 // "data"


Chromatic number and vertex covering number

Question: For any graph $G=(V,E)$ let $\tau(G)$ be the minimum cardinality of a vertex cover of $G$. Let $\chi(G)$ denote the chromatic number of $G$.
Is there a graph $G$ with $\tau(G) < \chi(G) - 1$?
Answer: Let $S$ be a minimum vertex cover. Give every vertex of $S$ a different color. Finally give all vertices of $V-S$ the same, new color.
I trust, you can take it from here.
Comment: Beautiful, thanks!!


'Certificate types are not available' When creating computer certificate?

Question: Environment
Windows Server 2008 sp1
Xeon CPU E5430 @ 2.66 GHz
16.0 GB Ram
64-bit Operating System
1TB Disk Space
Server Role: SQL Server
Other Information: Joint to domain, Logged in user domain administrator
Issue
Steps that cause issue:
Create a computer certificate using mmc snap-in 'certificates' by right clicking on 'Certificates' folder Under 'root\Personal' tree, and clicking All Tasks -> Request New Certificate. Certificate Enrollment window appears, you verify you are connected to your network and you are logged onto the domain. Then Click Next, which leads to a window stating the issue:
"Certificate types are not available"
"You cannot request a certificate this time because no certificate types are available. If you need a certificate contact your administrator."
Wanted Solution
Create a certificate on this server, to implement SSL connection to MSSQL servers.
Comment: I am trying to create a self signed certificate.... on the local computer... for use with SQL...
Answer: You are following the right steps (http://support.microsoft.com/kb/316898/en-us), but the error likely means that you either have no enterprise certificate authority (CA) in the domain, or the CA is not accepting new certificate requests for some reason.  It may also be that your installed CA is not allowing generation of "Computer" certificate types.  This can be checked in the CA configuration.
The solution depends on whether you already have an enterprise CA set up and configured.  If not then you need to create one (there is guidance on the Microsoft technet site, but it's not trivial) or else use another way of generating self-signed SSL certificates such as one of the free downloadable tools.
Answer: in my setup i have 4 DCs and needed the certificate for LDAPS.
i successfully created a certificate on the DCs that has the CA installed, but on the others i, like you, got the "Certificate types are not available" error.
the problem was that these DCs didn't trust the CA.
i added the certificate to the trusted root CAs in the default domain policy, gpupdate on the DCs and it worked
Answer: I had the same problem manually requesting computer certificates although they worked automatically and there was no problem requesting user certificates.
I resolved the problem by changing IIS directory security settings to allow anonymous access for the PKI virtual directory only!
Answer: I recently had this same issue. Assuming you are running AD CS, to resolve the issue remove the Active Directory Enrollment Policy settings within the GPO directing the client on where to locate certificate enrollment servers, and then added the same settings back:

Computer Configuration > Policies > Windows Settings > Security Settings > Public Key Policies > Certificate Services Client - Certificate Enrollment Policy

Edit this setting:
Under Certificate Enrollment Policy List, remove the Active Directory Enrollment Policy. Then re-add it and set it as the default. Perform a GPUPDATE on the client which is unable to see the certificate templates and attempt again.
Comment: Had the same issue as well.  All I had to do was run `gpupdate /force` on the server where I was requesting a new certificate.  Problem solved.


Drupal 8 Link Autocomplete Filter by Bundle

Question: Does anyone know how to limit the autocomplete suggestions of Link Fields to only certain bundles -- not globally, but per Link Field instance? I nearly found a solution in customizing https://github.com/minnur/Alter-Entity-Autocomplete , but this is global for all autocompletes, and I need to get the calling Link Field instance somehow.
Answer: You can now use the following contributed module to solve the issue:
Link Field Autocomplete Filter

This module adds a Link Field configuration for filtering the allowed
  content types in the autocomplete field.
Answer: This is possible with hook form alter:
<code>function hook_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
  // if $form_id ==  'xyz'
  $form['field_mylink']['widget'][0]['uri']['#selection_handler']="default:node";
  $form['field_mylink']['widget'][0]['uri']['#selection_settings']=[
    'target_bundles'=>['article'=>'article', 'page'=>'page'], //etc
  ];

}
</code>


Android Volley: Cannot resolve symbol Volley

Question: I want to use Volley to send requests from my Android app.
I have included this in the build.gradle
dependencies {
    ...
   compile 'com.android.volley:volley:1.1.0'
}

I want to use:
requestQueue queue = Volley.newRequestQueue(this);

But neither requestQueue nor Volley can be resolved.
I have tried:
import com.android.volley;

But it also says that volley can't be resolved. I have done a gradle sync.
I have not downloaded anything. My understanding is that adding Volley to build.gradle takes the place of actually downloading the library?
Answer: The correct import is import com.android.volley.toolbox.Volley; (you can check the code here), and this has to be a Context object
Comment: Perfect, thank you! This will also help me with the other import statements that I need.
Comment: Do you know how to import StringRequest needed in Google's example: https://developer.android.com/training/volley/simple.html
Comment: `import com.android.volley.toolbox.StringRequest;`
Comment: I found I had to restart Android Studio after adding it to the dependencies in the gradle file. Nothing else worked until I restarted.
Answer: Thanks to Blackbelt's answer, I was able to import the following for Google's standard example https://developer.android.com/training/volley/simple.html
import com.android.volley.toolbox.Volley;
import com.android.volley.RequestQueue;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;

The this in
RequestQueue queue = Volley.newRequestQueue(this);

became
RequestQueue queue = Volley.newRequestQueue(getContext());

also thanks to Blackbelt's answer. I had to play around with where I could call getContext() for my code. I ended up checking if the queue has already been instantiated inside my first request and set it if it hasn't.
Answer: I ran into this problem today. Following works for me:
In Android Studio: Build -> Clean Project, and then Build -> Rebuild Project


Parse error: syntax error, unexpected end of file

Question: Estou com um erro ao executar um código PHP

( ! ) Parse error: syntax error, unexpected end of file in C:\wamp64\www\site\sucessoemail.php on line 35

O código é este
<?php
mysqli_connect("localhost", "root", "") or die(mysql_error());

if(isset($_POST['seunome']) && isset($_POST['suasenha']) && empty($_POST['seunome'] ==false) && empty($_POST['suasenha'] == false)){

  $seunome  = $_POST['seunome'];
  $suasenha = $_POST['suasenha'];

$sqli = "CREATE DATABASE" .$_POST['seunome'];

$geral = mysqli_query($sqli) or die("Errro ao criar");

?>

Comment: Está certo que o código é esse? Ele diz linha 35 no erro. Se for esse, verifique onde fecha a chave aberta no `IF`.
Answer: Falta uma chave no final do código
<?php
mysqli_connect("localhost", "root", "") or die(mysql_error());

if(isset($_POST['seunome']) && isset($_POST['suasenha']) && empty($_POST['seunome'] ==false) && empty($_POST['suasenha'] == false)){

  $seunome  = $_POST['seunome'];
  $suasenha = $_POST['suasenha'];
} //Coloquei aqui, mas não sei se deveria ser mais abaixo

$sqli = "CREATE DATABASE" .$_POST['seunome'];
$geral = mysqli_query($sqli) or die("Errro ao criar");

?>

Comment: essa chave eu ja tentei da o mesmo problema
Comment: Jovem, a chave. Tá comentado no código.
Comment: sim ja coloquei ela antes, da  o mesmo problema.
Comment: Bom, então tá faltando informações na sua pergunta. Provavelmente tá faltando fechar mais chaves. Sem mais detalhes não tem como saber.


The message can not reach the email

Question: I'm trying to build a contact form in my website, I'm using asp.net with C#, when I submit the message it does not reach the Email, is it because I'm using local server? or there are mistakes in my code? I got this error message in the catch section: "Your message failed to send, please try again."
this is the code behind page C#
<code>try
{
    //Create the msg object to be sent
    MailMessage msg = new MailMessage();
    //Add your email address to the recipients
    msg.To.Add("email@example.com");
    //Configure the address we are sending the mail from
    MailAddress address = new MailAddress("email@example.com");
    msg.From = address;
    //Append their name in the beginning of the subject
    msg.Subject = txtName.Text + " :  " + ddlSubject.Text;
    msg.Body = txtMessage.Text;

    //Configure an SmtpClient to send the mail.
    SmtpClient client = new SmtpClient("smtp.gmail.com", 587);
    client.EnableSsl = true; //only enable this if your provider requires it
    //Setup credentials to login to our sender email address ("UserName", "Password")
    NetworkCredential credentials = new NetworkCredential("firstname.lastname@example.com", "*");
    client.Credentials = credentials;

    //Send the msg
    client.Send(msg);

    //Display some feedback to the user to let them know it was sent
    lblResult.Text = "Your message was sent!";

    //Clear the form
    txtName.Text = "";
    txtMessage.Text = "";
}
catch
{
    //If the message failed at some point, let the user know
    lblResult.Text = "Your message failed to send, please try again.";
}
</code>
this is the exception

System.Net.Mail.SmtpException: The SMTP server requires a secure
  connection or the client was not authenticated. The server response
  was: 5.5.1 Authentication Required. Learn more at at
  System.Net.Mail.MailCommand.CheckResponse(SmtpStatusCode statusCode,
  String response) at System.Net.Mail.MailCommand.Send(SmtpConnection
  conn, Byte[] command, MailAddress from, Boolean allowUnicode) at
  System.Net.Mail.SmtpTransport.SendMail(MailAddress sender,
  MailAddressCollection recipients, String deliveryNotify, Boolean
  allowUnicode, SmtpFailedRecipientException& exception) at
  System.Net.Mail.SmtpClient.Send(MailMessage message) at
  Default2.btnSubmit_Click(Object sender, EventArgs e) in
  c:\Users\looly\Documents\Visual Studio
  2015\WebSites\WebSite6\Default2.aspx.cs:line 46
Comment: We want to know the correct exception so just remove label inside the catch block.then Wrote exception..Catch(exception ex){throw ex};
Comment: I get $10 if the exception is pretty much `The server response was: 5.5.1 Authentication Required.`
Comment: At first glance your code seems OK. Have you configured Gmail correctly? It often blocks sending from apps it considers unsecured. Look if you have 2 step enabled, you might need need to generate an app specific password [SEE HERE](https://www.google.com/settings/security/lesssecureapps)
Comment: Post your exact exception.
Comment: I updated the post, equalsk you are right :D
Comment: @AfnanHumdan...Google may block sign in attempts from some apps or devices when you try to login from some app. As I said checking this answer may help you: http://stackoverflow.com/a/32475872/2946329
Comment: @AfnanHumdan check the updated answer.
Answer:
The server response was: 5.5.1 Authentication

Based on this error.you check the following steps.

Enter the correct login password.
To remove 2-Step Verification.
You have to enable login from other timezone / ip for your google
account.To do this follow the click here
and allow access by clicking the continue button.
Go to security settings at the following Click here and enable less secure apps . So that you will be able to login from all apps.

The message can not reach the email


How can I create database in the project folder in Django?

Question: I have a very simple website in Django for which I do not want to create an app separately for the purpose. So the models and admin.py file does not come while creating the django project. When we create an app, those files are automatically created which we have to register in Setting.py.
But my project is very short and I do not want to create an extra app for the purpose. Is there any way to create those database model in the project folder itself?
What I tried :
<code>1. created a models.py file : wrote my database model in it
2. also created an admin.py file and registered the database model
3. In the setting.py file added the project folder itself
</code>
But that does not seem to work because when I am trying to create migration its displaying me no changes detected.
Comment: I understand that your project is very simple, but what's the problem to create a app (subfolder)?
Comment: No problem, I am just asking is it possible
Comment: I think if you follow the default structure right now (without workarounds), it's gonna be easier and safe in the future if your project becomes bigger.
Answer: Django project != Django app. You have to do it the django-way, create the Django project then create the django app that you register with the django project.


How much data do I need in spatial hotspot analysis?

Question: I'm now doing a project about spatial hotspot analysis. I read many literatures, however, I can't find any papers tell how they determine the data size they used.
I mean, suppose we have crime location data, in some small cities, maybe our data size is relatively small. Under this condition, is our hotspots reliable? I though there must be a minimum requirement for data size in spatial hotspot analysis. Anyone knows how to determine the data size?
Thank you very much!
Answer: You need to read the original paper by Getis and Ord that introduces the G statistics:
Getis A, Ord JK. 1992. The analysis of spatial association by use of distance statistics. Geographical Analysis 24:189-206.
See the paragraph that begins at the bottom of page 191.
To paraphrase, the sampling distribution of $G_i$ under the null hypothesis (of complete spatial randomness..."CSR") is asymptotically normal. The expected value is based on the number of points $j$ that are connected to point $i$ relative to the total number of points. When the distance is sufficiently small such that the expected value is small, normality is lost; likewise, normality is lost when all points $j$ are connected to $i$.
This suggests that it is OK to use the normal approximation when you have a lot of points and your expected values are not too close to zero or one. This also suggests that this decision is somewhat context dependent: it depends on the number of points and their configuration.
You can also use a permutation test to assess the significance of $G_i$ or $G_i^*$. If the P-values obtained based on the normal approximation are wildly different from those obtained by the permutation test, it might suggest that your expected values are violating the assumption of the normal approximation.


Ruble currency symbol missing in a string in ios 13

Question: After updating ios to 13 version I've received an issue - ruble currency is missing in a string where it is using. I use Unicode to show the ruble symbol (const EXAMPLE_STRING = 'sometext\u00A0\u20BD';) and I can't use HTML or CSS code, because I have a constant string which insert in different places. So, in devtools everything is ok, but in a view - an empty square. I understand that it's a new ios, but may be someone was face with this issue? Many thanks for answering.
I tried to add a Helvetica font, because I used only a San Francisco font, but it didn't help. I also tried to insert just ₽ - had nothing as the result.
I used - font: 15px/1 SF-Regular, Helvetica-Medium, sans-serif;
Answer: I solved this problem - just change a font to Helvetica Neue and the ruble currency starts work correctly.
Comment: There is such a font "Helvetica Heue"
Comment: fixed the font name to Helvetica Neue


Como passar dois argumentos na função onclick do JavaScript, programando em PHP?

Question: Eu tenho um botão que gero com AJAX e nesse mesmo botão tem um evento onclick, e quero passar dois argumentos para ele, porém estou tendo bugs com ele.
Código PHP:
 echo ' <button type="button" class="btn btn-link btn-comentario-reposta" id="botao-esconde-resposta-'.$_POST['id'].'"
            onclick="acao_botao_esconde_resposta('.$_POST['id'].','. $btn_mostrar_resposta .')">Esconder respostas</button>';

Aí mostra isso onde era pra estar o botão Esconder respostas.
Comment: esse `echo` é resultado de seu ajax ?
Comment: o echo é que vai ser retornado para o ajax escrever no html.
Answer: O seu problema é que faltou escapar as '' dos seus argumentos, corrigindo o seu código ele fica assim :
echo ' <button type="button" class="btn btn-link btn-comentario-reposta" id="botao-esconde-resposta-'.$_POST['id'].'"
            onclick="acao_botao_esconde_resposta(\''.$_POST['id'].'\',\''. $btn_mostrar_resposta .'\')">Esconder respostas</button>';

Como funciona :
Para escapar algum caracter especial como "" as aspas ou  '' aspas simples que usamos para passar argumentos dentro das funções usamos a \ barra invertida para que no código ele considere o caracter como parte da string, um exemplo que pode esclacer melhor é o seguinte :
$id = $_POST['id'];
$email = $_POST['email'];
$html = '<button id="btn-'.$id.'" onclick="func_teste('.$id.','.$email.')"></button>';
echo $html;

Esse exemplo assima seria o seu caso onde acontece o erro e porque  ? Bem quando esse código for para o html ele vai ser gerado dessa maneira por exemplo:

<button id="btn-1" onclick="func_teste(1,firstname.lastname@example.com)"></button>

Como podemos ver a passagem de parametro está errada e por isso seu código está imprimindo )">Esconder respostas para evitar esse problema tem de colocar as \"\" aspas ou  \'\' aspas simples para fazer seu escape e assim elas se tornam literal.
$id = $_POST['id'];
$email = $_POST['email'];
$html = '<button id="btn-'.$id.'" onclick="func_teste(\''.$id.'\',\''.$email.'\')"></button>';
echo $html;

E o resultado será assim :

<button id="btn-1" onclick="func_teste('1','email@example.com')"></button>

Comment: mude os dois `.$_POST['id'].` para .$_POST["id"].
Comment: É isso mesmo, faltou escapar as aspas simples. +1
Comment: Qual seria o significado do uso da barra invertida e aspas simples?
Comment: @MuriloHass eu editei para responder ao seu comentário, desculpe se a edição n ficou muito boa mas é q eu fiz pelo celular ja que não estou perto de um computador
Comment: Eu entendi obrigado pela ajuda.
Answer: Pessoalmente acho que no seu caso é mais simples escrever o html como html e colocar apenas o que vem de php com <?=
<?php
$id = $_POST["id"];
?>
<button type="button" class="btn btn-link btn-comentario-reposta"
    id="botao-esconde-resposta-<?=$id?>"
    onclick="acao_botao_esconde_resposta('<?=id?>','<?=$btn_mostrar_resposta?>')">
          Esconder respostas
</button>


grep string from file in R

Question: When I use the command below to grep my target string px
x <- grep('px', readLines("file.txt"))

[]an$px

[1] 2 12  # x returns 2 and 12th line

But when I want to grep the string as [1]$px
x <- grep('[1]$px', readLines("file.txt"))

x returns integer(0)
My question is, how can I get 2 and 12 as well rather than integer(0) if my targeted string is [1]$px?
Comment: Please cut and paste the text of your file (or part of it) rather than posting an image link!
Answer: Brackets carry special meaning in regular expressions.  Add fixed=TRUE to your parameters in grep tells it to interpret the pattern as is.  The other option is to escape the brackets but if you don't need the full power of regular expressions and just want to search for a specific string then using fixed=TRUE is the better option anyways.
x <- grep('[[1]]$px', readLines("file.txt"), fixed = TRUE)

grep string from file in R


How to copy text to clipboard without using flash?

Question: I am using the below button to read data from a web service and display it in a prompt window. The problem I am having is newer versions of Chrome and FireFox and now IE 11 do not allow data to be copied to clipboard.
I have used Postman to test the end point /Areas/Journal/Handlers/CSVString.ashx it is returning data. but the below code is showing an empty box
Is there a way to copy data to clipboard without using flash ?
Any ideas why I am getting an empty window in IE when I run the below code ?
<input id="htmlCopyCSV" type="button" value="Copy" onclick="$.get('/Areas/Journal/Handlers/CSVString.ashx', function (data) { alert(data);window.prompt('Copy to clipboard: Ctrl+C, Enter', data); });" />

Answer: Bind this function to the copy button
function myFunction() {
  var copyText = document.getElementById("myInput");
  copyText.select();
  document.execCommand("Copy");
  alert("Copied the text: " + copyText.value);
}


Foreach remover images duplicadas

Question: Tenho código abaixo que puxa as imagens dos produtos do carrinho de compras do magento, porém ele está exibindo duplicado, ou seja, quando ele lista as imagens ele exibe duas vezes a mesma imagem.
<?php
    $items = Mage::getSingleton('checkout/session')->getQuote()->getAllItems() ;

        foreach($items as $item) {
            echo 'helper('catalog/image')->init($item->getProduct(), 'small_image').'"/>';

        }

?>

Gostaria de exibir apenas umas vez, acabar com esse loop.
Answer: array_unique($array)
<?php
    $items = Mage::getSingleton('checkout/session')->getQuote()->getAllItems() ;

    $items = array_unique($items);

        foreach($items as $item) {
            echo 'helper('catalog/image')->init($item->getProduct(), 'small_image').'"/>';

        }

?>

Comment: Cara vlw pela ajuda, mais mesmo assim não funcionou ainda, ele continua duplicando.
Comment: Então o problema está antes. Ao adicionar o produto no carrinho é preciso adicionar uma vez apenas.
Comment: Então também pensei nisso, mais está certo,  problema é que ele duplicando apenas imagens, por exemplo se tem um produto ele exibe uma imagem só e se tem dois produtos ele lista duas vezes e se tenho 3 produtos ele vai lista 3 vezes.
Comment: Faz um `count($items)` em baixo do `$items`. É pra trazer a quantidade de produtos no carrinho.
Comment: Poderia me ajudar em como fazer esse count
Comment: que estou com pouco de dificuldade nisso

Foreach remover images duplicadas


ZF: Problema ao gerar PDF (com mPDF) a partir de texto (html) criado com WYSIWYNG (plugin elrte)

Question: Galera,
Estou com problema na geração de PDF em texto que contenha tag
. Neste caso estou criando um módulo para geração de contratos.
O texto vem do banco e é criado a partir de um WYSIWYNG (plugin elrte).
Formatações na tabela não são renderizadas no PDF, causando empilhamento das palavras contidas na tabela.
Para geração do PDF estou utilizando mPDF.
Alguém já passou por isso? Alguma solução?
$mpdf = new mPDF();

$mpdf->WriteHTML($lsConteudo); //$lsConteudo vem do BD.

$mpdf->Output('contrato.pdf' , 'D');

Comment: eu estou com um problema parecido atualmente, mas diminui os problemas consideravelmente na geração dos PDFS removendo o CSS padrão que ele define no **config.php**
Comment: Vc removeu no próprio arquivo Leandro, ou existe algum método para desabilitar o carregamento?
Comment: removi manualmente no arquivo config.php do mPDF, tem um array lá com uns estilos padrão que ele inclusive aplica na hora que você manda gerar o PDF, o que implica nos problemas que você teve. mas nem tudo ele gera corretamente.
Comment: Entendi. Vou tentar remover e ver se tenho um resultado melhor.
Comment: sim, olha o exemplo no fim do código http://pastebin.com/DsaXUPyf
Comment: Não funcionou neste caso Leandro, mesmo retirando a formatação default.
Comment: dê uma olhada na documentação http://mpdf1.com/manual/index.php?tid=34, não sei se vai te ajudar, no caso aqui, o pessoal resolveu fazer com outro gerador de pdf, chamado **snappy** https://github.com/KnpLabs/snappy
Comment: É a documentação dele é mto vaga... não dá mtos exemplos de utilização de tabelas.
Comment: com tabelas ele se mostrou horrível.
Comment: Pessoal, ainda não consegui achar uma solução para esta questão preciso de mais sugestões... alguém?
Comment: conseguiu? se nao a gente procura uma solução juntos! =)
Comment: Uso o mPDF com o Smarty e chamo o css via link rel () no meu template, e funciona perfeitamente. já tentou colocar a referência ao css direto?
Answer: Transformar HTML em PDF nem sempre é tão simples, pois é necessário renderizar o conteúdo e então depois convertê-lo. As soluções que tentam converter o HTML para PDF baseado no style ou pressuposições simplistas tendem a ter muitas limitações, como com as tags table, img, etc.
A melhor alternativa provavelmente seja usar um renderizador HTML webkit que converta para PDF ou PNG, como preferir. O http://wkhtmltopdf.org/ é um dos melhores, temos usado há anos em um ambiente bem agressivo de conversão de tudo o que é tipo de documento, inclusive com imagens, CSS, tables, cabeçalhos e rodapés, margens customizadas, tudo:
1) Instale o wkhtmltopdf no servidor.
2) Crie um script (PHP, Perl, como tu quiser) que receba o HTML, invoque o comando wkhtmltopdf e dê a saída application/pdf de volta para o cliente.
3) Na página web, via javascript dê um POST do conteúdo HTML para o script criado no server-side.
Se já estiver no server-side e usar PHP, já existe inclusive um projeto que faz esse port: https://github.com/mikehaertl/phpwkhtmltopdf
Eu fiz um IPC direto com o executável wkhtmltopdf para ter controle total não deu mais de 10 linhas (no meu caso em PERL). Em PHP deve ser bem simples também.
Answer: A biblioteca HTML2PDF consegue apresentar alguns resultados bem interessantes mesmo com HTMLs envolvendo tabelas. Acho que você poderia tentar usá-la e ver se atende suas necessidades.
Um dos problemas de editores WYSIWYNG é que eles costumam "sujar" o HTML, dificultando o trabalho deste tipo de conversor.
Link da biblioteca
http://html2pdf.fr/en/default


Is there a way to supress particular messages or a class of messages on the screen?

Question: Is there a way of suppressing a particular class of messages from being displayed on the screen, such as the one displayed below?

Deprecated function: Methods with the same name as their class will
  not be constructors in a future version of PHP; GeSHi has a deprecated
  constructor in require_once() (line 837 of
  {site_root}/sites/all/modules/libraries/libraries.module)

It comes up all the time and it belongs  to the php and severity debug class of error messages.
I don't want to turn off the display of messages on the screen, just a particular class of message which come so often they are a nuisance.
It is possible to toggle their display on and off when required but still log them to the database?
Answer: You can use Disable Messages or look how they do it. Among other features you'll get a permission to specifically hide all messages of a given type from any role.

Gives a site owner options to disable specific messages shown to end
  users. The core drupal message system as offered by drupal_set_message
  is an excellent way for modules to send out messages to the end users.
  However not all drupal site owners are keen to show all the messages
  sent out by drupal core and all modules to their users. This module
  gives site administrators a reasonably powerful way to filter out
  messages shown to the end users.
Features

Filter out messages that match a full text string exactly.
Filter out messages that match a regular expression.
Permissions to specifically hide all messages of a given type from any role.
Disable all filtering for specific users.
Disable all filtering for specific paths.
Apply filtering only for specific paths.
Debug system to get messages in the HTML without showing it to the end users.

Apart from that I found this little gem:
function MYMODULE_preprocess_status_messages(&$variables) {

  // The exact message you want to filter.
  $message = 'Further instructions have been sent to your e-mail address.';

  if (isset($_SESSION['messages'])) {
    foreach ($_SESSION['messages'] as $type => $messages) {

      // Limit it to a certain type if you want to.
      if ($type == 'status') {

        $pos = array_search($message, $messages);

        if ($pos !== FALSE) {
          unset($_SESSION['messages'][$type][$pos]);
        }
      }
    }
  }
}

Source: https://api.drupal.org/comment/51793#comment-51793

Here's another alternative to filter all messages of a certain type.
/**
 * Implements hook_page_build().
 */
function MYMODULE_page_build(&$page) {

  $hide_types = ['status', 'error', 'warning'];

  if (isset($_SESSION['messages'])) {
    foreach ($_SESSION['messages'] as $type => $messages) {
      if (in_array($type, $hide_types)) {
        unset($_SESSION['messages'][$type]);
      }
    }
  }
}

You could also easily get the $account = global $user and check its roles to tighten this request if you need.

Last but not least – not recommended - you can remove or if-wrap the <?php print $messages; ?> variable in your theme's page.tpl.php. But editing templates for this kind of logic should be considered bad practice.
Comment: I have this module on my system, but it seems to be applied to end users only,but not for the administrator, which is what I am really looking for.
Comment: @vfclists – Permissions are set role-wise. Isn't this sufficient?
Comment: I will look into that
Comment: @vfclists – Added some snippets to be used in a custom module. Placing them into your theme's `template.php` might work as well.


REST - Http x Json

Question: Fiz algumas pesquisas e tenho alguma dúvidas sobre REST:

Http é Rest?
JSON e XML são apenas o formato de retorno de uma operação Rest?
REST x Web Services: são a mesmas coisas?
SOAP seria o oposto de HTTP?

Agradeço quem puder me ajudar.
Comment: Acho que essa pergunta responde o primeiro item: [O que é REST e RESTful?](http://pt.stackoverflow.com/q/45783/91)
Comment: Essa não bate na trave igual a primeira => [REST e HTTP são a mesma coisa?](http://pt.stackoverflow.com/q/95836/91)
Comment: Comentário muito útil @rray.
Comment: Mas ainda fiquei na dúvida, Http é Rest? E as demais questões, alguém?
Comment: Se eu tenho um arquivo JSP que retorna um JSON, ele não necesseriamente é um REST?
Answer: TL;DR:

Não
Não
Não
Não

Versão não tão curta:

Http é Rest?

HTTP é um protocolo de aplicações que especifica o comportamento e tráfego de hipertexto; REST é um estilo arquitetural cujo foco são elementos de dados. REST pode ser implementado sobre HTTP, porém HTTP pode ser utilizado para implementar várias outras arquiteturas - SOAP, por exemplo.

JSON e XML são apenas o formato de retorno de uma operação Rest?

Enquanto que a grande maioria das implementações atuais de REST utilizam JSON e XML como formatos de troca de dados com consumidores, eles não são apenas utilizados em estruturas REST. Qualquer processo que necessite de serialização de dados (arquivamento em disco ou autenticação, por exemplo) pode se beneficiar destes dois formatos.

REST x Web Services: são a mesmas coisas?

Um WebService pode ser implementado contendo endpoints REST, porém não exclusivamente. Como mencionado anteriormente, endpoints SOAP (entre outros) são práticas válidas.

SOAP seria o oposto de HTTP?

Não. Sendo SOAP um formato baseado em XML, a grande maioria das implementações ocorrem sobre HTTP.
Comment: @stringNome um alerta em relação a edição: os itens que você removeu na edição são relevantes, e podem até alterar a intenção do autor, então foi rejeitada. Quando for editar, procure fazer edições que deixem mais clara do conteúdo, sem que afete  a intenção do autor naquela resposta/pergunta.
Comment: @LuizaCH não necessariamente - um resultado JSON não implica em uma API REST. Várias APIs do Google expõem dados em JSON, porém não representam um objeto de dados nem implementam REST. Exemplo: http://maps.googleapis.com/maps/api/geocode/json?latlng=40.714224,-73.961452&sensor=true
Comment: @LuizaCH isso irá depender das tecnologias que você está utilizando na sua solução, e talvez fuja um pouco do tópico desta pergunta. Se desejar, crie uma nova pergunta e mostre-nos até onde você já chegou.
Comment: Se eu tenho um arquivo JSP que retorna um JSON, ele não necesseriamente é um REST?
Comment: Como posso chamar um arquivo de JSP que retorna dados via JSON?

REST - Http x Json


Shortening this if condition

Question: A few days ago I asked a question that might be a little unclear. Now I have written code that might illustrate the question better. Please look at the code below first:
int d;
d = DateTime.Today.Day;
if (d==1)
{
    hyperlinkButton1.Background=new SolidColorBrush(Colors.Black);
}
else if (d==2)
{
    hyperlinkButton2.Background=new SolidColorBrush(Colors.Black);
}
else if (d==3)
{
    hyperlinkButton3.Background=new SolidColorBrush(Colors.Black);
}
else if (d==4)
{
    hyperlinkButton4.Background=new SolidColorBrush(Colors.Black);
}
else if (d==5)
{
    hyperlinkButton5.Background=new SolidColorBrush(Colors.Black);
}
else if (d==6)
{
    hyperlinkButton6.Background=new SolidColorBrush(Colors.Black);
}
else if (d==7)
{
    hyperlinkButton7.Background=new SolidColorBrush(Colors.Black);
}
else if (d==8)
{
    hyperlinkButton8.Background=new SolidColorBrush(Colors.Black);
}
else if (d==9)
{
    hyperlinkButton9.Background=new SolidColorBrush(Colors.Black);
}
else if (d==10)
{
    hyperlinkButton10.Background=new SolidColorBrush(Colors.Black);
}
else if (d==11)
{
    hyperlinkButton11.Background=new SolidColorBrush(Colors.Black);
}
else if (d==12)
{
    hyperlinkButton12.Background=new SolidColorBrush(Colors.Black);
}
else if (d==13)
{
    hyperlinkButton13.Background=new SolidColorBrush(Colors.Black);
}
else if (d==14)
{
    hyperlinkButton14.Background=new SolidColorBrush(Colors.Black);
}
else if (d==15)
{
    hyperlinkButton15.Background=new SolidColorBrush(Colors.Black);
}
else if (d==16)
{
    hyperlinkButton16.Background=new SolidColorBrush(Colors.Black);
}
else if (d==17)
{
    hyperlinkButton17.Background=new SolidColorBrush(Colors.Black);
}
else if (d==18)
{
    hyperlinkButton18.Background = new SolidColorBrush(Colors.Black);
}
else if (d==19)
{
    hyperlinkButton19.Background=new SolidColorBrush(Colors.Black);
}
else if (d==20)
{
    hyperlinkButton20.Background=new SolidColorBrush(Colors.Black);
}
else if (d==21)
{
    hyperlinkButton21.Background=new SolidColorBrush(Colors.Black);
}
else if (d==22)
{
    hyperlinkButton22.Background=new SolidColorBrush(Colors.Black);
}
else if (d==23)
{
    hyperlinkButton23.Background=new SolidColorBrush(Colors.Black);
}
else if (d==24)
{
    hyperlinkButton24.Background=new SolidColorBrush(Colors.Black);
}
else if (d==25)
{
    hyperlinkButton25.Background=new SolidColorBrush(Colors.Black);
}
else if (d==26)
{
    hyperlinkButton26.Background=new SolidColorBrush(Colors.Black);
}
else if (d==27)
{
    hyperlinkButton2.Background=new SolidColorBrush(Colors.Black);
}
else if (d==28)
{
    hyperlinkButton28.Background=new SolidColorBrush(Colors.Black);
}
else if (d==29)
{
    hyperlinkButton29.Background=new SolidColorBrush(Colors.Black);
}
else if (d==30)
{
    hyperlinkButton30.Background=new SolidColorBrush(Colors.Black);
}
else
{
    hyperlinkButton31.Background=new SolidColorBrush(Colors.Black);
}

My question (as a beginner) is this: is there any way in C# to shorten this condition by making the application determine which hyperlinkbutton background it has to change depending on the value of d?
Answer: Define an array of the relevant controls, and use the integer to key into the array, remembering that arrays are 0-based and not 1-based.
var buttons = new [] {
    hyperlinkButton1,
    hyperlinkButton2,
    hyperlinkButton3,
    hyperlinkButton4,
    hyperlinkButton5,
    hyperlinkButton6,
    hyperlinkButton7,
    hyperlinkButton8,
    hyperlinkButton9,
    // ...
}

//....

buttons[DateTime.Today.Day-1].Background=new SolidColorBrush(Colors.Black);

Answer: The array based approach is a good alternative at a general level to the multiple if statements but since this is also tagged as Silverlight, you might be interested in taking advantage of the FrameworkElement.FindName Method if you can rely on the convention of naming the HyperlinkButtons with a common prefix.
var hyperlinkButton = this.FindName("hyperlinkButton" + DateTime.Now.Day) as HyperlinkButton;
if (hyperlinkButton != null)
{
    hyperlinkButton.Background = new SolidColorBrush(Colors.Black);
}

Comment: Thanks for the help, this has really make my life easier ;)
Answer: switch(d)
{
case 1: doThings(); break;
case 2: doThings2(); break;
case 3:
    doSomeThings();
    doMoreThings();
    break;
default:
    runThingsIfDIsNotListed();
    break;
}

etc.

Shortening this if condition


Using a Resource from a Nested Stack in Another Nested Stack with DependsOn

Question: I have been refactoring what has become a rather large stack because it is brushing up against size limits for CloudFormation scripts on AWS. In doing so I have had to resolve some dependencies (typically using Outputs) but I've run into a situation that I have never run into before...
How do I use a resource created in one nested stack (A) in another nested stack (B) when using DependsOn?
This question is a duplicate question but the answer does not fit because it doesn't actually resolve the issue I have, it takes a different approach based on that particular user's needs.
Here is the resource in nested stack A:
EndpointARestApi:
    Type: AWS::ApiGateway::RestApi
    Properties:
      Body:
        Fn::Transform:
          Name: 'AWS::Include'
          Parameters:
            Location: !Join ['/', [ 's3:/', !Ref SharedBucketName, !Ref WorkspacePrefix, 'endpoint.yaml' ]]

And here is the DependsOn request in stack B:
EndpointUserPoolResourceServer:
    Type: Custom::CognitoUserPoolResourceServer
    DependsOn:
      - EndpointARestApi
      - CustomResource ## this resource is in the same stack and resolves properly

This occurs with one other resource I have in this stack so I am hoping that I can do this easily. If not, I believe I would have to refactor some more.
Comment: DependsOn work only for resources in same stack. You can't use it across different stacks or between nested stacks.
Comment: Another possibility could be to add a `DependsOn: Stack A` attribute to the CloudFormation resource for stack B in the primary stack. This way, stack B will be created after stack A.
Comment: @Marcin can I put the resource in the primary CFN and have it used by nested stacks?
Comment: Yes, you can pass parameters to your nested stacks. These parameters can be based on the resources from the primary template.
Comment: @berenbums Yes! Hopefully I can test that tomorrow.
Answer: As suggested in comments I moved the DependsOn statement up to the primary CFN script in the resource requiring the dependency and made sure the dependency was on the other resource, not the nested resource, like this:
Primary
  ResourceA
  ResourceB
    DependsOn: ResourceA

Which ends up looking like this in the CloudFormation script:
EndpointUserPoolResourceServer:
    Type: "AWS::CloudFormation::Stack"
    DependsOn:
      - EndpointARestApiResource
    Properties:
      Parameters:
        AppName: !Ref AppName
        Environment: !Ref Environment
        DeveloperPrefix: !Ref DeveloperPrefix
        DeployPhase: !Ref DeployPhase


Popular DataGridView Editável C#

Question: Fiz um Form de edição de Tipos de Produtos onde ele tem um UserControl com a lista de Tipos de Campos Adicionais.
No método de adicionar está tudo certo.
No UserControl tem um DataGridView editável onde criei um DataGridViewTextBoxColumn e um DataGridViewComboBoxColumn visíveis.
Eu populo o ComboBox com os tipos de formatos de campos disponíveis no banco, é só o que o usuário pode selecionar (String, Int32 etc).
Meu problema é popular o DataGridView com os dados do Model para edição.
Eu utilizo um Repository para receber todos os dados do banco retornando um Model.
Todas as pesquisas que fiz apontam para a utilização de instrução SQL diretamente no Formulário. O que não posso fazer para não sair do padrão escolhido. (é um misto de MVVM com MVC) feito com o  pouco conhecimento que ainda tenho. "tá uma verdadeira bagunça mas não vou entrar nesse mérito".
TipoProdutoListUC.cs:
    //chamado do formulário para edição do Tipo de Produto
    //mesmo formulário utilizado para Edit e Add
private void btnEdit_Click(object sender, EventArgs e)
        {
            this.TipoProdutoModel = _tipoProdutoServices.GetById(int.Parse(this.dgvTiposProdutos.CurrentRow.Cells[0].Value.ToString()));
            TipoProdutoAddForm tipoProdutoForm = new TipoProdutoAddForm(this.CatalogoForm, this);
            tipoProdutoForm.Text = "Editando Tipo de Produto";
            tipoProdutoForm.TipoProdutoModel = this.TipoProdutoModel;
            tipoProdutoForm.CatalogoModel = this.CatalogoModel;
            tipoProdutoForm.StartPosition = FormStartPosition.CenterScreen;
            tipoProdutoForm.ShowDialog();
            this.TiposProdutosListUC_Load(sender, e);
        }

TipoProdutoAddForm.cs:

private void LoadUserControlCamposAdicionais()
        {
            camposAdicionais = new CamposTiposProdutosListUC(this);
            camposAdicionais.TipoProdutoModel = this.TipoProdutoModel;
            panelCampos.Controls.Clear();
            panelCampos.Controls.Add(camposAdicionais);
            camposAdicionais.Dock = DockStyle.Fill;
        }

Chamando o método Add or Update
//a função ADICIONAR é feita todo no TipoProdutoAddForm.
//Quero fazer a função Update em seguida. Também toda nele.
       private void btnSalvar_Click(object sender, EventArgs e)
        {
            if (ValidateChildren(ValidationConstraints.Enabled))
            {
                if (this.TipoProdutoModel.TipoProdutoId != 0)
                {
                    try
                    {

                        TipoProdutoUpdate();
                        CampotipoUpdate();
                    }
                    catch (Exception)
                    {
                        MessageBox.Show("Não foi possível atualizar o Tipo de Produto", "Atualizando Tipo de Produto");
                    }
                }
                else
                {
                    try
                    {
                        this.TipoProdutoModel = TipoProdutoAdd();
                        this.ListaCamposAdicionais = CampoTipoAdd();
                        MessageBox.Show($"Tipo de Produto Adicionado com sucesso", "Adicionando Tipo de Produto");

                    }
                    catch (Exception)
                    {
                        MessageBox.Show("Não foi possível adicionar o Tipo de Produto");
                    }
                }

            }
        }

Método TipoProdutoAdd()
        private TipoProdutoModel TipoProdutoAdd()
        {
            TipoProdutoModel returnedModel = new TipoProdutoModel();

            this.TipoProdutoModel = new TipoProdutoModel()
            {
                CatalogoId = this.CatalogoModel.CatalogoId,
                Descricao = this.textTipoProduto.Text
            };

            bool operationSucceeded = false;
            string dataAccesStatusJsonStr = string.Empty;
            string formattedJsonStr = string.Empty;

            try
            {
                returnedModel = _tipoProdutoServices.Add(this.TipoProdutoModel);

            }
            catch (DataAccessException e)
            {
                operationSucceeded = e.DataAccessStatusInfo.OperationSucceeded;
                dataAccesStatusJsonStr = JsonConvert.SerializeObject(e.DataAccessStatusInfo);
                formattedJsonStr = JToken.Parse(dataAccesStatusJsonStr).ToString();
                MessageBox.Show(formattedJsonStr, "Não foi possível adicionar o Tipo de Produto", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

            if (operationSucceeded)
            {
                MessageBox.Show("Registro Salvo com sucesso", "Salvando Tipo  do Distribuidor", MessageBoxButtons.OK, MessageBoxIcon.Information);

            }

            return returnedModel;
        }

Método CampoTipoAdd()
        private List<CampoTipoProdutoModel> CampoTipoAdd() //que que eu vou fazer com a lista retornada???
        {
            List<CampoTipoProdutoModel> modelList = new List<CampoTipoProdutoModel>();
            DataGridViewRowCollection rowsCamposAdicionais;
            rowsCamposAdicionais = this.camposAdicionais.dgvCampos.Rows; //peguei as linhas do DATAGRID
                                                                         //modelList = camposAdicionais.dgvCampos.Columns.

            bool operationSucceeded = false;
            string dataAccesStatusJsonStr = string.Empty;
            string formattedJsonStr = string.Empty;

            foreach (DataGridViewRow row in rowsCamposAdicionais)
            {
                if (row.Cells["ColumnNome"].Value != null)
                {
                    CampoTipoProdutoModel model = new CampoTipoProdutoModel();
                    model.Nome = row.Cells["ColumnNome"].Value.ToString();
                    model.FormatoId = int.Parse(row.Cells["ColumnFormato"].Value.ToString());
                    model.TipoProdutoId = this.TipoProdutoModel.TipoProdutoId;
                    modelList.Add(model);
                }
            }

            if (modelList.Count != 0)
            {
                foreach (CampoTipoProdutoModel model in modelList)
                {
                    try
                    {
                        _campoTipoProdutoServices.Add(model);

                    }
                    catch (DataAccessException e)
                    {
                        operationSucceeded = e.DataAccessStatusInfo.OperationSucceeded;
                        dataAccesStatusJsonStr = JsonConvert.SerializeObject(e.DataAccessStatusInfo);
                        formattedJsonStr = JToken.Parse(dataAccesStatusJsonStr).ToString();
                        MessageBox.Show(formattedJsonStr, "Não foi possível adicionar o Tipo de Produto", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }

                }
            }
            return modelList;

        }

Agora vem a Cereja do Bolo:
O UserControl que tem a lista de Tipos de Produtos.
CamposTipsProdutosListUC.cs:

//Todos esse IF's são para identificar se está adicionando ou atualizando.
//caso null está adicionando.
//esse !=0 é para não dá erro pois ele pega a Lista de Campos pelo ID do Tipo de Produto.
        private void CamposTiposProdutosListUC_Load(object sender, EventArgs e)
        {
            try
            {

                if (this.TipoProdutoModel != null)
                {
                    if (this.TipoProdutoModel.TipoProdutoId != 0)
                    {
                        ListaCampos = (List<CampoTipoProdutoModel>)_camposServices.GetAllByTipoProdutoId(TipoProdutoModel.TipoProdutoId);
                    }
                }
                ConfiguraDGV();

            }
            catch (Exception)
            {

                throw;
            }
        }

Método ConfiguraDGV()

//Configurando e populando a DataGrid.
//meu problema está aqui.
        private void ConfiguraDGV()
        {

            PopulaComboBoxFormatos();

            if (ListaCampos != null)
            {
                if (ListaCampos.Count > 0)
                {
                    this.ListaCampos = PopulaDgv();

                    dgvCampos.VirtualMode = true;
                    dgvCampos.AutoSize = true;
                    dgvCampos.AutoGenerateColumns = false;
                    dgvCampos.DataSource = this.ListaCampos; //vai antes ou depois dos foreaches?

                    //pra cada linha adiciona um model da lista
                    foreach (CampoTipoProdutoModel modelCampo in this.ListaCampos)
                    {
                        foreach (DataGridViewRow row in dgvCampos.Rows)
                        {
//Não sei mais o que fazer para os dados do Model ir para o DataGridView
                            row.Cells["ColumnCampoTipoId"].Value = modelCampo.CampoTipoId.ToString();
                            row.Cells["ColumnNome"].Value = modelCampo.Nome.ToString();
                            row.Cells["ColumnFormato"].Value = modelCampo.FormatoId;
                            row.Cells["ColumnTipoProdutoId"].Value = modelCampo.TipoProdutoId;

                        }
                    }
                }
            }
        }

E por último e não menos importante:
O método PopulaComboBoxFormatos()
        public void PopulaComboBoxFormatos()
        {
            List<FormatoCampoModel> modelsFormatos = new List<FormatoCampoModel>();
            try
            {

                modelsFormatos = (List<FormatoCampoModel>)_formatoServices.GetAll();

            }
            catch (Exception)
            {

                throw;
            }

            ColumnFormato.ValueMember = "FormatoId";
            ColumnFormato.DisplayMember = "Nome";
            ColumnFormato.Items.Clear();
            foreach (var model in modelsFormatos)
            {
                ColumnFormato.Items.Add(model);
            }

        }

Já tentei de todo o jeito fazer as células da linha carregar os dados do Model mas não sei o que fazer mais.
Se eu mudo para DataTable eu fico perdido para preencher o ComboBox.
Quero poder obter preencher os dados da Grid com os models.
Já pesquisei de todo o jeito. Tive que restaurar os arquivos no GIT várias vezes pq quando eu tento corrigir utilizando DataTable não consigo mais Ler os itens do ComboBox.
Se alguém puder me dar uma luz eu agradeceria muito.
Comment: *"Meu problema é popular o DataGridView com os dados do Model "* o DataGridView aceita como data souce uma `List` por exemplo, só criar um `List` e usar na propriedade `DataSource` e chamar o métod `Bind()` que vai funcionar
Comment: Então não preciso fazer esse foreach.
Posso apenas usar a ListCampos, que já é uma List e usar no DataSource.
Vou ver alguns detalhes sobre o Bind(). Nunca usei.
Vou tentar... dpois dou um feedback. vlw
Comment: Tem outra questão: o Model do DataGrid retornar um inteiro do Formato.
O Formato em texto para o usuário vem do ComboBox ColumnFormato. Não vai dar ruim?
Comment: @RicardoPontual eu já estava usando o DataSource=this.ListaCampos

Esse ListaCampos é um List.

Não estava querendo que ele gerasse as colunas automaticamente pois eu tenho que tratar a segunda coluna quem no Model tem um ID. E eu tenho que passar os dados de Outro Model que está no ComboBox.
Answer: Resolvi um problema e me deparei com outro.
@RicardoPontual acho que você não entendeu o problema. Mas obrigado mesmo assim pela ajuda.
Primeiro para trazer o Model para o DataGrid usei um exemplo do Docs da Microsoft passando um array de string com os valores do Model encontrado.
Método ConfiguraDGV()
Esse fica somente com um foreach e usei um for para cada item da List<ListaCampos>.
Esses row.Cells não ajudam em nada pois o valor vem sempre nulo.
Removi o DataSource, pois vou gerar manualmente por meio do Array, além de remover o VirtualMode para poder popular manualmente as linhas.
Então Ficou Assim:
private void ConfiguraDGV()
{
   PopulaComboBoxFormatos();
   if (ListaCampos != null)
   {
      if (ListaCampos.Count > 0)
      {
        this.ListaCampos = PopulaDgv();
        //dgvCampos.VirtualMode = true;
        dgvCampos.AutoSize = true;
        dgvCampos.AutoGenerateColumns = false;
        //dgvCampos.DataSource = this.ListaCampos;

        //pra cada linha adiciona um model da lista
        foreach (CampoTipoProdutoModel modelCampo in this.ListaCampos)
        {
            //para cada registro da LIsta de Campos adiciona um array à linha do DGV.
            for (int i = 0; i < ListaCampos.Count; i++)
            {
                string[] stringRow =
                {
                    modelCampo.CampoTipoId.ToString(),
                    modelCampo.Nome.ToString(),
                    //O Nome do Formato vem de outro Model, mas busquei do Repository diretamente.
                    //TODO: Melhorar isso
                    _formatoServices.GetById(modelCampo.FormatoId).Nome.ToString()
                };
                dgvCampos.Rows.Add(stringRow);
            }

        }
      }
   }
}

Segundo Problema
O ComboBox estava configurado errado.
Alterei o VAlueMember de FormatoId para Nome
problema resolvido.
ColumnFormato.DataPropertyName = "FormatoId";
ColumnFormato.ValueMember = "Nome";
ColumnFormato.DisplayMember = "Nome";
ColumnFormato.Items.Clear();
foreach (var model in modelsFormatos)
{
 ColumnFormato.Items.Add(model);
}

Fica aí pra quem tiver o mesmo problema que eu tive. Se encontrar uma solução melhor, me informem.
Mais uma vez obrigado @RicardoPontual pela ajuda. Serviu muito para eu buscar mais etendimento.

Popular DataGridView Editável C#


Discard longer dictionary matches which contain a nested target word

Question: I am using tokens_lookup to see whether some texts contain the words in my dictionary. Now I am trying to find a way to discard the matches that occur when the dictionary word is in an ordered sequence of words. To make an example, suppose that Ireland is in the dictionary. I would like to exclude the cases where, for instance, Northern Ireland is mentioned (or any fixed set of words that contains Britain). The only indirect solution that I figured out is to build another dictionary with these sets of words (e.g. Great Britain). However, this solution would not work when both Britain and Great Britain are cited. Thank you.
library("quanteda")

dict <- dictionary(list(IE = "Ireland"))

txt <- c(
  doc1 = "Ireland lorem ipsum",
  doc2 = "Lorem ipsum Northern Ireland",
  doc3 = "Ireland lorem ipsum Northern Ireland"
)

toks <- tokens(txt)

tokens_lookup(toks, dictionary = dict)

Answer: You can do this by specifying another dictionary key for "Northern Ireland", with the value also "Northern Ireland".  If you use the argument nested_scope = "dictionary" in tokens_lookup(), then this will match the longer phrase first and only once, separating "Ireland" from "Northern Ireland".  By using the same key as the value, you replace it like for like (with the side benefit of now having these two tokens, "Northern" and "Ireland", combined a single token.
library("quanteda")
## Package version: 3.1
## Unicode version: 13.0
## ICU version: 69.1
## Parallel computing: 12 of 12 threads used.
## See https://quanteda.io for tutorials and examples.

dict <- dictionary(list(IE = "Ireland", "Northern Ireland" = "Northern Ireland"))

txt <- c(
  doc1 = "Ireland lorem ipsum",
  doc2 = "Lorem ipsum Northern Ireland",
  doc3 = "Ireland lorem ipsum Northern Ireland"
)

toks <- tokens(txt)

tokens_lookup(toks,
  dictionary = dict, exclusive = FALSE,
  nested_scope = "dictionary", capkeys = FALSE
)
## Tokens consisting of 3 documents.
## doc1 :
## [1] "IE"    "lorem" "ipsum"
##
## doc2 :
## [1] "Lorem"            "ipsum"            "Northern Ireland"
##
## doc3 :
## [1] "IE"               "lorem"            "ipsum"            "Northern Ireland"

Here I used exclusive = FALSE for illustration purposes, so you could see what got looked up and replaced.  You can remove that and the capkeys argument when you run it.
If you want to discard the "Northern Ireland" tokens, just use
tokens_lookup(toks, dictionary = dict, nested_scope = "dictionary") %>%
  tokens_remove("Northern Ireland")
## Tokens consisting of 3 documents.
## doc1 :
## [1] "IE"
##
## doc2 :
## character(0)
##
## doc3 :
## [1] "IE"

Comment: Thank you, perfect! A quick follow up: I was also using `kwic` to store the matched keys; do you know any way to apply the same logic to it?
Comment: You'd need to be more specific here, since I'm not sure of that exactly use case. Maybe a new question?
Comment: I can open a new question but just to give you an idea I was using `test <- kwic(toks, pattern = dict)`
Comment: Please accept the answer if you are happy with it.


Rubato where there is no indication of rubato

Question: Unless I'm crazy (not impossible, tbh) every performance of Messiaen: Prelude No. 7, Plainte calme that I have heard does not seem to follow the sheet music.
There's a passage where the time signature changes from 3/4 to 6/8, but I'm yet to find a performance where I can hear the change in tempo.  Also, it seems that people play this song almost entirely with rubato, even though there is no rubato indication.
This rubato thing is not exclusive to Messiaen: many times I've heard great pianists employing rubato to pieces where the piece has no indication for it. People playing Chopin in particular, seem eager to add their own pulse.
So I guess my question is:
Where do these liberties come from; is this a matter of interpretation (player's choice), or is there something guiding these performances, like "composer X's pieces should be played more freely"?
And if there are guidelines, where can I learn more about them? (suggestions of book, authors, etc. are welcomed)
Comment: Measure numbers in the Messiaen?
Answer: In the case of Messiaen's works, there are usually recordings either by the composer himself, or by his wife Yvonne Loriod, her sister Jeanne Loriod, or by pupils and proteges (Pierre Boulez, Myung-whun Chung, George Benjamin, Peter Hill, Pierre-Laurent Aimard, ...) that were done under his supervision. These will give you a clear idea of his intentions. Specifically for the Preludes, there is a recording by Yvonne Loriod.
Messiaen can be a challenge for piano players who are used to a 19th century repertoire. During the Messiaen centenary in 2008, touring pianists would add a Messiaen number to their concerts, and I saw Jean-Philippe Collard do this (I don't remember the exact piece), and I thought his interpretation sounded very un-idiomatic and unnecessarily 19th-century-ish.
In Messiaen's works of the 1940's and thereafter, he used the idea of "valeurs ajoutées", where he would carefully notate fluctuations in measure or phrase length by adding note values to measures. There'd be no time signature, and only the vaguest of tempo indications. While this seemingly leaves a lot of freedom to the pianist, it does prescribe perceived changes in tempo very precisely, and mixing in traditional ideas of rubato clashes with the composer's intentions.

(excerpt from Le Merle Noir, 1952)
Answer: It's both composer and interpretation determined. For example, there's more room for rubato in Chopin than in Mozart, but there is room in both to allow some fluidity in the pulse.
In the case of the Messiaen, it's understood (by tradition, by being familiar with the composer) to use a great deal of rubato in the Prelude. However, while the Prelude does include some tempo changes (indicated by the composer), the changes in meter — like between 3/4 and 6/8 — are not necessarily changes in tempo.
Messiaen uses the meter changes to indicate changes in emphasis, not speed. For example, in mm. 7–8 the meter changes from 4/4 to 6/8. But the eighth notes remain at the same pace. What changes is that in 4/4 time, every other eighth note receives a metric emphasis; whereas, in 6/8 time, every third eighth note receives metric emphasis. In the case of this piece, no tempo change should be detected, just a shift in meter.
Answer: I'll address the general questions:

Many times i hear great pianists employing rubato where the piece has no indication for such thing. ... Where does these liberties come from: is this a matter of interpretation (player's choice) or is there something guiding these performances, like "composer X piece should be played more freely"? And if there are guidelines, where can i learn more about it?

Yes, if "rubato" means "not playing with perfectly strict metronomic rhythm," then this is a liberty that can be afforded to the player. And in fact, often it is not explicitly called for because it is implicitly expected. The sheet music doesn't tell you the audience to clap or you to bow, but these are conventions. In fact, I would guess that any music that expects no rhythmic freedom is more rare. I remember an impassioned lecture by a piano professor titled "Please Don't Play in Time," amounting to "Look, just because the music doesn't tell you how to bend time doesn't mean you shouldn't; rather, it's a clue that you should."
But how much freedom you give yourself, and the particular ways you exercise it, should not just be based on your own whim, but on informed "performance practice." Which is just an official phrase for "How people did it [in a given time, or place, or genre]." Some composers might actually expect absolutely strict metronomic rhythm; I'm not sure Steve Reich has strong feelings on the subject, but I wouldn't attempt his phasing compositions without keeping a steady tempo. Note, the entire notion of being "metronomic" is not a given for all periods of music. I mean, the metronome wasn't even invented before a certain point, of course; but even after that, there was a societal sea-change to embrace mechanization in the 20th century, and prior to that, a "mechanical" tempo might be not only undesirable but un-conceptualized.
The amount and "style" of rubato I use would depend on what I'm playing. In the case of Chopin, there is a lot written about his playing (I think, without bothering to look up documentation, that this is the origin of the term "rubato"?). In particular, contemporaries make note of the alterations of tempo in his right hand, but how the left hand was unaffected by them. Meanwhile, a classical or baroque work might manipulate tempo or rhythm according to slightly different conventions. Another factor that matters a lot is whether you are playing alone or with other people. A baroque solo-instrument "prelude" or "fantasia" explicitly expects a quasi-improvised freeness of tempo, that is perhaps different each time (but often following the same principle as Chopin: The "big beats" are spaced regularly even if what comes between is mutated greatly). But if you play as an ensemble, and especially if your material shares its rhythm with another player, then you can't just do whatever you want on the spur of the moment. (Though, even in a large ensemble, there can be fluctuations of tempo as long as they're agreed on and expected. Some such are ingrained: a waltz band could probably play the Blue Danube, with it's gradual accelerando, without a conductor. Some are familiar rhetorical gestures, like the slight ritardando or fermata going into the "big finish" of a musical number. Similarly, some historical ensemble music might make similar fluctuations without being told, simply because it's "how it's done.")
So how do you find out how rhythm and tempo are handled in the relevant performance practice for your piece? You have to do some research. Ultimately, to be a performer, you also have to be to some degree a musicologist. The most useful kind of research might be listening to other performances, but beware; some might be, themselves, uninformed performances; others might perpetuate a "canon" of practice that is different from the composer's intent. There are certain turns of timing that are expected in Gershwin's Rhapsody in Blue, but the original 1924 recording, with Gershwin at the piano, is lacking in them (as well as taking some radically different approaches to articulation and phrasing):

It also behooves us to read whatever there is to read about our genre, both primary sources and secondary sources who argue over how to interpret the primary ones. This can be problematic; what does it mean when a pre-metronome writer says something is "free"? How free?—but it does at least give us some groundwork.
Comment: The only non-notated tempo change I was told to play in my piano lessons for works from the vast majority of composers (e.g. Mozart, Bach, Beethoven, Schubert, Schumann) is the non-notated ritardando at the end of the piece. Heck, not all pieces end with such a ritardando (e.g. 20th-century pieces for the most part)!
Comment: @Dekkadeci I often choose the "straight ahead into the double bar" ending in baroque music. Or more of a "slight easing" as opposed to the "big finish" that things like Beethoven's 5th put you in mind of—"One! Five! One! Five—I'm not done yet—One! Five! One! Okay this is it, fiiiiiiiive... ONE!! ... Just kidding, FIVE!..."
Comment: @Dekkadeci But I do also preach to my students: what's on the page is the *minimum*, not the limit. It's the starting point. The composer doesn't notate every interpretive nuance because that would be busy and annoying (or because of some rhetoric about "interpretation," etc). Add to what's on the page.
Comment: Oh yeah, that reminds me - my piano teachers also told me to make my left hand slightly quieter than my right.


How to npm init/install/run build properly in a wordpress plugin?

Question: It may be a dumb question but I feel that I'm floundering around attempting to edit the wordpress plugin that I downloaded from github repo: https://github.com/WordPress/gutenberg-examples.
Right now, I'm following the block tutorial from https://developer.wordpress.org/block-editor/how-to-guides/block-tutorial/.
So what I did:

download the pre-built plugin in zip folder
upload it to wordpress site that I created in docker (https://developer.yoast.com/blog/set-up-wordpress-development-environment-in-docker/)
open the zip folder and move it to my plugins directory
open, for example, "01-basic-esnext" folder inside the gutenberg-examples folder and edit in block.build.js. The changes I made would be shown in the block editor in the wordpress post that I created.

However, what I'm confused about is the npm stuff that's mentioned in "Development" section.

For each of the examples that include an esnext example the following
commands are required to build the plugins:
To install the node packages
npm install
To build the production version of the plugin
npm run build
To build a development version, change to the local
directory of the block you are working on, and run npm start to watch
for changes and automatically rebuild as you develop.
cd 01-basic-esnext/
npm start

Before that, the "Development" section already mentioned building a docker/wordpress environment for the plugin right inside the gutenberg-examples folder.
However, the way I set up my stuff is different. I already have a docker running in my wordpress folder like what I followed in https://developer.yoast.com/blog/set-up-wordpress-development-environment-in-docker/ and this plugin is already in my plugins directory. I can easily edit the files in visual studio code and see the changes in my local wordpress site.
So should I be doing something to install the npm stuff or leave it alone?
Answer: npm is used for these WordPress plugins because the -esnext versions of the examples get built from Javascript modules. The build process runs on npm and nodejs.  That means, if you work on that -esnext code, that you're living in a hybrid world -- you have php and apache running your development web server, and you have nodejs and npm handling your builds.
The WordPress team carefully rigged a docker setup to support the process of edit / run for you. So if you use your own docker setup, you won't get the benefit of theirs.
When you have finished your development effort, you can use npm run build to build a .zip file which you can then install in your own WordPress instances using the Upload Plugin button at the top of the Add Plugins page.
Code is poetry, for sure. But development environments are not.


Understanding of $|X|=|X_G|+\sum_{i=k}^{n}|O_{x_i}|$

Question: In the book Abstract Algebra, Theory and Applications by Thomas W. Judson it is written :

Unfortunately the book don't give any example of $X_G$. I don't understand:
1- How $X_G$ can be? What is an example of it for some $X$ and $G$ and thus $X_G$?
2- What does non-trivial orbit means? $O_{x_i}={\{y\in X : gy=x_i for some g\in G}\}$, so $x_i\in O_{x_i}$. Does non-trivial means $O_{x_i}-{\{x_i}\}$?
3- How the sum come up? I mean a rigorous proof for $$|X|=|X_G|+\sum_{i=k}^{n}|O_{x_i}|$$.
Any clear simple explanation would be really appreciated.
Comment: You missed the "x_k,...,x_n" are representatives from the distinct $\underline{\text{nontrivial}}$ orbits of $X$. The equation is correct since you can divide the sum over all orbits into those for which the orbit is trivial (by definition you have $|X_G|$ such orbits of length $1$) and the non-trivial ones which is the remaining $\sum$ sign.
Comment: Think about why $X_G$ cannot be empty under the action of conjugation for an Abelian group G.
Comment: @ClémentGuérin - $X_G$ can't be a 'type/category' of orbit since it has the condition **for all g** but in orbit it is **for some g**, am I right?
Comment: @DavidP I think the problem is that I don't understand $X_G$. Would you please tell some example of G and X and so what is $X_G$? The book didn't have any! and I googled but I couldn't find any. Thank you.
Comment: @L.G. If $G=GL(n,K)$ and $X=K^n$ then $G$ acts naturally on $X$, for this action, $X_G$ has only one element : $X_G=\{0\}$. By definition, $X_G$ is the set of elements $x\in X$ that are left fixed by the action of any element $g\in G$ : $g.x=x$. By the definition of the orbit one can actually shows that $x\in X_G$ if and only if $|O_x|=1$ (this is why the $|X_G|$ naturally appears here).
Comment: @L.G. As another example, take $G$ a group and consider its action by conjugation over itself. That is $g.h:=ghg^{-1}$, then you can show that the set $X_G$ is here the center of $G$ noted $Z(G)$ (i.e. the set of elements of $G$ that commute with any element of $G$).
Comment: @ClémentGuérin - thank you for the conjugation example. Would you please help me what will be the nontrivial conjugacy classes of G? I still don't understand 'non-trivial' means here. Does it mean **only** excluding x=id? or more than that 'non-trivial' means?
Answer: Let's look at a concrete example from geometry.
Consider the case $X = \big\{ (\pm 1,\pm 1,\pm 1) \big\}$, the $8$ vertices of a $2\times 2\times 2$ cube centered at origin.
Let $G$ be the group of $3$-fold rotation (i.e rotation of multiples of $120^\circ$ ) along the diagonal passing through the two vertices $(+1,+1,+1)$ and $(-1,-1,-1)$. These $2$ vertices on the diagonal are invariant under any rotations of $G$. They
are example of $X_G$ i.e.
$$X_G = \big\{ (+1,+1,+1), (-1, -1, -1) \big\}$$
The remaining $6$ vertices falls into two sets.
$$\begin{align}
\mathcal{O}_1 &= \big\{ (-1,+1,+1), (+1,-1,+1), (+1,+1,-1) \big\}\\
\text{ and }\quad\mathcal{O}_2 &=
\big\{ (+1,-1,-1), (-1,+1,-1), (-1,-1,+1) \big\}
\end{align}
$$
Under actions of rotations in $G$, we have:

any vertex in $\mathcal{O}_1$ will get rotated to another vertex in $\mathcal{O}_1$, never to one in $\mathcal{O}_2$.
any vertex in $\mathcal{O}_2$ will get rotated to another vertex in $\mathcal{O}_2$, never to one in $\mathcal{O}_1$.
Given any pair of vertices $x, y$ in the same set, there is always a
rotation which send $x$ to $y$.

These two sets $\mathcal{O}_1$ and $\mathcal{O}_2$ are examples of the non-trivial orbits. i.e. orbits that are not singletons and consists of more than one elements.
Comment: @L.G. If you cannot visualize the $3$-fold rotation along the diagonal of a cube. How about the $4$-fold rotation along the $z$-axis for the octahedron with vertices at $(\pm 1,0,0)$, $(0,\pm 1,0)$ and $(0,0,\pm 1)$? In the case of octahedron, $X_G = \{ ( 0, 0, \pm 1 )\}$ while the remaining 4 vertices on the $xy$-plane falls into a single orbit.
Comment: @L.G. that's a perfectly valid argument.
Comment: Thanks a lot. Actually that's a brilliant example with clear explanation, except for I don't know how  by rotation of $120^on$ of (for example) pt (−1,+1,+1) you get pt (+1,−1,+1). I tried by a real cube but still it didn't work for me. How do you calculate them? (I think I need to study Euler rotation matrix in 3d, if there is no other simple way?) thank you.
Comment: @L.G. By definition, an element $x \in X$ belongs to $X_G$ when any only when $gx = x$ for all $G$, this is equivalent to the set $\{ gx : g \in G \}$ equals to the singleton $\{ x \}$ . This set is nothing but the orbit containing $x$!
Comment: (sorry I deleted my latter comment asking a proof of singleton ... before you sent comment because I thought I found it out, but still don't understand it by your last comment and the other answer also) Would you please help me with one my last question: Intuitively (though not a proof) it makes sense: when $x$ is some element of $X$ such that all the elements of $G$ is used up as action on $x$ but didn't change it to other element of $X$ so the partition of containing $x$ only would contain $x$! (Considering a mathematician's view point) can I consider this intuition as a proof? Thank you.
Answer:
$X_G$ is the set of elements of $x\in X$ such that $x$ is fixed by the action of any element of $g\in G$. I gave you in comment a relevant case where $X_G$ is non empty : $G$ acts on itself by conjugation. We see, in this example that $x:=1_G$ is fixed by any element $g\in G$ since $g.1_G:=g1_Gg^{-1}=gg^{-1}=1_G$. Hence the definition makes sense and does not always lead to the empty set. As a more trivial example $G$ acting trivially on $X$ then $X=X_G$.
Non-trivial  means (in this context) an orbit $O_x$ such that $O_x$ is not reduced to the singleton $x$, i.e. such that you can find $y\in O_x$ with $y\neq x$. Another formulation (in the case of finite sets) is the orbit of $x$ is non-trivial if $|O_x|>1$. Now this is interesting because of the following :

Take $x\in X$ then we have $x\in X_G\Leftrightarrow |O_x|=1$.

Let us prove this. If $x\in X_G$ then for any $g\in G$, $g.x=x$ so $O_x:=\{g.x|g\in G\}=\{x|g\in G\}=\{x\}$.
On the other hand if $|O_x|=1$ then $O_x=\{x\}$ but if we take any $g\in G$ we will have (by definition of the orbit) $g.x\in O_x$ and since it is contains only $x$, we get $g.x=x$, since it is true for any $g\in G$ we have that $x\in X_G$.

If you take $x_1,...,x_r$ representatives of the orbits for the action then clearly :

$$|X|=\sum_{i=1}^r|O_{x_i}| $$
Now you may impose that $x_1...x_{k-1}$ are representative of the trivial orbits and $x_k...x_r$ of the non trivial ones. Hence :
$$|X|=\sum_{i=1}^{k-1}|O_{x_i}|+\sum_{i=k}^r|O_{x_i}| $$
Now by definition $|O_{x_i}|=1$ for $i<k$ so :
$$|X|=\sum_{i=1}^{k-1}1+\sum_{i=k}^r|O_{x_i}| $$
$$|X|=(k-1)+\sum_{i=k}^r|O_{x_i}| $$
Now by definition $k-1$ is the number of trivial orbits which is by the highlighted result above the number of fixed points of the action ($|X_G|$) so :
$$|X|=|X_G|+\sum_{i=k}^r|O_{x_i}| $$
As for an example take $D_{4}$ the dihedral group of order $8$. Then it has $8$ elements :
$$\{1,r,r^2,r^3,s,sr,sr^2,sr^3\} $$
You have $5$ orbits, representatives are $1$, $r^2$, $r$, $s$, $sr$, among those only $1$ and $r^2$ are trivial. The other being of cardinal $2$.
Hence :
$$|D_4|=|O_1|+|O_{r^2}|+|O_r|+|O_s|+|O_{sr}| $$
$$|D_4|=1+1+2+2+2 $$
Here the two's correspond exactly to the $\sum_{i=k}^r|O_{x_i}|$ whereas the one's correspond to the number of trivial orbits i.e. $|Z(G)|=2$ here.
Comment: If $x\in X_G$ then for all $g$'s, $g.x=x$  (i.e. it is moved by no-one). In this case take $y\in O_x$ then we know that we can find $g_0\in G$ such that $g_0.x=y$. Since $x$ is moved by no-one, in particular it is not moved by $g_0$ so $y=g_0.x=x$. Whence $|O_x|=1$. On the other hand if $|O_x|=1$, take $g\in G$,  by definition there exists $g_0\in G$ such that $g.x=g_0.x$ ($g_0:=g$ is okay) so $g.x\in O_x$, since it only contains $x$ we have $g.x=x$, this being true for all $g\in G$, we have $x\in X_G$ by definition.
Comment: I understood all except for the 2. Elements of $O_x$ are those elements of $X$ such that **there exist(s) some** g(s) ... , but elements of $X_G$ are those elements of $X$ such that for **all** g's ... . I can't reconcile two different things: $\exists$ and $\forall$. Thank you.