How to configure a search box in laravel

Question: I am trying to put a search box in my home.blade but it is not working properly.
Here bellow is my home view
@extends('layouts.app')

@section('content')

    <form action="{{ route('home') }}">

                <input type="search" name="search" placeholder="Here the animal serial number..." aria-describedby="button-addon1" class="form-control border-0 bg-light">

                    <button id="button-addon1" type="submit" class="btn btn-link text-primary"></button>

    </form>
    @foreach($animal as $animal)

Details for the animal

Id: {{ $animal->id }}

Animal: {{ $animal->type->category }}

Gender: {{ $animal->gender }}

Place Of Birth: {{ $animal->user->address->city }}

Farm: {{ $animal->user->name }}

Date: {{ $animal->created_at }}

    @endforeach
    @if(request()->has('search') && request()->get('search') != '')

Details for the animal

Id: {{ $animal->id }}

Animal: {{ $animal->type->category }}

Gender: {{ $animal->gender }}

Place Of Birth: {{ $animal->user->address->city }}

Farm: {{ $animal->user->name }}

Date: {{ $animal->created_at }}

    @endif
@endsection

and my controller
public function index()
{
    $animal =Animal::all();
    if (request()->has('search') && request()->get('search') != ''){
        $animal = $animal->where('serial_number', 'like', "%" .request()->get('search')."%");
    }
    return view('home', compact('animal'))->with('message', 'Below is the result');
}

It bringing me an error like this
'Property [id] does not exist on this collection instance. (View: /Users/macair13/MeatracProject/resources/views/home.blade.php)'
meaning the animal I have passed in my controller is not worrking.
Comment: I assume your animal model actually has an Id in the table?
Comment: If an animal is searched, am I correct in assuming that you only want to show the one animal on the page and not have the foreach?
Comment: Yes that what i wanted but it seems like my search was not working
Comment: Are you using the `show()` method in this controller?
Comment: Oh no am using the index
Answer: There are a few problems to work through.
1) You have a variable name collision -
@foreach($animal as $animal)

This will overwrite your collection of animals ($animal) with the first individual animal in that collection.  On the next iteration foreach will try to iterate over each element of that single animal.  And those elements (like id) don't themselves have properties like id, so you get the error you are seeing.
You should change your variable names to avoid the collision, for example convention would be to use $animals, plural, to indicate it is a collection of more than one.  So:
Controller
$animals = Animal::all();
// ...
return view('home', compact('animals')) ...

View
@foreach($animals as $animal)

2) The search code in your controller:
$animal = $animal->where(...);

does not actually get the results.  You need to append get(), as shown in the docs:
$animal = $animal->where(...)->get();

3) As @Rwd pointed out in the comments, your view has 2 separate chunks of content, one which looks like it should display a collection of animals (the top one with foreach), and a second which looks like it should display just the search results.  Similar to problem 1 above, you have a name collision here - both sections are using $animal.  After the foreach loop has finished, $animal is the last animal in the collection of all animals - not your search result.
If I am understanding correctly, you probably want use 2 separate variable names, maybe $animals at the top to list all animals, and then maybe $result to show a single search result.
If that is true, you need to update as follows:
Controller
// For the top list of all animals
$animals = Animal::all();

// For the single search result
$result = false;
if (request()->has('search') && request()->get('search') != ''){
    $result = $animal->where(...)->get();
}

// Return them both, separately
return view('home', ['animals' => $animals, 'result' => $result])...;

View
@foreach($animals as $animal)

// ...

@if($result)
    {{ $result->id }}

Comment: C'mon @Jimmyjbk try a little harder! :-) Debug it! What happens when you `return $animal;` from your controller, instead of the view? If that works, you know your query is working.  Also, it sounds like a new problem right, not the one in your original question? New problems usually mean you are making progress, solving one thing at a time.
Comment: It looks like when the search functionality is used it's only meant to use the one animal so this would work for the foreach but not for the block underneath it.
Comment: Yeah Of course it is working for the animals but the search still not working
Comment: @Rwd you're right. And in fact the search code in the controller won't work either.  I've updated my answer.
Comment: still on problem with the '$animal' which is not define in the controller
Comment: Yes It is a new problem
Comment: @Jimmyjbk what is `$animal` supposed to be now? In 3) above I suggested using `$result` for your search, instead of `$animal`.  Are you still using `$animal`? If yes, that won't work, as I describe in 3).
Comment: for the line of result line in the controller, I even changed it to animals but still could not work
Comment: I am not sure what you mean now. Are you using the code I suggested in 3) in my answer? If yes, which line is giving you an error?


Acoustic plug-in not working at home but works at Guitar Center

Question: Just bought a A15V acoustic speaker and a Mitchell acoustic plug-in guitar at Guitar Center. It works fine when they plugged it at the store but doesn't work at home. Any ideas on why and how to fix this? Could it be the amount of electric power? Thanks
Comment: Did they use the exact same cords at the store that you used at home?
Comment: Sorry, you must go back to the store and complain to them.
Answer: Some basic troubleshooting may keep you from having to go to the store. First I assume the amp is an Acoustic brand A15V. Unless you have issues with the electricity at home the electric power is probably not the issue.
Does the amp power up when plugged in?
If you plug a cable into the amp and raise the volume on input 2 do you get a buzzing sound if you touch the end of the cable?
If yes to both the amp is probably fine. If no to either the amp may be the problem. If no to the second question it could also be your cable.
You did not mention the model of the guitar but it most likely uses a 9 volt battery for the preamp and the built in tuner. It won't work without it.
On most guitars the battery is under the electronic controls. There is a sample pic of an inexpensive Mitchell guitar below. It may or not be the same as yours.
Sometimes a guitar comes without a battery. Sometimes it comes with a battery but it is wrapped in plastic so it doesn't discharge. Check the battery compartment. Put one in if it is empty. If there is one there check that it is not wrapped in plastic and then place it with the poles in the right position. Of course also make sure the battery is good.
Sometimes a guitar will mute if the tuner is on so make sure the tuner is off when you test it. If none of this works then it's time to go back to the store.
Comment: Some guitars with active electronics have a microswitch inside the jack which turns off the electronics to save battery life when no cable is plugged in. Cheap plugs with high manufacturing tolerances may not correctly activate the switch. Also, the cable may just be broken.
Comment: @JörgWMittag Thanks for your comment. I believe almost all guitars do, otherwise I will be buying some stock in Duracell or Energizer ;) I did mention the possibility of a bad cable in paragraph 4.


Showing $u_1, u_2, u_3$ is basis

Question: Let $\{v_1, v_2, v_3\}$ be a basis for a vector space $V$. I want to show that $\{u1, u2, u3\}$ is also a basis where $u1 = v1, u2 = v1 + v2$ and $u3 = v1 + v2 + v3$
I wanted to use the standard basis vectors of $\mathbb R^3$ for vectors $v1, v2, v3$ to prove this as it is a know basis. So using $\{(1,0,0), (0,1,0), (0,0,1)\}$ which are a basis for $\mathbb R^3$ then $u1 = v1 = (100)$, $u2 = v1 + v2 = (1, 1, 0)$ and $u3 = v1 + v2 + v3 = (1, 1, 1)$
Then performing guassian elimination would trivially result in the identity matrix for $\mathbb R^3$ and finding it's determinant would be non-zero (1). Therefore $\{u1, u2, u3\}$ would be linearly independent and span $\mathbb R^3$ and so it too is a basis for the vector space $V$.
Is this the correct way to show this and is my choice to use the standard basis vectors for $\mathbb R^3$ suitable or does it need to be more general?
Answer: here is another way to do this. you have a basis  $V=\{v_1, v_2, v_3\}.$ we nee to show that $U=\{v_1, v_1 + v_2, v_1 + v_2 + v_3 \}$ is a basis.  we will show that  $U$ is linearly independent. that should prove that $U$ is a basis.
suppose $$xv_1 + y(v_1 + v_2) + z (v_1 + v_2 + v_3)= 0\tag 1$$ we can rewrite this as $(x+y+z)v_1 + (y+z)v_2 + zv_3= 0.$  now, use the fact that $V$ is a basis to conclude that $$z = 0, y+z = 0\to y = 0, x+y+z = 0\to x = 0.\tag 2$$
we have shown that $(1)$ implies $(2).$ that means $U$ is a basis.
Answer: It's much simpler than what you do: since $\{v_1, v_2,v_3\}$ is a basis by hypothesis, it is enough to prove $v_1, v_2,v_3$ can be expressed with $u_1, u_2, u_3$. This will prove $\{u_1, u_2, u_3\}$ is a set of generators and  as we're in dimension $3$, it's a basis.
Indeed $\, v_1=u_1$, $v_2=u_2-v_1=u_2-u_1\,$ and$\,v_3=u_3-v_1-v_2=u_3-u_2$.

Showing $u_1, u_2, u_3$ is basis


Best way to pass control values from form to separate class

