Trouble printing out parsed XML using Python

Question: Im having trouble figuring out why my second print statement doesn't print anything out, please HELP!
My first print statement print (root[0][1].text) is able to parse the xml file and print out AC-1 while the other print statement below the for loop
for varible in root.iter('number'):print(varible.text) doesn't seem to find the data at all.

ParseXML.py

filePath='/Users/userName/Desktop/xmlFile.xml'
tree = ET.parse(filePath)
root = tree.getroot()
#This print stmt prints 'AC-1'
print (root[0][1].text)
for varible in root.iter('number'):
        #This print stmt doesn't print anything
        print(varible.text)

xmlFile.xml

<controls:controls xmlns="http://scap.nist.gov/schema/sp800-53/2.0" xmlns:controls="http://scap.nist.gov/schema/sp800-53/feed/2.0" xmlns:xhtml="http://www.w3.org/1999/xhtml" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" pub_date="2015-02-03T10:11:18.645-05:00" xsi:schemaLocation="http://scap.nist.gov/schema/sp800-53/feed/2.0 http://scap.nist.gov/schema/sp800-53/feed/2.0/sp800-53-feed_2.0.xsd">
    <controls:control>
        <family>ACCESS CONTROL</family>
        <number>AC-1</number>
        <title>ACCESS CONTROL POLICY AND PROCEDURES</title>
        <priority>P1</priority>
        <baseline-impact>LOW</baseline-impact>
        <baseline-impact>MODERATE</baseline-impact>
        <baseline-impact>HIGH</baseline-impact>
        <statement>
            <description>The organization:</description>
            <statement>
                <number>AC-1a.</number>
                <description>Develops, documents, and disseminates to [Assignment: organization-defined personnel or roles]:
                </description>
                <statement>
                    <number>AC-1a.1.</number>
                    <description>An access control policy that addresses purpose, scope, roles, responsibilities, management commitment, coordination among organizational entities, and compliance; and
                    </description>
                </statement>
                <statement>
                    <number>AC-1a.2.</number>
                    <description>Procedures to facilitate the implementation of the access control policy and associated access controls; and
                    </description>
                </statement>
            </statement>
            <statement>
                <number>AC-1b.</number>
                <description>Reviews and updates the current:</description>
                <statement>
                    <number>AC-1b.1.</number>
                    <description>
                    Access control policy [Assignment: organization-defined frequency]; and
                    </description>
                </statement>
                <statement>
                    <number>AC-1b.2.</number>
                    <description>
                    Access control procedures [Assignment: organization-defined frequency].
                    </description>
                </statement>
            </statement>
        </statement>
        <supplemental-guidance>
            <description>
            This control addresses the establishment of policy and procedures for the effective implementation of selected security controls and control enhancements in the AC family. Policy and procedures reflect applicable federal laws, Executive Orders, directives, regulations, policies, standards, and guidance. Security program policies and procedures at the organization level may make the need for system-specific policies and procedures unnecessary. The policy can be included as part of the general information security policy for organizations or conversely, can be represented by multiple policies reflecting the complex nature of certain organizations. The procedures can be established for the security program in general and for particular information systems, if needed. The organizational risk management strategy is a key factor in establishing policy and procedures.
            </description>
            <related>PM-9</related>
        </supplemental-guidance>
        <references>
            <reference>
                <item xml:lang="en-US" href="https://csrc.nist.gov/publications/search?keywords-lg=800-12">NIST Special Publication 800-12</item>
            </reference>
            <reference>
                <item xml:lang="en-US" href="https://csrc.nist.gov/publications/search?keywords-lg=800-100">NIST Special Publication 800-100</item>
            </reference>
        </references>
    </controls:control>
</controls:controls>

Answer: Your XML file is such as all tags are preceded by "{http://scap.nist.gov/schema/sp800-53/2.0}".
Try out this piece of code to test it:
    root = tree.getroot()

    for item in root.iter('{http://scap.nist.gov/schema/sp800-53/2.0}number'):
       print(item.text)


Selection sort not sorting first value

Question: I wrote this c++ function to sort an array, it works, but it doesn't seem to work with the fist value: it isalways the bigger instead of the smaller!
    void s_iSort (double a[])
    {
        cout << "INCREASING SORTER:\n\n";
        unsigned int mx,maxx;
        double temp;
        cout << "Insert maximum element to sort: "; cin>>mx;
        for (int c=0; c<mx; c++)
            {
                maxx=0;
                for (int i=c; i<mx; i++)
                    if (a[i]<a[maxx])
                        maxx=i;
                temp=a[c];
                a[c]=a[maxx];
                a[maxx]=temp;

            }
        cout << "\nDONE!\n\n";
    }

What's worng with this?
Comment: Please provide a [mcve] (you are already close to that) and the input, expected and actual output
Comment: On the first round `if (a[i]<a[maxx])` will be the same as `if (a[0]<a[0])`. And then you never visit the first element again.
Answer: You should either use a debugger, or try to explain your algorithm to a rubber duck. However, I am in a rubber duck mood and will point you to a mistake:
for (int c=0; c<mx; c++) {
    maxx=0;
    for (int i=c; i<mx; i++) if (a[i]<a[maxx]) maxx=i;
    temp=a[c];
    a[c]=a[maxx];
    a[maxx]=temp;
}

In each iteration of this loop you want to go trough a range of elements, find the minimum value in that range and put it as the first element of that range. It works for the first iteration, but already on the second it goes wrong. You initialize maxx (which is supposed to be the first element in that range) to 0, ie the first element of the array. However you should only consider elements that have not yet been sorted, ie change it to
maxx = c;

Also note, that (apart from exercises) you should not write your own sorting algorithm but use std::sort.

Selection sort not sorting first value


EditText drawable hides after setting tint programmatically

Question: I have two EditText in my layout. I am using TextInputLayout and added drawableLeft, now I am trying to change its tint which is working fine for username field but it hides left drawable icon for password field. Below is the code, please guide me what I am doing wrong.
<LinearLayout
    android:layout_width="@dimen/margin_300"
    android:layout_height="wrap_content"
    android:gravity="center_horizontal"
    android:orientation="vertical">

<android.support.design.widget.TextInputLayout
                                android:id="@+id/userIDLayout"
                                android:layout_width="match_parent"
                                android:layout_height="match_parent"
                                android:layout_toEndOf="@+id/appCompatImageView4">

                                <android.support.v7.widget.AppCompatEditText
                                    android:id="@+id/edit_user_id"
                                    android:layout_width="match_parent"
                                    android:layout_height="wrap_content"
                                    android:drawableLeft="@drawable/ic_user_login"
                                    android:drawablePadding="@dimen/margin_10"
                                    android:drawableStart="@drawable/ic_user_login"
                                    android:drawableTint="@color/colorPrimaryDark"
                                    android:hint="@string/txt_user_hint"
                                    android:imeOptions="flagNoExtractUi|actionNext"
                                    android:inputType="number"
                                    android:maxLines="1"
                                    android:textSize="@dimen/txt_size_16" />
                            </android.support.design.widget.TextInputLayout>

                            <android.support.design.widget.TextInputLayout
                                android:id="@+id/userPasswordLayout"
                                android:layout_width="match_parent"
                                android:layout_height="wrap_content"
                                android:layout_toEndOf="@+id/appCompatImageView5"
                                app:passwordToggleEnabled="true">

                                <android.support.design.widget.TextInputEditText
                                    android:id="@+id/edit_user_password"
                                    android:layout_width="match_parent"
                                    android:layout_height="wrap_content"
                                    android:drawableLeft="@drawable/ic_user_password"
                                    android:drawablePadding="@dimen/margin_10"
                                    android:drawableStart="@drawable/ic_user_password"
                                    android:drawableTint="@color/colorPrimaryDark"
                                    android:hint="@string/txt_pin_hint"
                                    android:imeOptions="flagNoExtractUi|actionDone"
                                    android:inputType="numberPassword"
                                    android:maxLength="4"
                                    android:maxLines="1"
                                    android:textSize="@dimen/txt_size_16" />
                            </android.support.design.widget.TextInputLayout>

                        </LinearLayout>

Below is the code that I am using to change tint programmatically:
fun changeEditTextDrawableColor(colorId: Int, drawableId: Int, resource: EditText) {
    var drawable = resources.getDrawable(drawableId)
    drawable = DrawableCompat.wrap(drawable)
    DrawableCompat.setTint(drawable, resources.getColor(colorId))
    DrawableCompat.setTintMode(drawable, PorterDuff.Mode.SRC_IN)

    resource!!.setCompoundDrawablesWithIntrinsicBounds(drawable, null, null, null)
}

