Generics..? Super T

Question:
Possible Duplicate:
what is the difference between 'super' and 'extends' in Java Generics

A)
List<? super Shape> shapeSuper = new ArrayList<Shape>();

shapeSuper.add(new Square());       //extends from SHAP
shapeSuper.add(new DoubleSquare()); //extends from SQ
shapeSuper.add(new TripleSquare()); //extends from DS
shapeSuper.add(new Rectangle());    //extends from SHAP
shapeSuper.add(new Circle());       //extends from SHAP

for (Object object : shapeSuper) { ... }

Why must the iteration be of Objects when I can add only Shape and its
derivatives?
B)
List<? super Shape> shapeSuper = new ArrayList<Object>();

shapeSuper.add(new Object()); //compilation error

Why does the above line produce a compilation error?
Comment: Out of curiousity, what is the benefit of doing this over defining a Shape interface and then just creating a List? You can still test for specific classes and cast if necessary...
Answer: For your example, you can use a plain List<Shape> like Dan and Paul said; you don't need to use the wildcard question mark syntax such as List<? super Shape> or List<? extends Shape>). I think your underlying question may be, "when would I use one of the question mark style declarations?" (The Get and Put Principle that Julien cites is a great answer to this question, but I don't think it makes much sense unless you see it in the context of an example.) Here's my take at an expanded version of the Get and Put Principle for when to use wildcards.
Use <? extends T> if...

A method has a generic class
parameter Foo<T> readSource
The method GETS instances of T from readSource, and doesn't care if the actual object retrieved belongs to a subclass of T.

Use <? super T> if...

A method has a generic class parameter Foo<T> writeDest
The method PUTS instances of T into writeDest, and doesn't care if writeDest also contains objects that are subclasses of T.

Here's a walkthrough of a specific example that illustrates the thinking behind wildcards. Imagine you are writing a processSquare method that removes a square from a list, processes it, and stores the result in an output list. Here's a method signature:
void processSquare(List<Square> iSqua, List<Square> oSqua)
{ Square s = iSqua.remove(0); s.doSquare(); oSqua.add(s); }

Now you create a list of DoubleSquares, which extend Square, and try to process them:
List<DoubleSquare> dsqares = ...
List<Square> processed = new ArrayList<Square>;
processSquare(dsqares, processed); // compiler error! dsquares is not List<Square>

The compiler fails with an error because the type of dsquares List<DoubleSquare> doesn't match the type of the first parameter to processSquare, List<Square>. Perhaps a DoubleSquare is-a Square, but you need to tell the compiler that a List<DoubleSquare> is-a List<Square> for the purposes of your processSquare method. Use the <? extends Square> wildcard to tell the compiler that your method can take a List of any subclass of Square.
void processSquare(List<? extends Square> iSqua, List<Square> oSqua)

Next you improve the application to process Circles as well as Squares. You want to aggregate all your processed shapes in a single list that includes both circles and squares, so you changed the type of the processed list from a List<Square> to a List<Shape>:
List<DoubleSquare> dsqares = ...
List<Circle> circles = ...
List<Shape> processed = new ArrayList<Square>;
processSquare(dsqares, processed); // compiler error! processed is not List<Square>

The compiler fails with a new error. Now the type of the processed list List<Shape> doesn't match the 2nd parameter to processSquare, List<Square>. Use the <? super Square> wildcard to tell the compiler that a given parameter can be a List of any superclass of Square.
void processSquare(List<? extends Square> iSqua,
                          List<? super Square> oSqua)

Here's the full source code for the example. Sometimes I find it easier to learn stuff by starting with a working example and then breaking it to see how the compiler reacts.
package wild;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

public abstract class Main {
  // In processing the square,
  // I'll take for input  any type of List that can PRODUCE (read) squares.
  // I'll take for output any type of List that can ACCEPT (write) squares.
  static void processSquare(List<? extends Square> iSqua, List<? super Square> oSqua)
  { Square s = iSqua.remove(0); s.doSquare(); oSqua.add(s); }

  static void processCircle(List<? extends Circle> iCirc, List<? super Circle> oCirc)
  { Circle c = iCirc.remove(0); c.doCircle(); oCirc.add(c); }

  public static void main(String[] args) {
    // Load some inputs
    List<Circle> circles = makeList(new Circle());
    List<DoubleSquare> dsqares = makeList(new DoubleSquare());

    // Collated storage for completed shapes
    List<Shape> processed = new ArrayList<Shape>();

    // Process the shapes
    processSquare(dsqares, processed);
    processCircle(circles, processed);

    // Do post-processing
    for (Shape s : processed)
      s.shapeDone();
  }

  static class Shape { void shapeDone() { System.out.println("Done with shape."); } }
  static class Square extends Shape { void doSquare() { System.out.println("Square!"); } }
  static class DoubleSquare extends Square {}
  static class Circle extends Shape { void doCircle() { System.out.println("Circle!"); } }

  static <T> List<T> makeList(T a) {
    List<T> list = new LinkedList<T>(); list.add(a); return list;
  }

}

Comment: Disagree about the long post. Sure it took me a couple of minutes to read and digest, but I'm grateful for the detailed and practical explanation. I have a better understanding now than I did before. If readers aren't prepared to give a few minutes in order to understand some fairly intricate rules then they might as well not bother trying to understand it.
Comment: @ThisIsTheDave Then what's the difference between **** and **** ?
Comment: +1 The more I've read, the more I wanted to upvote you. You really deserve more upvotes. Thank you for the long post.
Answer: To expand on Paul's answer, by declaring shapeSuper as List<? super Shape>, you are saying that it can accept any object that is a super class of Shape.  Object is a superclass of shape.  This means that the common superclass of each of the list's elements is Object.
This is why you have to use the Object type in the for loop.  As far as the compiler is concerned, the list might contain objects that are not Shapes.
Comment: +1 for actually explaining what's wrong. Add a discussion of "? super T" vs. "? extends T" and I'll upvote again. Oh wait...
Comment: hehe mmyers. i like the explanation too., too bad we can't upvote a second time
Answer: The "Get and Put Principle" in section (2.4) is a real gem from Java Generics and Collections:

The Get and Put Principle: use an
  extends wildcard when you only get
  values out of a structure, use super
  wildcard when you only put values into
  a structure, and don't use a wildcard
  when you both get and put.

Also, declaring a type as List<? super Shape> shapeSuper is kind of bad form as it constrains its use. Generally, the only time I use wild cards is in method signatures:
public void foo(List<? super Shape> shapeSuper)

Comment: This is also known as the PECS principle (Effective Java 2nd Ed.).  "Producer Extends, Consumer Super".  If the parameter you are accepting is a producer, use 'extends'.
Comment: @Julien you say to use **super** when we put values. Why will we ever want to cast super-classes of X into X and then put them into a list of X? What's the advantage of using super at all? Why not simply don't use a wildcard regardless of put/get/put+get ?
Comment: @Pacerier this might be an old question but I think reading the book effective java (2008) will help you answer your question.
Answer: Try declaring shapeSuper as List<Shape> instead.  Then you can do
for (Shape shape : shapeSuper)

Answer: A)
Because super indicates the lower bounding class of a generic element. So, List<? super Shape> could represent List<Shape> or List<Object>.
B)
Because the compiler doesn't know what the actual type of List<? super Shape> is.
Your adding an object with shapeSuper.add(new Object()); but the compiler only knows that the the generic type of List is a super type of Shape but doesn't know exactly witch one it is.
In your example, List<? super Shape> could really be List<ShapeBase> forcing the compiler to disallow the shapeSuper.add(new Object()); operation.
Remember, Generics are not covariant.
Answer: (Disclaimer: I've never used "super" as a generic wildcard qualifier, so take this with a grain of salt...)
For (A), actually you can't add Shape and its derivatives, you can only add Shape and its ancestors.  I think maybe what you want is
List<? extends Shape> shapeSuper = new ArrayList<Shape>();

Specifying "extends" means Shape and anything derived from Shape.  Specifying "super" means Shape and anything Shape descended from.
Not sure about (B), unless Object isn't implicit.  What happens if you explicitly declare Shape as public class Shape extends Object?
Comment: The problem with (B) is because you can't add things to a generic container declared with a wildcard parameter.
Comment: Actually, I was wrong. add(new Shape()) works fine. The problem is a little thornier than that.
Answer: In reference to the above, I don't think this is correct:

by declaring shapeSuper as List<? super Shape> shapeSuper , you are saying that it
  can accept any object that is a super
  class of Shape

That does seem the intuitive at first glance, but actually I don't think that's how it works. You cannot insert just any superclass of Shape into shapeSuper. superShape is actually a reference to a List which may be restricted to holding a particular (but unspecified) supertype of Shape.
Lets imagine Shape implements Viewable and Drawable. So in this case the superShape reference may actually point to a List<Viewable> or a List<Drawable> (or indeed a List<Object>) - but we don't know which one. If it's actually a List<Viewable> you should not be able to insert a Drawable instance into it - and the compiler will prevent you from doing this.
The lower bound construct is still actually very useful in making generic classes more flexible. In the following example it allows us to pass into the addShapeToSet method a Set defined to containing any superclass of Shape - and we can still insert a Shape into it:
public void addShapeToSet(Set<? super Shape> set) {
    set.add(new Shape());
}

public void testAddToSet() {
    //these all work fine, because Shape implements all of these:
    addShapeToSet(new HashSet<Viewable>());
    addShapeToSet(new HashSet<Drawable>());
    addShapeToSet(new HashSet<Shape>());
    addShapeToSet(new HashSet<Object>());
}

Generics..? Super T


Solve $(\cos^2{x}+y \sin{2x})\frac{{\rm d}y}{{\rm d}x}+y^2=0$

Question: Solve
$$(\cos^2{x}+y \sin{2x}) \frac{{\rm d}y}{{\rm d}x}+y^2=0$$
Please help me to solve this. It is not possible for me to separate.
Attempt : If $M=\cos^2{x}+y \sin{2x}, N=y^2$ then $M_y=\sin{2x}, N_x=0$ are not equal.
Comment: Then you might want to try to find an integrating factor to multiply the equation by that puts the problem in exact form.
Comment: @mattos Yes. What will be the IF.
Comment: Multiply through your equation by $\mu(x,y)$ and then compute $M_{y}, N_{x}$ from the expressions $M = \mu(\cos^{2}(x)+y\sin(2x))$ and $N = \mu y^{2}$. The condition $M_{y} = N_{x}$ generates a linear, first order PDE in $\mu$ to solve which yields the form of the integrating factor.
Answer: $$(\cos^2{x}+y \sin{2x}) \frac{{\rm d}y}{{\rm d}x}+y^2=0$$
Divide by $\cos^2 x$ (The DE becomes exact):
$$(1+2y \tan x) y'+\dfrac {y^2}{\cos^2 x}=0$$
$$y'+\color {red}{2yy' \tan x +\dfrac {y^2}{\cos^2 x}}=0$$
$$y'+\color{red}{(y^2\tan x)'}=0$$
Integrate.
$$y+y^2\tan x=C$$
Comment: I added some lines Hope it"s clear now @user1942348 The DE is exact after you divide by $\cos^2 x$
Comment: $(y^2\tan x)'$ is not clear
Comment: Differentiate it will be more clear @user1942348  it gives $$2yy'\tan x + y^2/\cos^2x $$ Exactly what you have in the line before that.