Question: I have a WinForms application that creates a huge, custom textfile. To do this requires the user to configure dozens of controls on the main form and then click a Submit button. What is the best way to pass all those control values to my Generator class? The problem is I'm ending up with 20+ parameters to pass to a Generate() method. I can group some of those into Config objects (i.e. the date/time controls can be passed into a DateTimeConfig object) and then pass these config objects into the Generate() method to minimize the number of parameters needed, but it still feels like there must be a better way. Any ideas?
EDIT: Thank you for your responses, but I was hoping for something other than a configuration object (as that's what my OP mentioned). I guess what I was hoping for is some way to serialize the values of all the controls automatically, without having to build a custom object and then modify that everytime a control changes or gets added/removed.
Answer: Why not create a custom object class as container of your data and then pass the istance of this class to the Generator method as parameter?
Comment: This is what I've done now. I've grouped these 20+ controls into 4-5 config objects, then grouped those all into one master config object and passed the master to the Generate method. This works, but everytime I make a modification I have lots of parts to fix. Was hoping for some sort of serialization method I don't know about.
Answer: Look into Model Driven Development, where the parameters are grouped into business objects or data transfer objects (DTOs).  This is a more intuitive way to group parameters than by datetime, etc.
If you place those model objects in a separate project, you can pass those objects around the solution (from one method to another and one project to another) without having to serialize them or mess with long parameter list ordering.  You can even nest model objects inside other model objects.
In this example, notice you only have to change parameters in the Person object or the Address object and you never have to serialize or map anything:
// this is my business model object
public class Person
{
    public int PersonId { get; set; }
    public string PersonName { get; set; }

    // notice the Address object nested in the Person class
    public Address HomeAddress { get; set; }
}

// this is another class that lives inside the person class
public class Address
{
    public string Street { get; set; }
    public string City { get; set; }
}

In one class you could have this method that receives a person with an address and passes the person to another class's SavePerson class:
public void ProcessPerson(Person person)
{
    person.PersonName = "Robert";

    Address address = new Address();
    address.City = "Austin";

    person.Address = address;

    SavePerson(person);
}

Some other class (even in another project) can take that person and pass it to the persistence layer:
public void SavePerson(Person person)
{
    database.Save(person);
}

So if I want to add a State to the person I just change the Address class and I'm all done in one step, I don't have to add the state field to all the method parameter lists:
 public class Address
 {
    public string Street { get; set; }
    public string City { get; set; }

    //  this is the new property
    public string State  { get; set; }
 }

Answer: Create a model object that has a value for each control.
So let's say you have a form that has a first name, last name, birthday and salary.
Your model would be
public class SalaryModel
{
     public string FirstName {get; set;}
     public string LastName {get; set;}
     public DateTime Birthday {get; set;}
     public decimal Salary {get; set;}
}

Then when submit is clicked, you create this object and pass it to your generator class.
One reason for this is your generator needs to know NOTHING about the control other than it's value.  That is a generator class shouldn't be concerned about .IsVisible() or .TabOrder or any of that other junk.  It only cares about what the value is.
Answer: Create a container class. Keep an instance of it common for your main form and whatever form is going to use it/pass it to the other form or class as parameter.
Take all the values from your form and fill the container class. Usually a container/entity class would be full of properties and will have a very few methods.
Answer: Move you Generate() Method to a class and utilize the class properties.  You can also then support data binding from you form.
Ex.
Take this
Generate (List<int> x, bool Opt1);

to This
public class Generate
{
     List<int> Ids {get;set;}
     bool Opt1 {get;set;}
     bool Generate();
}


Cannot use string offset as an array in includes\form.inc on line 3575

Question: Before creating "form" custom module, everything was fine. After creating this module, I have got the following error message:

Cannot use string offset as an array in includes\form.inc on line 3575

I deleted the entire custom module folder, and cleared the cache as well. Still, I am getting the same error when modules page.
How do I overcome this error?
coding inside the form.module page is
        function form_menu() {
      $items = array();
      $items['form/form'] = array(
        'title' => t('My form'),
        'page callback' => 'form_form',
        'access arguments' => array('access content'),
        'description' => t('My form'),
        'type' => MENU_CALLBACK,
      );
      return $items;
    }

    /**
    * This function gets called in the browser address bar for:
    * "http://yourhost/form/form" or
    * "http://yourhost/?q=form/form". It will generate
    * a page with this form on it.
    */
    function form_form() {

      // This form calls the form builder function via the
      // drupal_get_form() function which takes the name of this form builder
      // function as an argument. It returns the results to display the form.
      return drupal_get_form('form_my_form');

    }

    /**
    * This function is called the "form builder". It builds the form.
    * Notice, it takes one argument, the $form_state
    */
    function form_my_form($form_state) {

        // This is the first form element. It's a textfield with a label, "Name"
      $form['name'] = array(
        '#type' => 'textfield',
        '#title' => t('Name'),
      );
      return $form;
    }

Comment: And when you say 'deleted', you did disable and uninstall it first right?
Comment: @uma Doing that is never a good idea I'm afraid, no telling what it will break. Try removing the row for your custom module from the `system` table completely, that should reset it. But **make a DB backup first** of course
Comment: Try disable/uninstall the module and clear the cache.
Comment: The OP said, "I deleted the entire custom module folder, and cleared the cache as well."
Comment: Somewhere in your form there is a property that should have a `#` in front of it. Without seeing your code it's impossible to help any further
Comment: Sounds like "everything is fine but motor is not working" case.
Comment: No. i didn't disable or uninstall the module, straight away deleted the folder.
Comment: @Clive. Will never repeat this way of doing things hereafter. Deleting the content related to the custom module in system table solved the problem. Once again thank u so much.
Comment: @Clive It seems that, with your two comments, you answered the question. _Cough cough..._ `;)`
Comment: @kiamlaluno I know I'm terrible at doing that ;) I've put an answer in
Answer: Deleting the module folder outright, without uninstalling it through the UI/Drush (even manually in the DB) is bound to cause a few problems.
To get rid of any errors caused by Drupal thinking the module files are still there, you can simply delete the row in the system table which corresponds to the relevant module; but make a database backup first, of course.
In case you haven't come across the pages before, you can disable modules at http://mysite.com/admin/modules and uninstall them at http://mysite.com/admin/modules/uninstall through the UI, or use Drush.
Answer: Run update.php after disabling that form module. My problem has been solved after doing this.


Is a 'root' an intrinsic property of a tree

Question: Is root an intrinsic property of a given tree?(Given a tree, can you uniquely determine the root?) Can't any vertex of a tree be chosen as a root? Aren't all trees rooted in that case?
Answer: NO; not necessarily a tree has a root.
A rooted tree is a tree in which one vertex has been designated the root.
Comment: I don't agree with you when you say "not necessarily a tree has a root": in a tree (i.e. connected acyclic graph) any vertex can be chosen as a root. Choosing a root in a tree just means to fix an order in the tree. I agree with you if you mean that there are trees that are not rooted in the sense that the root for that tree has not been chosen explicitly (i.e. the order has not been fixed), but it is always possible to chose a root.
Comment: @Taroccoesbrocco - if we can choose a vertex whatever and call it *root*, it seems hard to me call it "an intrinsic properrty" of the tree.
Comment: Now I see better what you mean, thank you. Maybe we can say that the existence of a root in a (non-empty) tree is an intrinsic property of the tree, but the tree does not determine univocally its root (if it has more that one vertex).
Comment: What @Taroccoesbrocco 's telling is exactly what I had in mind. By "intrinsic" I meant, given the tree, can you uniquely determine the root? If you can, please tell the algorithm. To conclude, just because no vertex has been thought of as the root, is it an unrooted tree?
Answer: This is just one common example of a pointed set (or rooted set). Given any non-empty set, any one of the elements can be chosen to be the root. The result is a rooted set. That is, a set with the extra structure of a root. Thus, there is one set, but many rooted sets with the same underlying set. Therefore, a root is not an intrinsic property of a set, but it is an intrinsic part of a rooted set.
Notice that this is much different than, for example, the center of a tree as described in MSE question 1874429 "The center of a tree is a vertex or an edge." which is unique for a given tree.


Secondary school level mathematical induction

Question:
It is given that
$$1^3+2^3+3^3+\cdots+n^3=\frac{n^2(n+1)^2}{4}$$

Then, how to find the value of
$2^3+4^3+\cdots+30^3$?
Which direction should I aim at?

Prove by mathematical induction, that $5^n-4^n$ is divisible by 9 for all positive even numbers $n$.

$$5^n-4^n=9m,\text{where $m$ is an integer.}$$
What I am thinking in the $n+1$ step is,
\begin{align}
& 5^{n+2}-4^{n+2} \\
= {} & 5^2(5^n-4^n)+5^24^n-4^{n+2} \\
= {} & 5^2(5^n-4^n)+4^n(5^2-4^2) \\
= {} & 5^29m+4^n9 \\
= {} & 9(5^2m+4^n)
\end{align}
Does this approach make sense?

Show that $a+b$ is a factor of $a^n+b^n$ where $n$ is a positive odd number.

I am thinking this in the $n+1$ step.
$$a^{2n+1}+b^{2n+1}$$
But then I cannot get it further.
Comment: You have three questions here. Please restrict yourself to one question per post--you can ask the other two questions in separate posts.
Comment: I will separate them cuz i was afraid I asking similar questions in related posts.
Comment: 1) Honestly, I'd come up with a new equation altogether.  There are principals to modify it to all even numbers but the are not direct.  2) Why are you trying to figure for n +2?  Induction wants n+1.  Otherwise it is good.  3) Well... For odd numbers you don't want an n+1 step but an n+2 step.  If n is odd, the *next* odd number is n+2.  Or if you want you can convert n to 2k + 1 (not n; need a new variable) and then the induction step is on k+1 to 2(k+1) + 1 = 2k + 3.
Comment: D'oh.  1) Factor out $2^3 = 8$ from all the terms.... (what the heck is *wrong* with me this morning????)
Comment: You should drink a coffee first ;)
Comment: For your first question, see [here](http://math.stackexchange.com/questions/62171/proving-13-23-cdots-n3-left-fracnn12-right2-using-induct).
Comment: @Martin Sleziak I am not asking how to prove it but how to find $2^3+4^3+\cdots+30^3$
Comment: Well, if you know that formula, all you have to do is plug $n=30$ into the formula and subtract $1=1^3$.
Answer: I'll give you a hint for the first one. Since you have asked three different questions, I wait to see if they tell you to split your question in there questions...
1
You already have a formula:
$$1^3 + 2^3 + 3^3 + \ldots  + n^3 = \frac{n^2((n+1)^2)}{4}$$
Hence in your case $n = 30$ but your sum starts from $2^3$ and not from $1^3$, hence you have to subtract $1^3$ (namely one):
$$2^3 + 3^3 + \ldots + 30^3 = \frac{30^2(30+1)^2}{4} - 1 = \frac{30^2\cdot 31^2}{4} - 1 = 216224$$
Edit because I understood nothing
Since you want only the sum of even numbers, then you have:
$$2^3 + 4^3 + 8^3 + \ldots + 30^3 = 2^3(1^3 + 2^3 + 3^3 + \ldots + 15^3) = 115200$$
Thanks to Crostule for notifying me.
Comment: Actually the correct sum is the one with even terms. So, it's $2^3(1^3+ \dots + 15^3)$
Comment: @Ed_4434 lol you're right. But at least he will understand how to proceed without mistakes!
Comment: Slightly more than a hint I'd say!
Comment: @Crostul Ah! Ops I missed the fact he wanted just the even ones -.-
Comment: @FourierTransform As did I hahaha
Comment: @Crostul Thanks! I think this makes sense!
Comment: @Fourier Transform Thanks for your reply anyway ;)
Comment: The OP question was $2^3 + 4^3 + 6^3....$ **not** $2^3 + 3^3 +4^3 + 5^3....$..  Crosul's sum is correct and .... D'oh!!! it must be early.  I thought of common factors and .... concluded it would be too hard.... d'oh!
Comment: EDITED. Sorry again for the misunderstanding.
Comment: Meh, happens to everyone.  Just take a gander at my idiotic comment on the main post!
Answer: Hints
1) $2^3+4^3+...+30^3=2^3(1^3+2^3+...+15^3)$ now apply the formula you got.
2) Assume that $9k=5^n-4^n$ then $5^{n+2}-4^{n+2}=25.5^n-16.4^n=25(9k+4^n)-16.4^n=9k'+9.4^n$
3) Change the questions to show that $(a+b)|(a^{2k+1}+b^{2k+1})$ for all $k\in\mathbb{N}$.Let $(a+b)x=a^{2k+1}+b^{2k+1}$ now $a^{2k+3}+b^{2k+3}=a^2.a^{2k+1}+b^2.b^{2k+1}$ again do substitution and it will work out.
Answer: 1) $2^3 + 4^3 + 6^3 + .... +30^3 = 2^3*1^3 + 2^3*2^3 + 2^3*3^3 + ... + 2^3*15^3 = 2^3(1^3 + 2^3 + .... + 25^3)$
2) Perfect.  You did great.  (Better than I did when I didn't realize it was only true for even numbers.)
3) If $n$ is odd then you don't want $a^{2n+1} + b^{2n+1}$ for the inductive step but either: $a^{n+2} + b^{n+2}$ (much like you did in 2) or $n = 2k+1;$ inductive step on $a^{2(k+1) + 1} + b^{2(k+1)+1}$. 2 1/2) or $n = 2k-1$ and $b^{2k+1} + b^{2k +1}$.  Either way will work.
Answer: For #3 use the technique of #2: For $n\in \mathbb N \cup \{0\}$ we have $$a^{2n+3}+b^{2n+3}=a^2(a^{2n+1}+b^{2n+1})+(-a^2+b^2)b^{2n+1}=$$ $$=a^2(a^{2n+1}+b^{2n+1})+(a+b)(b-a)b^{2n+1}.$$
Comment: $$a^n+b^n=(a+b)Q,\text{where $Q$ is a polynomial.}$$
\begin{align}
& a^{n+2}+b^{n+2} \\
= {} & a^2(a^n+b^n)-b^na^2+b^{n+2} \\
= {} & a^2(a+b)Q-b^n(a^2-b^2) \\
= {} & (a+b)(a^2Q-b^n(a-b))
\end{align}