Comment: Can you pl give try by removing              android:inputType="numberPassword" from your password edit text and if it work then I can suggest you way to fix
Comment: Its working fine if i remove `app:passwordToggleEnabled="true"`. i tested it. i guess the problem is happening coz of password toggle
Comment: Not sure app:"property" can be set at run time or not but it can help you to fix your issue
Comment: you mind if you could elaborate more.
Comment: Try calling `inValidate()` to the `View`.
Comment: inValidate() is not working :(
Answer: The issue is with setCompoundDrawablesWithIntrinsicBounds change it to setCompoundDrawablesRelativeWithIntrinsicBounds and it will start appearing.
Comment: This solution fixed an issue I had trying to set a drawable programatically (with no tint) onto an AutoCompleteTextView. Thanks!


Java: how to handle a LOT of fields and their encapsulation cleanly?

Question: Let's say I am tasked with coding some kind of an RPG. This means that, for example, I'll want to track a Character GameCharacter and stats thereof, like intelligence, damage bonuses or hitpoints.
I'm positively scared that by the end of the project I may end up with handling with very a high number of fields - and for each I would have to make sure they follow a very similar set of constraint and behaviours (for example, I want them to be bounded between a min and a max; I want to be able to distinguish between a "base value" and a "temporary bonus"; I want to be able to increment and decrement both without going through a setters and getters). Suddenly, for every field I would need one (two?) getter and four setters and maybe a couple resetters too! Even for 10 fields that means a LOT of methods all alike, eek.
For DRYness I have started encapsulating the logic of messing with those stats in Field classes, so that I could write code such as intelligence.applyBonus(10) or hitpoints.get() (which takes care the value returned is in range), etc. I have even gone to such a length to create classes to group those fields together, but that's not the point right now.
Now, I hit in this problem while "plugging" Field into GameCharacter: most Java textbooks say that each class should have private fields with public getters and setters. That sounds good in theory, and I've already built a whole class around an int; however, the idea doesn't sound as solid when you find yourself calling a getter to get... a getter:
thisCharacter.getIntelligence().get() //eeek

I'd much rather access the field directly. Maybe it's my Python/VB [1] "background", but for me it is cleaner, clearer and more straightforward:
thisCharacter.intelligence.get()

The (theoretical) problem with public fields is that I'm giving up all control on it; for example at some other point in the codebase, by misfortune, the following might happen:
thisCharacter.intelligence = somethingThatReallyIsNull;

Sounds like a subtle bug... but... I mean, should I really worry about that? I for one never plan to assign the Field directly [2], I have documented in the Javadoc that this is not something that should be done, but still I am new here so I'm a bit torn.
So I would like to hear what your take on this topic. Are the advantages of encapsulation so massive that I should go ahead and have getter getters and setter getters and so on... or should I take encapsulation in healthy measures and leave the Field as a public field?

[1] Yes, I know. I've been trying to forget. But we've just recently seen also a bit of C# and man, aren't properties sweet. Oh well.
[2] except in Constructors! And a getter won't save me from a faulty constructor.
Comment: "with public fields is that I'm giving up all control on it" - sure, but `public final` fields, nothing can go wrong. When your field is a wrapped int, then it should be `final`, as otherwise you'd have two way of setting it: `thisCharacter.getIntelligence().set(7)` and `someIntelligence.set(7); thisCharacter.getIntelligence(someIntelligence)`.
Answer: Sounds like you're thinking in terms of if(player.dexterity > monster.dexterity) attacker = player.  You need to think more like if(player.quickerThan(monster)) monster.suffersAttackFrom(player.getCurrentWeapon()).  Don't mess around with bare stats, express your actual intention and then design your classes around what they're supposed to do.  Stats are a cop-out anyway; what you really care about is whether a player can or cannot do some action, or their ability/capacity versus some reference.  Think in terms of "is the player character strong enough" (player.canOpen(trapDoor)) instead of "does the character have at least 50 strength".
Comment: Good point! Think beyond a simple transcription of D&D manuals.
Comment: While you do bring an excellent point, I am afraid it's fair to reconsider Uri's as the "answer" of the thread. :)
Answer: My experience is that in situations where you need a lot of fields, the number, nature, naming, and types of fields are so flexible and likely to change throughout the lifetime of your project that you would likely need some sort of map instead of fields.
For example have an attribute map from keys to values.
Provide public calls for getting and setting the attributes, but don't let everybody use them (or make sure they don't). Instead, create classes to represent each attribute you are interested in, and that class provides all the functions for manipulating that attribute. For example, if you have Strength, you could have a "StrengthManipulation" class that is initialized to a specific Player object, and then provides getters, setters (All with appropriate validation and exceptions), and perhaps things like calculating strength with bonuses, etc.
One advantage of this is that you decouple the use of your attributes from your player class. So if you now add an Intelligence attribute, you don't have to deal and recompile everything that manipulates only strength.
As for accessing fields directly, it's a bad idea. When you access a field in VB (at least in old VBs), you usually call a property getter and setter and VB simply hides the () call for you. My view is that you have to adapt to the conventions of the language that you are using. In C, C++, Java and the like you have fields and you have methods. Calling a method should always have the () to make it clear that it is a call and other things may happen (e.g., you could get an exception). Either way, one of the benefits of Java is its more precise syntax and style.
VB to Java or C++ is like Texting to graduate school scientific writing.
BTW: Some usability research shows that it's better to not have parameters to constructors and rather construct and call all the setters if you need them.
Comment: cf, The Universal Design Pattern: http://steve-yegge.blogspot.com/2008/10/universal-design-pattern.html
Comment: I agree with Uri. Having a map is a lot easier to maintain and scale, rather than using fields.
Comment: I always thought of it as a fairly straightforward idiom, but I guess anything straightforward ends up a pattern :)
Answer: Steve Yegge had a very interesting (if lengthy) blog post that covered these issues: The Universal Design Pattern.
Comment: Good call! That's a great article in defense of the "properties" pattern.
Answer: To me it looks like 'thisCharacter' might well have an 'intelligence' object for dealing with intelligence behind the scenes, but I question whether that should be public at all. You should just expose thisCharacter.applyInt and thisCharacter.getInt instead of the object that deals with it. Dont expose your implementation like that.
Answer: Keep your fields private! You never want to expose too much of your API. You can always make something that was private public, but not the other way round, in future releases.
Think as if you'll make that into the next MMORPG. You'd have a lot of scope for bugs, errors, and unnecessary evil. Ensure immutable properties are final.
Think of a DVD player, with its miniamilistic interface (play, stop, menu), and yet such technicality inside. You'll want to hide everything non-vital in your program.
Answer: It sounds like your main complaint isn't so much with the abstraction of setter/getter methods, but with the language syntax for using them.  Ie, you'd prefer something like C# style properties.
If this is the case, then the Java language has relatively little to offer you.  Direct field access is fine, until you need to switch to a getter or setter, and then you will have some refactoring to do (possibly ok, if you control the whole codebase).
Of course, if the Java platform is a requirement, but the language isn't then there are other alternatives.  Scala has a very nice property syntax, for example, along with lots of other features that could be useful for such a project.  And best of all, it runs on the JVM, so you still get the same portability that you'd get by writing it in the Java language. :)
Answer: What you appear to have here is a single layer of a composite model.
You might want to add methods that add abstractions to the model, rather than just having it as a set of lower level models.
The fields should be final, so even if you did make them public you couldn't accidentally assign null to them.
The "get" prefix is present for all getters, so it's probably more the initial look than a new problem as such.
Answer:
Are the advantages of encapsulation so massive that I should go ahead and have getter getters and setter getters and so on... or should I take encapsulation in healthy measures and leave the Field as a public field?

IMO, encapsulation has nothing to do with wrapping a getter/setter around a private field. In small doses, or when writing general-purpose libraries, the tradeoff is acceptable. But when left unchecked in a system like the one you're describing, its a an antipattern.
The problem with getters/setters is that they create overly tight coupling between the object with those methods and the rest of the system.
One of the advantages of real encapsulation is that it reduces the need for getters and setters, decoupling your object from the rest of the system in the process.
Rather than exposing the implementation of GameCharacter with setIntelligence, why not give GameCharacter an interface that better reflects it's role in the game system?
For example, instead of:
// pseudo-encapsulation anti-pattern
public class GameCharacter
{
  private Intelligence intelligence;

  public Intelligence getIntelligence()
  {
    return intelligence
  }

  public void setIntelligence(Intelligence intelligence)
  {
    this.intelligence = intelligence;
  }
}

why not try this?:
// better encapsulation
public class GameCharacter
{
  public void grabObject(GameObject object)
  {
    // TODO update intelligence, etc.
  }

  public int getIntelligence()
  {
    // TODO
  }
}

or even better:
// still better
public interface GameCharacter
{
  public void grabObject(GameObject object); // might update intelligence
  public int getIntelligence();
}

public class Ogre implements GameCharacter
{
  // TODO: never increases intelligence after grabbing objects
}

In other word, a GameCharacter can grab GameObjects. The effect of each GameCharacter grabbing the same GameObject can (and should) vary, but the details are fully encapsulated within each GameCharacter implementation.
Notice how the GameCharacter is now in charge of handling its own intelligence update (range-checking, etc), which can happen as it grabs GameObjects, for example. The setter (and the complications you note with having it) have disappeared. You might be able to dispense with the getIntelligence method altogether, depending on the situation. Allen Holub takes this idea to its logical conclusion, but but that approach doesn't seem to be very common.
Comment: That's exactly what I wanted to avoid!

getIntelligence()
setIntelligence()
applyIntelligenceBonus()
resetIntelligenceBonus()
getStrength()
setStrength()
applyStrengthBonus()
resetStrengthBonus()
getWisdom()
setWisdom()
giveWisdomBonus()
resetWisdomBonus()
getDexterity()
setDexterity()
applyDexterityBonus()
zeroDexterityBonus()
getHP()
setHP()
dealDamage()
healDamage()
...

You end up having a lot of redundant code doing the same operation on different fields. Maybe they aren't even consistently named.

That's the definition of error prone, IMHO. :)
Answer: In addition to Uri's answer (which I totally support), I'd like to suggest you consider defining the attribute map in data.  This will make your program EXTREMELY flexible and will factor out a lot of code you don't even realize you don't need.
For instance, an attribute can know what field it binds to on the screen, what field it binds to in the database, a list of actions to execute when the attribute changes (a recalculate hit% might apply to both strength and dex...)
Doing it this way, you have NO code per attribute to write a class out to the DB or display it on the screen.  You simply iterate over the attributes and use the information stored inside.
The same thing can apply to skills--in fact, attributes and skills would probably derive from the same base class.
After you go down this road, you'll probably find yourself with a pretty serious text file to define attributes and skills, but adding a new skill would be as easy as:
Skill: Weaving
  DBName: BasketWeavingSkill
  DisplayLocation: 102, 20  #using coordinates probably isn't the best idea.
  Requires: Int=8
  Requires: Dex=12
  MaxLevel=50

At some point, adding a skill like this would require no code change whatsoever, it could all be done in data pretty easily, and ALL the data is stored in a single skill object attached to a class.  You could, of course, define actions the same way:
Action: Weave Basket
  text: You attempt to weave a basket from straw
  materials: Straw
  case Weaving < 1
    test: You don't have the skill!
  case Weaving < 10
    text: You make a lame basket
    subtract 10 straw
    create basket value 8
    improve skill weaving 1%
  case Weaving < 40
    text: You make a decent basket
    subtract 10 straw
    create basket value 30
    improve skill weaving 0.1%
  case Weaving < 50
    text: You make an awesome basket!
    subtract 10 straw
    create basket value 100
    improve skill weaving 0.01%
  case Weaving = 50
    text: OMG, you made the basket of the gods!
    subtract 10 straw
    create basket value 1000

Although this example is pretty advanced, you should be able to visualize how it would be done with absolutely no code. Imagine how difficult it would be to do anything like that without code if your "attributes/skills" were actually member variables.
Answer: Consider using a "modeling" framework, such as Eclipse's EMF.
This involves defining your objects using something like Eclipse EMF editor,
or in plain XML, or in Rational Rose.  It's not as difficult as it sounds.
You define attributes, constraints etc.  Then the framework generates
the code for you.  It adds @generated tags to parts it added such as
getter and setter methods.  You can customize the code, and later edit
it either by hand or via some GUI, and regenerate the java files.


Como mudar tamanho do Popover no Bootstrap 3?

Question: Tenho o seguinte código de um efeito popover com o Bootstrap 3, estou utilizando o Bootstrap 3.3.7. Esse popover funciona da seguinte maneira, quanto o mouse passa em cima desse ícone aparece a mensagem. Tenho vários popovers na página, mas esse em específico é muito grande o conteúdo e eu preciso aumentar o width dele para que não saia da área de visão. Alguém sabe como?
Segue como tá o meu código e imagem do popover em funcionamento.