Upload very large file is tooo long

Question: I have ASP.NET Core WebApi application and need to upload very large file. I have enabled JWT Auth/Authz
services.AddAuthentication(cfg =>
{
     cfg.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
     cfg.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(JwtBearerDefaults.AuthenticationScheme, cfg =>
{ .. }

TTL of token is 2 minutes.
Then I have action in my controller like
public async Task<IActionResult> Add(IFormFile file)
{
     if (file.Length.ToMegabytes() > 500)
     {
        throw new BadRequestException(nameof(file), "File size should not exceed 500 MB");
     }
}

and config in web host
.UseKestrel(options =>
 {
    options.Limits.MaxRequestBodySize = null;
 })

When I  upload a large file (~1Gb) it is take a long time and then returns 401 before it step into my action.
How can I check that file has not valid size before it will be uploaded? Because uploading take a time more than 2 minutes and in a result I will get 401
Comment: Possible duplicate of [Asp.Net Check file size before upload](https://stackoverflow.com/questions/3094748/asp-net-check-file-size-before-upload)
Comment: It is not a duplicate, because I asked abiut asp.net core webapi but not for asp.net and jquery
Comment: afaik you can't do a proper check before file upload, because you'll need to upload the file in order for the server to know how big the file is.
Comment: but my token will be expire before all checks. how can I handle it without changes lifetime of token
Comment: I think main idea is not changed between any type of framework or lang, you should try to do that check first on client side
Comment: I do not have a client side, I have web api
Answer: The problem is that when modelbinding a file upload, the entire file contents have to be spooled to the server before the action can be invoked. However, particularly if you're uploading large files, you should not be modelbinding the upload, but rather, streaming it. This should have the side effect of getting around your authorization problem, as well, because the action will be invoked immediately.
The docs describe exactly how to stream large file uploads. It's not trivial, but this is how you should do it, regardless, for the best app performance and stability.
Comment: thanks, it make sense. can I use streaming but leave param `IFormFile file` in my action?
Comment: No. You have to manually parse the request body, as the documentation indicates. This is essentially what the modelbinder is doing, except in that case, it must finish streaming the file *before* it can bind the `IFormFile` param. This is because an action with a param cannot be invoked until the modelbinder has provided a value for that param.
Comment: So it means that I can't use Swagger anymore to upload file, right? is there any way to use swagger for streaming?
Comment: That's actually interesting. I hadn't considered the implications of this with something that actually *relies* on the method being self-documenting, like Swagger. *Theoretically*, if you add the attribute that disables modelbinding, I suppose you could keep the param; it just would have no value, so it would be a little confusing from a code perspective.
Comment: There *may* be a way to kind of trick out Swashbuckle/NSwag to tell it to offer an upload field without literally having a param. You'd have to check the respective documentation.

Upload very large file is tooo long


Cannot pass parameter 2 by reference usando PDO like

Question: Estou fazendo uma pesquisa no BD onde os parâmetros são passados e uso o LIKE para pesquisar, só que a pesquisa me retorna o erro PHP Fatal error:  Cannot pass parameter 2 by reference
$this->Query = $this->Conn->prepare('select * '.
                                    'from tabela '.
                                    'inner join tabela2 on tabela.pr_status = prstatus.prstatus_status '.
                                    'where :tableColumn like :inputSearchProtocol'
                                    );
$this->Query->bindParam(':tableColumn'          ,$this->tableColumn);
$this->Query->bindParam(':inputSearchProtocol'  ,'%'.$this->inputSearchProtocol.'%');

O erro no servidor aponta para a linha com o campo '%'.$this->inputSearchProtocol.'%'
Answer: O bindParam() recebe os parâmetros por referência, por isso você não pode usar literais, apenas variáveis.
Usando variável, fica assim:
$variavel = '%'.$this->inputSearchProtocol.'%';
$this->Query->bindParam(':inputSearchProtocol', $variavel);

Mas, provavelmente, é muito mais simples usar bindValue:
$this->Query->bindValue(':inputSearchProtocol'  ,'%'.$this->inputSearchProtocol.'%');

Manual:

https://secure.php.net/manual/pt_BR/pdostatement.bindparam.php

https://secure.php.net/manual/pt_BR/pdostatement.bindvalue.php

https://secure.php.net/manual/pt_BR/language.references.pass.php


Laravel carbon failed to parse time string

Question: I need to select users with specific age from model User, but have this error:
DateTime::__construct(): Failed to parse time string (birth) at position 0 (b): The timezone could not be found in the database

part of controller:
$users = User::where(Carbon::parse('birth')->diff(Carbon::now())->format('%y'), '>=', 18)->get();

when i use it in view all working fine:
 @foreach ($userss as $user)

 <?php  $age_year = Carbon::parse($user->birth)->diff(Carbon::now())->format('%y'); ?>

@endforeach

Thanks for answers!
Comment: I think datetime format issue
Answer: In your controller example, you are trying to parse the string 'birth' instead of the database field 'birth'.
Since you are returning a collection, just run through the returned collections with the filter() method before sending it down to your view. You can also use the age property instead of doing a diff
$users = User::get()->filter(function($user, $key) {
    return (Carbon::parse($user->birth)->age >= 18);
});

I did not test this, so you may get some typos, but this is how you will want to accomplish this task.
Comment: thanks, that's is it. Function is missed: $users = $users_all->filter(function ($patients, $key) {
return (Carbon::parse($user->birth)->age >= 18);
});
Comment: Thanks. I added the function declaration
Answer: try this:
User::where('birth','>=', Carbon::now()->subYears(18)->toDateTimeString());

not tested yet, but hope it works!
Answer: You can use Carbon's diff helper to calculate age, and filter method to filter objects(User in this case).
$users = User::get()->filter($user, $key) {
    return Carbon\Carbon::now()->diff($user->birth)->y >= 18;
});

There are also other helpers functions available with Carbon, some are:
// diffInYears(), diffInMonths(), diffInWeeks()
// diffInDays(), diffInWeekdays(), diffInWeekendDays()
// diffInHours(), diffInMinutes(), diffInSeconds()

Please review this for more information:
http://carbon.nesbot.com/docs/


Methods of variable selection

Question: A study stated that it used forward selection to chose variables for a multivariable regression model (in this case logistic) to evaluate association between predictor and outcome. They started with theoretically plausible variables until they had a decent model, and then tested additional covariates by adding them to the model and checking if the predictor effect size (in this case odds ratio) was changed by 5%. They did not include covariates that did not change the predictor effect size by this (I presume arbitrary?) threshold. I had read the faults of stepwise selection, which uses P-values, but had not come across this method before.

Is this a recognised method and is it any more/less problematic than conventional forward stepwise?
Can someone give an undergrad-level list of common variable selection techniques to read up on? Specifically for epidemiology/sociology, rather than machine learning. I'm coming across penalised regression (lasso/ridge) and PCA (for modelling propensity scores).
I assume variable selection methods depends on the goal of the model (eg. prediction, inference, propensity score, etc)? Can you tell me how/if each technique is suited to each common goals?
Answer: This sounds like a bad idea, though I can't exactly tell what the criterion for adding a predictor to the model was. How can a "predictor's odds ratio" be "changed" by 5% if it was just added to the model?
5% indeed was pulled out of you-know-where. The techniques Spatzle mentioned, forward/backward/best subset, are an improvement, because they base the variables chosen on a metric like AIC, which balances how well the model fits the data with the number of variables in the model (in an attempt to avoid overfitting). However, these algorithms too are actually usually a bad idea! They are "greedy," so they often fail to optimize well, and more importantly they still tend to overfit. It's also hard to interpret p-values/significance from these models since the variables are adaptively selected.
LASSO is a good place to start with variable selection. Ridge regression is less directly suited to variable selection. PCA does dimensionality reduction; variable selection is a specific type of dimensionality reduction that maintains variable definitions. PCA usually will spit out weird linear combinations of the original variables that will be hard to interpret.
The fact is, in the sciences where model interpretability and inference may be more important than predictiveness (i.e. you don't want to just throw all the data in a Random Forest or Neural Net), nothing really beats a careful, scientific approach to the problem. Make sure the variable codings are clean and sensible, and deal with missing data appropriately. Then choose covariates, a model, and functional forms for the covariates based on your scientific knowledge, perhaps tweaking the model slightly after fitting to improve model diagnostics. Some of your coefficients won't be significant, which is fine, and better yet your p-values will be honest!
Comment: _lasso_ has almost no chance of finding the right variables.
Comment: @FrankHarrell  I believe it in so far as the $L_1$ penalty is not omniscient, but could you kindly provide a link to some simulations which might quantify this?
Comment: https://www.fharrell.com/talk/stratos19/
Answer: I'd stick my neck and say that this described method sounds like abusive use of p-values. Moreover, some variables can be insignificant as individuals but significant as a group (see explanation regarding Linear Regression here)
Generally speaking, there are three common methods for variable selection:
a. Best subset
b. Forward selection
c. Backward selection
You can read some more here and here.
If you know Linear Regression well, you must have encountered $R^2$ and its wonderfully evil twin $\bar{R}^2$. The latter can be used as a criterion for adding/subtracting a covariate, like many others (AIC, Mallows' $C_p$ and more, see the above links).
As we cannot use these methods with logistic regression, my personal favorite criteria is proportional confusion matrix (which is confusion matrix divided by the number of samples). If there's an error type you can define as severer, you should look at minimizing it (usually the case with biostatisics, when true negative is worse than false positive); Otherwise, look at maximizing the correct prediction error (e.g modelling Obama vs. Romney, there should be no difference of severity between type 1 and type 2 errors). This is my favorite criterion, while working with backward selection. This can change, of course, depending on the number of predictors and the type of problem.
Comment: None of those methods has a good chance of finding the "right" model.   This is even more true when collinearities are present, and explains why ridge regression usually performs better than lasso or elastic net.
Comment: It doesn't even use p-values; it literally checks the percent change in the OR...
Comment: I think, the reason they are checking for change in OR is to allow for statistical confounding. I can't see why the approach in the study doesn't make sense

Methods of variable selection


How to find the common chord to $2$ parabolas

Question: Is there any method to find the common chord of $2$ intersecting parabolas $?$
I was told that equation of common chord of two parabolas is $S_1-S_2$ where $S_1$ and $S_2$ are equations of the parabolas, which does not seems to work in every case. So can any body help me out.
Thanks in advance.
Comment: Presumably, you find the two points where the parabolas intersect (assuming there are two such points), and find the equation of the line through those two points.
Comment: You need to find the zeros of S1-S2. Then evaluate S1 at those values. This gives you two distinct points. The segment from one another is the common cord.
Comment: hey jean, firstly thanks for replying so fast. consider a case when S1-S2 does not give the eq. of pair of st. lines(indirectly means that they cannot be factorized) then how will we proceed further??
Answer: You would need to start by finding the x-coordinates of their intersections, i.e. the points where $P_1 = P_2$.  In other words, you need to solve the equation $P_1 - P_2 = 0$ which may be where the idea of subtracting the equations came from.  Once you've solved that equation for x, you can use either equation to find the corresponding y values.  At that point, you've got two (x, y) pairs and the equation of the chord will be the equation through those points.
Comment: Solve by substitution:  y = (y^2 - 6y + 11)^2 - 6(y^2 - 6y + 11) + 1.  If you solve that equation,  you'll have the y-coordinates of the two points where the parabolas intersect.  That's going to be a fourth degree equation so solving it may be problematic.  I'll leave multiplying out the right hand side and seeing if it factors as an exercise.  Once you've done that, substitute the two real values that you get into the x = y^2 -  6y + 11 equation and you'll get the corresponding x-coordinates.  Now you know where the parabolas intersect.  Find the equation of the line through those points.
Comment: umm.. i didn't really get what u r saying. i would be happy if u explained with an example. take the parabolas- x=y^2-6y+11 and y=x^2-6x+1 (i have checked on desmos they intersect at 2 points).


First time organizing columns in text file

Question: I am a first time python user. I have a text file of star data that I need to sort the columns and then just take the data from the V band. I have no idea how to start. Can someone please help even if it's to just get me started?
Comment: Yes of course we will help! But we can't unless you give us more details, make the effort of detailing the process, and try to write some code so we can help you fix it.
Comment: Show use the file and the output you want...
Comment: Ok I can try, I'm completely new to to this so it might be difficult.

It's a large file with over 3000 data points, looks to be about 19 columns that aren't lined up properly (I think). The data are magnitudes taken with different filters, the filter I want information from is the V filter.
Comment: Assuming that the file is not in HTML format, the coloums is most likely delimited with spaces, tabs, quotes and/or commas. We need to see some 10-15 lines of the data.
Comment: `JD Magnitude Uncertainty HQuncertainty Band Observer Code Comment Code(s) Comp Star 1 Comp Star 2 Charts Comments Transfomed Airmass Validation Flag Cmag Kmag HJD Star Name Observer Affiliation Measurement Method Grouping Method ADS Reference Digitizer Credit
2446354.1 12.0   Vis. KOA        V    RZ PSC  STD
2446380.0 11.8   Vis. KOA        V    RZ PSC  STD
2446405.0 11.8   Vis. KOA        V    RZ PSC  STD
2446712.1 11.7   Vis. KOA        V    RZ PSC  STD
2446718.0 11.7   Vis. KOA        V    RZ PSC  STD
2446738.9 11.6   Vis. KOA        V    RZ PSC  STD`
Answer: If you can install Pandas from here then sorting on any column can be done like this:
#!/usr/bin/python
# read_stars.py

import sys
import pandas as pd

filename = sys.argv[1]  # or 'star_data.txt'
sep = '\t'  # or ',' or ' ', etc.
df = pd.read_csv(filename, sep)
print df.sort(['Band'])

Change the commented lines to better suit your needs. sep from your comment seems the separator may be tabs (so first try '\t' and change until parsing is successful).sys.argv[1] uses the file passed as a command line argument as such:
$ python read_stars.py star_data.txt
              JD Magnitude  Uncertainty  HQuncertainty  Band Observer Code  \
28  2.456420e+06    16.400        0.073            NaN     V           PSD
29  2.456421e+06     16.09        0.090            NaN     V           DKS

... (etc) ...

42                 STD             NaN           NaN       NaN
0                  STD             NaN           NaN       NaN

[58 rows x 23 columns]

Hope this helps!
Comment: when I enter this in I get this error

`__main__:1: FutureWarning: sort(columns=....) is deprecated, use sort_values(by=.....)`
Comment: That's true, sort(columns=....) is deprecated, change it to use sort_values(by=['Band'])


What happens if /home directory gets 100 percent usage / Debian

Question: My question is pretty simple but another opinion would be nice. We have Debian [2.6.18-6-686] machine, /home is mapped like this
df -h | grep home
/dev/mapper/local_disc-home
                      6,0G  5,1G  580M  90% /home

There are around 150 users folders in /home. My question is, what would happen if usage gets 100 percent. No user will be able to login and all logged users will lost terminals? Or there is some safety mechanism to keep sessions allive? If I understand this right every one user can full up the /home and that will affect all users.
Thx for answers
Answer:
what would happen if usage gets 100 percent. No user will be able to login and all logged users will lost terminals?

Generally, yes, if /home fills up the system will become largely unusable. People will probably not lose their existing terminal sessions, but they will be effectively dead in the water since they will not be able to create any more files.
New logins will generally fail because many tools want to write data into your home directory as part of the login process.  Simple command-line logins (e.g., using ssh) may succeed but the system won't be particularly useful.

If I understand this right every one user can full up the /home and that will affect all users.

This is why many storage administrators implement filesystem quotas...to prevent users from filling up a shared filesystem.  If you have 150 users and only 6GB of space, you want to make sure that no single user can use more than 40MB of space if you want to evenly distribute disk space.
You may also want to purchase additional disk space and expand the filesystem, because it sounds like you're oversubscribed given the number of users and the available space.
Here is an article that talks about using quotas in Linux.
Answer: In addition to larsks' answer: this is the reason why there is a percentage of reserved blocks when you create the file system (or tune it later). These reserved blocks can only be used by the super-user. You could consider this a buffer before even root will be unable to log into the system and rectify the situation.
From mkfs.ext3(8):

-m reserved-blocks-percentage
Specify the percentage of the filesystem blocks reserved for the super-user. This avoids fragmentation, and
  allows root-owned daemons, such as syslogd(8), to continue to
  function correctly after non-privileged processes are prevented from
  writing to the filesystem. The default percentage is 5%.


Como desabilitar controles com JQuery ao carregar a página

Question: Incluir o Código JS abaixo para desabilitar os campos quando o checkbox estiver marcado. Porém, quando eu carrego a página com ele marcado os campos precisam estar desabilitados, e o comando só os desabilita quando ocorre o click.
Como posso desabilitar os controles (textbox) com o carregamento da página?
<code><script type="text/javascript">
    $(document).ready(function ()
    {
        $('#chkContaProvisoria').click(function ()
        {
            if (this.checked)
            {
                $('#DadosConta_Conta_DtValidade').attr("disabled", "disabled");
                $('#DadosConta_Conta_Numero').attr("disabled", "disabled");
            }
            else
            {
                $('#DadosConta_Conta_DtValidade').removeAttr("disabled")
                $('#DadosConta_Conta_Numero').removeAttr("disabled")
            }
        });
    });
</script>
</code>
Apresentação do formulário com os campos
Answer: Podes fazer dessa forma
<code>$(document).ready(function(){
  $('#chkContaProvisoria').click(function ()
    {
        desabilitaTextBox();
    });

    //chama a função apos o carregamento da pagina,
    //se o checkbox estiver marcado ele desabilita o campo.
    desabilitaTextBox();

});

function desabilitaTextBox() {
    if ($('#chkContaProvisoria').is(':checked')) {
         $('#DadosConta_Conta_DtValidade').attr("disabled", "disabled");
         $('#DadosConta_Conta_Numero').attr("disabled", "disabled");
     } else {
         $('#DadosConta_Conta_DtValidade').removeAttr("disabled");
         $('#DadosConta_Conta_Numero').removeAttr("disabled");
     }
}
</code>
Comment: Top.. Funcionou.. valew


WPF - databinding controls in UserControl to class members within the same UC (C#)

Question: How can I databind the controls within my usercontrol to a class instance within the same UserControl in WPF/C#?
For example if I move the slider the value of a certain class member should update. If I change the class or some value within it it should change in the UserControl.
More general question: What is the easiest way to create UserControl that edits and loads public fields of one class?
Edit:
Usercontrol
public partial class ThresholdingSettingsUC : UserControl
{
    public ThresholdingSettings Settings { get; set; }

    public ThresholdingSettingsUC ()
    {
        InitializeComponent ();
    }
}

xaml
<UserControl x:Class="ColonyCounterApp.ThresholdingSettingsUC"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
         xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
         mc:Ignorable="d"
         d:DesignHeight="450" d:DesignWidth="300"

         >

<Grid>
    <DockPanel HorizontalAlignment="Left" Name="dockPanel1" VerticalAlignment="Top" Width="300">
        <GroupBox Header="Hue filter" Height="150" Name="gbHue" DockPanel.Dock="Top">
            <Grid>
                <CheckBox Content="Use hue filtering" Height="16" HorizontalAlignment="Left" Margin="6,6,0,0" Name="cbHue" VerticalAlignment="Top" />
                </Grid>
        </GroupBox/>
    </DockPanel>
</Grid>
</UserControl>

Class that should be bound to the control
public struct ThresholdingSettings:INotifyPropertyChanged
{
    ///
    ///
    ///
    public bool FilterHue {
        get
        { return filterHue; }
        set
        {
            if (filterHue==value)
            {
                return;
            }
            filterHue = value;
            OnPropertyChanged ("FilterHue"); }
        }
    private bool filterHue;

    #region INotifyPropertyChanged Members
    public event PropertyChangedEventHandler PropertyChanged;
    #endregion
    private void OnPropertyChanged (string propertyName)
    {
        PropertyChangedEventHandler h = PropertyChanged;
        if (h != null)
        {
            h (this, new PropertyChangedEventArgs (propertyName));
        }
    }
}

Answer: You could use ElementName (I'm assuming you mean members on the user control itself).
class UserControl1 : UserControl
{
    public UserControl1()
    {
        InitializeComponent();
    }

    public int Value { get; set; }
}

<UserControl xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
             mc:Ignorable="d"
             Name="myUserControl"
             d:DesignHeight="300" d:DesignWidth="300">
    <Grid>
        <Slider Value="{Binding Value, ElementName=myUserControl}" />
    </Grid>
</UserControl>

Answer: You could set the class instance as the DataContext of your userControl and use the default bind mechanism with a relative Path.
To support two way binding (class updates UI, UI updates class) the class should implement INotifyPropertyChanged (or have the specified properties defined as DependencyProperty).
If you cant alter the Class code, you'll need to expose the required properties in the UserControl and invoke it's PropertyChanged event (to allow the UI to update) and update the instance with the new value
Comment: The class implements INotifyPropertyChanged, I still cannot find where to put the databinding...
Comment: ``
Assuming ClassPropertyName is the name of the instance's property you wish to bind to, and that you set the class instance as your UserControl's DataContext


How to define a table of inline values in MySQL?

Question: Here is a way of defining inline table data within a SQL query:
SELECT 1 `id`, 'hello' `name`
UNION ALL
SELECT 2 `id`, 'goodbye' `name`

You can put this into something that expects a query returning the columns id, name and it will work correctly. However, this takes up a lot of unnecessary characters when there are more than one or two rows.
Is there a better way than UNION'ing multiple SELECT's for defining an inline table of values within a MySQL query?
Comment: You could create a temporary table. Here's a duplicate: http://stackoverflow.com/questions/9520442/mysql-create-inline-table-within-select-statement
Answer: If you want a sequence of integers and you're using MariaDB, the MySQL fork, you can use the SEQUENCE storage engine.
SELECT seq FROM seq_0_to_6

for example, will give you a table of integers 0-6.
Other than that, you asked whether there's a more efficient way than a UNION ALL query or a temp table definition to get a so-called inline table.
The answer is no, not really.
But there's one minor efficiency you didn't pick up on.  You don't need to repeat the column names more than once in your UNION ALL cascade.  So, instead of
SELECT 1 id, 'hello' name
UNION ALL
SELECT 2 id, 'goodbye' name
UNION ALL
SELECT 3 id, 'salut' name

You can do this:
SELECT 1 id, 'hello' name
UNION ALL
SELECT 2, 'goodbye'
UNION ALL
SELECT 3, 'salut'

It saves a few characters.
Notice also that UNION ALL is a better choice than UNION because UNION implies the removal of duplicates, which in turn implies a bunch of processing. UNION ALL skips that.


Render TableField

Question: I am using the TableField module and trying to render a field of this type in a custom block. I have tried many different approaches but I am not able to get any output. For instance:
{{ product.entity.field_table.value }}
{{ product.entity.field_table.0.value }}
{{ product.entity.field_table.entity.field_table }}

Can anyone tell me what I am doing wrong here?
I manage to output the table using the following code, but it does not seem to be the best solution:
{% for row in product.entity.field_table.entity.field_table.getValue().0.value %}

  {{ row.0 }}
  {{ row.1 }}

{% endfor%}

Comment: What is the proper structure? Have you debugged the code at all?
Comment: @Kevin - Yes I have tried to debug the code. I'm not sure how to show the entire structure. All other fields works fine, for instance I'm rendering a textarea named `field_ingrediens` like this: `{{ product.entity.field_ingredients.value }}`. The problem seems only to be with fields of type `TableField`.
Comment: I'm guessing the structure of the field is different.
Comment: @Kevin - Look at my update above.
Answer: This may not be the most elegant solution, but based upon your preliminary solution and using the output from {{ dump(tableItem }} (the dump is just commented out in the code below; also see code for meaning of tableItem), I was able to extend getting the necessary values in a generic way to output all the values of a given table. Also, after the table, the following code will output the caption of the tablefield widget. The field_data_tables is the machine name of the tablefield widget for this node. In reference to the original poster, the node in this code would correspond to the product in the OP.
Note that the code  also uses row and col counters because the last col and last row contain non-table values, so we have to exclude those in the {% for ... %} loops.
{# The tableItem is the array of table values in the tablefield widget #}
{# Last row & col contain non-table values so use counters to exclude last row & col #}

{% for tableItem in node.field_data_tables.getValue() %}

        {# dump(tableItem) #}

        {% set rowCount = tableItem['value'] | length %}

          {% set rowCounter = 1 %}

          {% for rows in tableItem['value'] if rowCounter < rowCount %}

            {%  set colCount = rows | length %}

              {% for i in 0..colCount-1 %}
                 {{ rows[i] }}
              {% endfor %}

            {% set rowCounter = rowCounter + 1 %}
          {% endfor %}

        {{ tableItem.caption }}

      {% endfor %}

Render TableField


Configuração de Servidor WHM/Apache + jQuery Ajax

Question: Recentemente comecei a ter o seguinte problema nos domínios do meu servidor com WHM:
Ao executar uma chamada AJAX assincrona em segundo plano, não consigo prosseguir, isto é, não consigo acessar mais nada no mesmo domínio pelo mesmo terminal que executou a chamada enquanto o processo não conclui.
Isso passa a impressão de lentidão no sistema, quando na verdade é apenas o problema de o dominio ficar "bloqueado" enquanto há um processo em segundo plano (mesmo se abrir outra aba do navegador)
Se acessar de outro terminal - ainda que esteja na mesma rede - acessa normalmente.
Isso é algo que acontece em testes locais (usando o PHP Built in) pq o BuiltIn não permite mais de uma conexão simultanea.
Mas isso não deve ocorrer no servidor.
Como antes não era assim, acredito que isso se deva a alguma alteração nas configurações do servidor.
Porém como não faço idéia do que possa ser, não consigo localizar nada nas configurações que possa ocasionar esse comportamento.
Obs: O sistema é feito em PHP 7. O servidor usa apache 2.4 + CloudLinux para evitar abuso de recursos por parte de um único domínio
Comment: @WendelRodrigues muito obrigado pela atenção e ajuda até o momento. Descobri qual foi a alteração do servidor que estava travando: O CORS. Corrigido e funcionando. Assim que tiver um tempo, vou postar a resposta em detalhes. Independenten disso porem, poderia por gentileza detalhar como resposta o que vc colocou a respeito do session_write_close()? Embora não era isso neste caso, mas daí te passo a recompensa pela ajuda prestada
Comment: Você já entrou em contato com suporte do seu servidor? Isso ocorre em qualquer lugar no sistema? Deu uma olhada no Web Console do navegador pra ver se mostra algum erro?
Comment: @WendelRodrigues a resposta é a mesma para as 3 perguntas: Sim. No caso da segunda pergunta, passou a acontecer em todo o sistema, mas só é sentido quando o processo é mais demorado.
Comment: Mas e ai, o suporte disse nada? Viu diferente no console? Tem como postar alguma coisa pra gente ver?
Comment: Talvez esse link possa te ajudar: https://pt.stackoverflow.com/questions/56304/servidor-apache-php-n%C3%A3o-responde-enquanto-est%C3%A1-fazendo-uma-requisi%C3%A7%C3%A3o-soap. Parece ser um problema semelhante ao que você descreveu, por isso quando acessa de outro terminal ele funciona, porque o bloqueio é na sua sessão.
Comment: Pensei nisso tb, mas os arquivos q usam sessão já fecham com session_write_close(), sendo q a maioria não usa sessão
Comment: Cara, o servidor deve estar bloqueando as requisições então. Já verificou isso com eles? Seu servidor tem stats? Vê quais páginas tem mais acessos e se são as que ocasionam os problemas.
Comment: As requisições não estão sendo bloqueadas. Elas executam. Só que uma de cada vez.
Comment: Hum, interessante. Vou dar uma lida sobre isso. Posta sim depois. ;) Vlws
Answer: Problema solucionado
Há um tempo, tive um problema semelhante, relatado aqui: Executando processos em segundo plano - Acessando mesmo script duas vezes
Contudo, desta vez o motivo foi outro: a última atualização de nosso servidor com WHM modificou uma diretiva que impedia o Cross-Domain. E como muitos dos nossos processos usam CORS, estava havendo um bloqueio.
Para corrigir, ao invés de mudarmos no servidor para que funcionasse, fizemos uso da dica neste outro link: Requisição Ajax cross-domain com Javascript puro (sem APIs)
Espero que as dicas nestes 2 links possa ser de ajuda a outros que passem por problemas similares.
Obrigado em especial ao @WendelRodrigues pela ajuda prestada!
Answer: Talvez esse link possa te ajudar: Servidor Apache/PHP não responde enquanto está fazendo uma requisição SOAP Parece ser um problema semelhante ao que você descreveu, por isso quando acessa de outro terminal ele funciona, porque o bloqueio pode ser na sua sessão.


PDOException: SQLSTATE[42S02]: Base table or view not found: 1146 Table

Question: In my site, I get the following error:

PDOException: SQLSTATE[42S02]: Base table or view not found: 1146 Table 'cambodia_ohchrProduction.ohchr_cache_block' doesn't exist: TRUNCATE {cache_block} ; Array ( ) in cache_clear_all() (line 167 of /home/cambodiaohchr/public_html/includes/cache.inc).

How can I fix problem?
Comment: Looks like an issue with database prefixes. Your settings.php file will have this setting and will need to be adjusted most likely.
Comment: Welcome to Drupal Answers! This question is too broad. We cannot debug a site to which we don't have access. We can give general advices, but they would not be much helpful to future readers.
Comment: This error happen when we try to update the content from backend. or we try to do any optration from the backend.
Answer: This error happened to me before, I don't really know why but the only solution that I can really tell you (and it worked for me) is to get some Database backup that you may have saved (from a past date) and export the schemas from the tables cambodia_ohchrProduction and revision_cambodia_ohchrProduction into your actual site .
Remember just the schemas of those 2 tables.
And that should work!
Answer: try to follow this steps they may work for you :

Connect to the cambodia_ohchrProduction database and create the ohchr_cache_block table
clear the cache and test if you have no error.
remove the table that has been create at step 1 and clear the cache again.


Looping through string to find space in MIPs

Question: I'm trying to find a space in a string, I'm getting into the loop but getting stuck. Here's what I have, I just don't know what I'm doing wrong. For the space label I did: space:  .asciiz " " and in the name label is a first and last name separated by one space which the user gives.
li $t0, 0
la $t0, name

la $t1, space

# loop to find space
loop2:

    lb $a0, 0($t0)
    #comparing char to space
    beq $a0, $t1, exit
    addi $t0, $t0, 1

    j loop2

exit:

Comment: There's no need for the `space` string. Just do `beq $a0, ' ', exit`. Or if the assembler doesn't accept that, `li $t2, ' '` before the loop, and then `beq $a0, $t2, exit` inside the loop.
Comment: `beq` compares register values, not pointed-to strings.  Like Michael said, `li $t1, ' '` to put  the space *ASCII character* in a register, not a pointer to it.
Answer: EDIT: $t1 is currently storing an address, you'll have to load the memory from it using lb $t2, 0($t1) or something similar
Also, try using an IDE like MARS to help debug your code
Comment: I am using mars but I deleted the increment and its still doing the same thing


Is there a way to display  firstly by a specified class?

Question: I'm trying to display a
 firstly by a specified class.
Example :

1st Pagaraph

2nd Pagaraph

3rd Pagaraph

Result
2nd Pagaraph -> has class="showfirst"
1st Pagaraph
3rd Pagaraph

How should I do to find class in
 and show that  firstly ?
Comment: Welcome to Stack Overflow! Please take the [tour] (you get a badge!) and read through the [help], in particular [*How do I ask a good question?*](/help/how-to-ask) Your best bet here is to do your research, [search](/help/searching) for related topics on SO, and give it a go. ***If*** you get stuck and can't get unstuck after doing more research and searching, post a [mcve] of your attempt and say specifically where you're stuck. People will be glad to help.
Comment: Also: Putting completely off-topic advertisements for in your profile is *allowed*, but uncool.
Answer: I recommend CSS Grid. You can simply change positions of elements just by using your custom classes, if you want to you can even change their order.
If your showfirst class is set to be at the top via CSS Grid, it will appear at the top.
https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Grid_Layout
Comment: thanks for sharing css grid but it's not what I looking for. I want to display a  firstly by finding a specified class like above example.
Comment: You can create a grid layout with CSS Grid which puts `showfirst` at the top. You can then set the rest to be rendererd after your `showfirst` class. In theory it should work


How much practicing time per week is enough to progress with piano for beginner?

Question: My 11 year old child starts learning piano from scratch, taking 30 min weekly lessons with the teacher. How many additional practicing time per week it is reasonable and clever to allocate for the typical, usual progress?
It is always possible to say "the more the better". However there is also school with other subjects to learn. From the other side, with no or very little time per week may be no sense to take lessons at all.
How much time (hours per week) would be a usual choice in such situation?
Comment: Well, I put it as a comment since in my opinion it doesn't answer your question... Anyway, I do think it could be better to practice daily, and one session should be short enough that one can practice well the whole time. It is mentally hard work, so if you try practicing for an hour it might be that you practice well for 15 minutes and then the rest is just fiddling around making no progress.
Comment: This depends on too many factors... How about you try something, like 15-30min/day of good practice, and then in a couple weeks ask the teacher and the kid how it's working?
Comment: A new idea from your notice is that may be better to allocate short duration daily rather than 1 hour chunk but less frequently. Do I understand this hint correctly?
Comment: For an 11 year old, I would say an hour is probably a bit long, especially if he is a beginner. 15 minutes to a half hour would be better. You don't want the child's mind to start wandering. Also, if you encourage a child to do his best for 15 minutes, then maybe go do his other homework, then come back for 15 more minutes, he will be surprised at how much improvement he makes in the second session. Walking away and coming back to a problem often solves the problem, and he might find that interesting.
Comment: I know this sounds downbeat but be prepared for her or him to be unable to motivate themselves and that you find yourself nagging them to practise day-after-day. Youth *is* wasted on the young: amazing ability to learn and often little desire to do so. That said, I was pleased my Mum & Dad had forced me to practise the violin. I gave up the day I turned 16 but took it up again in my forties and found it much much easier to return to than to start from scratch.
Comment: Would be nothing strange. Is this an answer?
Comment: From a parent-child perspective you could also ask at [parenting.se].
Comment: It is very similar if I would ask this question about myself and I only specify the age as I think this might be informative. I also cannot say "I am 11 ..." either as probably it us not allowed to use SO at that age.
Answer: How much time should your son spend practicing piano per week?
That implies he doesn't particularly love piano yet.  Or you wouldn't be able to tear him away from it.
Give him a schedule of 30 mins (broken up into a couple well defined tasks) per weekday starting at the same time every day.  Have him show off to you when practice time is -over-.  Ask if he wants to practice more than that.
If he absolutely loves piano, let him spend as much time as he likes.
Give it about 6 months, and if you still have to make him practice, consider finding a different lifelong skill that he -does- love.
Another instrument, computer programming, writing, there are plenty of worthwhile life long skills besides piano that your son might prefer.
I tried like heck to get my son into piano and computer programming (my loves).  No dice.  But he's doing ok at drama and has fun with photoshop and videos.  That's who he is.
Comment: +1 But I felt the need to mention that when I began playing the piano, I didn't practice and I even wanted to stop. However, my parents were firm with me and made me continue learning, and now I'm incredibly glad that they did. Sometimes, it's a good idea to make children keep at something for a while. The opinions of a child of that age can change a lot over the next few years of their life.
Comment: +1 The one thing I'd add is that my experience was that I disliked practicing the piano, but I loved improvising whole songs and wound up learning how to compose. Likewise, you might want to be sensitive if your kid doesn't like the piano per se but shows interest in related areas.
Comment: Or daughter... :-)
Comment: Oops :)  Yep.  Same deal.
Comment: Growing up, my parents always insisted that I be learning/playing at least one instrument, though they gave my my choice. I sometimes hated it (I even quit piano for saxophone, which I deeply regret now, because I'd be *so* good at piano by now), but, in hindsight, I'm very glad they insisted.
Answer: We all have a different tolerance for the amount of time we can focus on a task and actually be productive. After that time, the law of diminishing returns creeps in, and even if you push past it, it is likely you are not making any further advancement, and can in fact be damaging the skills you worked on by becoming unfocused and sloppy.
It was mentioned above that it is better to practice in smaller allocations daily then it is to go a day or more without practice and then try to push through a marathon practice session to make up for it.
When I sit down to practice guitar, I notice that after a while I found myself playing old songs and melodies I already knew, or noodling aimlessly while staring blankly off in the distance, or even fumbling for scales I already know with increased frustration. I've found this time to be around 20 minutes (for me).
If I catch myself as this starts to happen, and instead of pushing through, I go do something else (walk, chores, etc.). I can come back later, and am able to focus for another session.
I would suggest timing your child's practice. When you see the signs of failing attention, or restlessness I would clock this as the current practice target. At this time, introduce something new. Have a small break. Watch a concert pianist on the internet, listen to music.
My thinking is that if I don't have to fight my own brain telling me to do something else, and I am able to focus more during practice, I will enjoy said practice more, and will hopefully naturally increase the time I can focus in any one session.
Thanks!
Steve
Answer: Practising , in the beginner stages, can be quite onerous. Especially if one only has specific learning tasks - scales, part of a tune, etc. Given other things to do - make up a tune, 20 seconds long, just using D,E, F#,and B -for example, or play CABBAGE in as many different ways you can all over the piano. There are hundreds of ideas, will hopefully mean playing does NOT just mean learning tunes by rote, till they're perfect, then, so what ?
To me, practising can be like eating - we certainly do it 2 or 3 times a day, every day, and we certainly don't save it all up till the end of the week, just before the next lesson !!Short sessions often work well, as the 'boredom factor' doesn't have time to set in.Particularly in the early stages, when knowledge is limited, so only a few things can be 'learnt'.
There cannot possibly be a definitive answer to this question, as every child/beginner is different. Some will love performing a newly learnt piece, others hate it.Incentives to practise, let alone to learn, will vary from one individual to another.As a child, mine were 'no treats till you've done it'. It worked, but at the time my parents were hated for it. 50 yrs on, I'd be cursing them if they hadn't done it, 'cos nothing else worked - I play every day, and love it !!
Answer: The final strategy we use is 15 minutes every morning first thing to do. This seems sufficient to learn the task from the teacher she gets at the end of the 30 min weekly lesson.
We also play more over the weekend and sometimes in the evening but this time is more difficult to count.
Answer: My son begins at 4.5 year old. He was in a full-day daycare. I let him play 5-15 min per evening. It was a happy moment he enjoyed with me everyday.
At age5, he was in a half day kinder garden. I let him play 1.5 hour to 2 hour per day, with 15 min or 20 min per session. I praised him a lot, so he loved play piano. He made to RCM3 by end of age 5.
At age 6 he was in full day school and had academic home works, and sport classes also took in. He played 45 min per day, 6 days a week. He was proud of himself, and showed off his piano skills voluntarily in front of friends and families. He made to RCM5 by end of age 6.
At age 7 he became rebellious for the "boring" piano. He liked to try all kind of sports: basketball, soccer, skating, ski, swim, biking, chess, a long list. We had to "forced" him to play 60 min a day, 6 days a week. His progress slowed down comparing to his early years. He made to RCM6 by end of age 7.
At age 8 he began to admire other people who are better than him, pianists or classmates good at math or art. He wanted to be good at something. So we shrink his sport classes to skating, Ski, badminton and baseball. Increased the time allocating for math and writing. Decreased the time for piano. He played 60 min a day, 4 days a week.  He made to RCM9 by end of age 8.
So the key point is not how long a kid practice per day, it is how much he desires to be Good at piano.
Answer: Personally, I think this (ie, thinking in terms of time) is the wrong way to approach practicing.
I rather think for an effective practice (for effective anything, this applies to Algebra as well) you should set realistic goals, sit at the bench and don't leave it until you are done.
But how to size a unit of work?
It doesn't have to be "learn a new piece perfectly every day".
It could be small.
It could be "practice this up to a fraction X of the intended BPM until it's OK", "learn 10 new bars", etc.
Size your work units small enough that you can do them correctly, with no mistakes, in a single session - that, I guess, beats "go haphazardly through whole page in a sloppy fashion".
Leave the bench having actually accomplished something - be it play two more bars of a piece, doing arpeggios at a couple more BPMs or perform a whole concerto, in the same way you leave your desk after having solved a math problem :)
Funny story: I once heard a very good (classical) guitarist saying that his secret to practicing was to never make mistakes.
Got some dumbfounded looks, because hey, if you never makes mistakes you don't need to practice, right?
Wrong, he then explained: he never said anything about anything else, so if his average day had to be "play TWO bars at 1/4 speed - without mistakes", so be it - we'll raise the metronome tomorrow without carrying over today's mistakes.
Comment: I never would have learned anything if I held myself to this standard. I'm not saying it's wrong, just that it would have backfired badly with my personality. I actually had to make the opposite realization before I was able to enjoy music: it's ok to make mistakes.
Comment: You basically propose to split the teacher task into seven very short sections (just a few bars) and work in one per day, as the whole task must be ready after a week. This differs from alternative approach when the whole say 5 min piece is played every day, its quality gradually improving over the week.
Comment: So the *end goal* is being able to play a section or otherwise do something consistently with no mistakes. That's a common strategy I often use ("be able to play this exercise at 105 bpm 10 times in a row without any  mistakes"). The way you phrased it, it sounded like you were suggesting not making any mistakes during practice at all.
Comment: That said, less solid goals are often okay. On guitar right now, I'm playing around with playing the pentatonic minor scale over 12-bar blues in any key and across all positions. There's no stated goal, but the implied goal is being comfortable everywhere on the fretboard. I stop when I feel like it.
Comment: I think the rest of the answer is clear enough. I like what I *think* the anecdote is trying to say, but I shouldn't edit it so I don't misrepresent what the guitarist said. Did he mean that the *end* result of a practice session was that he was able to do something specific with no mistakes?
Comment: @h22: yes and no. I'm not saying that splitting tasks *by bars* is the best - you could also split the piece in two and then raise the speed every day, adding expression and working on phrasing the last day - *anything, really*. The main take away point is **clear goals** and "you are done *when you are done*", not "when the time's up". Just like regular homework - you don't do "10 minutes of maths", you do *a (whole) problem* until you have worked it out, **right**? **Your teacher can help you** to set the correct goals and in general help you build a routine - that's what teachers are for :)
Comment: Of course it is. **Especially** when performing in public. But I guess a good benchmark of effective practice can be to manage to do something - even very simple - with confidence and without mistakes, as opposed to "I repeated the same stupid mistake for 20 minutes straight but time's up so whatevs" :)
Comment: I didn't downvote, but I'm still not clear what you mean by no mistakes. This sounds wrong. You might practice *until* you're doing something consistently with no mistakes, but making mistakes is part of practice. Saying not to make mistakes at all leaves zero room for exploration and growth.
Comment: @GregJackson: What I was suggesting to the OP is **mainly** that instead of practicing for X minutes with no regard to the outcome, one might want to set **goals** for a practice session: "today I'm gonna learn ten new bars - and I'm not gonna leave the bench until I'm done". But **how to size a unit of work**? Well, make it **small enough** that you can learn to do it without mistakes in a single session. *In general*, for a useful practice, I'd favour perfecting a couple bars a time rather than haphazardly playing through a whole page in a sloppy fashion.
Comment: @GregJackson: of course that would be silly. But if you *constantly* make the same mistakes during practice and have to go over the same bits over and over again, I guess you should halve your metronome speed, take smaller chunks so that you can do them without mistakes, then *gradually* raise the speed and connect the chunks together.
Comment: Yes, it would be silly. That's why I was quite concerned with your answer.
Comment: @GregJackson: I further edited the answer - is it more clear now? Sorry, but I am no native English speaker and sometimes I find it hard to explain abstract stuff in an effective manner. Please do edit it if you think you can further clarify it.
Comment: I guess that really the take away point is "it's OK to start with small chunks" and "it's OK to start with the metronome at a ridiculously slow speed" - so slow and so small that you can ordinarily avoid *most* mistakes and definitely get rid of *all* of them by the end of a session.


Rails Gemoji helper for `:)`, `;)` etc.?

Question: So https://github.com/github/gemoji maps stuff like :cats: and :dogs: into emojis.
Example from Forem:
def forem_emojify(content)
  h(content).to_str.gsub(/:([a-z0-9\+\-_]+):/) do |match|
    if Emoji.names.include?($1)
      ''
    else
      match
    end
  end.html_safe if content.present?
end

How does one extend this to also map stuff like :), ;) etc.?
Answer: How about this?
def forem_emojify(content)
  h(content).to_str.gsub(':)', ':smile:').gsub(';)', ':wink:').gsub(/:([a-z0-9\+\-_]+):/) do |match|
    if Emoji.names.include?($1)
      ''
    else
      match
    end
  end.html_safe if content.present?
end

Edit with more information:
Why can't we just use the edit_emoji and add_alias methods?
Well, we can, like this:
Emoji.edit_emoji( Emoji.find_by_alias('smile') ) do |emoji|
  emoji.add_alias(":)")
end

that totally works! Now you can do this:
emoji = Emoji.find_by_alias(":)") #=> #<Emoji::Character:smile(1f604)>
emoji.name #=> "smile"
emoji.aliases #=> ["smile", ":)"]
emoji.raw #=>

but here's the problem: when you have unknown input like a comment, you have to find the aliases within the comment.
content = "I'm so happy :grinning: lol I just wanna :) but I'm :grimacing:"
emoji_pattern = /:([a-z0-9\+\-_]+):/
content.scan(emoji_pattern) #=> [["grinning"], ["grimacing"]]

you can see that when you have a string and you use that regular expression from the code sample. it only finds substrings that begin and end with a colon. You can also see that it extracts the alias from the colons, and then uses the name-without-colons to look up the emoji by alias. Our custom alias :) doesn't fit that pattern -- it begins with a colon but it doesn't end with one...
So what can you do? Sorry, but I dunno! There's a good reason GitHub suggests using a character to delimit your aliases -- it's pretty hard to find significant substrings in a big chunk of text. You can try improving the regular expression to also look for your aliases maybe?
Comment: @MarkBoulder added some follow-up. Sorry if it's not too satisfying :wink:
Comment: Pretty cool! But I noticed some new stuff about aliases in Gemoji's readme. You think something like this'd work? https://gist.github.com/frankie-loves-jesus/2a0ab7920b1e232a557d
Comment: Thank you so much Max - real decent answer! I owe you one!
Answer: I faced this same limitation. Ultimately wrote a parser extension for gemoji with emoticon support. See gemoji-parser.


night vision by accumulating pictures

Question: Would it be possible to recreate a mildly good image from combining multiple dark images using opencv. I know I can increase the contrast using histogram equalization and then do some gamma correction but cant seem to find a way to combine multiple dark images to create one good image.
Comment: You might be interested in [this](http://people.csail.mit.edu/yichangshih/time_lapse/).
Answer: The problem with dark, i.e. under-exposed images, is that they are inherently noisy. There are so few photons actually arriving at the sensor during the exposure that the arrival of even one, stray photon of noise significantly impacts the recorded brightness, i.e. one photon of noise messes up the reading when it is so dark that only 2 photons are expected because it represents a 50% error in the expected reading of 2 when a total of 3 photons arrive. The situation is much better at the bright end of the histogram where many photons arrive and, in percentage terms, an additional stray, noisy photon makes little difference.
As noise is generally pretty random, image averaging is a legitimate technique to reduce it and improve your SNR. Basically, you average the pixels from multiple exposures at every  position in the image, and the result of averaging two exposures of, say ISO 800, is generally similar to an image exposed at ISO 400. In general, the magnitude of the noise, drops by the square root of the number of exposures averaged, so averaging 4 exposures decreases the magnitude of the noise by a half.
There is an excellent write-up here with images and theory. As for doing that in OpenCV, it is basically just a matter of adding the images up and dividing by the number of images.
Note that this technique is only applicable to STILL images, of course.
Answer: I would advice a bit different approach. Integrating image domain over time would be not the best idea if the camera is moving, or if there are moving objects in view, since that would introduce blurring.
Instead, you may try some image enhancement. I have recently discovered several approaches, namely Retinex and CLAHE. It turns out that even on noisy dark images there is enough information about the dark parts, it is just not in the range that is noticeable.
You can find retinex implementation in GIMP (source too), and CLAHE in OpenCV.
Both methods are rather fast, and can even be combined, to achieve more balanced results (retinex seems to overamplify noice sometimes on textureless regions, CLAHE can be tuned to avoid this, but generally has less impact on result than retinex)

night vision by accumulating pictures


What can be gained by including the distribution of the dependent variable in a GLM?

Question: In this discussion on probit vs. OLS models 'Conjugate Prior' mentions that probit and all GLMs allow to specify a DV distribution.
How is the GLM improved by specifying a DV distribution and what is the implied DV distribution for OLS then?
Answer: GLMs aren't improved by specifying a DV distribution; the specification of a distribution is part of forming a GLM.  For example, if we perform a logistic regression, which is a kind of GLM, we are saying the dependent variable is distributed Bernoulli conditional upon the values of the regressors (independent variables.)  Where the improvement comes is that by specifying a GLM we are able to use maximum likelihood to estimate the parameters, which, assuming the model is correct, have lots of nice properties as the sample size gets large.
OLS minimizes the sum of squared errors; this doesn't imply any conditional distribution for the dependent variable, it's just an objective function.  If, however, we assume that the errors are i.i.d. Normal, then the OLS procedure not only minimizes the sum of squared errors, it also maximizes the likelihood.


Update number in same place on web page with javascript

Question: Is there a way to make JavaScript print a counter continuously in the same place on the page?
for(var x=0; x<3000; x++){
    document.write(x + '
');
    document.body.innerHTML = "";
}

I want the number x to update and replace the previous number, however this code seems to wait until the loop is finished before showing a number (by then it is too late)
Is there a way to say, print number x, now wait 100ms, now clear and update in the same space the new value for x, and repeat?
(I know that the innerHTML is killing the whole page, for now all this pages needs to do is run a counter, so other elements are irrelevant. What I don't want is a printed list of all those numbers, and I need a delay)
Thanks!
Answer: The browser will not update the display while JavaScript is running. To make a timer happen you need to use setTimeout() or setInterval(). Also, avoid document.write() unless you have a good reason to use it (if you're not sure what makes a good reason then don't use it at all).
You want something like this:

Then:
window.onload = function() {
    var x = 0,
        max = 3000,
        ctr = document.getElementById("counter");

    function incrementCounter() {
       ctr.innerHTML = x;
       if (x++ < max)
           setTimeout(incrementCounter, 100);
    }

    incrementCounter();
}

Demo: http://jsfiddle.net/nnnnnn/v5hmE/
Note that the above updates only the contents of the "counter" div, so any other elements on your page would not be affected.
Homework assignment for you: Google everything you didn't understand in that code.
Comment: You're welcome. I assigned homework because (a) it was a cop-out to avoid explaining everything in detail, but also because (b) I got the impression you genuinely want to learn and would therefore benefit from finding stuff out for yourself. A tip: when googling JavaScript stuff add " mdn" to your search, e.g., "settimeout mdn" - the first result is usually a page from the [Mozilla Developer Network](https://developer.mozilla.org/en-US/docs/JavaScript), a really good JS resource.
Answer: Yes! For that purpose I would recommend you two things:

To use a container (lets say a div) for that purpose:
and refer to it as document.getElementById('counter').innerHTML = x
To use javascript timers before updating.

Hope that helps,
Comment: Hey Ramon, how do I populate that div? Because JavaScript runs before its populated (even if I put in some paragraphs) and returns a error thats its Null (If I run this in Chromes console after its loaded it works, but not when the page runs)
Comment: Hi @Joseph, there comes another story. You will find many situations in which you would like to execute javascript code after the page finishes loading. That's why I would recommend you to take a look at one of the best Javascript libraries ever created: jQuery. Apart from that functionality, it will also save you from issues as cross browser compatibility, and will keep you apart from reinventing the wheel(as there are plenty of helpful plugins for jQuery - i.e. jQueryUI).
Answer:
...however this code seems to wait until the loop is finished before showing a number...

Don't use a for loop for this. You need a specific interval like you say. Use a function with a setTimeout and some recursion:
var x = 0;
var speed = 100;
function update() {
  if (x <= 3000) {
    setTimeout(function() {
      // update DOM here
      x++;
      update();
    }, speed);
  } else {
    return false;
  }
}

Demo: http://jsfiddle.net/elclanrs/PRC9R/
You can change the interval to say 9 so it looks believable but goes faster.
x += 9; // instead of x++


How to add php in views?

Question: I created a view, and I need to put some PHP or JavaScript in it. I would like to add some if conditions.
Is this possible?
Comment: Hello, and welcome to Drupal Answers. The answer to your question is _yes_, although that doesn't help you much. May you expand your question, and explain what you need to achieve? That would make the answer more detailed, and useful to you (and future readers).
Answer: Yes, it is possible.
If you want to use PHP in views header, you can go to configure header, select "Global: Text area" and have to change text format to PHP code; you have to first install the PHP filter module.
If you want to use PHP in view fields, you can use the Computed field module.
If you want to use PHP in a view itself, you have to customize your views and then you can easily add PHP code to it.
Answer: It kind a depends of where in your view you want to use php. But if it is in fields there are two options:

Views Custom Field (d6 only)
Views PHP - in dev though
Answer: in the field of view  you can add Global PHP field
you can fiend this field in the header or in footer

How to add php in views?


Limit points of a sequence $z_n=1+i^n\frac{n}{n+1}$ of complex numbers.

Question: I want to find all the limit points of the following sequence:
$$z_n=1+i^n\frac{n}{n+1}$$
Any help is appreciated.
Answer: Hint: Look at the sub-sequences
$$b_{n}\equiv a_{4n+k},\:\:k\in\{0,1,2,3\}$$
Answer: Since $\dfrac{n}{1+n}\to1$ as $n\to\infty$, then $z_n\to2,0,1+i,1-i$.
Answer: Those are $1+\{-1,1,i,-i\}=\color{red}{\{0,2,1+i,1-i\}}$ Given that $\dfrac{n}{1+n}\to1$ and $i^n\in \{-1,1,i,-i\}.$


Please help me with how to do the left hand

Question:
I am confused about how to play the left hand; I know that we have three sounds here but in the 3rd beat how can I hold the B and play another B? It makes sense for the first beat: hold the E and play the B, but how to play the rest?
Comment: This is an "easy piano" arrangement of Chopin's Etude in E you can only play on a grand piano with a 3rd pedal (sustain pedal). https://en.wikipedia.org/wiki/Sustain_pedal
Comment: @AlbrechtHügli - doesn't every piano come with the sustain pedal? Do you mean the sostenuto pedal (middle one on some pianos - not to be confused with the middle practice pedal on others)?
Comment: Yes, Tim, you are  correct. I wasn't  quite woken up when writing it ;)
Answer: In reality, because the sustain pedal is holding the 1st E, and later in the bar, the B, there's no need to keep a finger on either - the pedal's job takes over.
It is often confusing seeing piano music written like this - but consider the stem direction - it's written in parts, as if for two different instruments to play the bass clef notes, and technically needs all the notes written in to fulfil the sums for note values in each bar. Play each part separately, and it may make more sense - but of course on piano, it just looks incomprehensible from the music.
Answer: In the 2nd bar it doesn't matter as the half note B is hold - like Tim says. But in some other chords with non-chord tones  I think the sustain pedal isn't a good solution and I would use it carefully. If you consider the arrangement as a 3 voice piece of the melody and chords in the r.h. and in the left hand you have a bass line and a rhythmic accompaniment I wouldn't use the sustain pedal if not necessary when the bass line and the accompaniment are not the same note and only a 5th between.
It would also be reasonable to play the bass note B 8vb (an octave lower) ...
but someone may say: Using the pedal must be trained too!
Comment: As this is not an original edition of the composer I was wondering whether Chopin wrote this pedal marks. I looked in my own sheet music and it is as you say full of pedal marks. (Breitkopf Edition). Now I found this comment or question:  https://www.pianostreet.com/smf/index.php?topic=38739.0
Also the wiki research confirms my intention: *In regard to the pedal Cortot recommends pedal changes synchronized with the bass line (six changes per bar), although many critics say this is too much to be necessary. No pedal indication by Chopin is found in manuscripts or original editions.[22*]
Comment: Except the piece is heavily marked with ped. signs, so the composer seems to want it used - a lot.


How make node view return without menu?

Question: Perhaps the question is simple, but I can not understand how to return the body of a node without a menu.
I did a module that loads the content of node into the custom area.
<code>function loadnode_in_region_menu_alter(&$items) {
    $items['load_node/%'] = array(
        'page callback' => 'loadnode_in_region_node_page_view',
        'page arguments' => array(1),
        'access callback' => 'user_access',
        'access arguments' => array('access content'),
        'type' => MENU_CALLBACK,
    );

return $items;
}

function loadnode_in_region_node_page_view($nid) {
    $node = node_load($nid, NULL, false);
    $vnode = node_view($node);
    return drupal_render($vnode);
}
</code>
JS looks like
<code>    jQuery.ajax({
        type: 'GET',
        url: Drupal.settings.basePath + 'load_node/' + id,
        dataType: 'html',
        success: function(data){
            jQuery('#ajax-result').html(data);
        },
    });
</code>
Result looks like this, with a duplicate menu

If I change line from
<code>    return drupal_render($vnode);
</code>
to
<code>    echo drupal_render($vnode); OR print drupal_render($vnode);
</code>
The result looks like I would like it, but some fields are not displayed correctly, such as voting and image. Looks as if they are not themed.

How to return themed node body without a menu?
Answer: You can create tpl for the menu and render the content and design tpl as required or create tpl for the content type in theme
Comment: Thanks for the answer. The problem is that besides the menu the module re-adds scripts to the custom region. In fact, it adds the whole page. I tried to create **region--(r_description).tpl.php** but it does not replace formatting (the same situation as here [https://www.drupal.org/node/1200498](https://www.drupal.org/node/1200498)). Do you know another way how this can be done?

How make node view return without menu?


How do I construct params for a get request?

Question: I am trying to do:
export interface ApiCallOptions {
  abc: string,
  xyz: number
}
makeRequest (options: ApiCallOptions) {
  return this.http.get('/some/path/to/endpoint', { params: options });
}

I get an error that ApiCallOptions isn't a HttpParams object...  I tried casting options as HttpParams, still fails..
So then I tried:
  const params = new HttpParams({ fromObject: options });
  return this.http.get('/some/path/to/endpoint', { params: params });

And I get:

The expected type comes from property 'fromObject' which is declared
here on type 'HttpParamsOptions'

What am I doing wrong?
Comment: Did you try: `const params = new HttpParams({ fromObject: options } as HttpParamsOptions);`?
Answer: You could do something like that:
makeRequest (options: ApiCallOptions) {
  return this.http.get('/some/path/to/endpoint', { params: this.buildParams(options) });
}

private buildParams(params) {
  let httpParams = new HttpParams();
  let keys = Object.keys(params);
  keys.forEach(key => {
    if (params[key] !== null) {
      httpParams = httpParams.append(key, params[key]);
    }
  });
  return httpParams;
}

What is the outcome?
Comment: is this really the "angular way?"  Seems so ridiculous to have that much code to make a simple get request.
Comment: That is because there are generators like OpenAPI that perform that work for you: https://github.com/OpenAPITools/openapi-generator
The generator take a specification as input, and generates your model/dto and services requests. However, is my solution working?
Answer: From HttpParamsOptions
export interface HttpParamsOptions {
  /**
   * String representation of the HTTP parameters in URL-query-string format.
   * Mutually exclusive with `fromObject`.
   */
  fromString?: string;

  /** Object map of the HTTP parameters. Mutually exclusive with `fromString`. */
  fromObject?: {[param: string]: string|number|boolean|ReadonlyArray<string|number|boolean>};

  /** Encoding codec used to parse and serialize the parameters. */
  encoder?: HttpParameterCodec;
}

For the fromObject property, it implements the index signature with property name as string.

For the HttpParams instance:
import {
  HttpParamsOptions,
} from '@angular/common/http';

const paramsOption = {
  fromObject: options as { [key: string]: any },
} as HttpParamsOptions;
const params = new HttpParams(paramsOption);

Comment: But modifying the interface like that seems obnoxious..  The point is to specify WHAT is expected to be passed to the endpoint.  adding `[key: string]: any` totally removes any benefit and again makes me say "UGH TYPESCRIPT IS TERRIBLE!!!"


$f$ continuous with derivative $f'(x)=0$ for all $x\in \mathbb{R}\setminus A$ where $A$ is countable implies $f$ constant

Question: I would like to find a "simple" proof of the following statement:

Let $f\in C(\mathbb{R})$. Let $A$ be a closed and countable subset of $\mathbb{R}$. Suppose $f'(x)=0$ for all $x\in\mathbb{R}\setminus A$. Show $f(x)$ must be constant.

Here, a simple proof to me can assume knowledge of Folland's Real Analysis Chapters 1-7. There are other questions on here and here asking for the same thing. This is a qualifying exam question and genuinely, I am stuck. Some thought suggests that $\mathbb{R}\setminus A$ might be dense and so I could try to argue that $f'(x)=0$ for $x\in A$ from there. I couldn't get this to work.
The Cantor-Lebesgue function shows that if $A$ being countable is replaced by $m(A)=0$, then the result is false. So, any proof must rely on $A$ being countable.
Thanks for any ideas.
Comment: What exactly is missing in Folland's Real Analysis' Chapters 1-7 that linked proofs use?
Comment: On Folland I find the following sentence: It is a highly nontrivial theorem
that if F is continuous on [a, b], $F'(x)$ exists for every $x \in [a,b]\ A$ where A is
countable, and $F'\in L^1[a,b]$, then F is absolutely continuous and hence can be recovered by integration
Comment: See also https://math.stackexchange.com/questions/3311385/how-far-can-we-push-the-fundamental-theorem-of-calculus-for-riemann-integral?noredirect=1&lq=1 (not saying this gives a "simple proof")
Comment: @Conifold One of the linked proofs used Cousin's lemma which isn't something in Folland. I was hoping there's a proof that uses material in Folland which makes it quicker/simpler. Unless of course, the proof in that second link is the best one can hope for.
Comment: I guess since Folland stated it highly nontrivial, there wouldn't be an easy proof(The proof in Rudin where $A=\varnothing$ uses some decomposition of functions or spaces
Answer: Isn't it immediate from a cardinality argument?
Suppose $f$ is not constant.  So there exists $a<b$ such that $\{a,b\}\subseteq f(\mathbb{R})$.
By IVT, $f(\mathbb{R})\supseteq[a,b]$.
Since $A$ is closed, the complement $\mathbb{R}-A$ is countably many open intervals.  On each of these open intervals we have $f'=0$ so $f$ is constant by MVT.  So $f(\mathbb{R}-A)$ is countable.
That leaves uncountably many values in $[a,b]$ that need to come from the countable set $A$, contradiction.
Comment: Now I understand why those other proofs are so convoluted. They do not assume that $A$ is closed, only that it is countable.
Comment: This is a very nice proof. I'm impressed that it did not rely on any measure theory or even knowledge of analysis at the level of Folland. Thank you!


Clearing a form field in Javascript upon click

Question: Sorry for the newb question in advance! I'm making a Calculator app in Javascript and am having a hard time getting the "C" (clear) button to clear the field. EDIT: To clarify, the Clear button should not only clear the field but also everything held in memory so that I can start a fresh calculation. <input type="reset" value="C"/> clears the field but holds the last buttons I've pressed in memory.

      <form>
        <input type="text" id="output" />
      </form>

      <button onclick="handleClick(1)">1</button>
      <button onclick="handleClick(2)">2</button>
      <button onclick="handleClick(3)">3</button>
      <button onclick="handleClick(4)">4</button>
      <button onclick="handleClick(5)">5</button>
      <button onclick="handleClick(6)">6</button>
      <button onclick="handleClick(7)">7</button>
      <button onclick="handleClick(8)">8</button>
      <button onclick="handleClick(9)">9</button>
      <button onclick="clear(0)">C</button>
      <button onclick="handleClick('+')">+</button>
      <button onclick="handleClick('-')">-</button>
      <button onclick="handleClick('/')">/</button>
      <button onclick="handleClick('*')">*</button>
      <button onclick="evaluateExpression()">=</button>

The "clear" function just does not want to work. Where am I going wrong?
Comment: http://stackoverflow.com/about
Answer: Do reset on form . link
document.getElementById("frm").reset();

or Set the value of textbox like this
 document.getElementById('output').value = "";

Comment: document.getElementById("form").reset(); gives me an error of: "Uncaught TypeError: Cannot call method 'reset' of null "
Comment: While 'document.getElementById('output').value = "";' DOES clear the field, when I press the next number it appends the next number to what I've just cleared. Ex: press 4 then C. Field clears. Press 2. 42 appears.
Answer: Why not just use the built-in reset type?
<input type="reset" value="C"/>

This would have to be inside the <form>.
Comment: Hmm, upon testing, while that clears the field it does not clear what's in javascript's memory. After clearing, when I press "7" for example, it will hold the last action I pressed ("+" in my case), then add 7 to it. For example I did 2+2 which gave me 4. Then I press clear, press 7 then it gives me 11.
Comment: it will not work if form contains a field like:

after reset the form, it'll still contain "abc" in the text field...
Answer: For resetting form input fields, this worked for me:
 document.getElementById('elementId').value = "";

If you are trying to reset elements on the page that isn't a form, this worked for me:
 document.getElementById('elementId').innerHTML = "";

Answer: Can you not just set the text of output to a blank string?
( or )
more likely if your doing a calculator set it to 0?
document.getElementById("output").value = 0;

Answer: Here is an example of clearing the value of an input field
<input id="entry" type="text"></input>
<button id="clear">Clear</button>

var entry = document.getElementById("entry"),
    clear = document.getElementById("clear");

function clearfield() {
    // EDIT: place code for clearing anything else that would be affected here
    entry.value = "";
}

clear.addEventListener("click", clearfield, false);

on jsfiddle
And here is an example of using form.reset
<form id="myForm">
    <input id="entry" type="text"></input>
</form>
<button id="clear">Clear</button>

var clear = document.getElementById("clear"),
    form = document.getElementById("myForm");

function clearfield() {
    // EDIT: place code for clearing anything else that would be affected here
    form.reset();
}

clear.addEventListener("click", clearfield, false);

on jsfiddle
Also, inline javascript is considered bad practice and you should consider a method such as addEventListener instead.
i.e. onclick="doit();"

Why use addEventListener?
addEventListener is the way to register an event listener as specified
  in W3C DOM. Its benefits are as follows:
It allows adding more than a single handler for an event. This is
  particularly useful for DHTML libraries or Mozilla extensions that
  need to work well even if other libraries/extensions are used. It
  gives you finer-grained control of the phase when the listener gets
  activated (capturing vs. bubbling) It works on any DOM element, not
  just HTML elements.
Answer: Are you trying to do this.?
then try this code,
function clear(data) {
         document.getElementById("output").value=data;
      }

Comment: @PradeepKumarPrabaharan Glad that helps PPK! :)
Answer: On C button click, clear the output value
 document.getElementById('output').value = "";

Answer:  $(function(){
    $("input").click(function(){
        if(this.value == 0)
        {
            this.value='';
            return;
        }
        else
        {
            return;
        }
    });
});

Cange the "input" to #YourFieldId, and get rid of the if inside, but keep the this.value=' ';
That is the best way to clear fields on click if you can use jquery...
You could also always have a condition to check the input and then clear like the code above clears input fields that have a '0' in them.


Expanding conditional probability for Gibbs sampling with many parameters

Question: I'm trying to use Gibbs sampling to get the following target distribution:
$$ p(a,b,c \lvert x, z) $$
Where $z = f(x,a,b,c)$ and the rest are independent. I know the following conditional probabilities and can sample from them:
$$ p(a\lvert x, z, b, c), \, p(b\lvert x, z, a, c),  \, p(c\lvert x, z, b, a)$$
My question is how to express the target distribution I need using the ones above.
My attempt was to start with the following:
$$ p(a,b,c \lvert x, z) = \frac{p(a,b,c,x,z)}{p(x,z)} $$
But I'm not sure how to continue (or if it's the right direction)
Answer: This is the Hammersley-Clifford(-Besag) theorem:. Here is the version presented in our book.
Definition: Let $(Y_1, Y_2, \ldots, Y_p) \sim g(y_1,\ldots,y_p)$, where $g^{(i)}$
denotes the marginal distribution of $Y_i$. If $g^{(i)}(y_i)> 0$
for every $i=1, \ldots, p$, implies that $$g(y_1,\ldots,y_p) > 0$$
then $g$ is said to satisfy the positivity condition.
Theorem (Besag, 1974) Under the above positivity condition, the joint distribution $g$ satisfies
$$
g(y_1,\ldots,y_p) \propto \prod_{j=1}^p \; {g_{\ell_j}(y_{\ell_j}|y_{\ell_1},
\ldots,y_{\ell_{j-1}},y_{\ell_{j+1}}^\prime,\ldots,y_{\ell_p}^\prime) \over
g_{\ell_j}(y_{\ell_j}^\prime|y_{\ell_1},\ldots,y_{\ell_{j-1}},
y_{\ell_{j+1}}^\prime,\ldots,y_{\ell_p}^\prime)}
$$
for every permutation $\ell$ on $\{1,2,\ldots,p\}$ and
every $y' \in \mathfrak Y$.
The conditioning on $(x,z)$ mentioned in the question is irrelevant in that case, since every distribution appearing above is then conditional on $(x,z)$.
Comment: I really appreciate the answer, but I'm not sure how to use the theorem for my case yet


Proof by contradiction and ZF set theory

Question: The following is quoted from Sir Michael Atiyah's draft proof of Riemann Hypothesis, Section 5, stating that 'To be explicit, the proof of RH in this
paper is by contradiction and this is not accepted as valid in ZF, it does require choice.' Does this means that a proof by contradiction is only valid in ZFC, not in ZF, provided the assumption that Axiom of Choice can not inferred by the axioms of ZF?
Comment: Any proof or disproof of RH from ZFC is one from ZF.
Comment: I think there is a confusion there. Constructive mathematics is usually done in a setting where the Law of Excluded Middle does not hold, so proof by contradiction is not valid. In many constructive settings choice fails, because the axiom of choice implies LEM in general (although in some constructive settings, choice is in fact a theorem). The thing is that sometimes any choiceless settings is called "constructive", but this is in a non-technical sense. I can only imagine this as the source of confusion.
Comment: Here is the claimed outline of the proof: https://drive.google.com/file/d/17NBICP6OcUSucrXKNWvzLmrQpfUrEKuY/view?from=timeline&isappinstalled=0 . In Section 5, paragraph 4, the author claims that the proof by contradiction requires choice. I interpret it as requiring the axiom of choice. In the wikipedia page https://en.wikipedia.org/wiki/Zermelo%E2%80%93Fraenkel_set_theory , ZFC is described as extension of ZF with controversial AC.
Comment: Building off of @AsafKaragila's comment, the term "constructive" is actually a really dangerous one here. It can refer to: arguments not involving the excluded middle; constructions not involving the axiom of choice; or even (in older, primarily Russian literature) computable. And just for kicks, the closely-related term "constructible" refers to elements of [Godel's constructible universe](https://en.wikipedia.org/wiki/Constructible_universe) which - just to make matters worse - satisfies choice! And all this ignores its common *informal* use as "explicit."
Answer:
Does this means that a proof by contradiction is only valid in ZFC, not in ZF, provided the assumption that Axiom of Choice can not inferred by the axioms of ZF?

No. It's not entirely clear to me what Atiyah is claiming, although I think that's the most direct reading, but that statement above is false. Moreover, we can prove in a precise sense that choice plays no essential role in the Riemann hypothesis, and that the "provided ..." bit of your question is unnecessary.
Specifically, the key points are:

Proof by contradiction is perfectly valid in ZF. The validity or invalidity of proof by contradiction is an issue about the underlying logic, not the theory, and ZF and ZFC use the same underlying logic (namely, classical first-order logic).
It is known that ZF cannot prove the axiom of choice (at least, as long as ZF is consistent in the first place); this was proved by Cohen (following a much simpler proof, due to Godel, that ZF cannot disprove AC unless ZF is inconsistent.)
Most interestingly, any proof of RH from ZFC can be turned into a proof of RH from ZF, even if the original proof seems to fundamentally use the axiom of choice. This is a consequence of an absoluteness theorem: absoluteness theorems state that certain axioms (e.g. choice) can be removed from proofs of sentences which are particularly "simple" in form, and it turns out that RH can be expressed in a sufficiently simple manner for an appropriate absoluteness result to apply.

Note that my second and third bulletpoints definitely require proof. They're absolutely (hehe) not obvious, and it's perfectly reasonable for mathematicians outside of logic to not be familiar with them (especially the third). That said, they do demonstrate that the set-theoretic concerns raised are void.
Comment: Thanks Noah, your answer, together with https://math.stackexchange.com/questions/970511/zf-set-theory-and-law-of-the-excluded-middle very much clear up my confusion.


The argument type 'dynamic Function(bool?)?' can't be assigned to the parameter type 'void Function(RangeValues)?'.dartargument_type_not_assignable

Question: import 'package:flutter/material.dart';
class OpeningHoursSettings extends StatelessWidget {

  final Function(bool?)? onSliderChanged;

  const OpeningHoursSettings({
    super.key,required this.onSliderChanged,
  });

  ///.....

  RangeSlider _buildSlider(BuildContext context){
    return RangeSlider(divisions: 24,values:
       RangeValues(
         openingHours.openAt,
         openingHours.closeAt),min: 0, max: 0,
         **onChanged: onSliderChanged**
  );
  }

I have made the problem part bold.
The error thrown is

The argument type 'dynamic Function(bool?)?' can't be assigned to the parameter type 'void Function(RangeValues)?'.dartargument_type_not_assignable

I read the docs of null safety but in vain
Answer: If you check the definition of RangeSlider(onChangedit is
 final ValueChanged<RangeValues>? onChanged;

So you can change the function dataType like,
  final Function(RangeValues)? onSliderChanged;