Disprove by counterexample: If $f(0),f(1),f(2)$ are in $\mathbb{Z}$, then $a,b,c,d$ are in $\mathbb{Q}$

Question: Let $f(x) = ax^3 + bx^2 + cx + d.$
Is it sufficient to disprove the implication by showing that at least one variable is not in $\mathbb{Q}$?
 Or do we need to show that $a,b,c,d$ are all not in $\mathbb{Q}$?
Here's my rationale for showing at least one is not in $\mathbb{Q}$.
If $f(0$) is in $\mathbb{Z}$, then $d$ is in $\mathbb{Z}$ because $f(0) = a(0) + b(0) + c(0) + d$.
Comment: "...at least one is not in $\mathbb Q$.." Which one then? $d\in\mathbb Z$ implies that $d\in\mathbb Q$ because $\mathbb Z\subseteq\mathbb Q$. You seem to reason that $d\in\mathbb Z$ implies $d\notin\mathbb Q$. Am I misreading or overlooking?
Comment: You are correct that is my reason. But if that's the case, then how can I attempt this problem?
Comment: You can't _show_ that in general, at least of the coefficients are irrational, since there are loads of examples where they _are_ rational (for instance, any choice of $a, b, c, d$ being integers). It says "Disprove by counterexample", and that's what you have to do. Show us one example of a degree-three polynomial with coefficients that aren't all rational, but where $f(0), f(1)$ and $f(2)$ are integers.
Comment: Does it make sense to choose values for the coefficients, say irrational numbers, and show that although f(0),f(1),f(2) is in the integers, either a,b,c, or d is not in Q.
Comment: @helto Yes, that does make sense. See the answers to your question. It appears that $a,b,c$ can be irrational while $f(0),f(1),f(2)\in\mathbb Z$.
Comment: Great. Thanks all.
Answer: Consider $a = \sqrt{2}$, $b = -3\sqrt{2}$, $c = 2\sqrt{2}$, and $d=0$. Then $f(1) = \sqrt{2} -3\sqrt{2}+2\sqrt{2} = 0$ and $f(2) = 8\sqrt{2}-12\sqrt{2}+4\sqrt{2} = 0$. So $a,b,c \notin \Bbb Q$ but $f(0), f(1), f(2)\in \Bbb Z$.
Answer: From $f(0)\in\Bbb Z$ we have $d\in \Bbb Z$ and from $f(1)\in\Bbb Z$ we get $A=a+b+c\in\Bbb Z$ and finally from $f(2)\in\Bbb Z$ we get $B=8a+4b+2c\in\Bbb Z$. Hence for example if we choose $A=B=0$ we get $3a+b=0$ so $c=2a$ and we can choose for a counterexample
$$a=\pi, b=-3\pi, c=2\pi, d=m\in \Bbb Z$$


JOMSOCIAL: An error at New User Registration Progress bar

Question: During user Registration progress bar is set to 150% in step 3 and to 134% in step 4. Here is the code from progressbar.php:
<?php
class CProgressbarHelper{

    static public function getHTML( $max=100, $currval=0, $barclass='outerpgbar', $barfillclass='innerpgbar'){

        if(!is_numeric($max) || !is_numeric($currval) || $max < 0 || $currval < 0)
        return '
Progress bar cannot be generated properly
';

        $width = intval(($currval/$max) * 100) ;
        $barclass = (!empty($barclass))
                    ? 'class="'.$barclass.'"'
                    : 'style="background-color:white; height:.8em; border :1px solid #D0D0D0; margin-bottom:10px; padding:1px; "' ;

        $barfillclass = (!empty($barfillclass))
                    ? 'class="'.$barfillclass.'" style="width:'.$width.'%;"'
                    : 'style="width:'.$width.'%; height: 100%; background-color:blue; position:relative;"' ;

        //class progressbarfill : inside of the progress bar
        $html = '
'.
                    '

'.
                '
';

        return $html;
    }
}

I have also tried an answer to such an issue at another blog as to change the line 1055 of /administrator/components/com_community/installer.helper.php from
$html .='

 '. $percentage .'%

';

to
$html .='

 '. $(percentage/2) .'%

';

But it is still not working properly. In fact, it has cut the progress bar in half on the first user registration page.
I can't show the image here clearly, but you can understand it by registering at Jomsocial>>Demo. In fact, you won't see the error there.
Answer: The code which called this function passed a value for $currval which is higher than $max. Something like getHTML(100, 154) (this will give you 154% as result).
You may add the following line:
if ($currval > $max) $currval = $max;

(before the $width = intval(($currval/$max) * 100); line)
This way, you avoid having percentage higher than 100%.


Should I practice the open C major scale with fingers 2-3-4?

Question: Ever since I learned about scales, I've practiced playing the C scale every day as follows:

Now, after learning another major scale pattern with four fingers and no open strings, I realised that this shape too can be moved around, if only I had practiced it with fingers 2-3-4 instead of 1-2-3. So my question is: Is there any reason to keep practicing this pattern with fingers 1-2-3? Would it be beneficial to move to 2-3-4?
Answer: It's good that you have realised patterns are moveable around the guitar fingerboard, so well done! There is more mileage in learning something like this at open position with fingers that leave the index free to play lower notes once you've left open strings.
Eventually, you may well leave open strings completely when soloing - which obviously uses all those scale notes (and sometimes more!), at which point you can play in any key you like - open strings are somewhat restricting, and controlling them, and applying vibrato aren't easy either.
You've learned a one octave scale, but there are more useful shapes, starting on the bottom and going up to the top string, meaning two octaves. Lots of tunes go above that top C, and below that bottom C in your scale, so it's a bit restrictive, without knowing the extra few notes. trouble is, if you start that 'C scale' on the bottom string open, you're effectively playing E Phrygian rather than C major!
Answer: Although it certainly can't hurt to be able to play it with 2-3-4 as well, I don't think it makes much sense to practice that. Yes, the 2-3-4 turns up in shifted versions, but these are different anyway because you also need the index finger where you'd have just empty strings in the C-major version. So better practise them right away in the shifted version.
The only situation where this would come handy is when you have a static bar with the index, and use the other fingers to play melodies. However, a bar generally makes the hand less flexible, so you don't want to do that unless you need the bar for a sustained chord. Then again if there's such a chord, you won't have all of 2-3-4 available, and therefore need to adapt the scale pattern you use for the melody anyway. So again not much you could translate from having practised C-major with 2-3-4 and empty strings.


Do predicted values differ if variables included stepwise or simultaneously?

Question: You make a linear model #1 of the following form to predict adult human height:
$$
y = \beta_{0.1} + \beta_{1.1}\text{Height}_\text{dad} + \beta_{2.1}\text{Height}_\text{mom}
$$
You calculate fitted values $\hat{y_1}$.
Now you add $\beta_3x_3$ to make model #2 from the same data.
$$
y = \beta_{0.2} + \beta_{1.2}\text{Height}_\text{dad} + \beta_{2.2}\text{Height}_\text{mom} + \beta_{3.2}\text{Age}
$$
You calculate fitted values $\hat{y_2}$.
Now you make model #3 from the same data, but model #3 uses the fitted values from model #1 instead of $Height_{dad}$ and $Height_{mom}$.
$$
y = \beta_{0.3} + \beta_{4.3}\hat{y_1} + \beta_{3.3}\text{Age}
$$
You calculate fitted values $\hat{y_3}$.

In terms of prediction, what is the conceptual difference between the predicted values from models #2 and #3?
When would model #3 be appropriate, if ever?
Comment: Short answer is no (to the question as written in the body).
Comment: @Affine: question has been improved
Answer: Everything depends on which parameters are relevant in explaining the dependent variable.
Case 1: Age is not relevant. $\beta_3$ = 0
In this case it shouldn't matter if you do it stepwise or simultaneously.
Case 2: Age is relevant $\beta_3\neq$  0, but Age is orthogonal to other regressors in the model.
In this case it shouldn't also matter if you do it stepwise or simultanously.
In other cases results should be different.
I am also assuming that the estimates are consistent, i.e. this is not an errors-in-variables model (regressors are not measured with an error), or if there are other relevant regressors that are missing from the model, these are orthogonal to those that are included in the model.
Follow the link for an in depth treatment Endogeneity.
Comment: Fascinating, "But the OLS estimator $\hat{\beta_1}$ is a biased and inconsistent estimator of $\beta_1$ in the true model, except in the special case where all of the [$\beta \ne 0 ??] omitted variables are orthogonal to all of the included variables."
Comment: @jtd Does this answer your question, or is there some part that is not covered?
Comment: Apologies. Your answer claims there is no conceptual difference as long as all (significant) omitted variables are orthogonal to all included variables but I still haven't understood the conceptual difference if that assumption fails (which may be quite common). Is this a standard assumption (noting that linearly independent, uncorrelated, and orthogonal are all different) or a strong assumption? (http://www.psych.umn.edu/faculty/waller/classes/FA2010/Readings/rodgers.pdf)
Comment: @jtd I don't quite understand what you are asking. In general when we are building a model there is always an implicit assumption that we are including what's necessary. But since we cannot know if we had left out something important in advance, we can at least check whatever we left out doesn't cause wrong (biased is more correct term) coefficients for those we included. For this we can check whether the residuals of the regression is correlated to any of the included variables.
Comment: You suggest that if residuals follow classical assumptions, then model meets orthogonality requirement, and thus models #2 and #3 are equivalent in all cases?
Comment: @jtd I am willing to say yes, but there may be some additional requirements like linearity of the true model (which is another assumption to start with in linear regression) to say such a strong statement that it applies to "all" cases. Basically all those assumptions of linear regression are there to tackle such issues.


404 status code and its double meaning on a common-almost-restful api