<a href="#" data-toggle="popover" data-placement="left" data-trigger="hover" title="Informação" data-content="conteudo vem aqui">

-
$('[data-toggle="popover"]').popover({html: true});

Bibliotecas que estou utilizando além do arquivo Bootstrap.min.css baixado no site, a versão é a 3.3.7:

<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.3.1/css/all.css">

Comment: Cara vc está usando alguma outra biblioteca que tenha esse popover? Pois ele não parece ser o modelo default do Boostrap... Coloquei esse seu código ai usando os arquivos padrão da documentação eu não consegui simular esse comportamento. Inclua as demais informações na pergunta. Arquivos CSS e JS extras que tenha usado e tudo mais
Comment: @hugocsl atualizei a pergunta com todas as bibliotecas que estou utilizando
Answer: Você pode aumentar não só o width do popover como qualquer outra propriedade Css dele normalmente:

$(function() {
  $('[data-toggle="popover"]').popover({html: true})
})
.popover-content {
    color: red;
    font-size: 10px;
    width: 300px;             // aumenta o width
}
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.3.1/css/all.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

<a href="#" data-teste="popover" data-toggle="popover" data-placement="right" data-trigger="hover" title="Informação" data-content="conteudo vem aqui">
Comment: Teu método tbm me mostrou que da pra alterar não só o width, muito bom!
Answer: A class .popover do Bootstrap 3 tem um max-width default de 270px, basta vc substituir esse valor no .popover que venha seguido do buttom que tenha um id por exemplo...
#teste + .popover {
    max-width: 350px;
}

Eu fiz assim, repare que um .popover tem uma largura default de 270px, e o .popover que vir depois do buttom com id="teste" vai ter a largura que coloquei no CSS de 350px

$('[data-toggle="popover"]').popover({html: true});
#teste + .popover {
    max-width: 350px;
}
<link rel="stylesheet" type="text/css" media="screen" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" />

<button type="button" id="teste" class="btn btn-lg btn-danger" data-toggle="popover" title="Popover title" data-content="And here's some amazing content. It's very engaging. Right?">345</button>

<button type="button" class="btn btn-lg btn-danger" data-toggle="popover" title="Popover title" data-content="And here's some amazing content. It's very engaging. Right?">123</button>

Veja pelo DevTools que quando vc clica no buttom é adicionada em seguida dele uma div com a classe .popover conforme imagem abaixo:

OBS: Aqui está a documentação oficial do Bootstrap 3 sobre o Popover: https://getbootstrap.com/docs/3.3/javascript/#live-demo-1
Comment: Sua resposta resolveu meu problema, obrigada!
Comment: @C.Oli legal que deu certo! Boa sorte ai com o projeto!


How many data points are in a given quantile in Quantile regression?

Question: I hope somebody can help me with a, probably very fundamental, issue of understanding concerning quantile regression.
My dataset is very skewed, so I've looking at the data with quantile regression because of all the literature claiming that this allows us to make inferrences about the marginal parts of the distribution. However, when we're dealing with a specific quantile, isn't the usual way of frameing this quantile as 'quantile x contains all values below y'.
So, if I perform quantile regression in for all the centiles (0.1,0.2,...,0.9). And I e.g. look at the results for quantile 0.8. Am I then looking at regression coefficients calculated for all members of the dataset below the 0.8 quantile value? Or exactly 'how far back' do the regression include data points?
Attempting to illustrate with graphics...when I look at regression coefficients for the 0.8 quantile, how much of my data is included in the calculation of these results? The entire distribution up until 0.8, or just the members between the current and the previous QR regression point (0.7)
Comment: The title "Quartile plot" is certainly a typo for "Quantile plot". More importantly, as both scales go from 0 to 1, it's hard work to figure out what is being plotted. Abuse of terminology abounds in the literature, but historically quantiles are values of a variable corresponding to particular cumulative probabilities. So, for example median and quartiles correspond to cumulative probability 0.5 and (0.25, 0.75) respectively. The name or label of a quantile (e.g. that for cumulative probability 0.25) should not be confused with its value (42, or whatever).
Answer: Quantile regression uses the full distribution for every quantile. The best way to understand it is to think of regular linear regression. Regular linear regression is providing an estimate of how much covariate  $A$ affects the mean of the outcome $y$. Quantile regression on the Median (50th percentile) provides an estimate of how much covariate $A$ affects the position of Median of the outcome $y$. You need the whole distribution to determine the position of the median (i.e. the point at which 50% of $y$ is above and 50% of $y$ is below).
The same reasoning carries over to the 80th percentile. Quantile regresion tells you how much covariate $A$ affects the position of the 80th percentile, i.e. the point at which 20% of the sample is above, and 80% is below. So it uses the whole distribution to calculate this estimate.
Your example plot is confusing. In future please provide actual code and sample data used to produce such a plot so we can give you more direct insight.
So using a sample data set examining the effects of income on food expenditure in R we have:
<code>library(quantreg)
data(engel) # data in quantreg to be used as a useful example
head(engel)
Linear.Regression <- coef(summary(lm(foodexp ~ income, data=engel)))
Median <- coef(summary(rq(foodexp ~ income, tau=0.5, data=engel)))
Eightieth <- coef(summary(rq(foodexp ~ income, tau= 0.8, data=engel)))

plot(x=engel$income, y=engel$foodexp, cex=0.5,
     xlab="Income", ylab="Food Expenditure")
abline(a=Linear.Regression[1,1], b=Linear.Regression[2,1],
       col="red")
abline(a=Median[1,1], b=Median[2,1], col="blue")
abline(a=Eightieth[1,1], b=Eightieth[2,1], col="green")
</code>
You get a plot that looks like this:

The red line is the linear estimate, the blue line is the median estimate (50th percentile), and the green line is the 80th percentile estimate.
Note: this example is the same one provided by Roger Koenker 2005 "Quantile regression"
Comment: Helpful. For those struggling with red and green, the red line mostly lies below the others and the green mostly above.


How to reconcile the frequentist method with assessing the fairness of a coin?

Question: Imagine I have a factory for assessing the fairness of coins. I have no assumptions on the coins; i.e, a given coin has an equal probability of exhibiting any form of "bias". For example. the probability of a coin being exactly fair (50-50) is the same as the probability of it being "biased" towards head in a 70-30 ratio.
If I were to toss a given coin a given amount of times (thus creating a sample), over time I would have come up with a binomial distribution for coins with the same bias. Well, that is given a fixed amount of times per sample, but if I were to try and generalize my method and not give a fixed amount, I would come out with a "continuous form of a binomial distribution". Let's call it a "sample distribution".
If I were to try and come up with the sum of PDFs of all of the possible sample distributions (one for each coin bias ratio), I would imagine I would have come up with a U shaped function (much like the PDF of a beta distribution with a=b<1). In a sense, this function would describe the PDF of the distribution of sample results over time for all of the coins coming into my factory in a world where my initial assumption is correct.
If I understand correctly, according to the frequentist paradigm, my confidence level and interval would be the same for any sample result (given that I do not change the sample size), but in a world where my initial assumption is correct, that would mean that I would be wrongly skewed in my estimations of coins; i.e, my estimations would determine that the proportion of bias in coins is far greater than it actually is.
How do I reconcile this?
Update
I believe I have missed a crucial point in the definition of the confidence interval, where it says that the interval's width is not only dependent on the confidence level and the sample size, but also on the sample's variance - the larger the sample variance, the larger the interval width.
In terms of our sample -- a binomial experiment -- the variance of a sample can be intuitively expressed in the ratio between 1's and 0's, which is expected to be lower as we stray from 50%. It also probably important to take into consideration that the binomial distribution for every p will approach a limit (CLT?), indicating that samples of a fair coin (0.5) should not exhibit small variance with a large enough sample.
This means that the larger the coin bias is (further from 0.5), the smaller its interval width would be (or given a fixed desired interval width, the higher the confidence level would be), which is in fact even "worse" than if the interval would've been fixed to the sample size and confidence level (regardless of sample variance).
Comment: What you refer to as a "sample distribution" sounds like a *posterior distribution* and your "continuous form of a binomial distribution" would be a Beta distribution.  The rules of probability, as embodied in Bayes' Theorem (which a frequentist would use in this setting!), imply the posterior distribution would not be U-shaped.  What all this suggests is that you investigate the basic theory of estimation so that you can carry out calculations correctly: that will effect the desired reconciliation. For Web research, good keywords are "conjugate prior," "Beta", and "Binomial."
Comment: @whuber I'd rather not delve into Bayesian concepts for the sake of this question, as it seems to me that they add complexity for the purpose of optimization of estimations, which is not an interest of this question. Regardless, I find it hard to understand why such a "sample distribution" would not be U shaped, and what shape would it take otherwise. My reasoning for it being U shaped is that the variance in binomial distribution decrease as we stray from 0.5, meaning that the edges will be more dense, thus having higher values when summing all of the distributions together.
Comment: @whuber (can't edit previous comment) I meant that the sum of all of the "sample distributions" would be U shaped, not that any individual "sample distribution" would be U shaped (they would be reversed-U / bell shaped).
Comment: @whuber Isn't the sum of all the "sample distribution" (what I concluded to be a U shaped function akin to a beta with a=b<1) is just the jeffreys' prior probability for a bernoulli trial -- Beta(1/2, 1/2)?
Comment: You have formulated your situation explicitly in terms of a prior distribution ("I have no assumptions about the coins" *really* means you are assuming a uniform prior), so there's no avoiding "Bayesian concepts," even though this is a frequentist analysis.  I see no way to interpret your "sum of sample distributions" as a prior distribution.
Comment: @whuber I'm really not proficient in the Bayesian terminology and its concepts, as they seem much more complex. I am not interested in assessing this question under different assumptions, but rather to have no assumption and to only apply the principle of indifference. In such a case, I conclude that the distribution of the samples over time would yield a U-shaped distribution. I don't know if it counts as a prior distribution because I am not proficient in this term. I'm merely observing that in this reality, the frequentist method would be "biased" towards coin-unfairness.
Comment: The "principle of indifference," unfortunately, is purely Bayesian.  Your conclusion is mathematically contrary to your assumptions.  Bayes' Theorem applies even in frequentist calculations, so use it!
Comment: @whuber You're saying a frequentist would not use confidence intervals for this problem? If so, then in what problems a frequentist would use them? or rather, if the Bayes' theorem would not have been thought of, how would a frequentist approach this problem?
Comment: The frequentist approach is *identical* to the Bayesian approach because you have stipulated a definite prior.  The Bayesian approach departs from the frequentist approach only where there isn't a definite way to choose a prior.  Indeed, many frequentist methods--including confidence intervals procedures--are justified through analyses that use prior probabilities.
Comment: @whuber I am still left confused as to when should one use confidence intervals. Actually, according to the wikipedia article on this matter (1), it is said that the frequentist approach would assume a fixed maximum error (in a sense, using an interval width as in the 0.5 case, which is the least confident one). Even with a fixed interval not depending on the variance of the actual coin, it still seems to me that the estimate is "biased" (not in a technical sense) and isn't fit for this case.  (1) https://en.wikipedia.org/wiki/Checking_whether_a_coin_is_fair
Answer:
If I understand correctly, according to the frequentist paradigm, my confidence level and interval would be the same for any sample result (given that I do not change the sample size)

Hm, for binomial distributions, your confidence interval depends on p(1-p), so it wouldn't be the same.
Also, with a frequentist approach (e.g., MLE) you don't make an assumption about 50/50, but you simply observe the ratio. I.e., your estimate is "heads / (heads+tails)".
You can make an assumption in the Bayes approach for your 50/50 estimate and do MAP. E.g., your estimate can become
$$
\hat{\theta}=\frac{\left(heads+\gamma_{1}\right)}{\left(heads+\gamma_{1}\right)+\left(tails+\gamma_{0}\right)}
$$
where you can add $\gamma_{1}=\gamma_{0}=0$ for no assumption. Or some arbitrary large values if you want to make a strong 50/50 assumption.
Comment: Why does the interval depend on `p(1-p)`?
Comment: because the variance of a binomial distribution is np(1-p)
Comment: Yes I was missing the part where the variance of the sample is considered when calculating the interval. Take a look at the "update" section of the question.
Comment: Reg the updated question: "This means that the larger the coin bias is (further from 0.5), the smaller its interval width would be (or given a fixed desired interval width, the higher the confidence level would be), which is in fact even "worse" than if the interval would've been fixed to the sample size and confidence level (regardless of sample variance)." yeah, but this is intuitive, right? If you have a 50/50 ratio, there is more randomness (entropy if you will), so the confidence interval should be larger because it's easier to skew your estimate in either direction.
Comment: Yep. I guess I had the notion that somehow the frequentist paradigm had an answer to this unfortunate nature of reality. Seems not :)
Comment: As a general comment about your comment: I would say that frequentist statistics are a great approach most of the time, if you don't have any additional information about a given problem except what you observe :)


Will Tunneling help in this scenario?

Question: I have a computer running 24 hours at a site protecteed by firewall, this computer call it 'A' can connect to internet but unable to host a site since the port is blocked.
I have an idea to purchase a VPS and host a website there call it 'B', however VPS often comes with low storage size for my files. My idea is when a client browse 'B' website and click a link to download a file, the file will be fetched from computer 'A'
so the case is
1. Client browse web hosted in VPS (computer 'B')
2. Client request to download a file from 'B'
3. 'B' connect to 'A' via tunneling and get the file from 'A'.
Do you think tunneling can serve this purpose or should is there any other method?
I hope this is related to server things.
Comment: As Lucas notes, it's kind of a shitty setup.  An alternative is to host the static assets on Amazon S3: http://docs.amazonwebservices.com/AmazonS3/latest/dev/WebsiteHosting.html  If your site is entirely static, hosting on S3 may be a less expensive option than the VPS.
Answer: You can, indeed, do that with a tunnel and ftp the files. Another possibility is a networkshare.
But in my opinion this is a bit of shitty setup. If the connection between your PC and VPS ever drops, your website breaks.
I think you should invest more in a VPS and get a bigger drive, or get some type of external filehosting.
Comment: Hi Lucas, thanks for answering. My website is not really an important site, just for groups of our community, so I prefer cheaper solution.

Will Tunneling help in this scenario?


tkinter list of labels not displaying properly

Question: I'm setting up a simple GUI to display the status of network ports.  If I use individual commands for each label, this works fine:
from tkinter import *

root = Tk()
root.geometry('400x225')
root.configure(background='white')
pFontsize = 10

p1 = Label(root, text = '1', background = 'white',font=('Calibri', pFontsize),anchor='center').place(relwidth = 1/14, relheight = 1/10, relx = 1/14, rely = 2/10)
p2 = Label(root, text = '2', background = 'white',font=('Calibri', pFontsize),anchor='center').place(relwidth = 1/14, relheight = 1/10, relx = 2/14, rely = 2/10)
p3 = Label(root, text = '3', background = 'white',font=('Calibri', pFontsize),anchor='center').place(relwidth = 1/14, relheight = 1/10, relx = 3/14, rely = 2/10)
p4 = Label(root, text = '4', background = 'white',font=('Calibri', pFontsize),anchor='center').place(relwidth = 1/14, relheight = 1/10, relx = 4/14, rely = 2/10)
p5 = Label(root, text = '5', background = 'white',font=('Calibri', pFontsize),anchor='center').place(relwidth = 1/14, relheight = 1/10, relx = 5/14, rely = 2/10)
p6 = Label(root, text = '6', background = 'white',font=('Calibri', pFontsize),anchor='center').place(relwidth = 1/14, relheight = 1/10, relx = 6/14, rely = 2/10)
p7 = Label(root, text = '7', background = 'white',font=('Calibri', pFontsize),anchor='center').place(relwidth = 1/14, relheight = 1/10, relx = 7/14, rely = 2/10)
p8 = Label(root, text = '8', background = 'white',font=('Calibri', pFontsize),anchor='center').place(relwidth = 1/14, relheight = 1/10, relx = 8/14, rely = 2/10)
p9 = Label(root, text = '9', background = 'white',font=('Calibri', pFontsize),anchor='center').place(relwidth = 1/14, relheight = 1/10, relx = 9/14, rely = 2/10)
p10 = Label(root, text = '10', background = 'white',font=('Calibri', pFontsize),anchor='center').place(relwidth = 1/14, relheight = 1/10, relx = 10/14, rely = 2/10)
p11 = Label(root, text = '11', background = 'white',font=('Calibri', pFontsize),anchor='center').place(relwidth = 1/14, relheight = 1/10, relx = 11/14, rely = 2/10)
p12 = Label(root, text = '12', background = 'white',font=('Calibri', pFontsize),anchor='center').place(relwidth = 1/14, relheight = 1/10, relx = 12/14, rely = 2/10)
p13 = Label(root, text = '13', background = 'white',font=('Calibri', pFontsize),anchor='center').place(relwidth = 1/14, relheight = 1/10, relx = 1/14, rely = 5/10)
p14 = Label(root, text = '14', background = 'white',font=('Calibri', pFontsize),anchor='center').place(relwidth = 1/14, relheight = 1/10, relx = 2/14, rely = 5/10)
p15 = Label(root, text = '15', background = 'white',font=('Calibri', pFontsize),anchor='center').place(relwidth = 1/14, relheight = 1/10, relx = 3/14, rely = 5/10)
p16 = Label(root, text = '16', background = 'white',font=('Calibri', pFontsize),anchor='center').place(relwidth = 1/14, relheight = 1/10, relx = 4/14, rely = 5/10)
p17 = Label(root, text = '17', background = 'white',font=('Calibri', pFontsize),anchor='center').place(relwidth = 1/14, relheight = 1/10, relx = 5/14, rely = 5/10)
p18 = Label(root, text = '18', background = 'white',font=('Calibri', pFontsize),anchor='center').place(relwidth = 1/14, relheight = 1/10, relx = 6/14, rely = 5/10)
p19 = Label(root, text = '19', background = 'white',font=('Calibri', pFontsize),anchor='center').place(relwidth = 1/14, relheight = 1/10, relx = 7/14, rely = 5/10)
p20 = Label(root, text = '20', background = 'white',font=('Calibri', pFontsize),anchor='center').place(relwidth = 1/14, relheight = 1/10, relx = 8/14, rely = 5/10)
p21 = Label(root, text = '21', background = 'white',font=('Calibri', pFontsize),anchor='center').place(relwidth = 1/14, relheight = 1/10, relx = 9/14, rely = 5/10)
p22 = Label(root, text = '22', background = 'white',font=('Calibri', pFontsize),anchor='center').place(relwidth = 1/14, relheight = 1/10, relx = 10/14, rely = 5/10)
p23 = Label(root, text = '23', background = 'white',font=('Calibri', pFontsize),anchor='center').place(relwidth = 1/14, relheight = 1/10, relx = 11/14, rely = 5/10)
p24 = Label(root, text = '24', background = 'white',font=('Calibri', pFontsize),anchor='center').place(relwidth = 1/14, relheight = 1/10, relx = 12/14, rely = 5/10)

i1 = Label(root, background = 'black').place(relwidth = 1/14, relheight = 1/10, relx = 1/14, rely = 3/10)
i2 = Label(root, background = 'black').place(relwidth = 1/14, relheight = 1/10, relx = 2/14, rely = 3/10)
i3 = Label(root, background = 'black').place(relwidth = 1/14, relheight = 1/10, relx = 3/14, rely = 3/10)
i4 = Label(root, background = 'black').place(relwidth = 1/14, relheight = 1/10, relx = 4/14, rely = 3/10)
i5 = Label(root, background = 'black').place(relwidth = 1/14, relheight = 1/10, relx = 5/14, rely = 3/10)
i6 = Label(root, background = 'black').place(relwidth = 1/14, relheight = 1/10, relx = 6/14, rely = 3/10)
i7 = Label(root, background = 'black').place(relwidth = 1/14, relheight = 1/10, relx = 7/14, rely = 3/10)
i8 = Label(root, background = 'black').place(relwidth = 1/14, relheight = 1/10, relx = 8/14, rely = 3/10)
i9 = Label(root, background = 'black').place(relwidth = 1/14, relheight = 1/10, relx = 9/14, rely = 3/10)
i10 = Label(root, background = 'black').place(relwidth = 1/14, relheight = 1/10, relx = 10/14, rely = 3/10)
i11 = Label(root, background = 'black').place(relwidth = 1/14, relheight = 1/10, relx = 11/14, rely = 3/10)
i12 = Label(root, background = 'black').place(relwidth = 1/14, relheight = 1/10, relx = 12/14, rely = 3/10)
i13 = Label(root, background = 'black').place(relwidth = 1/14, relheight = 1/10, relx = 1/14, rely = 6/10)
i14 = Label(root, background = 'black').place(relwidth = 1/14, relheight = 1/10, relx = 2/14, rely = 6/10)
i15 = Label(root, background = 'black').place(relwidth = 1/14, relheight = 1/10, relx = 3/14, rely = 6/10)
i16 = Label(root, background = 'black').place(relwidth = 1/14, relheight = 1/10, relx = 4/14, rely = 6/10)
i17 = Label(root, background = 'black').place(relwidth = 1/14, relheight = 1/10, relx = 5/14, rely = 6/10)
i18 = Label(root, background = 'black').place(relwidth = 1/14, relheight = 1/10, relx = 6/14, rely = 6/10)
i19 = Label(root, background = 'black').place(relwidth = 1/14, relheight = 1/10, relx = 7/14, rely = 6/10)
i20 = Label(root, background = 'black').place(relwidth = 1/14, relheight = 1/10, relx = 8/14, rely = 6/10)
i21 = Label(root, background = 'black').place(relwidth = 1/14, relheight = 1/10, relx = 9/14, rely = 6/10)
i22 = Label(root, background = 'black').place(relwidth = 1/14, relheight = 1/10, relx = 10/14, rely = 6/10)
i23 = Label(root, background = 'black').place(relwidth = 1/14, relheight = 1/10, relx = 11/14, rely = 6/10)
i24 = Label(root, background = 'black').place(relwidth = 1/14, relheight = 1/10, relx = 12/14, rely = 6/10)