Question: In a truly restful application I should follow links to reach my resources, while the only "magical already known URL" should be the application entry point. Direct queries like GET /user/john should be issued after having at least a link to /user or as a result from a search url specified by a previous link, like GET /user?username=john
But as following links forces more features, further development time and a smarter client, the actual reality is that most of the restful apis that I have written and used are partially restful: they are a collection of well defined URIs and methods, all previously known to the user by some documentation. In the end, the State Transfer part of what REST means is not present in most of them.
Well, following that reality where URLs are previously known, the 404 code turns to be an issue: How to differentiate the 2 meanings that 404 can have:

A correct 404 that means "Resource not found, but you can try again in the future". Example: GET /user/mario while mario is not a registered user
A incorrect usage of the api that means "No resource will ever be found here, you are using this API incorrectly". Example: GET /foobar/123

It is kinda important to differentiate those two scenarios because as a service maintainer, they are basically telling me if its an expect error and I should not be worried (first case) or an unexpected error and I should be worried as the service integration with my clients has issues (second case)
I tried searching for a better status code to represent the second case, and the closest ones I found were the 406 Not Acceptable (but it is a response directed to an Accept header that cannot be fulfilled) and the 410 Gone (that can be confusing as no resource was there, but the good part is that it tells the client to never try that URL again). Nevertheless, none of the two are good enough to be used for solving this
How did you or would you do to solve that?
Side node: python eve is an interesting project that tries to be a restful api with the State Transfer part. It implements HATEOAS for that
Comment: In the last example with the incorrect usage, when would this happen? It sounds to me that this one should return a `405` - that's at least what our API does if I'm for instance calling an endpoint with a wrong HTTP method (calling a method with a `POST` request, but the method only allows `GET` requests e.g.).
W3 suggests, that you should return a `410` for when a resource is permanently moved and will never be at the given path anymore: http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html - why is `410` confusing?
Comment: 410 means something was previously present at the URL but no longer is, so don't retry the URL ever again. That is not useful if there was nothing previously at the URL but then something appears at a later time.
Comment: Agreed with Remy, the 410 is bad because it tells the client that is a valid url for something that is not there anymore, while the real cause is that the url is malformed and thus always wrong
Comment: `405` almost nails it. It is a `Method not allowed` directive while what I need is an `URL not allowed` directive. Discussion on top of the `403` alternative is probably near to solving this
Comment: +1 for using the term RESTful and saying what you said in the first two paragraphs
Answer: What about using 403 for the first case (together with the explanation) and 404 for the second? Since the RFC 403 refers to 404 as an alternative response code they might be related...

403 Forbidden: The server understood the request, but is refusing to fulfill it.
Authorization will not help and the request SHOULD NOT be repeated. If the request method was not HEAD and the server wishes to make  public why the request has not been fulfilled, it SHOULD describe the  reason for the refusal in the entity. If the server does not wish to make this information available to the client, the status code 404 (Not Found) can be used instead.

403: You understand what the client wants but refuse to fulfill it. The client should not try again - it's forbidden until this resource is created - which you can explain as part of the answer.
404: You know that the client wants something you won't provide and can tell him in good faith, that this resource will never exists.
Update:
RFC 2119 explains how the "SHOULD NOT" has to be interpreted:

SHOULD NOT   This phrase, or the phrase "NOT RECOMMENDED" mean that
there may exist valid reasons in particular circumstances when the
particular behavior is acceptable or even useful, but the full
implications should be understood and the case carefully weighed
before implementing any behavior described with this label.

I think for your use case this is true. The client request shouldn't be repeated *without solving the reason stated in the 403 answer: "accessing this resource is forbidden because no user named mario exists". But if the client is sure that the reason went away, he is free to try again. But this might be only my interpretation of the 403 "should not be repeated" statement.
Comment: I like the `403` alternative, but what worries me is the *the request SHOULD NOT be repeated* part. In my first example the resource can be found in the requested URL in a matter of time, so the query can be repeated
Comment: Using the `404` for the second case implies that the URL can be repeated. It also goes against common practice, but is not a big issue though and it maybe can solve it. It is something to think of
Comment: Hmm, where do you get that 404 implies that it can be repeated? I considered 404 a "you want something crazy enough that I have no idea how to help you". Like asking me to find the north for you and giving me a plumb because it always points in a certain direction. You might call it "incorrect api usage" - but you might get away with calling it just crazy and be done with it.
Comment: Interesting, the [404 code in wikipedia](http://en.wikipedia.org/wiki/List_of_HTTP_status_codes#404) is stated as `The requested resource could not be found but may be available again in the future` while the [RFC it references](https://tools.ietf.org/html/rfc2616#section-10.4.5) it is `The server has not found anything matching the Request-URI. No indication is given of whether the condition is temporary or permanent.` Well, this means that `404` is simply not time aware of the resource life cycle
Comment: If the URL may be valid at a later time, I would stick with 404, being that it basically means "resource not found RIGHT NOW, I don't know about later".
Comment: I totally agree that 404 would be a valid response - for both cases. The question is: Is there another valid response (e.g. 403 or another) that would  allow to distinguish between these two cases?
Answer: There is no way to differentiate the two reasons, by design of RFC 2616 Section 10.4.5:

10.4.5 404 Not Found
The server has not found anything matching the Request-URI. No
indication is given of whether the condition is temporary or
permanent. The 410 (Gone) status code SHOULD be used if the server
knows, through some internally configurable mechanism, that an old
resource is permanently unavailable and has no forwarding address.
This status code is commonly used when the server does not wish to
reveal exactly why the request has been refused, or when no other
response is applicable.
Comment: What you think about the `403` code, like xworker pointed out in his reply?


How to do pagination for photos on Facebook graph data using Android-SDK?

Question: I want to get all the photos in my profile. I want to use pagination as a query at a time returns a few results. My response has  'after' and 'before' tags. Even when I use the after parameter in my query I keep getting the same results back, no new data gets added. How should I modify my query so that I get the next set of results?
My query -
do {
            Bundle parameters = new Bundle();
            parameters.putString("fields", "photos{source}");
            parameters.putString("after", afterString[0]);
            GraphRequest request = GraphRequest.newMeRequest(
                    AccessToken.getCurrentAccessToken(),
                    new GraphRequest.GraphJSONObjectCallback() {
                        @Override
                        public void onCompleted(
                                JSONObject object,
                                GraphResponse response) {
                            Log.i("GetPhotoUrlTask", response.toString());
                            parsePhotoUrls(response);
                        }
                    });
            request.setParameters(parameters);
            request.executeAndWait();
        } while (!noData[0] == true);

My response -
{Response:  responseCode: 200, graphObject: {"id":"965494620","photos":{"data":[{"id":"47832732","link":"https:\/\/www.facebook.com\/photo.php?fbid=4783552732&set=a.411783262.126046.10&type=1"},
...
...
...
"paging":{"cursors":{"after":"TVRBNE16UTJOREl5TlRVeE1UQXdPakV5TnpnMU1ETTVPVGM2TXprME1EZAzVOalF3TmpRM09ETTIZD","before":"TkRjNE16STNNekkxTlRVek1EQTJPakV6TlRVMk1UQXhNekk2TXprME1EZAzVOalF3TmpRM09ETTIZD"}}}}, error: null}

How should I modify my query so that I get the next set of results?
Answer: Have a look at

https://developers.facebook.com/docs/graph-api/using-graph-api/v2.4#paging

You should be able to get the next results with
https://graph.facebook.com/me?fields=photos{source}&after={after_token}

where {after_token} is the token coming from the last request, in your example TVRBNE16UTJOREl5TlRVeE1UQXdPakV5TnpnMU1ETTVPVGM2TXprME1EZAzVOalF3TmpRM09ETTIZD
Comment: Query 1:- Response: After1

Query2&after={after1}:-  Response: After2

Query3&after={after2}:- Response: After1

Why am I getting back the same value for after param in query 3?
Comment: I don't understand what you're saying
Comment: The value of the after parameter in the response is alternating, which means i am getting 2 sets of data repeatedly, but not all the data


Thread scheduling when releasing lock

Question: My expectation when unlocking a mutex was that the scheduler checks for other threads currently trying to lock this mutex and then execute one of those waiting threads. I wrote a test program (see code below) with 2 threads both trying to acquire the same mutex in a loop and do some work (sleep for 1ms). The difference is that one thread t1 waits a short while between unlocking and trying to reacquire the mutex and the other thread t2 doesn't. I was expecting that both threads acquire the mutex about the same number of times. However, on windows t1 often acquires the mutex only a single time and the other thread hundreds of times. On linux the behavior is different and both threads get work done with t2 roughly twice as many. Why does t1 on windows almost never acquire the mutex? How do I have to modify the code so that it does?
Example code:
#include <iostream>
#include <thread>
#include <mutex>
#include <atomic>

using namespace std;

int main()
{
    mutex m;
    atomic<bool> go(false);
    int t1Counter = 0, t2Counter = 0;

    thread t1([&] {
        while(!go);
        while(go) {
            this_thread::sleep_for(100us);
            lock_guard<mutex> lg(m);
            this_thread::sleep_for(1ms);
            ++t1Counter;
        }
    });
    thread t2([&] {
        while(!go);
        while(go) {
            lock_guard<mutex> lg(m);
            this_thread::sleep_for(1ms);
            ++t2Counter;
        }
    });

    go = true;
    this_thread::sleep_for(1s);
    go = false;
    t1.join();
    t2.join();

    cout << t1Counter << " " << t2Counter << endl;
}

Comment: Accidental synchronization problem, those sleep_for() calls are not innocent.  You can tell something is amiss from the t2Counter value.  If t2 runs (nearly) unimpeded then the value should be close to a 1000.  My crystal ball says that you see something closer to 60 or 95.  On Windows, a sleep can only complete at the clock tick interrupt, it ticks 64 times per second by default.
Comment: The search terms you are looking for are "fairness" and "starvation". Windows mutex doesn't guarantee fairness. I'm not familiar with Linux; looks like its implementation is more fair.
Comment: Calling `std::this_thread::yield` between unlock and relock might change the picture somewhat.
Comment: @IgorTandetnik Doesn't really change much. Thread t1 runs about ~5 times instead of only once, but t2 still runs hundred of times.
Comment: @HansPassant You are right. Replacing the sleep_for with some busy waiting sleep does give much more sensible results.
Answer: On Windows, std::mutex is implemented using a slim reader/writer lock.  This lock implementation is not fair (meaning that it provides no guarantees about the order in which waiting threads will acquire the lock).  Windows moved away from fair locks some time ago because Microsoft deemed lock convoys a more serious problem than thread starvation.
You can read more about slim reader/writer locks on Microsoft docs: Slim Reader/Writer (SRW) Locks
Joe Duffy has also blogged about the fairness versus lock convoy issue: Anti-convoy locks in Windows Server 2003 SP1 and Windows Vista

Thread scheduling when releasing lock


How can I round only the left corners of a button?

Question: This is the referential image of the button:
Answer: Should be able to use the short-hand for border-radius like so:

button {
  border-radius: 2rem 0 0 2rem;
}
<button>Hello World</button>


MySQL - The server quit without updating PID file

Question: I have installed MySQL 5.6.16 on Debain 7.4.
But i encountered problems with starting mysql, where every time i start mysql i get this error:
The server quit without updating PID file (/var/run/mysqld/mysqld.pid). ... failed!

After a lot of googling i saw that i should rename/move my.cnf file from /etc/mysql to see if mysql starts. And it start and stop without problems, but if try to connect to database with my software i get this:
Caught database OperationalError: (2002, "Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2)")

Then i tried adding/deleting everything from /var/run/mysqld and adding users and groups but nothing changes.
And i can't find any log files from mysql even setting them up in my.cnf.
This is my.cnf file from /etc/mysql Pastebin
Comment: How you installed Mysql on yuor Debian via apt-get or you compiled it?
Comment: @AbhishekAnandAmralkar i complied it.
Comment: Launch the start script in debug mode and see where/why it fails. bash -x /etc/init.d/mysql start
Comment: This is what i get in ouput: http://pastebin.com/DDw3VzNv
Comment: Solved by installing 5.5 from debian repository. I think there is a bug in 5.6.16
Answer: I encountered a similar problem. In my case, it was a missing PID file. So I had to manually kill the MySQL process and then restart it. The PID file was then created when I restarted MySQL.
Here's a great post that may help you:
http://linuxadministrator.pro/blog/?p=225


Modificando um JSlider

Question: Eu gostaria de fazer duas coisa:
1º: adicionar um label, ou qualquer coisa, que me permita colocar um "texto" abaixo das cores. Exemplo na ilustração:

2º: Fazer com que o ponteiro/indicador do slider, vá para a cor de acordo com o um determinado número digitado no campo (no método abaixo está mais claro de entender)
package pacote01;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.KeyEventDispatcher;
import java.awt.KeyboardFocusManager;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.image.BufferedImage;
import java.util.Dictionary;
import java.util.Hashtable;
import javax.swing.ImageIcon;
import javax.swing.JComponent;
import javax.swing.JFrame;
import static javax.swing.JFrame.EXIT_ON_CLOSE;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JSlider;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;

public class Slider extends JFrame {

    public static final Color[] COLORS = {Color.red, Color.orange, Color.yellow, Color.green, Color.blue};
    private static final int COMPRIMENTO = 30;
    private static final int ALTURA = 10;

    private JSlider slider = new JSlider(0, 100, 0);
    public JTextField campo = new JTextField();

    private double valor;

    public Slider() {
        setSize(525, 300);
        add(montaSlider());
        setLocationRelativeTo(null);
        setVisible(true);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
    }

    private JComponent montaSlider() {
        JPanel jpSlider = new JPanel();

        jpSlider.add(campo);
        campo.setPreferredSize(new Dimension(100, 20));

        campo.addActionListener(new ActionListener()//Caixa consulta é o campo que é digitado o código.
        {
            @Override
            public void actionPerformed(ActionEvent e) {
                KeyboardFocusManager.getCurrentKeyboardFocusManager().addKeyEventDispatcher(new KeyEventDispatcher() {
                    @Override
                    public boolean dispatchKeyEvent(KeyEvent e) {
                        if (e.getID() == KeyEvent.KEY_RELEASED && e.getKeyCode() == KeyEvent.VK_ENTER) {
                            definePonteiro();
                        } else {

                        }
                        return false;
                    }
                });
            }
        });

        int majorSpacing = slider.getMaximum() / (COLORS.length - 1);
        Dictionary<Integer, JLabel> dictionary = new Hashtable<>();
        slider.setMajorTickSpacing(majorSpacing);
        slider.setPaintLabels(true);
        slider.setPaintTicks(true);
        slider.setSnapToTicks(true);
        for (int i = 0; i < COLORS.length; i++) {
            ImageIcon icon = createColorIcon(COLORS[i]);
            JLabel label = new JLabel(icon);
            int key = i * majorSpacing;
            dictionary.put(key, label);
        }
        slider.setLabelTable(dictionary);
        jpSlider.add(slider, BorderLayout.CENTER);
        return jpSlider;
    }

    private ImageIcon createColorIcon(Color color) {
        BufferedImage img = new BufferedImage(COMPRIMENTO, ALTURA, BufferedImage.TYPE_INT_RGB);
        Graphics g = img.getGraphics();
        g.setColor(color);
        g.fillRect(0, 0, COMPRIMENTO, ALTURA);
        g.dispose();
        return new ImageIcon(img);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                Slider s = new Slider();
            }
        });
    }

    public void definePonteiro() {
        valor = Double.valueOf(campo.getText());
        if (valor <= 11.5) {
            //seta o ponteiro na 1ª cor
            System.out.println("1ª");
        } else if (valor <= 20) {
            //seta o ponteiro na 2ª cor
            System.out.println("2ª");
        } else if (valor <= 30) {
            //seta o ponteiro na 3 cor
            System.out.println("3ª");
        } else if (valor <= 40) {
            //seta o ponteiro na 4ª cor
            System.out.println("4ª");
        } else if (valor <= 50) {
            //seta o ponteiro na 5ª cor
            System.out.println("5ª");
        }
    }
}