root.mainloop()

Working
However, when I create a class then set up a list to do the same thing, I only see one label displayed:
from tkinter import *

root=Tk()
root.geometry('400x225')
#root.attributes('-fullscreen', True)
root.configure(background='white')

class networkPort:
    numFontsize = 10
    num = Label(root, background = 'white',font=('Calibri', numFontsize),anchor='center')
    indicator = Label(root, background = 'black')

ports = []
for i in range(24):
    ports.append(networkPort)
    ports[i].num.configure(text = str(i+1))
    if i > 11:
        y = 4
    else:
        y = 2
    ports[i].num.place(relwidth = 1/14, relheight = 1/10, relx = (i%12 + 1)/14, rely = y/10)
    ports[i].indicator.place(relwidth = 1/14, relheight = 1/10, relx = (i%12 + 1)/14, rely = y+1/10)

root.mainloop()

Not Working
I'm fairly new to Python, so I'm quite confident it's something I'm doing wrong here.  Any suggestions?
Comment: You have used `class variables` instead of `instance variables`.  There is only one set of `class variables` for a class, so you overwrite the `class variables` in each iteration.  Suggest to go through tutorials on Python OOP.
Comment: Yep, I figured something like that was happening when I added a delay to the loop and saw the same label getting redrawn in each location.  The last time I wrote anything with OOP was Borland Turbo Pascal over 30 years ago, so you're right I definitely need to read up.  Thanks for the advice!
Answer: You have used class variables instead of instance variables. There is only one set of class variables for a class, so you overwrite the class variables in each iteration.
Below is an example of using instance variables:
class NetworkPort:
    def __init__(self, master, num):
        numFontsize = 10
        self.num = Label(master, text=num, background='white', font=('Calibri', numFontsize), anchor='center')
        self.indicator = Label(master, background='black')

ports = []
for i in range(24):
    ports.append(NetworkPort(root, i+1))
    y = 4 if i > 11 else 2
    ports[i].num.place(relwidth=1/14, relheight=1/10, relx=(i%12+1)/14, rely=y/10)
    ports[i].indicator.place(relwidth=1/14, relheight=1/10, relx=(i%12+1)/14, rely=(y+1)/10)

Comment: Yep, works perfectly.  Also, I wasn't aware that Python allows that particular if..else syntax.  Thanks again!
Answer: I've managed to adjust it so you maintain the original proportions of the GUI under a class based structure:
from tkinter import *

class NetworkPort:
    def __init__(self, master):
        self.master = master
        master.geometry('400x225')
        master.configure(background='white')
        self.num_font_size = 10

        # List to be populated with indicator widgets
        self.widgets = []

        x = -1
        y = 0

        for i in range(24):

            # On 12 iteration move to new line (y), reset to first column (x)
            if i == 12:
                x = 0
                y = 3

            # Move to new column with each iteration
            else:
                x += 1

            # Generate network port number
            num = Label(master, background='white', text=i + 1, font=('Calibri', self.num_font_size), anchor='center')
            num.place(relwidth=1 / 14, relheight=1 / 10, relx=(x + 1) / 14, rely=(y + 2) / 10)

            # Generate network indicator label
            indicator = Label(master, background='black')
            indicator.place(relwidth=1 / 14, relheight=1 / 10, relx=(x + 1) / 14, rely=(y + 3) / 10)

            # Add indicator label objects to list
            self.widgets.append(indicator)

        # Example of adjusting one specific indicators colour by accessing the widget list
        self.widgets[3].config(bg='red')

if __name__ == "__main__":
    root = Tk()
    NetworkPort(root)
    root.mainloop()

Hopefully that helps, feel free to query anything you're curious about.
Comment: Thanks for that.  Much cleaner code :-)  However, I actually require a list of classes, because in later code each instance will need to be addressed individually by index, eg: to ping, change the background to green/red, then perform specific API calls to reconfigure the specific device attached to each port, based on subsequent QR code input and predefined lookup tables.
Comment: To troubleshoot, I added time.sleep(0.5) and root.update() in between each place command.  It turns out each label actually displays, then disappears as soon as the next place is executed.  So, even though I'm appending a new class instance to the list, it appears to be referencing the same Label object every time???
Comment: You can directly reference the individual tkinter elements added in the `for i in range(24):` by adding the objects to a  list as opposed to creating a list of classes. You can either use `winfo_children` for all objects or, since i imagine you want to just update the indicator labels, create a widget list of just those. I've updated my code to show how you'd update the colour of a single indicator label as an example.
Comment: Understood, and thanks for the updated code.  I agree, if all I was trying to do was implement this on-screen representation, it's a far better way to do it.  However this is not the whole class definition, only the portion which applies to the GUI.  there's a bunch of socket connections, and other things that need to happen individually for each instance.  In the context of the whole application, the snippet provided by acw1668 is actually how it needs to be implemented (which is why it's marked as answered).  My mistake was one of syntax, not design.  Thanks again for your help!


Congruence problem $12x\equiv3\pmod{45}$

Question: $$12x\equiv3\pmod{45}$$
Find all possible solutions to above congruence and show procedure in detail.
Comment: First step: The congruence is equivalent to $4x\equiv 1\pmod{15}$.
Comment: Found and shown, now what?
Comment: Welcome to MathSE! What work have you done on this problem so far, and where are you stuck? This is not a homework-answering site: we want to see that you have done significant work on the problem.
Comment: Then $4x \equiv 16 (mod 15)$.
Answer: As $(12,3,45)=3$
divide throughout by $3$ to find $$4x\equiv1\pmod{15}\equiv16$$
$$4x\equiv16\pmod{15}\iff x\equiv4\pmod{\dfrac{15}{(15,4)}}$$
Answer: Dividing through by $3$ we get , $$4x \equiv 1 \pmod {15} \Rightarrow 4\cdot4x \equiv 4\cdot1 \pmod{15}$$
$$\Rightarrow x\equiv4\pmod{15}$$
$$\Rightarrow x = 15k+4 \text{ where } k \in \mathbb{Z}$$


Change ansible output

Question: I have some tasks with loops and when I run them I get something like this in output:
TASK [mytask : Create files] **********************************************
changed: [localhost] => (item=(censored due to no_log))
changed: [localhost] => (item=(censored due to no_log))
changed: [localhost] => (item=(censored due to no_log))

Is there a way to change it to
TASK [mytask : Create files] **********************************************
changed: [localhost] => (create file1)
changed: [localhost] => (create file2)
changed: [localhost] => (create file3)

without external utils?
Answer: There's loop_control:
- name: create files
  file:
    path: "/tmp/tmp_{{ item }}"
    state: touch
  with_items: [1,2,3]
  loop_control:
    label: "create file {{ item }}"

Change ansible output


Deny windows pop-up error messages with batch or powershell

Question: I am working on a way to start a program via a network drive.(Example follows). Is there a way to suppress these error messages from Windows via Batch or Powershell while the script is running? Or maybe a way to dynamically search for the Network drive without trying all possible ways.
Code Exapmple:
@echo off
start A:"Path to .exe" 2>nul
B...
C...
// For every possible drive letter

Comment: You could use Win32_LogicalDisk and select only those with a Network Drive Type from both Batch and PowerShell. Try searching, using those terms, we're not here to do it all for you.
Comment: I just needed some input cause i cant find anything on the net. Thanks.
Comment: What error messages? The question does not contain any examples. As @Compo said, you can iterate over a list of network drives. It is easier in PowerShell IMO. Then, if the '\path to .exe" exists, you want to run it. Is that correct?
Answer: you can easily get all successfully connected network drives with the net use command. Put a for /f loop around to get the drive letters only:
for /f "tokens=2" %%a in ('net use^|findstr /b "OK"') do (
  start "" "%%a\path to .exe\app.exe"
)


Error message for a subset of dataframe: number of rows of result is not a multiple of vector length (arg 1)

Question: I am trying to get a summary table for a subset of the variables in my dataframe. The subset focuses on numeric variables only. So I created a subset with only numeric variables and calling the subset as numtable. However I am getting an error message:
Warning message:
In cbind(Variables, Missing, Type, Min, Max, Mean, SD) :
  number of rows of result is not a multiple of vector length (arg 1)

Here are the codes:
#Summary of the numeric variables in the dataset
numvars <- names(df) %in% c("age_years", "sex", "sop1", "servcode", "los", "admt", "ptstatus", "msdrg",
                            "msmdc", "sm_er", "diagnosis_order1", "diagnosis_order2", "diagnosis_order3", "diagnosis_order4", "diagnosis_order5",
                            "diagnosis_order1", "diagnosis_order1", "diagnosis_order1", "diagnosis_order1", "diagnosis_order1", "diagnosis_order1",
                            "diagnosis_order6", "diagnosis_order7", "diagnosis_order8", "diagnosis_order9", "diagnosis_order10", "diagnosis_order11", "diagnosis_order12",
                            "diagnosis_order13", "diagnosis_order14", "diagnosis_order15", "diagnosis_order16", "diagnosis_order17", "diagnosis_order18", "diagnosis_order19",
                            "diagnosis_order20" ,"diagnosis_order21", "diagnosis_order22", "diagnosis_order23", "diagnosis_order24", "diagnosis_order25", "diagnosis_order26",
                            "diagnosis_order27", "diagnosis_order28", "diagnosis_order29", "diagnosis_order30", "diagnosis_order31", "diagnosis_order32", "diagnosis_order33",
                            "diagnosis_order34", "diagnosis_order35")
numtable <- df[numvars]
Variables <- names(numtable)
Missing <- sapply(numtable, function(x) sum(is.na(x)))
Type <- sapply(numtable, function(x) class(x))
Min <- sapply(numtable, function(x) min(x, na.rm = TRUE))
Max <- sapply(numtable, function(x) max(x, na.rm = TRUE))
SD <- sapply(numtable, function(x) format(round(sd(x, na.rm=TRUE), 2), nsmall = 2))
Mean <- sapply(numtable, function(x) format(round(mean(x, na.rm=TRUE), 2), nsmall = 2))
#To get the simple table
knitr::kable(as.data.frame(cbind(Variables, Missing, Type, Min, Max, Mean, SD), row.names = FALSE))
#To get the Latex table for the rows
knitr::kable(as.data.frame(cbind(Variables, Missing, Type, Min, Max, Mean, SD), row.names = FALSE), "latex")

Suppose I have this dataframe:
df <- data.frame(age_years = c(33, 11, 45, 67, 8, 99), sex = factor(c(0, 1, 1, 0, 0, 0)))

    > df

          age_years       sex
        1          33          0
        2          11          1
        3          45          1
        4          67          0
        5          8           0
        6          99          0

Answer: My guess is that one of the variable that you have manually selected is not numeric. What does Type return? Do all of them return numeric?
Also you can select the variables dynamically instead of manually selecting them which may lead to errors. Try this approach :
df <- type.convert(df)
numtable <- Filter(is.numeric, df)
Variables <- names(numtable)
Missing <- sapply(numtable, function(x) sum(is.na(x)))
Type <- sapply(numtable, function(x) class(x))
Min <- sapply(numtable, function(x) min(x, na.rm = TRUE))
Max <- sapply(numtable, function(x) max(x, na.rm = TRUE))
SD <- sapply(numtable, function(x) format(round(sd(x, na.rm=TRUE), 2), nsmall = 2))
Mean <- sapply(numtable, function(x) format(round(mean(x, na.rm=TRUE), 2), nsmall = 2))
#To get the simple table
knitr::kable(data.frame(Variables, Missing, Type, Min, Max, Mean, SD))
#To get the Latex table for the rows
knitr::kable(data.frame(Variables, Missing, Type, Min, Max, Mean, SD), "latex")

Comment: Hi, yes all of them return numeric. In the table, I want to include Type as a column showing the type of a variable.
Comment: Then my guess is wrong. Do you get the same error when you use my answer? I tried with `df <- mtcars` and both your code and mine work. Can you provide sample of your dataset with `dput(df)` ?
Comment: No, I don't get any error when I use your answer. But I instead of numeric I am getting integer as type for variables.
Comment: So that is what their `class` is.
Comment: I am doing the same thing character variables as well, actually. The type to indicate whether the variable is a character or numeric.
Comment: Hmmm....Can you provide a small example dataset for us to work with?
Comment: I added a small example dataset with age_years and sex. It from this question: https://stackoverflow.com/questions/66647156/creating-a-label-column-in-r-for-the-unnamed-variables
Comment: Actually I figured it out and accepted your answer. If I exclude ``df <- type.convert(df)`` of your answer then it is fine. I get the output as numeric instead of integers and there are no errors. Btw could you help me with this question please: https://stackoverflow.com/questions/66647156/creating-a-label-column-in-r-for-the-unnamed-variables.


JS import module and run on page load

Question: I want to call my function main() using html onload event and console.log text imported from another (generateObject.js) file, but when I import function, onload event stop working and function main() is not anymore used.
html:
<!DOCTYPE html>

    <meta name="viewport" content="width=device-width, initial-scale=1.0"/>

generateObject.js:
export function hello() {
    return "Hello";
}

main.js:
import { hello } from './generateObject.js';
function main(){
      console.log(hello());
}

main();

When I try console.log("text") in main() it works but when I try to use imported function it's not.
What should I do to fix that?
Errors in Chrome console:
Uncaught SyntaxError: Cannot use import statement outside a module (main.js:1)

index.html:8 Uncaught ReferenceError: main is not defined at onload (index.html:8)

Comment: I have answered your question. check to see if it solves your problem
Comment: are you calling the function in your main.js file? At the end of the file in main.js do this `main()`
Comment: but I want to call it on page load and in html body I have: onload="main()"
Comment: provide a working code snippet as what you have tried. it would be difficult to comment without knowing the context.
Comment: ok, I edited the post, added html code and chrome errors
Answer: modules will have its own scope. They are not available in the global scope like the normal scripts. So it's accessible only inside main.js in your case.
To make it work you need to add it to global scope explicitly.
import { hello } from './generateObject.js';
function main(){
      console.log(hello());
}

window.main = main;

Alternatively, you can remove the event handler from HTML and add it in the JS file.
html
<!DOCTYPE html>

    <meta name="viewport" content="width=device-width, initial-scale=1.0"/>

main.js
import { hello } from './generateObject.js';
function main(){
      console.log(hello());
}

window.addEventListener('load', main)

Comment: change the main.js reference to ``
Comment: This is a CROS error. you would have to run a server. Follow this to create a server `https://www.w3schools.com/nodejs/nodejs_http.asp` or install an npm package like `http-server`
Comment: Thanks, I used  window.addEventListener('load', main)  and secound error is fixed, but first (Uncaught SyntaxError: Cannot use import statement outside a module (main.js:1)) is still there, have you any idea what is wrong?
Comment: :D it brings two others problems in chrome:

Access to script at 'file:///D:/Programming/.Playground/gameInJS/main.js' from origin 'null' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https.

 and

 GET file:///D:/Programming/.Playground/gameInJS/main.js net::ERR_FAILED
Answer: generateObject.js:
export function hello() {
    return "Hello";
}

main.js:
import { hello } from './generateObject.js';
function main(){
      console.log(hello());
}

main();

Working example
Comment: I gather examples are working cause they use Parcel (looks default on codesandbox.io) and as a nota bene says under [https://parceljs.org/getting_started.html#-getting-started](http://web.archive.org/web/20200609063345/https://parceljs.org/getting_started.html) : "Parcel converts JS assets to ES5, which won't run in in the context of a `
Comment: Unfortunately its not help :/
Comment: Hm. Try to use ```window.onload```. Here is the code: https://codesandbox.io/s/priceless-cdn-b686p
Answer: You should add at the end of main.js a call to the main function. Try writing main(); at the bottom of the file.
Comment: Unfortunately its not working, still same errors in chrome console :/

JS import module and run on page load


Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:2.5.1:compile (default-compile)

Question: Ao clicar no install em qualquer um das minhas três partes MVC, ele faz referência ao erro citado.
================================================================================
 Scanning for projects...
[INFO]
[INFO] Using the builder org.apache.maven.lifecycle.internal.builder.singlethreaded.SingleThreadedBuilder with a thread count of 1
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] Building Zeladoria Front-End 0.0.1-SNAPSHOT
[INFO] ------------------------------------------------------------------------
[INFO]
[INFO] --- maven-resources-plugin:2.6:resources (default-resources) @ front-end ---
[WARNING] Using platform encoding (Cp1252 actually) to copy filtered resources, i.e. build is platform dependent!
[INFO] Copying 0 resource
[INFO]
[INFO] --- maven-compiler-plugin:2.5.1:compile (default-compile) @ front-end ---
[WARNING] File encoding has not been set, using platform encoding Cp1252, i.e. build is platform dependent!
[INFO] Compiling 9 source files to C:\Users\eduardo\Desktop\categorias_novo\Versao 3.8 Rodrigo\zeladoria-all\front-end\target\classes
[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 0.875 s
[INFO] Finished at: 2015-05-19T09:38:18-03:00
[INFO] Final Memory: 6M/15M
[INFO] ------------------------------------------------------------------------
[ERROR] Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:2.5.1:compile (default-compile) on project front-end: Fatal error compiling: tools.jar not found: C:\Program Files\Java\jre1.8.0_31\..\lib\tools.jar -> [Help 1]
[ERROR]
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR]
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoExecutionException
================================================================================

Ou seja ela não me permite instalar para poder rodar no Jetty/Apache. Alguém sabe como resolver isso?
Comment: Desde que o ambiente esteja corretamente configurado, JAVA_HOME, PATH e M2_HOME configurados, testar no CMD, com a opção -U, para forçar a baixar os updates.
Answer: Isto acontece por que para compilar o código é necessário um JDK, não um JRE, que é o que está sendo usado pois, ou está no PATH, ou é o padrão configurado na sua IDE.
Veja este trecho:

tools.jar not found: C:\Program Files\Java\jre1.8.0_31..\lib\tools.jar

O tools.jar só existe no JDK, que uma biblioteca não presente no core java e que contém utilitários para o JDK, inclusive para a compilação. Para solucionar isto você deve antes instalar um JDK e então depois configurá-lo.
Caso este usando o maven "embutido", por exemplo no eclipse, basta ir em Window --> Preferences --> Java --> Installed JREs e se não existir um JDK adicionado, basta clicar em Add... e escolher o diretório do JDK. Veja imagem:

Caso esteja usando pela linha de comando, configura JAVA_HOME para o diretório do JDK (algo como C:\Program Files\Java\jdk1.8.0_31 instalado.
Na linha de comando você precisará também configura a variável de ambiente PATH, adicionando a ela %JAVA_HOME%\bin
Comment: Resposta aceita!
Comment: Muito obrigado! É que eu tinha apagado a metadata e por isso ele estava rodando no JRE e não na JDK. Feito o devido add, agora roda de boa.
Comment: Tranquilo @user25240. Caso tenha sido útil, peço que considere aceitar a resposta :)
Comment: Primeira postagem aqui, como faço pra aceitar a sua resposta?
Comment: @user25240 dê uma olhada no [tour](http://pt.stackoverflow.com/tour), lá explica certinho ;)
Comment: Vc saberia me dizer se agora por estar dando erro nos imports se teria algo a ver com isso? Visto que é o mesmo projeto no qual eu estava trabalhando antes.
Comment: @user25240 Quais *imports*? Se for de alguma dependência, veja se a dependência esta sendo resolvida corretamente. Se for preciso inclua uma nova pergunta.


When and where does Panels get the title out of a View?

Question: Two part question about Drupal 7, Panels 3, and Views 3.
I have a view that I have added to a content area in a panels page.  Right now, the title from the display is being used as the pane title.  I need to dynamically set the title of this from a module.

When does Panels pull out the display title from the view?
Where exactly does it pull it out from?

I cannot seem to override this from any view hook.  For example,
function foo_views_pre_view (&$view, &$display_id, &$args)
{
    $view->display[$view->current_display]->display_options["title"] = "Foo";
}

doesn't seem to affect the pane title, though the value does propagate through all of the other view hooks.
I suspect I can create a workaround and use a custom block instead of the view directly, but I would rather not do that in this case.
Thanks.
Answer: I was hoping that someone would answer this, so I wouldn't have to answer my own question when I found the solution.
Credit goes to a co-worker (who doesn't really post here) who reminded me that you also need to update the handler:
function foo_views_pre_view (&$view, &$display_id, &$args)
{
  $view->display[$view->current_display]->display_options["title"] =
  $view->display[$view->current_display]->handler->options["title"] = "Foo";
}

When you do this, the title does propagate properly to the pane title.
Comment: In my case I had to change `$view->display['default']->handler->options['title']` rather than the `$view->current_display`.
Answer: Drupal grabs the view title from the view itself when the view is rendered.
You can over ride this in the panels settings area, by manually setting it.

Revision:
Have you tried doing this with a preprocess function something like
function MYTHEME_preprocess_panels_pane(&$vars) {
 if ($vars['pane']->type == 'node_title') {
  $vars['template_files'][] = 'panels-pane-node-title';
 }
}

Comment: Thanks, but as my question states, I specifically need to set the title from within a module and not the UI.
Comment: The pane preprocess is less than ideal because at this point the $pane->content has rendered content, so which particular view/display was used is now gone.


TableView Cell Button changes other cell's content

Question: Upon clicking a button on a specific tableview cell, the button clicks and changes to a check mark. However, other cells change to a check mark as well. And reloading the tableview does not make the check marks disappear. I understand this has to do with reusable cells. But how do I update the cellForRowAtIndex from a method being called upon clicking the cell's button?
 -(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    // Configure the cell...
    static NSString *ReusableIdentifier = @"Cell";
     SetListTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ReusableIdentifier forIndexPath:indexPath];

    cell.delegate = self;

    if ([self.selectedRows containsIndex:indexPath.row]) {
    [cell.plusButton setBackgroundImage:checkImage forState:UIControlStateNormal];
        }
        else {
            [cell.plusButton setBackgroundImage:plusImage forState:UIControlStateNormal];
        }

    return cell;

    }

Method in custom cell's class.
- (IBAction)addSongButtonPressed:(UIButton *)sender
{
[self.delegate addSongButtonPressedOnCell:self];

UIImage *checkImage = [UIImage imageNamed:@"check.png"];
[self.plusButton setBackgroundImage:checkImage forState:UIControlStateNormal];

}

Method from the cell's delegate.
-(void)addSongButtonPressedOnCell:(id)sender
{
    NSIndexPath *indexPath = [self.searchTableView indexPathForCell:sender];
NSMutableDictionary *track = [self.searchTracks objectAtIndex:indexPath.row];

[self.selectedRows addIndex:indexPath.row];

}

Comment: The problem with your `IBAction` method is that it doesn't track the selection state anywhere *outside* your button - So when the cell is reused you will have lost the selection state.  You are also unable to restore the selection state when a selected cell comes back into view
Comment: You need to show your code for the button click and `cellForRowAtIndexPath`, but you cannot rely on the cell to track state - you need to track state in some other data structure and reflect that when you provide the cell in `cellForRowAtIndexPath`
Comment: Can you provide an example? @Paulw11
Answer: You need to track selection state outside of the cell - the cell is a transient object that displays information from your data model, you can't use it to store state.
Since you have immutable dictionaries for your track data you will need to add an additional data structure to store your selection state.  I would use an NSMutableSet.
Add a property to your view controller
@property (strong,nonatomic) NSMutableSet *selectedRows;

and initialise it in viewDidLoad
self.selectedRows=[NSMutableSet new];

Then you can use to to track/check selection state -
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

// Configure the cell...
static NSString *ReusableIdentifier = @"Cell";
SetListTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ReusableIdentifier forIndexPath:indexPath];

NSDictionary *track = [self.searchTracks objectAtIndex:indexPath.row];
cell.searchSongTitle.text = [track objectForKey:@"title"];
cell.searchArtist.text = [[track objectForKey:@"user"]objectForKey:@"username"];

cell.plusButton.tag=indexPath.row;

if ([self.selectedRows containsIndex:indexPath.row]) {
    [cell.plusButton setBackgroundImage:checkImage forState:UIControlStateNormal];
}
else {
    [cell.plusButton setBackgroundImage:nil forState:UIControlStateNormal];
}

//If there is no picture available. Adds a Custom picture.
if ([[track objectForKey:@"artwork_url"] isEqual:[NSNull null]]){
    cell.searchAlbumArtImage.image = [UIImage imageNamed:@"SoundCloudLogo"];
}
else{
    //Init the cell image with the track's artwork.
            UIImage *cellImage = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:[track objectForKey:@"artwork_url"]]]];