Answer:
1º: adicionar um label, ou qualquer coisa, que me permita colocar um "texto" abaixo das cores.

Ao invés de posicionar abaixo, fiz uma forma alternativa e que altera o minimo possível seu código, posicionando os valores internamente nos labels coloridos.
Para isso, primeiro precisaria criar uma array de tamanho idêntico ao do array COLORS, colocando os valores nele:
public static final Color[] COLORS = {Color.red, Color.orange, Color.yellow, Color.green, Color.blue};
//5 cores, 5 valores
public static final String[] valuesColor = {"10", "20","30","40","50"};

depois, aproveitando o laço que você utiliza para preencher as cores, adicione estes valores como texto nos labels, alinhando horizontalmente no centro em seguida:
for (int i = 0; i < COLORS.length; i++) {
    ImageIcon icon = createColorIcon(COLORS[i]);
    JLabel label = new JLabel(icon);
    //aqui você vai adicionar o valor
    //correspondente a cor de mesmo indice
    label.setText(valuesColor[i]);
    label.setForeground(Color.white);//altere a cor dos números como quiser aqui
    label.setHorizontalTextPosition(JLabel.CENTER);//centraliza o texto
    int key = i * majorSpacing;
    dictionary.put(key, label);
}

Com essas alterações, os valores serão exibidos dentro dos labels coloridos.

2º: Fazer com que o ponteiro/indicador do slider, vá para a cor de acordo com o um determinado número digitado no campo

Basta utilizar a boa e velha matemática :)
Seu slider é iniciado com 100 sendo seu valor máximo e 0 sendo seu valor minimo, como são 5 cores, logo cada tick do slider é igual a 100/5, ou seja, o espaço entre cada "tracinho" é 25. Sabendo desta informação, basta posicionar o knob conforme o label abaixo dele:
public void definePonteiro() {

    valor = Double.valueOf(campo.getText());
    //variavel que armazenará a posicao do knob
    int sliderPos = 0;

    if (valor <= 11.5) {
        sliderPos = 0;
    } else if (valor <= 20) {
        sliderPos = 25;
    } else if (valor <= 30) {
        sliderPos = 50;
    } else if (valor <= 40) {
        sliderPos = 75;
    } else if (valor <= 50) {
        sliderPos = 100;
    }
    slider.setValue(sliderPos);
}