cell.searchAlbumArtImage.image = cellImage;

            }
return cell;

}

And then your button press handler becomes -
- (IBAction)cellAddSongButtonPressed:(UIButton *)sender {
    NSInteger index =  sender.tag;
    [self.selectedRows addIndex:index];
    [sender setBackgroundImage:checkImage forState:UIControlStateNormal];
}

It would be cleaner to create a Track class rather than using an NSDictionary
Comment: thanks, current code still is showing repeats. I need to use the delegate right? In order to access my locally stored searchTracks.
Comment: Note how my code uses the tag that you put into the button.  You can't use the `sender` to find the cell because `sender` is the button.
Comment: Still not working with tagged index. Also, I'm using NSMutableIndexSet
Comment: Are you still setting the tag on the plus button in `cellForRowAtIndexPath`?  It needs to be `indexPath.row`
Comment: You might need to set some breakpoints or add some NSLogs, because the code shown in your question looks OK
Comment: prepareForReuse ended up being the fix.


Admin Menu Extra Items and Errors

Question: Not quite sure how to explain this, but I will go through what I did, and when the errors started happening.
I have enabled the default taxonomy view in Views, changed it to fields, and added a grouped filter.
After saving, I see the error "Warning: htmlspecialchars() expects parameter 1 to be string, array given in check_plain() (line 1583 .../html/includes/bootstrap.inc)." AND suddenly the admin menu has loads of new items in it?

I read up on it, but cant see any fixes, so try disabling and re-enabling the taxonomy view, and also admin menu.
Now the error message has gone, everything works fine, but I am left with all of these extra menu items in the admin menu.
I have logged in as other lower level users, and their admin menus are fine, yet as the super user (with all permissions) I have about 20 or 30 menu items added to the menu before the usual entries.
I have no idea where to start looking with this. The error above seems to happen when a module passes an array through check_plain(), so it usually a module error rather than core. But in this case, it seems to be the taxonomy view that has triggered it, unless its a coincidence.
Can anyone offer guidance?
EDIT: Also tried flushing cache. And worst comes to worse can revert to a backup 5 days ago, but will lose a fair bit of content, so want to avoid this.
EDIT: Looking phpmyadmin, I can see that all of these new menu items have indeed been added to the menu_links table, but do not appear in the structure > menus > management list.
Answer: Reverting the taxonomy view back to its original state, and then rebuilding the changes again made the errors disappear from watchdog, but the management menu and admin menu were still completely messed up.
To fix this, I installed Devel module, and the ran a SQL query to delete all menu rows added by system.
mysql> delete from menu_links where module='system';

I then navigated to /devel/menu/reset
This successfully re-built the management menu, and everything went back to normal.
Note: I also used backup and migrate to quickly clone the website onto a local server and test the changes before making the changes on the production environment.

Admin Menu Extra Items and Errors


Binary classification machine learning

Question: I have

data set (30,000) mapping people to incomes(<=some number  ,>some number)
each instance has 15 features so as age, education.

I would like some advice/pointers as to the best machine learning classifier for my task. To be implemented in Java to train. I have three main choice decision tress, navie bayes or a perception but am not sure which would best fit my problem. Any java implementations i could be pointed in the direction of would also be great. Thanks
Comment: Why are you treating it as a classification problem? For me it sounds more like a regression problem...? If you still want to treat it as a classification task, then why only two groups?
Answer: There's really no way to tell apriori which algorithm will be best for a given problem. The best approach is usually to try several different algorithms, validate them out-of-sample on a test set or through cross-validation, and then choose the algorithm with the lowest out-of-sample error.
Weka is a great Java machine learning library.  I'd also add logistic regression to your list, as it's one of the simplest and most common approaches to binary classification.
Answer: Before selecting learning algorithm you have to answer several questions (actual program and library names follow the long introduction) :

How well do you need to understand the resulting model?
How different do you expect the testing (unknown) cases to be from the training set?

The first question is very important in the cases that you need to  provide a mechanism or causality explanation of the results (i.e. the more educated a person is, the bigger is its income). In these questions you may stick to simple models such as logistic regression or pruned decision trees. If all you need is accurate predictions, then you may try more "black box-ish" methods such as neural networks, random forests etc. Do note though that in these cases you gain flexibility but loose the ability to debug and troubleshoot your models.
Which brings us to a second question: how different do you expect the testing cases to be from the training set? If the answer is "pretty much" or "I don't know", then you have to limit yourself to less flexible models, as your chances to overfit your model raise exponentially with the flexibility (number of parameters and descriptors/predictors) in your model.
You also need to formulate how you compare classifier performance. This hangout provides a nice background on this issue.
Another pivotal issue is the nature of the data. Bayesian classifiers, for example, are most suitable for discrete data, so proper discretization IS an issue, neural networks that user perceptrons handle continuous and discrete values, but you have to be careful how you encode nominal values.
What ready-to-use programs to use
Weka is a java-based program full with loads ready to use machine learning algorithm, evaluation methods etc. There is also excellent data mining book that uses Weka for all the examnples: Data Mining: Practical Machine Learning Tools and Techniques
Knime is somewhat similar to Weka (uses Eclipse), it also has a companion book: Guide to Intelligent Data Analysis
Jubaus is a machine learning framework (no GUI) with Java (among others) bindings.
Pointers to easy-to-understand code for learning purposes
If you want to implement an algorithm by yourself or study from a source-code, I highly recommend Programming Collective intelligence. Although it uses Python and not Java, and also it has been criticized for coding style and too shallow theoretical background, it shows how popular learning algorithms are implemented in easy to comprehend step-by-step manner.
Answer: If you are trying to learn a mapping between people's features to their incomes, then you don't have a binary classification problem, you have a regression problem.
You might start experimenting with linear regression, polynomial regression, and if they fail, move to multi-layer perceptron neural networks (with an unbounded output layer activation function) or support vector machine regression.
Keep in mind that if your data set comes from a random sample of the population, income will be distributed according to a heavy-tailed distribution (e.g. Pareto), that is, there will be a small, but non-negligible, number of people with an income much higher (orders of magnitude) than the average.
This is problematic for typical regression algorithms because it makes the underlying optimization problems "stiff", resulting poor speed or even numerical instability.
Furthermore, evaluating the accuracy of your regression algorithms with standard error measures such as mean squared error might be misleading, because the algorithm will typically mispredict these high-income instances (since they will be probably intrinsically difficult to predict given the input features) and these will have a disproportionally high effect on the overall error measure.
I suggest you might try to preprocess your data applying a log or a log log transformation to incomes, and then normalize them, and all your numeric input features, to fall approximately within some small interval (e.g. -1..1 or 0..1).
Comment: His classes are a binary discretization of income, so that does make it a classification problem (on the question of whether to model this as regression or classification, there is [a big discussion here](http://stats.stackexchange.com/questions/49953/classification-vs-regression-for-prediction-of-the-sign-of-a-continuous-respons/50399?noredirect=1#comment98886_50399)). If he chooses the threshold for discretization right, he can even solve the heavy tail issue you mention (make the class distribution fifty/fifty).
Comment: "(<=some number ,>some number)" I interpreted as a discretization of income into two classes.
Comment: The OP didn't mention discrete classes in the question

Binary classification machine learning


Multiple forms on one page

Question: I try to input several forms into one page via Controller. With code which is
under, I see those forms but after submit one of them, nothing happens. Any of data is send to database. Has anyone idea how to fix this?
<?php

namespace Drupal\Core\Entity\ContentEntityForm;
namespace Drupal\student\Controller;
use Drupal\node\Entity\Node;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Controller\ControllerBase;
use Drupal\node\NodeInterface;
use Drupal\node\Entity;
use Drupal\node\NodeForm;
use Drupal\Core\Form\FormBase;
use Drupal\Core\Url;
use Drupal\Core\Link;
use Drupal\Core\Routing;
use Drupal\Core\Entity\ContentEntityForm;

class SFormController extends ControllerBase {

  function new_form() {

    $build = [];

    foreach ($stud as $id => $name) {

      $node = \Drupal\node\Entity\Node::create(['type' => 'student']);
      $form = \Drupal::service('entity.form_builder')->getForm($node, 'student_form');

      $build[] = $form;
    }
    return $build;
  }
}

?>

Comment: Do you mean multiple versions of the same form on a single page?
Comment: yes, exactly. After page inspect i see they have different id
Answer: You need to make the form ID dynamic, so that it is different for each instance on the page. As you're extending EntityForm, you'll have to extend it, then register your form on the node class, and finally call your form class.

Extend the entity form:
class MyEntityForm extends EntityForm {
  public function getFormId() {
    // The dynamic form ID allows for the form to be
    // reused on a page.
    return parent::getFormId() . '-' . $this->getEntity()->id();
  }
}

Register your form class on the node entity type:
/**
 * Implements hook_entity_type_alter().
 */
function HOOK_entity_type_alter(array &$entity_types) {
  $node = &$entity_types['node'];
  $node->setFormClass('my_form_type', 'Drupal\[MODULE]\Form\MyEntityForm');
}

Call your form from your controller:
  $form = \Drupal::service('entity.form_builder')->getForm($node, 'my_form_type');

Comment: And can i add this to Controller? Or should I change controller to form and create function build() instead of custom newForm() like above?
Comment: You add this to your custom form. It's not related to the controller.
Comment: Looking at your code, I can see you are passing an unsaved node to the form. This means that the entity ID will return null, and the code above as it stands will not work as all instance of the form will still have the same form ID. You will need to decide how the forms can be uniquely identified on your site, and return a dynamic form ID accordingly.
Comment: Are You able to show the most correct way? And I am not sure if i understood you correctly with "You add this to your custom form. It's not related to the controller". Should I change everything to be a Form, and not controller?
Comment: Ahh, I see, it's not a form you've created. I've updated my response accordingly.
Comment: The problem is, that i have those fields from custom content and I've created new form display. I didn't implement those fields in any Form.php. And how can i get $node in my controller?
Comment: And it don't have to be a controller. I can move everything to Form.php, I just thought it is a good way to do this too
Comment: See my updated response above.
Comment: Where should i put  code from step 1 and 2? Should i put $node to controller arguments? I tried put it to .module but i see an error `Class 'EntityForm' not found`
Comment: You need to extend `Drupal\Core\Entity\EntityForm` with a `use` function in your code. As for where to put the code, that's getting into PHP OOP discussions, which are more than I can put in the comments. The solution above requires an understanding of PHP OOP, class extensibility, and autoloading with namespaces.
Comment: `function student_entity_type_build(array &$entity_types) {
  $entity_types['node']->setFormClass('student_form', 'Drupal\node\NodeForm');
}` As you can see here i impelent NodeForm class. How can i connect this with your class? (step 1)
Comment: I am closer but I need to disable redirect, i guess
Comment: i've added `public function submitForm(array &$form, FormStateInterface $form_state) {
    $form_state->setRedirectUrl('');
    return;` to `class MyEntityForm extends EntityForm` with no luck :( any ideas?
Comment: https://drupal.stackexchange.com/questions/163626/how-to-perform-a-redirect-to-custom-page-after-node-save-or-delete that is the answer, now is ok
Comment: Please mark this question as the answer if it was correct.

Multiple forms on one page


How to change bloc state data after a request without sending the request again?

Question: i'm new to flutter and i'm having some trouble with data managment using bloc. I`m building an app that make a request(get_things) using bloc and recieve as response a list of objects( example: {"things": [{"id": 1, "color" : "green"},{"id":2 , "color":"blue"},...] ).
With this response i build a widget presenting these "things" using blocState. Then i make another page that calls the same bloc to create a similar widget,but in this page we can create, modify or delete "things" and make the request to change them on the database (modify_things).
The problem is i'd like both pages to update the list after a change without making a request to backend to rebuild the lists with the modified list.
What i though as a solution was to save the blocState data of the initial request somewhere and then use this locally to make the changes to the widgets(lists). What i mean is, i delete one "thing" and send the request to modify the database, and at the same time i modify the saved blocState list locally to reflect this change. This way i only have to use get_things once and modify_things only when i make changes to the list.
Is this a good aproach? this method seems cumbersome, but as i'm fairly new to flutter so i couldn't think of anything else.
As for what i have the need to make less requests and manage this locally, it's because i've been told that in the future these "things" can get really big, and that making a request everytime i need to see the widget could eventually be a performance issue.
Answer: If I understand you correctly, you send [{"id": 1, "color" : "green"},{"id":2 , "color":"blue"},...]  to page A and then you want to use the same data on page B.
The clean way, I guess, would be to add an event on page A with myBloc.add([{"id": 1, "color" : "green"},{"id":2 , "color":"blue"},...] ) which also triggers page B to load. Then myBloc yields a state with that and potentially more data, showing page B.
But of course you could also declare a PageADisplayState storedState; in myBloc  and then before yielding the state store it by storedState = things; yield PageADisplayState(things);
Comment: i already get the data on page B  by calling the page A bloc that make the request get_things. Then i make a widget that allows me  to select a "thing", edit it and then send the request edit_things to reflect the change on my database. What im trying to do is to get this new modified list of things to display in both pages without the need to make a request everytime i refresh the page.  I guess what i'm asking is if the data stored on my blocState can be modified without checking the backend for changes. Please let me know if i'm not being clear enough.
Comment: If you have 2 blocs, you can use my Q&A here to send data back to blocA: https://stackoverflow.com/questions/64011595/flutter-inter-bloc-communication-passing-data-events-between-different-blocs. To not trigger a new backend request I sometimes simply store the data as a var in that bloc and use `if (myVar == null) then myVar = getData()`. So data is pulled on first execution, then I reuse or manipulate that data
Comment: What a coincidence! I was just thinking about doing exactly that. I think my problem was thinking that this was a messy solution. I'm trying to use clean architecture with bloc, so the idea of intentionally avoid using the blocState for everything is a bit alien to me. I appreciate the input.
Comment: I will ! But before that i have another question you may be able to help with. i'm having trouble managing myVar with the list inside. I'd like to use it to build the widgets in these pages that manage my "things". i've been reading about state managment a bit but i'm a clueless about how to make myVar is shared across the pages so when it's modified(edit or delete "things"), every page can reflect the change after a refresh. It should work like some "global variable" across the pages that involve this list of "things".  I appreciate the help!


Inner Join está retornando resultados repetidos

Question: Possuo três tabelas! Sendo uma delas uma tabela de relação!
São elas:
Pessoa:
Tratamento:
Tabela de Relação entre Pessoa e Tratamento:
Gostaria que ao passar o ID da pessoa, a consulta retornasse os NOMES dos tratamentos selecionados.
Exemplo:
ID 8, ele retornaria Reiki e Astrologia; ID 9, ele retornaria Reiki, Astrologia e Coaching Desenvolvimento Pessoal!
O que está acontecendo na minha consulta:
Já tentei fazer a consulta colocando Distinct, mas não está dando certo! É como se ele estivesse retornando dois resultados(o que eu espero são dois resultados mesmo) só que está vindo todos os outros tratamentos também.
Meu trecho de código:
Select * FROM tratamento INNER JOIN pessoa_tratamento_r ON 8 = pessoa_tratamento_r.ID_PESSOA

Desde já agradeço a ajuda! E por favor, se quiserem colocar links ou outras indicações para estudo, façam isso! Se há outras maneiras também de fazer esta pesquisa, por favor, digam!
Comment: `select t.nome from tratamento t inner join pessoa_tratamento pt on pt.id_tratamento = t.id_tratamento  and pt.id_pessoa = 8`
Answer: Faltou relacionar as chaves das tabelas (FK da pessoa_tratamento com a PK da tratamento) no JOIN, conforme o @Rovann comentou ficaria assim:
select t.nome
from tratamento t
     inner join pessoa_tratamento pt on pt.id_tratamento = t.id_tratamento
where pt.id_pessoa = 8


How to call field label & values in custom content type page template

Question: I have created a custom page--mycontent-type.page.tpl for customizing display with html tags classes & attributes.
I'am unable to call that content type fields & their label.
I've tried these to print values but not worked for me.

<?php print render($content['field_name']); ?>
<?php print render($page['content']['field_name']); ?>
<?php print render($fields['field_introduction']->content); ?>

Please suggest me what code call the actual fields & label. Thanks in advance :)
Comment: page tpl's are quite high level and after all of the content has been pulled together for rendering. If you want to change things on a specific content type you might be better using node--mycontent-type.tpl.php. Or is there a specific reason you need the node fields in the page.tpl
Comment: Yes I have some specific reason to call field's label & its value individually and add many classes attributes some javascript and extra headings that I'am unable to do by field formatter class module.
Comment: If you're not preprocessing then it won't matter what template you're using. I don't see how a page template changes this vs a node template. These variables don't exist at the page level.
Comment: The question wasn't very clear but the reason I suggested it would be in a page.tpl within $content you'd only have the regions. Within the node tpl you'd have the actual node fields within $content (plus $node) which looked to be what he was after
Comment: Thanks, gentleman for your suggestions.....The reason being I am asking this question because my design is ready with html css javascript jquery.....the problem I am facing in customizing it to drupal 7 theme is that the Labels & values has lots of css classes & attributes & some inline javascript. So I am unable to put those classes javascript by content type manage display field formatter method. Please suggest me some solution for this
Answer: For the objective of adding classes to fields in a node (as you made clear in your comment) you can use hook_node_view to intercept the node and then you can change the markup of your fields.
You can find detailed examples here.