Veja o resultado das duas mudanças em funcionamento:
Comment: @Java testando aqui, deu certo. Testa ai tambem: https://pastebin.com/4rUmTxSE
Comment: Obrigado, tu é fera !
Comment: @Java o certo não seria passar para o método `definePonteiro()`? A lógica é a mesma da atual, só que ao inves de capturar do campo de texto, você passa o valor recebido para os ifs.
Comment: será que é porque eu estou usando float ?
Comment: https://pastebin.com/8Pi0FSU4 olha ai como eu fiz, fazendo favor.
Comment: @Java não problema algum nesse código, mudei o imc para 50 e o slider iniciou na ultima posicao.
Comment: @Java complicado, testei aqui e mudou normalmente. Tente criar um novo projeto, copiando as classes para ele, pode ser o cache da IDE.
Comment: uma dúvida, eu agora tentei fazer o processamento (capturar o texto) em outra classe, e tentei passar como parâmetro para a classe Slider, porém não deu certo. Eu fiz slider = new Slider(valorDaVarialvel); depois do calculo.
Comment: então, é a mesma lógica, usando o system.out eu confirmei que o valor tem, mais não esta funcionando, sera que o valor esta sendo perdido quando eu passo para o definePonteiro() na outra classe?
Comment: @Java nesse código você não chama o método `definePonteiro()` nunca. Ai nada vai acontecer mesmo. E JSlider só recebe int, você precisa fazer cast para int senão seu código nem vai compilar.
Comment: https://pastebin.com/8Pi0FSU4 converti o valor, e chamei o método no construtor, talvez a chamada esteja errada ?
Comment: esse ultimo que eu postei ? Aqui não foi não :(
Comment: eu não consegui, mais vou refazer aqui para ver se encontro o erro.
Comment: acredito que sei o porque do erro, porém não sei o que poderia ser feito, se isso for realmente a causa. Eu espalhei uns system.out e percebi que deixando a chamada do método no construtor, ele esta executado so de adicionar o componente na tela, porém ta td 0. depois quando digita o valor, e faz processamento de td correto, mais não seta o ponteiro.
Comment: Vamos [continuar esta discussão no chat](http://chat.stackexchange.com/rooms/59505/discussion-between-diegofm-and-java).

Modificando um JSlider


How would i convert all these variables into a list. where i could call a random film in python or is there a better way to sort through this?

Question: I am working on a project where I can list my favourite films, then call a random film from the list. Is there a easier way i can do this rather than typing each film out?
Here is my code below:
from dataclasses import dataclass
import webbrowser
import random
class Film():
    def __init__(self, name, genre, rating):
        self.name = name
        self.genre = genre
        self.rating = rating #0-100

    def get_name(self):
        return ("The Name of the film is: " + str(self.name))
    def get_genre(self):
        return (" The Genre of the film is: " + str(self.genre))
    def get_rating(self):
        return (" The rating of the film is: " + str(self.rating))
    def get_namerate(self):
        return self.get_name() + self.get_rating()

    def __str__(self):
        return self.get_name()+ self.get_genre() + self.get_rating()

#horror
h1 = Film("the shining, shining" + "\n", "horror \n ", 76)
h2 = Film("get out \n" ,"horror \n",77)
h3 = Film("midsommer \n","horror \n",74)
h4 = Film("IT \n", "horror \n", 70)
h5 = Film("hereditary\n", "horror \n", 81)
#animation
a1 = Film("up \n", "animation", 82)
a2 = Film("shrek \n", "animation \n", 86)
a3 = Film("Spiderman, into the spider-verse \n", "animation \n", 91)
a4 = Film("zootopio", "animation", 82)
a5 = Film("Monsters inc", "animation", 86)
#Drama
d1 = Film("about time \n", "drama", 87)

Answer: you can use a new class which store all the object to each film and can implement all the method to it.
class Films:
    def __init__(self, films):
        self.films = films
    def get_all_films(self.):
         return [ film.__str__() for film in self.films]

films = Films([h1,h2, h3, h4, h5, a1, a2, a3, a4, a5, d1])
print(films.get_all_films())

Comment: I have tried that but it shows __init__ missing 2 required positional arguments "genre" and "rating"
Comment: @DannyMoham1 when creating a `Film` class instance you need to add these values there
Comment: I have done that at the top of the code though with the initial class?
Comment: @DannyMoham1 yes


How to obtain the mass of a particle rotating around an axis when the difference of tensions in a wire are known?

Question: The problem is as follows:

A particle of mass $m$ is tied to a very thin wire. Assume the wire is
  inflexible and of negligible mass. The particle is spinning about a
  fixed axis as shown located in the center of the circle. Let $T_a$ and
  $T_b$ be the modulus of the tensions in the string when the particle
  is located in the points $a$ and $b$ respectively. Find the mass $m$
  of the particle if the difference between the tensions
  $T_{b}-T_{a}=39.2\,N$. Assume $g=9.8\frac{m}{s^2}$

The alternatives are as follows:
$\begin{array}{ll}
1.&0.8\,kg\\
2.&2.0\,kg\\
3.&5.8\,kg\\
4.&1.0\,kg\\
5.&0.5\,kg\\
\end{array}$
For this problem what I've attempted to do was to use the force at the top to be as follows:
$T+mg=\frac{mv_a^2}{R}$
At this point the Tension must be zero (I don't know if this statement is correct.)
This reduces the top equation to:
$v_a=\sqrt{Rg}$
Then to obtain the speed in the lowest point would be by the conservation of mechanical energy:
$E_i=E_f$
$\frac{1}{2}mv^2_{a}+mgR=mg(-R)+\frac{1}{2}mv_{b}^2$
Then inserting in the above equation would give the speed for the bottom:
Cancelling masses and multiplying by $2$ to both terms:
$v^2_{a}+4gR=v^2_{b}$
Since it is known $v_{a}$ then:
$v_{b}^2=Rg+4Rg=5Rg$
Finally I'll use these in the given statements:
The tension in the top:
$T_a+mg=\frac{mv_{a}^2}{R}$
Tension in the bottom.
$T_b-mg=\frac{mv_{b}^2}{R}$
Doing a difference between these:
$T_b-T_a=2mg+\frac{mv_{b}^2}{R}-\frac{mv_{a}^2}{R}$
Replacing the known values:
$T_b-T_a=2mg+\frac{m(5Rg)}{R}-\frac{m(Rg)}{R}$
$T_b-T_a=2mg+4mg=6mg$
Then:
$39.2=6m(10)$
Which results into:
$m=0.67\,kg$
But the answers sheet indicates that the mass is $2\,kg$.
For doing that what it should happenned is that the "$2mg$" is negative in the right side of the equation but I can't find a way to do that. Can someone help me here?. Is it me?, or did I overlooked anything?. Help.
Answer: Applying Newton's second law in (a) and (b) we have:
$$
T_a + m\,g = m\,\frac{v_a^2}{R}\,, \; \; \; \; \; \; T_b - m\,g = m\,\frac{v_b^2}{R}
$$
and subtracting the first equation from the second, we have:
$$
T_b - T_a = 2\,m\,g + m\,\frac{v_b^2 - v_a^2}{R}\,.
$$
So, imposing the conservation of mechanical energy between (a) and (b), we have:
$$
\frac{1}{2}\,m\,v_a^2 + m\,g\,R = \frac{1}{2}\,m\,v_b^2 - m\,g\,R
$$
from which:
$$
v_b^2 - v_a^2 = 4\,g\,R\,.
$$
In conclusion, we get:
$$
T_b - T_a = 6\,m\,g \; \; \; \Rightarrow \; \; \; (39.2\,N) = 6\,m\,(9.8\,m/s^2) \; \; \; \Leftrightarrow \; \; \; m \approx 0.67\,kg\,,
$$
as you correctly calculated!


Bootstrap confidence intervals: proving correctness

Question: I am working on using a bootstrap technique to compute confidence intervals of a parameter of interest.
Let $\textbf{Z}_1, ... \textbf{Z}_n\in\mathbb{R}^d$ be an (iid) random sample. From this random sample, we compute $\hat{\theta}$ parameter (very ugly to express explicitly). I would like to obtain CI for this parameter.
I utilize the basic bootstrap technique. This involves randomly sampling, with replacement, from our random sample to generate multiple bootstrap samples, each matching the size of our original dataset. For each bootstrap sample, I calculate the estimate of the statistic $\hat{\theta}^\star$. Subsequently, we determine the $95%$-quantiles of the re-sampled statistics to derive the confidence intervals. I want to prove their asymptotic correctness. Is there some general result that I can use? I only found theoretical justification using Berry-Essen theorem for $\theta$=mean, but my statistic $\theta$ is much more complicated.
In summary, I want to prove something like this:
Theorem
Let $\hat{\theta}$ be an estimator (from a sample size $n$) of $\theta$ and let $\mathbb{E}||\textbf{Z}||^2<\infty$.
Denote the resamples from the original sample as $(\textbf{Z}^\star_{1,1}, \dots \textbf{Z}^\star_{1,n}),\dots, (\textbf{Z}^\star_{B,1}, \dots, \textbf{Z}^\star_{B,n})$, with corresponding estimates $\hat{\theta}_1^\star, \dots, \hat{\theta}_B^\star$ for $B\in\mathbb{N}$.
Let $U:=\hat{\theta}_{(\alpha)}^\star$ represent the $B(1-\alpha)$ largest value out of  $\hat{\theta}_1^\star, \dots, \hat{\theta}_B^\star$.
Then,
$$\lim_{n\to\infty}\lim_{B\to\infty}P(\hat{\theta}<U) =\alpha. $$
Answer: How you prove this depends on your statistic $\theta$; there are complicated and straightforward versions depending on how difficult $\theta$ is. Fundamentally, though, the bootstrap works by the delta method; there's no need for the Berry-Esseen theorem.
A simplifying fact is that $\hat\theta$ is going to have a Normal distribution, so getting the tail probabilities asymptotically correct just implies getting the asymptotic mean and variance parameters correct
Often, your statistic $\hat\theta$ will be a differentiable function of a mean. In that case, you prove that the bootstrap is correct for the mean, and it transfers to being correct for the statistic automatically.  Or your $\hat\theta$ solves
$$\frac{1}{n}\sum_{i=1}^n U_i(\theta)=0$$
and $U_i$ has some regularity conditions that make $\hat\theta$ asymptotically Normal.  Again, you show the bootstrap is correct for the mean, and the same arguments that make $\hat\theta$ asymptotically Normal also show the bootstrap is correct.
There's a more general argument that requires more background maths.  If your data are from an iid sequence in $\mathbb{R}^d,$ then the empirical CDF is asymptotically Normal:
$$\sqrt{n}(\mathbb{F}_n-F)\stackrel{w}{\to} Z$$
where $Z$ is a Gaussian process indexed by $\mathbb{R}^d.$ The delta method then says that any suitably differentiable function $\theta(\mathbb{F}_n)$ is asymptotically Normal.  Since the bootstrap is correct for $\mathbb{F}_n$, in the sense that
$$\sqrt{n}(\mathbb{F}^*_n-\mathbb{F})\stackrel{w}{\to} Z$$
for the same limiting $Z$ (for almost all data sequences), the delta method also says the bootstrap is correct.
A good source for this with the details is Chapter 23 of Asymptotic Statistics by van der Vaart. He starts off with the mean, and then the delta-method in finite-dimensional cases, and then the infinite-dimensional case. Finally, he talks about higher-order accuracy for sufficiently well-behaved statistics through the Edgeworth expansion.
Comment: Thanks! I read the chapter of van der Vaart, indeed it is the best possible reference to my question. If you are interested, I provide more information about my problem here: https://stats.stackexchange.com/q/639016/348308


PrimeFaces.widget.InputText is not a constructor

Question: This is a javascript error I have every time the tomcat server is restarted.
After the page is refreshed there is no error any more.
Does anybody know what's wrong?
Answer: You can declare your ajax-loaded primeface components as below and the problem is solved.
This is because primefaces doesn't load all the widget's javasripts at the first load of the page, you have to force it to load the libs for your ajax-loaded widgets.
<code>    <p:accordionPanel rendered="false" />
    <p:inputText rendered="false" />
    <p:inputMask rendered="false" />
    <p:autoComplete rendered="false"/>
</code>
Comment: This is interesting. Why doesn't Primefaces load these javascripts?


Make URL from 1 field available to another field [Drupal 8]

Question: Drupal 8 Twig question:
I have 2 fields: textfield and a linkfield.
When the linkfield is filled, the text entered in the textfield should become the link.
I cannot edit the node.html.twig for this, I want to do this in the field--textfield.html.twig to include the URL (if it is set).
But I don't know how to make the URL from "field--linkfield.html.twig" available in "field--textfield.html.twig"
(Needed because the link module is still a little bit broken in Drupal 8 (no optional URL possible)).
Answer: If you want to get a field value from another field in a field template you have to use the parent entity (in your case a node) element['#object']:
{{ element['#object'].field_textfield.value }}

or a url from a link field:
{{ element['#object'].field_linkfield.0.url }}

Comment: Perfect! Now I know what to look/learn for in Twig :) thanks a lot!


How to use class file instead of java file when compiling with maven

Question: We received an updated .class file but not the .java file for a project.  How can I ensure this new class file is used, and placed in the right directory, in the compiling of our maven pom without affecting the project?
Comment: Better ask for a JAR, not for unpackaged classes.
Comment: the service providing the files to me doesn't give jar files for these kinds of changes.  they expect us to manually make the changes to the java site post-deployment.
Comment: Sorry but receiving an single class file simply wrong way ...The transfer of things is done via jar files which usually have also a version which is related to a version control tag etc. to make it reproducible...
Answer: Getting extracted class files is highly unusual. Normally, you get a jar and use it as dependency. In the case you have such class files, I would manually bundle them into a jar file and upload them to your Maven repository with appropriate coordinates (groupId, artifactId, version). Then you can reference them as dependency in your pom.xml.
Comment: I think your solution is certainly viable, but I did not know how to package a class file into a jar back then, but I could do everything else you suggested. The solution I posted and accepted is what I've been using since.  Thanks for the tip,
Answer: Not sure if this is the best method, but i was able to accomplish using this class file as a replacement for .java and no .jar file being provided by adding this resource argument to the maven pom file.
<resource>
    <directory>${project.basedir}/src/main/java/com/action/helper</directory>
    <targetPath>${project.build.directory}/classes/com/action/helper</targetPath>
    <excludes>
        <exclude>**/*.java</exclude>
    </excludes>
</resource>


Integration with the RDF module

Question: I have a module that creates HTML output.
What are the functions made available from the RDF module that allows a module to integrate with it?
Answer: Themes will work with the RDF module if they use the proper attributes variables. If you are generating HTML outside of the core theming system (which seems unusual), you will need to get this information yourself.
The RDF mapping API is quite well documented. Essentially there is a mapping between fields and RDF, so a title field could have a mapping to dc:title.

rdf_get_namespaces() will show the namespaces that need to be included in your document
rdf_mapping_load() will show the rdf mappings for an entity type

You can then add RDFa markup to the fields as you output them.
If you are using standard theme functions, then as long as you stick to the Drupal 7 guidelines, all the RDF magic should be done for you. Specifically, make sure that you use $attributes $title_attributes and $content_attributes.

Integration with the RDF module


Joining tables to fill lists of entities

Question: I am using JPA and Hibernate, but my need is too complicated to build a HQL, at least for me.
I decided to use native SQL.
I need to get some records/entities with their child lists but, i need to filter childs, i do not want all the childs.
Is this possible?
For example i have three tables like
conversation_table:
id
mail_table:
id, conversation_id, sender_id
user_table:
id, married_bool
I need conversation entities having lists that filled by mails those are send by married users.
I tried so far
Select * from conversation_table join mail_table on ( mail_table.sender_id=user_table.id and user_table.married_bool=true)

I am getting an error like:
user_table is unknown

I tried
Select * from (conversation_table, user_table, mail_table) join mail_table on ( mail_table.sender_id=user_table.id and user_table.married_bool=true)

I am getting
mail_table is non unique table/alias

This is only a light example,  also need to fill some entity lists of mail entity in other tables for example recipient_table, i think i have to add join clauses for filling these too in native query, am i right? Also i am getting 'not known'/'non unique alias' errors, when try this additional join clauses.
Thanks for suggestions.
Answer: Something like this:
SELECT *
FROM conversation_table CT
   JOIN mail_table MT
      ON CT.Id = MT.conversation_id
   JOIN user_id UI
      ON MT.sender_id=UI.id
WHERE UT.married_bool = 1

Answer: If you really want to use Hibernate ORM for this query they Criteria Query is the best approach for this. Recently, i have the same requirement and have used Criteria only.


Which key to move higher to?

Question: When you are singing in the key of C and you want to go a bit higher, then do you go to G (next on the circle of fifths) or C# / D (closest tone above c)?
Edit: just to clarify:
when I said go higher I meant when someone tells you that they can't sing in the key that you are playing cause it is too low. (and not in the middle of the song).
Comment: The answer is in your phrase "a bit". A fifth is a *huge* interval in terms of vocal range (standard classical voice-leading practices tend to assume a vocal range limited to an octave plus a fifth).
Comment: If you are just transposing for the singer, push it so it fits in his range, then choose a key everyone can play in. Some of us don't see why we have to play 6 flats just because the singer drank too much last night. Usually one or two tones will do. If it doesn't, maybe find another arrangement? because it may not sound good.
Comment: Note also that going up a fourth would be just as sensible in terms of the circle of fifths as going up a fifth would be.
Answer: Things to consider when picking a key for your vocal piece:

The top and bottom notes for the vocal parts in the range of the original piece - you ideally want to pick a key where the singers can sing both their top and bottom notes comfortably and well-supported. If you can't, you'll have to compromise or get creative to get a musical result.
The "tessitura" of the melody; i.e. the heart of the range of the melody. If most of the melody lies within a particular fifth, for example, it may be worth it to sacrifice a little on the top/bottom comfort to make sure this range is absolutely where you want it to be.
What impact the change in key will have on the accompaniment. In addition to the range consideration, fingering and playing the instrument may be more difficult in one key than another. This may be the decisive factor if two keys a half-step apart are equally viable.
What impact the key change will have on the timbre of the piece. A jump of a fourth or fifth or more may result in a piece that sounds dramatically different because of where it lies in the person's voice. In some cases, the change can weaken the composer's intent. The calculus can be even more complicated when you consider the changes of timbre in the accompaniment as well.

Finally, my understanding is that the idea of tying music to absolute pitch didn't exist in Renaissance music and earlier, so transposition to the right key for your voice is generally correct and common practice when performing those early pieces. In practice I've found these shifts are usually limited to a semitone to a minor third in either direction, for reasons of timbre and range indicated above.
Comment: Beethoven would have disagreed. "I wrote it in that key - it'll be sung in that key!"
Comment: This answer's the true question which is not about modulating to a higher key within a song, but transposing the entire song to fit the singer's range.
Comment: Sounds about right - but in a clash between the composer's will and what a musician can musically perform (as noted in the question), the composer sometimes loses. But yeah, hearing say the Moonlight Sonata mvt 1 in anything but C#min would bug me - and I'd absolutely be able to tell!
Answer: The two usual changes up are one semitone and one tone. The tone is probably the better one, as it uses two notes from the original tonic in the new dominant, whereas the semitone uses one. Either has been used successfully. Going up (?) to G is the next in the circle of fifths, but may well be difficult to sing, as the range will be much higher (or lower).
Don't know why this was voted as best answer. Maybe it answered the un-edited question. For the new answer, it will depend entirely on the tessitura of the vocalist that can't reach certain notes. As before, a tone, tone and a half, is usual, but that will also impact on the ability of the accompanying musician to play in the new key. C is fine on the guitar, Eb not so for some. Same on keyboards. A capo is good for taking keys up, not so for going down. I sing a particular song with one guitarist, who refuses to take it down a tone to suit my range, because of the new chords.
Comment: @RedSonja - It goes up a semitone at a time. The range is only one octave, from the second note in a key, to an octave above. Given that most vocalists would have a tessitura of a couple of octaves, it doesn't usually cause problems. Start low enough!  For the instrumentalists, however, it's a slightly different story, as you allude...
Comment: I think this is a great answer if the question was about modulating to a new key within a song.  But the question is about transposing a song in it's entirety to a new key to better fit a singer's range.  Before the question was edited, I also thought it was about modulating to a new key within a song.
Comment: Find the sheet music of Mack The Knife. It goes up a tone for each verse. Which can make life hard for the vocalist. It's also a bit hard on the musicians, but if it's got 6 # it's only one verse, hang on for the next one.
Answer: From what I know from experience, it purely depends on the singer. What I mean is that if you sing a song from C, it might be too low for your voice and moving it to C# or D might still be too low. So, you might have to move it to F or G. I don't think there is any rule as to where to move it to. Sing the song from a couple of different tones and see which one fits you better. This won't only be easier for you, it will be better for your voice too (you won't stretch it and possibly damage it).
Comment: Thanks for the reply. What you said seems to match what Tim said. Will accept his answer since he answered first.
Answer: Well, if your accompanist is playing a chromatic button accordion (good chances when Russian/Serbian/Swiss/French/Belgian/Finnish), the "natural" transposition is by multiples of minor thirds.  Those are trivially achieved, moving by columns on the treble side and by three columns on the bass side.  Chances are that an experienced CBA accordionist will not overly complain about other transpositions (assuming he has at least a five-row instrument where moving inwards by one or two rows is usually an option without having to change the fingering significantly).  But the minor third is the trivial option pretty much any player can do.
Unfortunately, it does not lend itself all that well to "stepping up", the practice of moving every or at least the last stanza up by a semi- or whole tone.  Stepping up by all of a minor third is sort of weird harmonically and takes quite a bit of getting used to.
But as "adapt to singer's range", a minor third is usually finely grained enough, and if your whole accompaniment (that isn't electronically transposable) is such a chromatic button accordion, this is the change you'll not have to start negotiating for.
Answer: I've had the same question and I don't believe you're getting the answer you want.
The answer is that while a G note resonates with C more favorably, because it's a fifth ... Doh Re Mi Fa Soh ... Soh (the G in Cmaj) rhymes with Doh (the C in Cmaj) better than Re (the D in Cmaj) rhymes with Doh.
Take as another example two notes which are five octaves apart. Their 'quality' or 'voice' sound similar because they are octaves but you wouldn't change a song in Cmajor – with the first C note being a C2 on piano, to a Cmajor starting at C7 on piano.
Instead you'd raise the key to C#2 or D2 or such.
Raising or lowering a key is absolute, the frequencies ... C, C#, D, etc... higher while harmony is relative, how each note sounds relative to the other ... the Soh and Doh example.

Which key to move higher to?


How to create test users on the localhost?

Question: I would like to make test users on my localhost (in my case I am using WAMP). Since I need to be able to authenticate them via email. I am not getting it to work what can I do?
Comment: you got some advance with your problem?
Comment: Hi, yes, solved it the way by activating the user  in the admin area. By putting the user on 'active' . So email comfirmation is not needed. However the drawback is that you have to log in and log out all the time to test it. I will try one of the module for this. Thanks
Answer: To add new user you can go to admin/people/create (localhost/YOUR-SITE/admin/people/create) and create the user, you don't need to enter a real email. And if you want to test the site with different users you can use the Masquerade module.

The Masquerade module allows site administrators (or anyone with
  enough permissions) to switch users and surf the site as that user (no
  password required). That person can switch back to their own user
  account at any time.
This is helpful for site developers when trying to determine what a
  client, logged in as themselves, might see when logged into the site.
Answer: very easy, go to people section and add a new account manually. and change user state to active
Comment: The question contains "***I need to be able to authenticate them via eMail***". Can you update your answer to address that part of the question?
Comment: Actually I found out this works when you login with the created user name.
Answer: I don't know whether there is a generic alternative, but I used the Test Mail Server Tool when I built my Drupal website on a localhost. Also, if you need to create a lot of test users, the Devel module can come in handy. After installing it, you can automatically create any number of users with randomly filled in user fields. I am not sure whether the authentication via email will still work in that way, but you can give it a try.
Answer: If you use something like Mailcatcher/Mailhog on your local dev stack, it will catch all outgoing mail instead of actually allow it to be sent to users. You can then log into its admin, and view the emails, and obtain the content/link within.
Dev stacks like drupalvm.com come with this option and is an easy switch on. Test emails to your hearts content.
You don't want to test with a module that does any sort of mail rerouting (all mail goes to user 1 for example) because that isn't really testing in near - real world conditions.


Change Colorbox maxWidth option in Backbone.js?

Question: I'm using Handlebars.js for HTML template. Like this:

        {{#ifCond ImagePath '==' "/images/noneImage.jpg"}}

          {{else}}

          {{/ifCond}}
...

This is my Colorbox template and its working. If product hasn't a picture, get col-md-8 class. (If has a image, get col-md-16)
My Colorbox JS is here:
 productDetail.bind('onLoaded', function () {
      productDetailLB = new lightbox({
        html: '

',
        className: 'product-detail-lightbox',
        maxWidth: 870,
        height: 500,
        onComplete: function () {
          productDetail.setElement('.productDetail');
          productDetail.render();
        }
      });
    });

But if product hasn't an image, I want maxWidth: 500
How can I fix it? Thank you.
Comment: have you tried setting maxWidth as auto or just not setting it?
Comment: When I not setting, its crashed on the page. Not a solution.
Comment: and can you use a conditional to setting maxWidth?
Answer: Make maxWidth a function that tests if there's an image. If no, return 500, otherwise, return 870.
 productDetailLB = new lightbox({
    html: '

',
    className: 'product-detail-lightbox',
    maxWidth: function(){
        if ($('.product-image')){
            return 870;
        } else {
            return 500;
        }
    },
    height: 500,
    onComplete: function () {
      productDetail.setElement('.productDetail');
      productDetail.render();
    }

EDIT: Since I don't have a lot of context, no guarantees that this will work.  All I did was test if there is a div element with the class "product-image" using jquery. You should be able to figure out the if statement on your own if it doesn't.
Comment: thank you! Can you give and example if statement? Because I put some code about if but not working.
Comment: Also note that in order for this to work, anytime you want to reference maxWidth, you have to call it (eg. someObject.maxWidth(), not someObject.maxWidth)
Comment: This is the right approach. If howeveer it's not working, try with the dom ready instead of binding 'onLoaded'


Mapping routes with Terraform and API Gateway

Question: I am building an API with AWS Lambda and API Gateway, keeping infrastructure in terraform. I have been mapping each route in my API to API Gateway using the terraform resource aws_apigatewayv2_route; if I do not, I get a 404 error. Rather than having to map each route to terraform is there a way to map all routes by default and then let the actual API code handle 404 errors? This is primarily to not have to change terraform every time I add a new endpoint to my API.
This is one route example:
resource "aws_apigatewayv2_route" "one_single_route" {
  api_id    = aws_apigatewayv2_api.my_api.id
  route_key = "POST /one-single-route"
  target    = "integrations/${aws_apigatewayv2_integration.my_integration.id}"
}

can I do something like this instead:
resource "aws_apigatewayv2_route" "all_routes" {
  api_id    = aws_apigatewayv2_api.my_api.id
  route_key = "ALL /*"
  target    = "integrations/${aws_apigatewayv2_integration.my_integration.id}"
}

Comment: "can I do something like this instead" - why not run the code and find out yourself it it works?
Comment: What's wrong with adding the code to all routes?   you could have that in a variable or from some other input like all files in a folder... then resource loops over that,
Answer: In API Gateway you can define a greedy path with ANY method to forward all requests to your integration lambda.
Update your:
route_key = "ALL /*"

To:
route_key = "ANY /{proxy+}"

https://docs.aws.amazon.com/apigateway/latest/developerguide/http-api-develop-routes.html


Marcadores no google maps buscando do banco de dados

Question: Como faria para preencher marcadores de estados no google maps, buscando os dados da latitude, longitude e titulo de um banco de dados.
Hoje já tenho essa função funcionando, porém os dados dos estados estão fixos em um javascript.
Abaixo está o código que tenho hoje:
<code>function init_map() {
    var myOptions = {
        zoom: 4,
        center: new google.maps.LatLng(-14.2392976,-53.1805017),
        mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
    marker = new google.maps.Marker({
        map: map,
        position: new google.maps.LatLng(-27.276409, -48.844043),
        icon: "img/1444113052_map-marker.png",
        title: "Santa Catarina"
    });
    marker = new google.maps.Marker({
        map: map,
        position: new google.maps.LatLng(-18.5779703,-45.4514505),
        icon: "img/1444113052_map-marker.png",
        title: "Minas Gerais"
    });
}

google.maps.event.addDomListener(window, "load", init_map);
</code>
Comment: Você já tem um banco de dados com essas informações? Em que formato?
Comment: Na verdade não tenho a tabela ainda. Será uma coisa bem simples, com a latitude, longitude e titulo. O formato estava pensando em json ou xml.
Answer: Olá,
Faz então o resultado deste banco ser escrito em formato Json, com php ou a linguagem que preferir.
Os dados ficam em uma matriz, que depois você acessa com um loop. Confere esta documentação:
https://developers.google.com/maps/documentation/javascript/examples/icon-complex
<code>  var beaches = [
    ['Bondi Beach', -33.890542, 151.274856, 4],
    ['Coogee Beach', -33.923036, 151.259052, 5],
    ['Cronulla Beach', -34.028249, 151.157507, 3],
    ['Manly Beach', -33.80010128657071, 151.28747820854187, 2],
    ['Maroubra Beach', -33.950198, 151.259302, 1]
  ];

for (var i = 0; i < beaches.length; i++) {
      var beach = beaches[i];
      var marker = new google.maps.Marker({
        position: {lat: beach[1], lng: beach[2]},
        map: map,
        title: beach[0],
        zIndex: beach[3]
      });
    }
</code>


Proving this by quadratic function

Question:
Given are $x$, $y$ and $z\ge0$, if $x^2+y^2+z^2+2xyz=1$, show that
\[x+y+z\le\dfrac32.\]
I want to solve this by quadratic function.

Let $x+y+z=k$, so $z=k-x-y$. Plug in and expand to have
\[-2 x {{y}^{2}}+2 {{y}^{2}}-2 {{x}^{2}} y+2 k x y+2 x y-2 k y+2 {{x}^{2}}-2 k x+{{k}^{2}}-1=0.\]
See this as a quadratic function of $y$, so $\Delta\ge0$, which implies that
\begin{align}4 {{x}^{4}}-8 k {{x}^{3}}+8 {{x}^{3}}+4 {{k}^{2}} {{x}^{2}}-12 {{x}^{2}}+8 k x-8 x-4 {{k}^{2}}+8\ge0.\tag{1}\end{align}
We need to find the minimum of $k$, so that $\exists~x$ for $(1)$ to be true. When $k=\dfrac32$,
\[4 {{x}^{4}}-4 {{x}^{3}}-3 {{x}^{2}}+4 x-1=0\implies\left[ x=1\operatorname{,}x=-1\operatorname{,}x=\frac{1}{2}\right]\]
are all solutions of $\Delta=0$. How to prove $k\ge\dfrac32$ don't work?
Comment: The condition is $x, y, z \ge 0$. If the condition is: $x, y$ are real numbers, and $z \ge 0$, the inequality is not true.
Comment: @RiverLi The inequality sign was reversed. I think it is correct now.
Comment: Yes, it it true.
Answer: If $x = 1$, clearly the desired inequality is true.
In the following, assume that $x < 1$.
Proceeding along OP's approach,
we have
$$\Delta = 4(1-x^2)[3 - 2k -(x-k+1)^2] \ge 0$$
which results in
$k \le 3/2.$
Answer: By using our condition and C-S we obtain:
$$2=\sum_{cyc}\frac{x}{x+yz}=\sum_{cyc}\frac{x^2}{x^2+xyz}\geq\frac{(x+y+z)^2}{\sum\limits_{cyc}(x^2+xyz)}=$$
$$=\tfrac{(x+y+z)^2}{x^2+y^2+z^2+\frac{3}{2}(1-x^2-y^2-z^2)}=\tfrac{(x+y+z)^2}{\frac{3}{2}-\frac{1}{2}(x^2+y^2+z^2)}\geq\tfrac{(x+y+z)^2}{\frac{3}{2}-\frac{1}{6}(x+y+z)^2},$$ which gives $$3-\frac{1}{3}(x+y+z)^2\geq(x+y+z)^2$$ or
$$x+y+z\leq\frac{3}{2}.$$
Comment: Nice. There is a typo after first =.
Comment: @River Li I fixed. Thank you!

Proving this by quadratic function


What is the boundary of the upper half plane?

Question:
Let $\mathbb H : = \{z \in \mathbb C\ |\ \mathfrak {I} (z) \gt 0 \}.$ Then what will be $\partial \mathbb H\ $?

I feel like it is $\mathbb R$ but in my book I found that it is $\mathbb R_{\infty}$ which might be thought of as the one point compactification of $\mathbb R.$ If we are in the extended complex plane then it's fine but if we aren't there how can we even talk of the point at infinity. This fact confuses me a lot. Could someone shed some light on it?
Thanks for investing your valuable time in reading my question.
Comment: $\Bbb R$ is the boundary in $\Bbb C$ and $\Bbb R \cup \{ \infty \}$ is the boundary in the extended plane (aka Riemann sphere).
Comment: Which textbook is that?
Comment: Then I assume that the boundary wrt to the extended plane is meant. That would be natural because automorphism of the upper half-plane are Möbius transformations, which are usually considered as mappings from the Riemann sphere to itself.
Comment: @Martin R it is actually mentioned while discussing the automorphisms of the upper half plane.
Comment: @Martin R$:$ I think you are right. I realized that now. But the author didn't mention it explicitly anywhere which is the main source of my confusion. Thanks for your suggestion.
Answer: Yes, as you suspect, and as @Martin R comments, there is a context-dependence. Literally, in the set $\mathbb C$, the boundary is certainly just $\mathbb R$.
Many complex analysis sources are (perhaps reasonably) a little vague about whether they implicitly include "the point at infinity" or not. And, indeed, it certainly depends what's happening. Indeed, every entire function "extends" to a function on the Riemann sphere with possibly an essential singularity at $\infty$. This doesn't add much to what we already know.
In contrast, the linear fractional /Moebius transformations only really make sense on the Riemann sphere, since they typically map a point in the "finite part of $\mathbb C$" to $\infty$, and vice-versa. Nevertheless, some traditional discussions ignore this "flaw", and behave as though linear fractional transformations map $\mathbb C$ to itself. Well, yeah, actually, they approximately do. :)
(Some questions about conformal mapping of non-compact regions are also ambiguous, depending whether we intend to pay intention to $\infty$ or not.)
This sort of textbook/quiz question is yet another one of those where we have to either be able to guess the mental state of the asker, or answer in a qualified fashion. The latter is more real-life (assuming some baseline sanity about one's personal version of it): "The answer depends on context. The literal topological boundary in $\mathbb C$ is just $\mathbb R$. But if we are implicitly thinking of the upper half-plane as a subset of the Riemann sphere, then the topological boundary is $\mathbb R\cup\infty$."
(Yes, I know, in some quasi-adversarial contexts, that sort of answer is not allowed, etc., but don't take it to heart...)
Comment: garret sir many many thanks for your detailed answer. Now it's quite clear to me what's going on here.


There are $6$ points in the plane such that each point is connected to exactly $3$ distinct points. Find the number of all possible pairs

Question: There are $6$ points in the plane such that each point is connected to exactly $3$ distinct points. Find the number of all possible pairs. Example : If the points are $\{1,2,3,4,5,6\}$ such that $1$ is connected to $2,3,4$ then, $2,3,4$ will already be connected to $1$, so, you have to find the other two choices for these three numbers. And so on. We have to find all possible $(a,b)$ where $a,b$ represent the connected points like $(1,2), (1,3), \cdots$. Note that $(1,2)$ and $(2,1)$ will be same.
My take on the part :
I think Principle of Inclusion-Exclusion will be appropriate here but cannot think of a solution using that. Also, by finding all possible choices for a pair $(a,b)$ seems hard. I did a brute force calculation and it seems to be $9$ pairs.
Answer: You are overthinking it. Every point is connected to $3$ points, so we have $6\cdot 3=18$ pairs, but we've counted each pair twice, so there are only $9$.
Comment: Oops, yes. Thank you!