Show that a set of polynomials form a basis for the polynomial vector space

Question: I need to show that the set $B=\{1,1-x,1-x^2,...,1-x^n\}$ is a basis for the vector space $V=\{P(x)\in\mathbb{K}[X]|deg(P(X))\leq n\}$.
I know that I need to show that B is a spanning set and a linearly independed set. So here is what I did: Let p(x)=$a_0+a_1x+...+a_nx^n \in V, \alpha_0,\alpha_1,...,\alpha_n \in \mathbb{K}$ such that $p(x)=\alpha_0+\alpha_1x+...+\alpha_nx^n$, and I need to find $\alpha_0,...,\alpha_n$. But here is where I stuck because I get something like $1-x^n=x^n$.
Answer: Note that $$\alpha_0\cdot 1+\alpha_1\cdot (1-x)+\cdots +\alpha_n\cdot(1-x^n)=\alpha_0+\cdots+\alpha_n-\alpha_1x-\cdots -\alpha_n x^n.$$
So, if you consider $a_n=-\alpha_n, \cdots, a_1=-\alpha_1, a_0=\alpha_0+\cdots +\alpha_n$ then you have
$$a_0+a_1x+\cdots +a_nx^n=\alpha_0\cdot 1+\alpha_1\cdot(1-x)+\cdots +\alpha_n \cdot(1-x^n).$$
Answer: You just need to show that $B$ is linearly independent.
Assume we have the equation:
$a_0+a_1.(1-x)+...+a_n.(1-x^n)= 0$  then we get:
$a_n.x^n+...+a_1.x -(a_0+...+a_n)=0$
Because $(x^n,...,x,1)$ is the basis we must have:
$a_n$=...=$a_1$=$0$  and $a_0+...+a_n$=$0$, hence $a_n=...=a_1=a_0$=$0$
Answer: Hint
Let $n>0$ and
$p(x)=a_0+a_1x+a_2x^2+....a_nx^n$ be an element of $V$.
then it can be written as
$p(x)=\sum_{k=0}^na_k+\sum_{k=1}^n (-a_k)(1-x^k)$
thus $B$ is a spanning set.


Erro no db:create no Mac OSX Montain Lion

Question: <code>alexandesigner$ rails server

dyld: lazy symbol binding failed: Symbol not found: _mysql_get_client_info
  Referenced from: /Users/alexandesigner/.rvm/gems/ruby-2.0.0-p353/extensions/x86_64-darwin-12/2.0.0-static/mysql2-0.3.15/mysql2/mysql2.bundle
  Expected in: flat namespace

dyld: Symbol not found: _mysql_get_client_info
  Referenced from: /Users/alexandesigner/.rvm/gems/ruby-2.0.0-p353/extensions/x86_64-darwin-12/2.0.0-static/mysql2-0.3.15/mysql2/mysql2.bundle
  Expected in: flat namespace

Trace/BPT trap: 5
</code>
Como resolvê-lo?
Answer: Consegui resolver o problema!
seguindo um post no SOEN, nesta pergunta: https://stackoverflow.com/questions/13773633/symbol-non-found-when-run-rails
It means that you're trying to run ruby 1.8.7 with gems that were compiled for ruby 1.9.3 - something has got its knickers in a twist
I'd try re-installing the gems into a clean gemset and make sure you are using the ruby version that you think you are
Que rapidamente traduzido:
"Isso significa que você está tentando executar ruby 1.8.7 com gemas que foram compilados para ruby 1.9.3 Eu ia tentar re-instalar as gemas em uma gemset limpo e verifique se você está usando a versão ruby que você pensa que é"
Eu percebi que era as versões do mysql2 que estava utilizando, só alterei e setei no gemfile de 0.3.15 para 0.3.11
Comment: Que bom! Você pode aceitar sua resposta. Aí no lado esquerdo, abaixo dos votos.


How to show that $K\leq S_4$ is a normal subgroup?

Question: Let $K=\{(1),(1,2),(3,4),(2,4),(1,4),(2,3)\}$ is a subgrope of $S_4$, we want to show that it is a normal subgroup.
I know that i have to examine the condition of normality in $S_4$ i.e. for all $g\in S_4, g^{-1}Kg=K$. I think this takes times or I am missing something near. Please give me the right hint. Thank you.
Edit: $K = \{(1),(12)(34),(13)(24),(14)(23)\}.$
Comment: What is your text book? Most probably it is a typo or you simply miscopied... It could probably be $\,\{(1), (12)(34), (13)(24), (14)(23)\}\triangleleft S_4\,$
Comment: It is not a subgroup! $(1,2)(2,4)=(1,2,4)\notin K$.
Comment: It is printed as above as in my text note.
Answer: Maybe your course instructor intended $K = \{(1),(12)(34),(13)(24),(14)(23)\}.$ That is, $K$ consists of the identity, together with all products of two disjoint $2$-cycles. This is a subgroup. It is also normal because the identity is conjugate only to the identity, and because the set of products of two disjoint $2$-cycles is closed under conjugacy, so that $\sigma K\sigma^{-1} = K$ for all $\sigma \in S_{4}.$
Answer: This isn't going to work on two fronts:
First your subset $K$ is not a subgroup: $(1 \ 2)(2 \ 3) = (1 \ 2 \ 3)$ so $K$ is not closed under the group operation.
Second your subset $K$ is not closed under conjugation: $(2 \ 3)^{-1}(1 \ 2)(2 \ 3) = (1 \ 3)$.
Maybe you meant the subgroup generated by $K$?  But $K$ generates all of $S_4$ so in that case it is trivially normal.


Como resolver o erro Call to undefined function mysql_connect()

Question: Estou fazendo um inventário de TI para cadastro e quero fazer a conexão ao banco de dados, mas tá dando esse erro:

Fatal error: Uncaught Error: Call to undefined function
  mysql_connect() in C:\xampp\htdocs\xampp\cadastrando.php:9 Stack
  trace: #0 {main} thrown in C:\xampp\htdocs\xampp\cadastrando.php on
  line 9

Como poderia resolver esse erro?
Segue abaixo o meu código.
HTML:
<form method="post" action="" onSubmit="">
        <fieldset>
            <legend>Sistema de Inventário</legend>

            Setor:
            <input class="form_inp" type="text" name="" size="30" required>

            Usuário:
            <input class="form_inp" type="text" id="" name="" size="30" required>

            O/S :
            <input class="form_inp" type="email" name="" size="30" required>

            Hd :
            <input  class="form_inp"type="text"  name="" size="30" required>

            Memória:
            <input class="form_inp" type="text" id="" name="" size="30" required>

            Processador:
            <input class="form_inp" type="text" id=""  name="" size="30" required>

            Cd/Dvd:
            <select class="form_inp"  name="Dados">
                <option value="Sim">Sim</option>
                <option value="Não">Não</option>
            </select>

            Placa Mãe:
            <input class="form_inp" type="text" id="" name="" size="30" required>

            HostName:
            <input class="form_inp"type="text" id="" name="" size="30" required>

            Monitor/Patrimônio/Marca/Modelo:
            <input class="form_inp" type="text" id="" name="" size="30" required>

            Nobreak/Patrimônio/Marca/:
            <input class="form_inp" type="text" id="" name="" size="30" required>

            Placa de Rede :
            <input class="form_inp" type="text" id="" name="" size="30" required>

            Placa de Vídeo:
            <input class="form_inp" type="text" id="" name="" size="30" required>

            <input type="submit" style="float: right;" value="Cadastrar" >
            <input type="reset" style="float: right;" value="Limpar">

        </fieldset>

php/bancodedados:

   <title>Cadastrando...</title>

<?php
$host = "localhost";
$user ="roor";
$pass = "";
$banco = "cadastro";
$link = mysqli_connect("host", "user", "pass", "database");
mysqli_select_db($banco) or die (mysqli_error());
?>
<?php
$setor=$_POST['setor'];
$usuario=$_POST['usuario'];
$hd=$_POST['hd'];
$memoria=$_POST['memoria'];
$propressador=$_POST['processador'];
$cd=$_POST['cd'];
$placam=$_POST['placam'];
$host=$_POST['host'];
$monitor=$_POST['monitor'];
$nobreak=$_POST['nobreak'];
$placar=$_POST['placar'];
$placav=$_POST['placav'];
$sql=mysql_query("INSERT INTO setor(setor,usuario,hd,memoria,processador,cd,placam,host,monitor,nobreak,placar,plavav) VALUES('$setor,$usuario,$hd,$memoria,$processador,$cd,$placam,$host,$monitor,$nobreak,$placar,$placav'))");
?>

Comment: http://pt.stackoverflow.com/questions/579/por-que-n%C3%A3o-devemos-usar-fun%C3%A7%C3%B5es-do-tipo-mysql da uma lida se puder.
Comment: No PHP7 essas funções não existem mais.
Comment: Se for atulizar um código com o MySQLi pode olhar [essa resposta](http://pt.stackoverflow.com/a/32822/91)
Comment: estou usando o php 7
Comment: @rray fiz uma atualização e deu um erro diferente e tentei outras formas e deu o mesmo erro .
Comment: Como já disse o @rray, esta função foi descontinuada (é o 1o parágrafo da resposta aceita na original, indicada no quadro amarelo).
Answer: A função mysql_connect() foi descontinuado.
Agora se usa mysqli_connect().
$link = mysqli_connect("host", "user", "pass", "database");

Isso também vale para os outros comandos que comecem com mysql_. Devem ser mysqli_.
Portanto:
mysqli_query($link, $query);

Comment: Fiz uma atualização mais apareceu esse erro e fiz de outras formas e nada ;Warning: mysqli_connect(): php_network_getaddresses: getaddrinfo failed: O nome solicitado �
Comment: Isso aconteceu porquê provavelmente os dados de conexão estão errados.


Finding eigenvalue of a matrix expression

Question: Consider the following matrix
$A=\left[\begin{array}{lll}1 & 0 & 0 \\ 2 & 3 & 0 \\ -3 & 1 & -2\end{array}\right]$
How can I find the eigenvalues of $3 \mathrm{~A}^{3}+5 \mathrm{~A}^{2}-6 \mathrm{~A}+2 \mathrm{I}$?
I know the matrix $A$ has eigenvalues $1,3,-2$ and also that I can use cayley Hamilton theorem and reduce the matrix expression, but that doesn't reduce it enough so that I can avoid multiplication of matricies.
Can anyone please help me how to do this?
Thank you.
Comment: It is clear that $A$ has eigenvalues $1,3,-2$ as it is triangular.  Suppose that $v$ were an eigenvector with corresponding eigenvalue $\lambda$ for the matrix $A$... can you reason that $v$ is also an eigenvector for $A^2$ with eigenvector $\lambda^2$?  Note, $A^2v = A(Av)$ and use what you know about eigenvectors.  Can you generalize and show that any matrix polynomial $f(A)$ will also have $v$ as an eigenvector with $f(\lambda)$ as the eigenvalue where we plug in the scalar $\lambda$ in place of $A$'s and $1$ in place of $I$'s?
Comment: Yes, thank you very much. I got it
Answer: Hint: If $Av = \lambda v$, then what can we say about $(3A^3 +5A^2 - 6A + 2I)v$?
Answer: If  $a$   is a eigen value of the matrix $A$  then  $a^2$ is the eigen value for $A^2$...similar arguments for $A^m$, where m is a positive  integer.
Similarly, $k*a$ is the eigen value for $kA$.
Now  use the previously mentioned  rules (observations) to calculate the eigen value of any expression  with out calculating the  powers of the matrix.
Comment: You are my best friend.Take greeting  from me
Comment: Knowing $\LaTeX$ is an "overkill". You just need to write your formulae between dollar signs as `$A^2$` for $A^2$.
Comment: Please give me more information how to write the question perfectly.
Comment: @maa I've edited your question to format the mathematical expressions correctly. If you click "edit", you can see the changes that I made: all I did was put in `$....$` ("dollar signs") around any mathematical expressions.


How to use a service class in a controller class?

Question: I'm trying to integrate this amazing calendar  in my project. I get trouble with the service thing. I'm using this kind of structure:
application/
    modules/
        agenda/
            controllers/
                CalendarController.php
            models/
            services/
                CalendarService.php
            views/
                filters/
                helpers/
                scripts/
                calendar/
                    view-calendar.php
    module2/
    module3/

I route this in my application.ini this way:
resources.router.routes.agenda.route = /apps/agenda/
resources.router.routes.agenda.defaults.module = agenda
resources.router.routes.agenda.defaults.controller = calendar
resources.router.routes.agenda.defaults.action = view

I pointed my browser on, and I obtained this message:
Message: Invalid controller class ("Agenda_CalendarController")

I fixed it with my Agenda_ suffix and refreshed my browser. Obtained this:
Message: Controller "Agenda_CalendarController" is not an instance of Zend_Controller_Action_Interface

So I instanced it with "extends Zend_Controller_Action". Obtained this: :-)
Fatal error: Class 'Service_Calendar' not found in /home/[PATH TO MY APP FOLDER]/application/modules/agenda/controllers/CalendarController.php on line 30

I can't figure out what's going wrong. Someone have a hint or two for me :-)
Note: I do not know if that means anything, but I use NetBeans and if I press CTRL while hover a class method of service in the controller class; related popup informations are correct.
Solution:
Thanks guys, You gave me the path to go further. My modules bootstraping wasn't set properly. with your hints I found this post from Bob Allen, where he describes the same problem.
When you know what you're searching for... :-)
Thanks, my problem is fixed and I know a bit more!
Comment: Try moving `application/modules/agenda/services/CalendarService.php` to `application/services/Calendar.php` and see if it has any luck finding the class.  You may need to rename the class using your application namespace (e.g. Application_Service_Calendar).
Answer: The naming convention for a controller isn't the same for model/service/view etc., in the sense that you needn't prepend the type in the filename, as you would with a controller. They must follow the basic autoloading name-to-path schema.
So, the declaration for you service would be: Agenda_Service_CalendarService, because that maps to modules/agenda/services/CalendarService.php (note the inflection - from the services folder to the _Service_ singular - that's ZF working and it happens for models, too).
Also make sure you've properly initialized the module (having its own Bootstrap.php file, set up in application.ini).
PS: NetBeans knows where your class is, because it scanned the files and saw the declaration, not the logical inclusion of that class.


Changing values of items in an array using javascript

Question: var num = [ 5 ];
var row = [0, 1, 2, 3, 4, 5];
row[4] = num
alert (num.indexOf(row[4])); /* alerts: -1 */
alert (num.indexOf(row[0])); /* alerts: -1 */
alert (row[4]);              /* alerts:  5 */
alert (row);                 /* alerts: 0, 1, 2, 3, 5, 5 */

I don't understand why the first two alerts return "-1" instead of, respectively, "5" and "0", do you have any ideas?
Answer: line1:
row[4] = num

line2:
alert (num.indexOf(row[4])); /* alerts: -1 */

line3:
alert (num.indexOf(row[0])); /* alerts: -1 */

after line 1 is executed
row[4] = [5] and not 5 as you may think therefore indexOf returns -1
now, for the second part:
num is still [5], so what is the index of row[0] or what is the index of 0 in that variable?? well -1 too (since that value is not present in that array)
Answer: row[4] = 4
num does not contain value 4 thus -1 is returned (-1 means no such item in an array)
same goes to num.indexOf(row[0])
arrayToLookThru.indexOf(valueToLookFor) - this is how it works.
indexOf returns position of the first element with a given value and -1 if no elemets found.


Como enviar mais de um opção de checkbox por email?

Question: Estou tentando enviar mais de um checkbox marcado por email, com PHPMail, só consigo enviar o ultimo item marcado, tentei fazer um if com foreach mais não adiantou, talvez ainda não esteja sabendo fazer, como eu consigo colocar essa função nesse checkbox em baixo:
<?php
if(!empty($_POST['checkbox'])) {
foreach($_POST['checkbox'] as $check) {
       echo $check . "
";
}}

$Nome = $_REQUEST['Nome'];
$Tel = $_REQUEST['Tel'];
$Email = $_REQUEST['Email'];
$Mensagem = $_REQUEST['Mensagem'];

$mail->WordWrap = 50;
$mail->IsHTML(true);
$mail->Subject  =  "Contato do site Webwork"; // Assundo
$mail->Body     =   " Nome: $Nome \n
". // Usuario
                    " Tel.: $Tel \n
".
                    " Email: $Email \n

".    // Email
                    " Mensagem: $Mensagem \n
"; // Mensagem

Queria imprimir a resposta de mais de um check no corpo do email, como eu faço isso?
<form action="executa.php" method="post" name="form1">
<input type="checkbox" name="checkbox[]" value="Primeiro" />
<input type="checkbox" name="checkbox[]" value="Segundo" />
<input type="checkbox" name="checkbox[]" value="Terceiro" />
<input type="checkbox" name="checkbox[]" value="Quarta" />
<button type="submit" value="Enviar">Enviar</button>
</form>

Comment: No seu form campo do checkbox deve ter o `name` seguido de colchetes: `name="produtos[]"`
Comment: Existe mais de um **$_POST['nome']** ?
Comment: Já tinha, editei para colocar o form.
Comment: Eu consigo dar um echo, e aparece para mim, mas no email eu não sei como enviar.
Answer: Use o implode() para transforma o array de checkbox enviados em um string seperando os itens por um delimitador, feito concate esse resultado a sua mensagem:
$selecionados = !empty($_POST['checkbox']) ? implode(', ', $_POST['checkbox']) : '';

$mail->Body = 'Mensagem..... '. $seleciondos;

Comment: Ficou perfeito, muito obrigado.


How to parse JSON "nearby search response" from Google Places API in Swift/Xcode

Question: The Google Maps API is working great and I am getting the appropriate JSON response. However, I'm having trouble parsing the intricate and complex JSON response in order to obtain the specific information I need, such as location name. I have gone through basically every YouTube tutorial and online post I could find and nothing has helped me. I've included the current code I'm using and a link to the documentation outlining the JSON response I'm getting. Any help would be much appreciated!
https://developers.google.com/places/web-service/search#nearby-search-and-text-search-responses
func nearbyLocations(latitude: Double, longitude: Double) {

    let jsonUrlString = "https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=\(latitude),\(longitude)&radius=25&key=..."

    guard let url = URL(string: jsonUrlString) else { return }

    URLSession.shared.dataTask(with: url) { (data, respone, err) in

        guard let data = data else { return }

        do {
            guard let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? [String: Any] else { return }
            print(json)
        } catch let jsonErr {
            print("json error:", jsonErr)
        }

    }.resume()
}

Answer: You can parse normal like:

if let results = json["results"] as! [[String:Any]], let firstResult = results.first {
    let geometry = firstResult["geometry"] as! [String:Any]
    let location = geometry["location"] as! [String:Any]
    let lat = location["lat"] as! Double
    let lng = location["lng"] as! Double
}

Comment: No problem, Good luck! :D
Answer: Use Codable to parse the JSON response.
Models:
struct Root: Codable {
    var results: [SearchResult]
    var status: String
}

struct SearchResult: Codable {
    var id: String
    var icon: String
    var name: String
    var placeId: String
    var reference: String
    var types: [String]
    var vicinity: String
    var geometry: Geometry
    var photos: [Photo]
    var openingHours: [String:Bool]?
}

struct Geometry: Codable  {
    var location: Location
}

struct Location: Codable  {
    var lat: Double
    var lng: Double
}

struct Photo: Codable {
    var height: Double
    var width: Double
    var photoReference: String
}

In the models above, add the keys as per your requirement. Also any of the above keys are not sure from the API, mark them as optional.
Parsing:
Parse the data your obtained in URLSession.shared.dataTask like,
do {
    let decoder = JSONDecoder()
    decoder.keyDecodingStrategy = .convertFromSnakeCase
    let root = try decoder.decode(Root.self, from: data)
    print(root)
} catch {
    print(error)
}

Usage:
For the sample JSON response in the link you provided, you can access the properties of your response using root like,
root.status //OK

root.results.first?.name //Rhythmboat Cruises

root.results.first?.geometry.location.lat //-33.870775

Read more about Codable and how it works here.
Comment: Do accept (tick on left) if the answer helped. Also, `Codable` is a much efficient and readable way with much lesser code that `JSONSerialization`.


Is the windows server 2008 r2 firewall in amazon ec2 not necessary

Question: Under normal circumstances, is the windows server 2008r2 firewall, running on an amazon ec2 instance even necessary? Can it safely be turned off? It appears that thru the security groups, amazon is providing a firewall for the machine, or am I missing something?
Answer: This is a matter of personal preference. If you're not using VPC I would say it's safe to turn it off. If you were using VPC, I would leave it on to act as another security blanket that protects your internal network from the perimeter if it's exploited. Since there's only one NIC attached to your instance and Security Groups are handling all the access control lists, I personally would turn it off.


Complex count in ruby

Question: I would like to identify and count the posts that have a specific number of messages and a post.location that is not nil.
I have approximately 100k rows and it is for a statistical use so I need fast queries (I might have to index post.location by the way).
How can I do it the easiest and quickest way?
Here is my schema :
create_table "posts", :force => true do |t|
  t.string   "ref"
  t.string   "title"
  t.string   "author"
  t.datetime "created_at"
  t.datetime "updated_at"
  t.string   "location"
  t.float    "lat"
  t.float    "long"
end

create_table "messages", :force => true do |t|
  t.integer  "post_id"
  t.integer  "status_id"
  t.integer  "user_id"
  t.string   "content"
  t.datetime "created_at"
  t.datetime "updated_at"
  t.float    "lat"
  t.float    "long"
end

add_index "messages", ["post_id"], :name => "index_messages_on_post_id"
add_index "messages", ["created_at"], :name => "index_messages_on_created_at"

Answer: The SQL Query you are looking for should look a lot like this:
SELECT COUNT(posts.id)
FROM posts
JOIN messages ON (posts.id = messages.post_id)
GROUP BY (posts.id) HAVING (count(messages.id) > ?)
WHERE posts.location IS NOT NULL

You can then convert that to a ActiveRecord Query or just use find_by_sql.
(I wrote this from memory so you might have to tweak it in some places .. but the general idea should work).
Comment: That looks good, and how do I verify that post.location is not nil?
Answer: You can use this scope in you Post model
scope :give_a_valid_name, lambda {|n| joins(:messages).having("COUNT(messages.id) = #{n}").where("location IS NOT NULL")}
Then use Post.give_a_valid_name(5).size to get the number of posts that have 5 messages.
Hope this helps.
Answer: OK I managed to get through it thanks to both Tigraine's and az7ar's answers. Here's what worked out:
Post.joins(:messages).select('post_id as id').group("post_id").having("count(*) = 1").where('location IS NOT NULL')
Thank you Tigraine for the JOIN advice and az7ar for the .where("location IS NOT NULL")syntax.

Complex count in ruby


How to prevent the beep sound caused by alt key pressed in a WinForms TextBox?

Question: I'm creating a routine that allows the user to replicate keyboard shortcuts into a textbox for 'custom keyboard shortcuts' customization, but every time the alt key is pressed with another letter, it produces another sound.
I'm capturing the keys in the textbox_keydown event to parse the modifiers + other keys into a readable Shift + A or Ctrl + Shift + B manner into that very same textbox. Should I be doing this in a different event like textbox_previewkey instead of textbox_keydown? How can I prevent the alt modifier key + a letter or number causing the Beep sound?
the textbox is just a normal .net 3.5 textbox with the only edited properties of it being the ReadOnly property to false. Is there a better way I could re-do this?
I'm currently just checking that if any modifiers keys are pressed and then + a-z or 0-9, then to go ahead and input the appropriately pressed keys into that same textbox like Shift + A or Ctrl + Shift + Y.
Comment: +1 Your question & answer was usefull for me. Thanks.
Comment: If you have a message box in the method call, things might not work as expected. See [cannot-disable-beep-sound-on-textbox-keydown-event](http://stackoverflow.com/questions/19219597/cannot-disable-beep-sound-on-textbox-keydown-event)
Answer: Handle the KeyDown event of the TextBox, e.g. with void HandleKeyDown(object source, KeyEventArgs e) and inside enter: if (e.Alt) e.SuppressKeyPress = true;.
(also works for the Return key)
Answer: Disregard, I was able to solve the problem by suppressing the keycode right from the start without affecting it's normal functions. Here is what I used:
e.SuppressKeyPress = (e.KeyCode == e.KeyCode);

Comment: You realize that this is the same as saying e.SuppressKeyPress = true, right?
Comment: unless `KeyCode` returns `double.Nan` ;)
Answer: You need to set e.Handled = true; in order to prevent the keystroke from bubbling up.
Comment: HI
I had the same problem, e.Handled = true didn't solve the problem. e.SuppressKeyPress = true did it.


Fatal error: Cannot use object of type stdClass as array in

Question: I get an fatal error on the 'add content page'.
Fatal error: Cannot use object of type stdClass as array in
function mymodule_form($form, $form_state){
    $form['mymodule'] = array(
        '#type' => 'textfield',
        '#description' => t('Please enter your text here.'),
        '#required' => TRUE,
    );
    $form['mymodule_submit'] = array(
        '#type' => 'submit',
        '#value' => 'Submit this form'
    );

    return $form;
    return node_content_form($node, $form_state);
}

The problem's happen when I add my form, when I use only the
return node_content_form($node, $form_state);

it is working fine, what do I wrong?
Comment: @user27485 Please can you clarify what you're trying to  do here? [`hook_form()`](https://api.drupal.org/api/drupal/modules!node!node.api.php/function/hook_form/7) is used exclusively by modules that declare node types. Is that what you're trying to do, or are you trying to use the form for an existing content type in a different context (maybe at another url, embedded in another page, etc)? Or are you trying to create your own form from scratch?
Comment: You haven't initialised `$node`
Comment: @GisleHannemyr A couple of lines from the bottom of the question: "The problem's happen when I add my form, when I use only the `return node_content_form($node, $form_state);`. I missed that first too, I think the OP is just switching back and forth between the two returns for testing. `$node` being uninitialised is causing that error when `node_content_form` tries to pass the null object off to `node_type_get_type()`
Answer: There are two related but distinct concepts that seem to be conflated in your code, i.e. hook_form, and the notion of a drupal form builder function. Hook_form uses the template explained by @gisleHannemyr.
The template for a form builder function is:
function mymodule_example_form($form, &$form_state) {
  ...
  return $form;
}

Use hook_form to create or override node creation forms, and a form builder function for any other (non-node-related) form.
If you simply want to alter an existing (node or other) form, you should use hook_form_alter, instead.
Answer: It always a good idea to read the documentation.
The template for hook_form is:
hook_form($node, &$form_state)

The first parameter passed into the ($node in the template) is an object.  In your hook, you've called it $form.  That is confusing.  You're also treating it as an array.  That is just wrong, and is what triggers the error message you see.
Additional quirks:
The second parameter is passed as reference.  You're implementation is passing it as a value (it won't bite you, since you're not using it, but you better get it right anyway).
You've got a spurious second return statement at the end. It will not do any harm, since it is never executed, but it is confusing.
Here is how your hook should start and end (the bit in the middle looks OK),
function mymodule_form($node, &$form_state) {
    $form = array();

    // build the form array.

    return $form;
}

Comment: I think there is some confusion here between hook_form and the concept of a builder function for a form. The latter takes $form and &$form_state as args. https://drupal.org/node/1702548
Comment: @olyN, well, the OP's question shows `hook_form` being used.  I that is not what the OP intended to use, he/she needs to edit the question.
Comment: Agreed. So the syntax used in the question mixes the two concepts.
Comment: Great spot @GisleHannemyr, didn't even consider OP might be trying to implement `hook_form()`. Out of both possibilities this makes the most sense with the OP's current code


$\lim_{x\to x_0 ;x\in X} f ( x)$ exists if f is a uniform continuous function and $x_0$ is an adherent point

Question:
Proposition: Let $X$ be a subset of $R$, let $f:X\to R$ be a uniformly continuous function, and let $x_0$ be an adherent point of $X$. Then $\lim_{x\to x_0 ;x\in X} f ( x)$ exists.

Proof
Take any sequence $(a_n)_{n=1}^\infty$ where $a_n\in X$ and it converges to $x_0$. We know such a sequence exists because $x_0$ is an adherent point of $X$.
Since $(a_n)$ is a convergent sequence, then its cauchy.
$f$ is a uniform continuous function,hence, if $(a_n)$ is cauchy, $(f(a_n))$ is also cauchy. Again, because $(f(a_n))$, then its convergent and hence the limit exists.
Is my proof correct?
Comment: You have to prove that this limit is independent of the approximating sequence $(a_n)$.
Comment: @Jose27 I took any convergent sequence, is that enough?
Answer: You have just proved limit exists for a specific convergent sequence $x_n\to x_0$, you have to show then the limit is independent of the convergent sequence. That is if $x_n\to x_0,y_n\to x_0$, then $\lim f(x_n)=\lim f(y_n)$, which should be easy if you make use of the uniform continuity of $f$ on $X$ and pass to limit.

Respond to J.G's comment:
Given $x_n\to x_0,y_n\to x_0$, we know $\lim f(x_n),\lim f(y_n)$ exists and aim to show $\lim f(x_n)=\lim f(y_n)$. Consider sequence $z_n$ defined as $(x_1,y_1,x_2,y_2,\cdots)$ which is a combination of $(x_n),(y_n)$. Then we know $z_n\to x_0$ and by similar argument, we know $\lim f(z_n)=l\in \mathbb{R}$. Since $f(x_n),f(y_n)$ are two subsequence of a convergence sequence $\lim f(z_n)$, we know they must convergent to the same limit, hence $\lim f(x_n)=\lim f(y_n)$.
Comment: @J.G I have edited the answer.
Comment: I should use the fact if (a_n) and (b_n) are equivalent, then their image under f are equivalent?
Comment: @MAS Yes, I think that is the idea.
Comment: @JohnZHANG I had a similar argument as MAS, but I can't show the part you explain. To know that we have not yet seen that two sequences are equivalent. Are you able to complete the proof in your comment?


Verifying Access Tokens Generated from Multiple Client IDs with Okta

Question: I have two applications using the same backend. Both frontend applications uses different client IDs. what is the best way to go about verifying access tokens for both frontend applications. Below is the basic structure of what I have.
const OktaJwtVerifier = require('@okta/jwt-verifier');

const oktaJwtVerifier = new OktaJwtVerifier({
  issuer: process.env.OKTA_ISSUER,
  clientId: process.env.OKTA_CLIENT_ID

});

const oktaToken = await oktaJwtVerifier.verifyAccessToken(accessTokenString,[
    process.env.OKTA_CLIENT_ID,
]);

Is there a way to send in an array of issuer and clientId? The objective is to verify access tokens coming generated from two applications APP X and APP Y, that is, clientId X and clientId Y
Answer: You don't need to verify the client id, as it's one used to obtain the token. Okta's GitHub repo README.md gives you an idea of claims/conditions to be verified for access tokens (https://github.com/okta/okta-jwt-verifier-js#access-tokens), so please check.
Here is a snipper from the verification library, which shows that you don't need client_id for access token verification
  async verifyAccessToken(accessTokenString, expectedAudience) {
    // njwt verifies expiration and signature.
    // We require RS256 in the base verifier.
    // Remaining to verify:
    // - audience claim
    // - issuer claim
    // - any custom claims passed in

    const jwt = await this.verifyAsPromise(accessTokenString);
    verifyAudience(expectedAudience, jwt.claims.aud);
    verifyIssuer(this.issuer, jwt.claims.iss);
    verifyAssertedClaims(this, jwt.claims);

    return jwt;
  }

In general, it doesn't matter what was the client id, through which a token got obtained, but rather the content of the token:

who it is for
who issued it
its expiration time
scopes
custom claims

If you are concerned about client IDs, you can eliminate it on authZ server level by introducing constraints for its access policy/rule.
Comment: client_id is only required for id_token validation, for access you don't need it. I edited my response to include a snippet from the library you are using. Not sure where you found client_id as a required parameter
Comment: I know the client ID don't need to be verified, however, they are used to verify the access token. So access token generated with Client ID `X` needs to be verified with client ID `Y`
Comment: In further testing, I realize the client id and issuer is necessary to validate tokens coming in.


The page will strangely refresh when I click the button

Question: Here's my code:
<!DOCTYPE html>

    <title>中国工程院无线投票系统</title>
    <meta http-equiv="Content-Type" content="text/html;charset=utf-8">
    <link rel="stylesheet" href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css">
    <link rel="stylesheet" href="css/login.css">

中国工程院无线投票系统

        <form>

                用户名

                    <input type="text" v-model="account.username" class="form-control" placeholder="Username" required
                           autofocus>

                密码

                    <input type="password" v-model="account.password" class="form-control" placeholder="Password"
                           required>

            <button v-on:click="validate" class="btn btn-lg btn-primary btn-block">登录</button>
        </form>

In the login.js file:
var login = new Vue({
    el:"#login",
    data:{account:{}},
    methods:{
        validate:function () {

        },
        say: function (){

        }
    }
});

At the beginning, I thought it had something to do with the code within method "validate". However, after I deleted all the code inside, the page still get refreshed when I click the button which is not supposed to happen.
Comment: `button` default type will reload the page on click.  Add `type='button'` to `button`.
Comment: @mrogers thank you!
Answer: You should add type="button" to your <button>.
If you don't specify a type of a <button> in a <form>, it will behave like a submit button by default, which refreshes the page.
Docs:

<type="submit"> The button submits the form data to the server. This is the default if the attribute is not specified, or if the attribute is dynamically changed to an empty or invalid value.
Comment: @XINDILI Maybe you should accept this answer, if this helped you.
Answer: Or you can do it the vuejs way using Event modifiers like this:
<button v-on:click.prevent="validate" class="btn btn-lg btn-primary btn-block">登录</button>

The prevent event modifier prevents the default behaviour.
Its just like using event.preventDefault() inside your event handler
Answer: Add @submit.prevent to your form.
<form @submit.prevent>
 ....
</form>

Answer: When using a form element, the submit action refreshes the page unless you specify return false; at the end of the onsubmit attribute.  I believe you are having the same issue here.
Try putting a semicolon at the end of your onclick attribute (before the quote), then type return false; and it should solve your problem.
Comment: `return false` isn't [consistent](https://stackoverflow.com/questions/1357118/event-preventdefault-vs-return-false). `e.preventDefault` is the proper way.


Bayesian random variables VS. MLE fixed variables

Question: "Bayesian inference treats model parameters as random variables whereas frequentist inference considers them to be estimates of fixed, 'true' quantities." (Ellison 2004)
What does it mean in the Bayesian methodology that parameters are random? And how does this differ from Maximum Likelihood estimation where they are fixed?
Isabella Ghement's response in this thread is a good start, but I still don't completely understand the "randomness" of the parameters.
Comment: The randomness is commonly explained by pointing out that the parameters are unknown and hence with some probability is equal to some specific (but unknown) value. This is then formalized by the prior distribution that specifies with what probability the parameters take on a certain value. But perhaps you could be more specific why or how the "randomness" puzzles you? How is that you do not find the other answer satifying?
Answer: If you allow me, for a moment forget about the frequentist v/s Bayesian style of things and let us simply dive into what are we "modeling".
Imagine that all samples $x$ in a dataset belong to some set $\mathcal{X}$ and the probability of observing a sample $X = x$ is $p(X = x)$. (Note the usage of capital letter for a random variable and $x$ a realization of $X$). If you don't like talking in probabilities, think of this as just assigning some positive "score" to every sample. Hence, if something doesn't belong in $\mathcal{X}$, it's score is zero. As an example, if $\mathcal{X}$ were the set of all kinds of cats and dogs, $p (X = \text{any kind of tiger}) = 0$.
The goal of all machine learning is to estimate this object $p(X)$, why? Because if you could truly achieve this goal of getting the true $p(X)$, you could do all kinds of things - generate all possible cats and dogs (by sampling from $p(X)$), check if something is a cat or a dog and so on. Here I have subsumed things like classification labels $Y$ etc. into $X$ as they don't matter for this discussion.
If you are on board with this, the next step is to actually "learn" $p(X)$. We make modeling choices and assumptions to make this problem computationally tractable. I make the following choice to explain this distribution -

$p(X)$ can be explained by certain hidden parameters $\theta$ which are jointly modeled as $p(X, \theta) = p(\theta) p(X | \theta)$

Is my choice correct? Who knows? But I made this modeling choice. How do we recover $p(X)$ from this? By simply using the rule of probability to marginalize out all the possible parameters $\theta$, $p(X) = \int p(X, \theta) d\theta$. Whether this is possible in practice, is a different question altogether, but we have hopefully devised a model which can allow us to do that.
Our sole purpose now after making our modeling choice explicit is just to find that $\theta$ which will "explain" the sample(s) we have seen. One way to "explain" the sample(s) is to measure "likelihood" $p(X|\theta)$ - higher likelihood means better fit under the modeling assumptions (note again it doesn't have anything to do with reality, it is the best under the assumptions we chose to stick with). Hence, we must maximize $p(X|\theta)$ and find the best one, say $\theta^\star$.

$\theta^\star = \underset{\Theta}{\text{argmax} } p(X | \theta)$

This is Maximum Likelihood Estimation (MLE). This estimator claims that there is one best $\theta^\star$ (the result of your optimization process) which can be used to explain everything about your data.
Now comes the Bayesian and tells you, I don't want to put all eggs in one basket and make sure I don't miss out on other possible $\theta$'s. A Bayesian is uncertain and always quantifies uncertainties. And hence says, I will use the Bayes theorem to build a probability distribution around all possible $\theta$'s to quantify my uncertainty as

$p(\theta | X) = \frac{p(X | \theta) p(\theta)}{p(X)}$

In simple words, a Bayesian is assigning scores to all possible $\theta$'s without ever claiming what is the true one. You might ask how do we know what is the true one? We then further use decision theory to pick a $\theta^\star$ based on some risk function (a discussion for another time). And hence, a Bayesian treats $\theta$ as a random variable (and therefore a probability distribution to quantify it). $p(\theta)$ is the prior - what the Bayesian "believes" could be the true values before seeing any sample and $p(\theta | X)$ is what the Bayesian "believes" after seeing the sample.
How do you go from being a Bayesian to a frequentist? Simply find the "mode" of $p(\theta | X)$ - a $\theta^\star$ which gives you the best score to "explain" $X$. This problem then becomes

$\theta^\star = \underset{\Theta}{\text{argmax} } p(X | \theta) p(\theta)$

(notice we don't need $p(X)$ as it is independent of $\theta$). This is known as Maximum a-posteriori Estimation (MAP). If you have no strong feelings about the prior, you can imagine using a uniform prior where you initially believe that all $\theta$'s are equally likely to be $\theta^\star$. Assuming that, $p(\theta) \propto 1$ can also be dropped out of the optimization as it becomes a constant and you recover Maximum Likelihood Estimation (MLE).
In conclusion, both schools are modeling the same things, Bayesians are just explicit about their choices.
Comment: This was very helpful, thank you!
Answer: Here is my answer: Think about the data generation process. Suppose we have a random variable $X$ depending on a parameter $\theta$. We assume $\theta$ follows some distribution as in the Bayesian philosophy.
In this case, consider the joint distribution of $(X, \theta)$. Each time $X$ is generated, a $\theta$ is generated as well. However, you cannot see the value of $\theta$.
So in this way, both $X$ and $\theta$ are random. This is how I understand it.


Pass data from child component to template in angular2

Question: I've got two components - Home and Counter and I want to be able to increment template variable in Counter from Home. It doesn't work, except initialization - the variable is initialized to 17, but after that the increment doesn't work.
CounterComponent
import { Component, Input } from '@angular/core';

@Component({
  selector: 'counter',
  styleUrls: ['app/counter.component/style.css'],
  templateUrl: 'app/counter.component/counter.component.html'
})
export class CounterComponent {

  public counter: number = 17;

  activate() {
    this.counter++;
  }

  deactivate() {
    this.counter--;
  }
}

counter.component.html
The counter is: {{counter}}

HomeComponent
import { Component } from '@angular/core';
import { CounterComponent } from './counter.component/counter.component';

@Component({
  selector: 'home',
  directives: [CounterComponent],
  providers: [CounterComponent],
  templateUrl: 'app/home.component.html'
})
export class HomeComponent {

  constructor(public counter: CounterComponent) {}

  doSomething() {
    this.counter.activate();
  }

}

home.component.html
Home component

<button (click)="doSomething()">Activate</button>

<counter></counter>

Answer: I would reference the counter component using the ViewChild decorator. With this instance, you can interact programmatically with it.
@Component({
  (...)
})
export class HomeComponent {
  @ViewChild(CounterComponent)
  counter:CounterComponent;

  doSomething() {
    this.counter.activate();
  }
}


Circular permutations with opposite gender sitting together

Question:
How many ways can n men and n women sit in a round table given that the same gender never sit next to each other.

By trial and error, I think that the answer is n!(n-1)!
First, I tried n!n!/2n because there are 2n people in the circle but it is wrong, so I tried (n-1)!(n-1)!, using 2 circular permutation formulas, which is also wrong. Finally, I end up with n!(n-1)! which I think is correct. But why is it only one circular permutation formular and one normal permutation?Why is it not two circular permutation?
Comment: If they all shift over by one seat, is that considered a different arrangement?
Comment: Nope, that it seen as identical.
Answer: Suppose we label one of the seats as seat 1, and the remainder numbered clockwise to $2n$. Also suppose one of the women is named Alice. We will call two seatings equivalent if they are identical after we rotate the seatings until Alice is sitting in seat 1.
If Alice is in seat 1, all of the women are then seated in the odd numbered seats. And there are (n-1)! such seatings of women (we already know where Alice is sitting!).
Then for each of those seatings of just the women, there are n! distinct ways to seat the men. Thus, your $(n-1)!n!$ total seatings.
You could also think of this as: given a seat labeled 1, the are $2(n!n!)$ possible outcomes - $n!n!$ when seat 1 is occupied by a woman, and $n!n!$ when seat 1 is occupied by a man. We take this "modulo" the $2n$ possible places that an arbitrary woman (Alice) is seated, so the result is $\frac{2(n!n!)}{2n} = (n-1)!n!$.


Prove that for $n\in\mathbb{N}$, $\sum_{k=1}^{\infty}\left[\frac{n}{5^{k}}\right]=15\iff\left[\frac{n}{5}\right]=13.$

Question: How to show that the following relation? : for $n\in\mathbb{N}$, $$\sum_{k=1}^{\infty}\left[\frac{n}{5^{k}}\right]=15\iff\left[\frac{n}{5}\right]=13.$$ It's not obvious to me. Can anyone help me? Thank you!
Comment: 15=sigma([n/5^k])60 or n/5>12. Now you are left with cases [n/5]=12,13,14. Can you handle this?
Answer: There are three parts to the claim:

If $\frac{n}{5}<13$ then $\sum_{k=1}^{\infty}\left[\frac{n}{5^{k}}\right]<15$
If $13\leq\frac{n}{5}<14$ then $\sum_{k=1}^{\infty}\left[\frac{n}{5^{k}}\right]=15$
If $\frac{n}{5}\geq14$ then $\sum_{k=1}^{\infty}\left[\frac{n}{5^{k}}\right]>15$

So choose whichever part strikes your fancy and tackle it in isolation. Repeat until all three are done.
Answer: Observe that $\sum_{k=1}^{\infty}\left\lfloor\frac{n}{5^k}\right\rfloor=\nu_5(n!)$, where $\nu_5(n!)$ is the exponent of the largest power of $5$ that divides $n!$ (if you are not familiar with this, then see Legendre's formula).
Since this sum is $15$, thus  the highest power of $5$ that divides $n!$ is $15$.
Consider $n!=(1\cdot 2 \cdot 3 \cdot 4 \cdot \color{red}{5})(6\cdot 7 \cdot 8 \cdot 9 \cdot \color{red}{10})\dotsb ((n-4) \cdot (n-3) \cdot (n-2) \cdot (n-1) \cdot \color{red}{n}).$
Each group of $((a+1)\cdot (a+2) \cdot (a+3) \cdot (a+4) \cdot (a+5))$ contributes a single power of $5$, until we reach $25$, where we get a contribution of $2$ towards the exponent of $5$. Likewise until we reach $50$ each such group of five numbers contribute only a single power of $5$ and so on. Thus the number $n$ must be such that
$$n!=\underbrace{(1\cdot 2 \cdot 3 \cdot 4 \cdot \color{red}{5})}_{5^1}\underbrace{(6\cdot 7 \cdot 8 \cdot 9 \cdot \color{red}{10})}_{5^1}\dotsb \underbrace{(21\cdot 22 \cdot 23 \cdot 24 \cdot \color{red}{25})}_{\color{green}{\boxed{5^2}}}\dotsb \underbrace{(61\cdot 62 \cdot 63 \cdot 64 \cdot \color{red}{65})}_{5^1} \dotsb ()$$
When $n=65$, that is the first time we will have $\nu_5(n!)=15$. Thus $65 \leq n < 70$ which implies $\left\lfloor\frac{n}{5}\right\rfloor=13.$
Comment: That some nice Latex'ing
Answer: It's simple.
Let us assume $\left[\frac{n}{5}\right]=13$ to be true.
Since $\left[\frac{n}{5}\right]=13$,
$\Rightarrow\frac{n}{5}\in[13,14)$
$\Rightarrow n\in[13*5,14*5)$
$\Rightarrow n\in[65,70)$
Let us consider,
$$\sum_{k=1}^{\infty}\left[\frac{n}{5^{k}}\right]=\left[\frac{n}{5}\right]+\left[\frac{n}{5^2}\right]+\left[\frac{n}{5^3}\right]+\left[\frac{n}{5^4}\right]+ …...$$
We know that $\left[\frac{n}{5}\right]=13$.
Previously we had found $n\in[65,70)$, so $\frac{n}{5^2}\in\left[\frac{65}{25},\frac{70}{25}\right)$, or $\frac{n}{5^2}\in\left[2.6,2.8\right)$
So, $\left[\frac{n}{5^2}\right]=2$
For other terms till infinity, the fraction inside the floor function goes below one and thus the value of floor will be zero. So we finally get the following result,
$$\sum_{k=1}^{\infty}\left[\frac{n}{5^{k}}\right]=13+2=15$$
Hence proved!


Spring Boot Exception(Error) Handling for RESTful Services

Question: I have the following RESTful Services method :
@PostMapping("/ajouterNewField")
public String ajouterField(@Valid @ModelAttribute("field") Fields field, Model model) throws IOException {

    fieldDao.save(field);
    // SOME CODE
    return displayListeChamps( model);
}

The method is working fine and my question is how to handle any error (database not connected ...) or every issue that can happen durring the execution of this RESTful Services method.
Answer: Basically you'll have to a sort of exception handler for any kind of exception your method might throw:
public class FooController{

    //  ...
    @ExceptionHandler({ CustomException1.class, CustomException2.class })
    public void handleException() {
    //
    }
}

Here's a nice article about that: https://www.baeldung.com/exception-handling-for-rest-with-spring
Answer: You can use @ControllerAdvice
Refer to the code below
@ControllerAdvice
public String NyExceptionHandlerAdvice {
    private final Logger logger = ...;

    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    @ExceptionHandler({MyRunTimeException.class})
    public void handleMyRunTimeException(Exception e) {
        logger.error("Exception : ", e);
    }
    return MY_ERROR_STRING;
}

Best Practice is:
You can have your code throw RunTimeExceptions and handle all of them together or separately in handler methods similar to handleMyRunTimeException above.
You can decide what status code your request should return upon exception.
Comment: update: i have drafted my understanding around @ControllerAdvice in [How to handle exceptions is Spring Rest Service](http://www.amitph.com/spring-rest-service-exception-handling/)


Problem clarification for Folland 5.33, real analysis

Question: I am trying to understand a problem in folland's real analysis.
In a norm linear space.
There is no slowest rate of decay of the terms of an absolutely convergent series, that is, there is no  sequence $\{a_n\}$ of positive number such that $\sum a_n |c_n| < \infty$ iff $\{c_n\}$ is bounded.
I am confused by the problem, take $\mathbb{R}$ for example, I can certainly let $\{c_n\}$ be $\{\frac{1}{n^2} \}$, and $\{a_n\}$ be $\{1\}$, then $\sum a_n |c_n| < \infty$ and $\{c_n\}$ is bounded and $\{a_n\}$ are positive, I am certainly misinterpreting the problem, but I'm not sure what I'm misinterpreting, any help with clarifying my confusion would be helpful, thanks!
Comment: You want to show that if $(a_n)_n$ is any sequence of positive numbers, then the following does *not* hold: For every sequence of real numbers $c = (c_n)_n$, we have that $c$ is bounded if and only if $\sum_n a_n |c_n|<\infty$.
Comment: Ah, thank you, I was reading it as A iff B, where A is the statement
"there is no sequence $\{a_n\}$ of positive numbers such that $\sum a_n |c_n| < \infty$", and B is the statement $\{c_n\}$ is bounded. That cleared things up!
Answer: Your sequence $a_n=1/n^2$ does not work: $\sum_{n}a_n|c_n|$ is convergent even for $c_n=\sqrt{n}$ which is not bounded.
P.S. This is an interesting reference.
Comment: I see... I edited my answer with a (hopefully) interesting reference.
Comment: Thank you for your answer, my problem was that I was reading the statement incorrecly, I was reading it as A iff B, where A is the statement
"there is no sequence $\{a_n\}$ of positive numbers such that $\sum a_n |c_n| < \infty$", and B is the statement $\{c_n\}$ is bounded, which led me to think that this is a statement about $\{c_n\}$.


Esconder e mostrar um icon em mat-table angular 7

Question: Galera, tenho uma mat-table do material angular, estou usando angular 7, tenho dois botões, um de play e outro de pause, começa mostrando os botões de play nesta lista, estou tentando implementar uma lógica para, quando o usuário clicar no play na linha correspondente, apenas ele suma para poder mostrar o botão de pause, mas apenas na linha clicada, (ícone tem função de botão)segue cógido
<ng-container matColumnDef="action">
  Action

     <mat-icon [id]="row-click" matTooltip="Metas de campanhas" (click)="getAction()">play_circle_outline</mat-icon>
     <mat-icon [id]="row-click" matTooltip="Metas de campanhas" (click)="getAction()">pause_circle_outline</mat-icon>

Monstra primeiro a lista de plays e se clicar no play então mostra apenas o pause daquela linha em questão, alguém ?
Comment: Você pode utilizar jquery?
Comment: Não André, senão vai ficar "gambi" rsrsrs
Comment: É interessante usar os recursos do próprio Angular
Comment: Utilize o *ngIf ele pode validar isso
Comment: @OtavioCapel eu já fiz ngif, porém ainda não consegui acertar a lógica para tal ...
Comment: Você pode criar uma variavel: `play: boolean = false`isso fara com que o botão de play seja mostrado primeiro. ai nos icones vc faz :
  PLAY
 PAUSE
Ao usuario aperta play você inverte o valor da variavel.
Comment: Então, eu fiz desta forma, porém, pelo fato de ser uma lista, no caso uma tabela, já fiz isso mas ele some todos os plays e vice-versa, entendeu ... ?
Comment: a lógica é clicar o primeiro icon de play da tabela e apenas ele mudar
Answer: Uma possível solução (não tão elegante) é adicionar uma propriedade a mais ao teu dataSource como sendo um boolean, "pausado" por ex.
Os métodos de play e pause seriam os responsáveis por setar essa variável da respectiva linha do dataSource, já dentro do 	 tu só verifica essa variável com o *ngIf


Highcharts bubble graph bubble getting cut off on top

Question: I have a Highcharts bubble graph on my page and the top of one of the bubbles is getting chopped off because it is right at the top of the y axis. I've set the maxSize to 50% and would like to keep it that way. Is there a way to allow the bubbles to not have this overflow hidden sort of effect?
Answer: Without seeing an example I can only say to try adjusting the yAxis max value. That way there would be space to render your items. Or you can calculate your highest yValue bubble's radius and increase your yAxis by that pixel ammount in yAxis values.
Comment: Yeah, I thought about as well. I was hoping there would have been a built-in way to fix this with a property, but this solves my problem.
Comment: I haven't seen a way to accomplish this with any of the existing properties. I've just done this for now. Thanks!


probability - If k-universal hash family then (k-1)-universal hash family

Question: Regarding this question: If k-universal hash family then (k-1)-universal hash family
It's been answered and I dont understand the answer:
\begin{align}
Pr[h(x_1) = i_1 &\land \cdots \land h(x_{k-1}) = i_{k-1}]
\\&= Pr[h(x_1)=i_1 \land \cdots \land h(x_{k-1})=i_{k-1}\land h(x_k)=1]
\\&+ Pr[h(x_1)=i_1 \land \cdots \land h(x_{k-1})=i_{k-1}\land h(x_k)=2]+\ldots
\\&+Pr[ h(x_1)=i_1 \land \cdots \land h(x_{k-1})=i_{k-1}\land h(x_k)=m]
\\&= \frac{1}{m^k}+\frac{1}{m^k}+\ldots +\frac{1}{m^k}=\frac{m}{m^k}=\frac{1}{m^{k-1}}
\end{align}
Why is the first equality correct?
Answer: By definition, $h$ takes one of the values $1$ through $m$. Thus the event that it takes certain values at $x_1$ through $x_{k-1}$ is the disjoint union over $1\le j\le m$ of the events that it takes those values and also the value $j$ at $x_k$. The probability of the disjoint union of events is the sum of the probabilities of those events.
Comment: I think I understand. Thank you!


R Shiny - Problem passing reactive data to model

Question: I'm trying to be an R Shiny app that utilizes a pre-built xgboost model and generates a prediction on user inputs to the model. IDEALLY, it would be reactive to their inputs so that users could see how the prediction changes based on making changes to their inputs (i.e. modifiable events).
My process so far has been to build the UI and then use the UI inputs to display a reactive data table as proof of concept that my data is getting into the model correctly (i.e. encoded the same way I trained the model).
Where I'm having problems is trying to take that reactive df and pass it to a function to generate a sparse matrix (or do anything to it for that matter). I feel like there's something fundamentally I'm missing in how to 'handle' the reactive df.
library("shiny")
library(xgboost)

xgb.bst <- readRDS('xgb_bst.RDS')

ui <- shinyUI(
  pageWithSidebar(
    headerPanel("Calculator")
    ,
    sidebarPanel(
      selectInput("age", "Patient Age",
                  choices = c("< 40" = 0,
                              "40 - 49" = 1,
                              "50 - 59" = 2,
                              "60 or older" = 3)),
      selectInput("bmi", "Patient BMI",
                  choices = c("< 30" = 0,
                              "30 - 39" = 1,
                              "40 - 49" = 2,
                              "50 - 59" = 3,
                              "60 or greater" = 4)),
      selectInput("race", "What is the patient's race?",
                  choices = c("White" = 0,
                              "African American" = 1,
                              "Asian" = 4,
                              "Pacific Islander" = 1,
                              "Native American" = 3,
                              "Other/Not Reported" = 5)),

      checkboxInput("cardiach",
                    label = "History of MI"),

      actionButton("submit","Submit")),

    mainPanel(uiOutput('table'))
  ))

server <- shinyServer(
  function(input,output,session){

    Data = reactive({
      if (input$submit > 0) {
        df <- data.frame(Age = input$age,
                         BMI = input$bmi,
                         Race = input$race,
                         Cardiac = as.integer(input$cardiac),
        return(list(df = df))
      }
    })

#    output$table <- renderTable({
#      if (is.null(Data())) {return()}
#      print(Data()$df)
#    }, 'include.rownames' = FALSE
#    , 'include.colnames' = TRUE
#    , 'sanitize.text.function' = function(x){x}
#    )

    df_matrix <- data.matrix(Data)
    mdata <- xgb.DMatrix(df_matrix)

    pred <- predict(xgb.bst, newdata = mdata)

  })

shinyApp(ui = ui, server = server)

And I keep getting errors such as:
Listening on http://127.0.0.1:3890
Warning: Error in : object of type 'closure' is not subsettable
  52: is.data.frame [#44]
  51: data.matrix
  50: server [#44]
Error : object of type 'closure' is not subsettable

I get the feeling I'm not handling the reactive data properly but I'm not entirely sure why or how. Any help would be appreciated. Even if it was just being able to print a summary of my reactive df. Commented code was how I displayed the reactive table.
Comment: `Data` is a reactive function. It should be called like `Data()`
Comment: The problem with your code is that `Data` is a reactive function, but you are trying to define `df_matrix` and `mdata` as non-reactive objects.  [Rstudio's documentation on reactivity][1] may be a helpful read.

In your case, try chaining reactive's together by making `df_matrix` and `mdata` reactives that depend on `Data`

  [1]: https://shiny.rstudio.com/articles/reactivity-overview.html
Answer: Here's what you probably need. You can change the output type of 'table' as per your needs. -
# Use mainPanel(verbatimTextOutput('table')) in ui

server <- shinyServer(
  function(input,output,session){

    pred <- eventReactive(input$submit, {
      Data <- data.frame(Age = input$age,
                 BMI = input$bmi,
                 Race = input$race,
                 Cardiac = as.integer(input$cardiac), stringsAsFactors = F)
      df_matrix <- data.matrix(Data)
      mdata <- xgb.DMatrix(df_matrix)
      predict(xgb.bst, newdata = mdata)
    })

    output$table <- renderPrint({
      pred()
    })
  })

shinyApp(ui = ui, server = server)

Comment: Thank you @Shree and the two other commenters. Not only was that a workable solution, I also see how and why I was going wrong. Much appreciated!


In Drupal 8, how do you add attributes to a link generated by the core Link field? (or, generally a render array with #type set to "link")

Question: So I have a situation where I have a core Link field on a node. I wanted to style that link with custom attributes, so I created a field.html.twig override to do that, only to find that the link itself is printed elsewhere. There doesn't appear to be a template or theme hook for the link; given that the core Twig debug functionality doesn't report a child template being invoked.
I tried pulling the URL out directly and rendering my own link, but that class (Drupal\Core\Url) isn't on the Twig whitelist, so getting the URL out will just cause a WSOD. There doesn't appear to be an Attributes object that I could add things into.
I could use theme_preprocess_field to call Drupal\Core\Url->toString() directly and store it in another variable, but I'd be throwing out whatever attributes are generated by default. I'd rather participate in however Drupal is rendering this link directly; or, if it's not extensible, at least know how to replicate what core does.
(For the record, the solution recommended in another question of using theme_preprocess_field to write attributes into #options does not appear to work.)
EDIT: As requested, here is the code I tried for a preprocess hook to add attributes:
<code>function MYTHEME_preprocess_field(&$variables) {
    $element = $variables['element'];
    if ($element['#name'] == 'field_extra_links') {
        $variables['items'][0]['content']['#options']['attributes']['class'][] = 'Button';
    }
}
</code>
Comment: As far as the render array version goes, there are two ways: `'#options' => ['attributes' => ['foo' => 'bar']]` and `'#attributes' => ['foo' => 'bar']`. The link element preRenderLink method handles either. A preprocess does sound like the right way, if you can add the code to the question someone might be able to point out any problems
Comment: Added code example for what didn't work
Comment: Did you install Devel Kint? This should help give you some insight as to what is in the array. Also enabling Twig debug would give more insight as to what templates are available and or being used.
Comment: Either use $variables['attributes'] or hook_form_alter.
Answer: Answering my own question: the original suggestion was actually a valid solution; the way I had my theme configured meant that the hook wasn't loading. Stupid mistakes!


how can I change all price view in drupal commerce

Question: I want to change default drupal view of price in all of my field,
as a example I want to remove '00' and add my custom postfix to it,
I found hook_commerce_price_field_formatter_prepare_view but when I implement it in my module it not called,really I am not sure this hook is suitable and ca  achieve my need??
I just want the all price fields changes to my desire only  in front-end view (only in view, because my payment method is according to main currency)
Answer: You can do this using the Commerce Currency API
Implement hook_commerce_currency_info_alter and add your own commerce_currency_format handler
e.g:
/**
 * hook_commerce_currency_info_alter
 *
 * Add custom currency format to selected currencies
 */
function MY_MODULE_commerce_currency_info_alter(&$currencies){
  $currencies['IRR']['format_callback'] = 'MY_MODULE_commerce_currency_format';
}

/**
 * Currency format callback
 *
 * Remove decimal places from output
 * while keeping commerce_amount_to_decimal formatting the same
 *
 * See: commerce_currency_format
 */
function MY_MODULE_commerce_currency_format($amount, $currency, $object = NULL, $convert = TRUE) {

  // Format the price as a number.
  // In our case, we remove decimal places
  $price = number_format(commerce_currency_round(abs($amount), $currency), 0, $currency['decimal_separator'], $currency['thousands_separator']);

  // Establish the replacement values to format this price for its currency.
  $replacements = array(
    '@code_before' => $currency['code_placement'] == 'before' ? $currency['code'] : '',
    '@symbol_before' => $currency['symbol_placement'] == 'before' ? $currency['symbol'] : '',
    '@price' => $price,
    '@symbol_after' => $currency['symbol_placement'] == 'after' ? $currency['symbol'] : '',
    '@code_after' => $currency['code_placement'] == 'after' ? $currency['code'] : '',
    '@negative' => $amount < 0 ? '-' : '',
    '@symbol_spacer' => $currency['symbol_spacer'],
    '@code_spacer' => $currency['code_spacer'],
  );

  return trim(t('@code_before@code_spacer@negative@symbol_before@price@symbol_spacer@symbol_after@code_spacer@code_after', $replacements));
}

Comment: is this work only in view ?
Comment: our country payment system is with raw price(more zeros), I want to remove some "0" in view, just in view but in payment main value used (with more "0"), It this suitable or it change every where?
Comment: It will work across the site, wherever, the price is displayed.
Comment: only in display or in back-end operation?
Comment: Both the front-end and back-end display will use the new format callback. Note: the raw price value is still stored in the database, the format callback is only used for display.
Comment: tnx for your attention, I will test it,
Answer: I'm gonning to complete what David Thomas wrote.
1/ Create a custom module with the code. Replace My_Module by the name of your module.
/**
 * hook_commerce_currency_info_alter
 *
 * Add custom currency format to selected currencies
 */
function MY_MODULE_commerce_currency_info_alter(&$currencies){
  $currencies['IRR']['format_callback'] = 'MY_MODULE_commerce_currency_format';
}

/**
 * Currency format callback
 *
 * Remove decimal places from output
 * while keeping commerce_amount_to_decimal formatting the same
 *
 * See: commerce_currency_format
 */
function MY_MODULE_commerce_currency_format($amount, $currency, $object = NULL, $convert = TRUE) {

  // Format the price as a number.
  // In our case, we remove decimal places
  $price = number_format(commerce_currency_round(abs($amount), $currency), 0, $currency['decimal_separator'], $currency['thousands_separator']);

  // Establish the replacement values to format this price for its currency.
  $replacements = array(
    '@code_before' => $currency['code_placement'] == 'before' ? $currency['code'] : '',
    '@symbol_before' => $currency['symbol_placement'] == 'before' ? $currency['symbol'] : '',
    '@price' => $price,
    '@symbol_after' => $currency['symbol_placement'] == 'after' ? $currency['symbol'] : '',
    '@code_after' => $currency['code_placement'] == 'after' ? $currency['code'] : '',
    '@negative' => $amount  $currency['symbol_spacer'],
    '@code_spacer' => $currency['code_spacer'],
  );

  return trim(t('@code_before@code_spacer@negative@symbol_before@price@symbol_spacer@symbol_after@code_spacer@code_after', $replacements));
}
2/ Go to Custom Currency Setting (admin/commerce/config/currency/custom-settings) and setup the field Format Callback with: My_Module_ommerce_currency_format
At this point your node will display what you asked, but not your views (or your fields).
3/ To use this setting into your views display, you have to display the node inside your views. If you display a field it won't work. Views > Show: Content
Cheers


Application crash at runtime

Question: This will be my second question along these lines as the previous post seems to have pretty much stopped drawing attention, so sorry for the spam. Anyways, last time I posted because I was getting a runtime crash as well as various errors within my code, and someone managed to help me beyond the errors in the code. However, after fixing the code I'm still getting crashes. Included is the code I have for my project and the log cat file at the bottom.
A quick overview of what its supposed to do: I'm trying to make a few edit text fields add up into a TextView field so that users can type in numbers in the edit text columns and see the result in the textview.
package com.example.gideon.timemanagement;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Editable;
import android.widget.EditText;
import android.text.TextWatcher;
import android.widget.TextView;

public abstract class Customize extends AppCompatActivity implements TextWatcher {

EditText a;
EditText b;
TextView ht;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_customize);

    EditText a = (EditText) findViewById(R.id.exerciseHours);
    EditText b = (EditText) findViewById(R.id.sleepHours);
    TextView ht = (TextView) findViewById(R.id.healthTotal);
}

private TextWatcher Ht = new TextWatcher() {

    @Override
    public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

    }

    @Override
    public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

    }

    @Override
    public void afterTextChanged(Editable editable) {

        if (!a.getText().toString().equals("") && !b.getText().toString().equals("")) {
            ht.setText(String.valueOf(Integer.valueOf(a.getText().toString()) + Integer.valueOf(b.getText().toString())));

        }
    }
};

02-10 18:53:40.167 23713-23713/com.example.gideon.timemanagement I/zygote:
  Not late-enabling -Xcheck:jni (already on)
  02-10 18:53:40.174 23713-23713/com.example.gideon.timemanagement W/zygote:
  Unexpected CPU variant for X86 using defaults: x86
  02-10 18:53:40.393 23713-23713/com.example.gideon.timemanagement
  I/InstantRun: starting instant run server: is main process
  02-10 18:53:40.532 23713-23731/com.example.gideon.timemanagement
  D/OpenGLRenderer: HWUI GL Pipeline
  02-10 18:53:40.662 23713-23731/com.example.gideon.timemanagement I/zygote:
  android::hardware::configstore::V1_0::ISurfaceFlingerConfigs::hasWideColor
  ay retrieved: 0
  02-10 18:53:40.662 23713-23731/com.example.gideon.timemanagement
  I/OpenGLRenderer: Initialized EGL, version 1.4
  02-10 18:53:40.662 23713-23731/com.example.gideon.timemanagement
  D/OpenGLRenderer: Swap behavior 1
  02-10 18:53:40.662 23713-23731/com.example.gideon.timemanagement
  W/OpenGLRenderer: Failed to choose config with EGL_SWAP_BEHAVIOR_PRESERVED,
  retrying without...
  02-10 18:53:40.662 23713-23731/com.example.gideon.timemanagement
  D/OpenGLRenderer: Swap behavior 0
  02-10 18:53:40.682 23713-23731/com.example.gideon.timemanagement
  D/EGL_emulation: eglCreateContext: 0xb1eabb60: maj 3 min 0 rcv 3
  02-10 18:53:40.726 23713-23731/com.example.gideon.timemanagement
  D/EGL_emulation: eglMakeCurrent: 0xb1eabb60: ver 3 0 (tinfo 0xb1eef120)
  02-10 18:53:40.728 23713-23731/com.example.gideon.timemanagement
  E/eglCodecCommon: glUtilsParamSize: unknow param 0x00008cdf
  02-10 18:53:40.728 23713-23731/com.example.gideon.timemanagement
  E/eglCodecCommon: glUtilsParamSize: unknow param 0x00008cdf
  02-10 18:53:40.728 23713-23731/com.example.gideon.timemanagement
  E/eglCodecCommon: glUtilsParamSize: unknow param 0x00008824
  02-10 18:53:40.728 23713-23731/com.example.gideon.timemanagement
  E/eglCodecCommon: glUtilsParamSize: unknow param 0x00008824
  02-10 18:53:40.759 23713-23731/com.example.gideon.timemanagement
  D/EGL_emulation: eglMakeCurrent: 0xb1eabb60: ver 3 0 (tinfo 0xb1eef120)
Comment: What the crash .post the stacktrace. Seems like NPE.
Comment: Why is your Activity abstract class? And that logcat isn't the actual error
Comment: so many reason for crash, first view declaration in both local and global are same, textwatcher method name are same.
Comment: @cricket_007 `abstract` was a good catch .
Comment: post your full crash logcat
Comment: If I don't make the class abstract it throws an error when trying to build.
    Error:(12, 8) error: Customize is not abstract and does not override
    abstract method afterTextChanged(Editable) in TextWatcher

Also, how do I even get the full log cat? I have no idea.
Answer: Inside oncreate, remove EditText and Textview definitions because already you declare them as member variables in the class
add TextChangedListener on your editText
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_customize);

 a = (EditText) findViewById(R.id.exerciseHours);
 b = (EditText) findViewById(R.id.sleepHours);
 ht = (TextView) findViewById(R.id.healthTotal);
 a.addTextChangedListener(this);
 b.addTextChangedListener(this);
 }

Also remove abstract from class definition
Comment: i do not think so removing declaration make error gone
Comment: check edited answer
Comment: Removing Abstract from the class causes an error.

Error:(12, 8) error: Customize is not abstract and does not override abstract method afterTextChanged(Editable) in TextWatcher
Comment: refer https://stackoverflow.com/questions/32467483/class-is-not-abstract-and-does-not-override-abstract-method-onclickview-in-onc

Application crash at runtime


Why do batsmen in T20 matches sit close to the boundary, instead of sitting in the dressing room?

Question: Why do batsmen in T20 matches sit close to the boundary, instead of sitting in the dressing room? Is there any logic behind it? Or this is just a rule?
Answer: On top of @kartshan's answer, the main reason that couple of batsmen are padded and waiting in the dug-out rather than the pavilion is that batsmen are dismissed as timed-out in 90 seconds in T20 cricket instead of the 180 seconds in other forms.
Comment: Fair enough.. :)
Answer: T20 as a concept was to make the cricket fast paced,as short as possible and make the game appealing to all people (something like how baseball is in US). The idea was to make each innings last only for around 90 minutes so that it attracts more people to watch the game.
One of the ways to reduce the time taken by batsmen to occupy the crease was to make them sit near the boundary.

The prime reason why Batsmen sit close to the boundary in the T20
  matches is to reduce the time taken by the next batsmen to occupy the
  crease. Also it gives flexibility to send out any batsmen according to
  the team's current situation.

If you see, at least two three batsmen will be padded up in a T20 game all the time.


Best way to organise content

Question: I am making a site which will deal with various micro-topics about a subject.
Each subject will have the following:

A backgrounder (one-time)
A news blog (obviously recurring)
FAQs (basically static)
Set of links/documents (static too, but it can simply be updated)

My problem is organizing the content.
I could set every topic as taxonomy term and create four content types (Backgrounder, Blog, Faq, and Link). Soon, I'll run into probably a few thousand topics.
Since each term page will have to serve as the homepage for that topic, I have no clue how to organize such a page.
I could also set each topic as a node with additional fields (Backgrounder, Blog, Faq, and Link). This would probably look awful, when the content of a field becomes long. Managing this might become difficult. Since most of the content would be node fields, the actual node area might not have any content. Search indexing becomes a hassle.
Right now I am quite clueless.
Any advice towards the right direction would be of great help.
Answer: First off, this isn't really a question that has a single correct answer.
It is really up to the site builder as to how they want it to work and it depends greatly on the use cases of the site and any business rules related to the content.
As such, it isn't the best question for a site like this, however I will say a couple of things:

Having thousands of taxonomy terms is ok if your content requires it. You might have a thousands of taxonomy terms and tens or hundreds of thousands of nodes. That's fine.
The second option you mention doesn't sound like a good idea. Mainly the use of fields as blogs etc. doesn't sound right conceptually. Plus handling revisions, permissions, comments for blog posts etc. is going to be a hassle to say the least.
The first option mentioned doesn't necessarily have to have the term page as the topic homepage. It could be done other ways, like having the backgrounder node as the topic homepage or using a views page with arguments to be the homepage.
Another possible solution is to have the backgrounder node be the home page and link everything to that via an entity reference field, removing the need for taxonomy at all.
As for laying out the home pages, consider using the panels or context modules combined with views.

These are not nearly all the possibilities, there are a bunch of other ways things could be done, so you can see you will not be able to get someone to give you a definitive answer.

Best way to organise content


Vetor dentro de vetor. O que ele faz nesse contexto?

Question: Foi perguntado a 40 alunos o nível de qualidade da comida na cantina estudantil, em uma escala de 0 a 10. ( 1 significando horrorosa e 10 significando  excelente). Coloque as quarenta respostas em um array inteiro e resuma os resultados da pesquisa.
    public static void main(String[] args) {

    Scanner sc = new Scanner(System.in);
    final int tamanhoResposta = 40, frequencySize = 11;
    int response[] = {5, 10, 6, 7, 3, 7,5 ,6 ,3, 10, 4,5,4,9,8,7,5,6,5,6,4,5,6,7,8,4,3,8,9,10,9,6,5,3,9,5,9,10};
    int frequency[] ={0};

    for(int i = 0; i < tamanhoResposta; i++){
        ++frequency[response[i]];
    }

    System.out.println(" Avaliação ===================== Frequência " );
    for(int ii = 0; ii < frequencySize; ii++){
        System.out.println(ii + " ");
        System.out.println(frequency[ii]);
    }

Eu não entendi para que serve essa parte, mas o que isso faz?
++frequency[response[i]];

Ele dá essa exceção:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5
Comment: O downvoter podia aproveitar que passou por aqui e responder a pergunta ou explicar como ela pode ser melhorada.
Comment: @AlineGonzaga sua pergunta teve 5 votos positivos e um negativo, totalizando 4 pontos até o momento. O que o Caffé sugeriu no comentário dele, é que o _downvoter_ (a pessoa que votou negativo) se manifestasse para ajudar a resolver ou melhorar a questão.
Comment: downvoter? Não entendo...
Comment: Também acho. Valeu por me explicar o termo.
Answer: O operador ++ é um incrementador. Se você tem uma variável chamada x pode fazer:
x++;

que o mesmo que:
x += 1;

que é o mesmo que:
x = x + 1;

que é o mesmo que:
++x;

A diferença é o que o último faz o incremento de um antes de usar o valor da variável. Isso é útil em uma expressão, mas não em um statement, como é o caso utilizado. Ou seja, nesse caso poderia ter escrito frequency[response[i]]++; que dava no mesmo. Ou poderia ter escrito frequency[response[i]] = frequency[response[i]] + 1;. Bem mais longo, né?
Obviamente o que ele está incrementando é um elemento do array frequency. Conhece arrays, né? Qual é esse elemento? É o primeiro elemento? Ou seja, é o 0? É o 1? Ele é determinado por uma variável. No caso é a response[i];, que por sua vez também é um elemento de um array. Então ele está pegando o elemento de response determinado por i, e esse elemento está sendo usado como índice de frequency.
Não confunda o array com seus elementos. Todos são variáveis. O array é uma variável que contém um porção de variáveis, mas cada elemento é uma variável individual.
Uma forma diferente de escrever a mesma coisa:
int x = response[i];
int y = frequency[x];
y = y + 1;
frequency[x] = y;

Coloquei no GitHub para referência futura.
Ficou mais claro agora?
Comment: Primeiro, qual o problema de ter um vetor dentro de outro vetor? Um vetor é só uma coleção de dados. Quais dados podem ter dentro de um vetor? Qualquer coisa pode estar ali. Inclusive outro vetor. Uma matriz não é o vetor de vetores? Isto é uma simplificação, mas é uma forma de entender a questão. Mas neste caso nem está usando um vetor dentro de outro. Está usando um elemento de um vetor com índice de um elemento de outro vetor. É a informação que você tem. Sabe fazer teste de mesa? Isto ajuda entender muita coisa.
Comment: A um elemento de `frequency`. Não dá para perceber no exemplo destrinchado que eu eu fiz?
Comment: Ficou mais claro, mas por que eu iria colocar um vetor dentro de um mesmo vetor? preciso ler só mais um pouco sobre isso e escolho a resposta...
Comment: Rs. :) Estou começando a entender. Vou testar.
Comment: Desculpe, agora eu vi. Fui um pouco desatenciosa.
Comment: Hum, pelo que entendi ele conta quantas vezes a ocorrência de um número e armazena...no vetor...
Comment: Sim. E não mude a pergunta no meio do caminho.
Comment: Você não quer mais me ajudar bigown?
Comment: Posso ajudar sim, mas em outra pergunta, essa, como ela foi feita originalmente já tem uma solução. Você não pode ir mudando a pergunta para por todos os problemas do código. Se ele ainda tem problema, faça outra pergunta.
Comment: CERTO! ^------^


Incorrect translation from logic address to machine address, GDT

Question: I'm using bochs to debug the JOS of MIT. I'm confused at the address of the bochs's output:
(0) [0x0010002e] 0008:0xf010002e (unk. ctxt): mov ebp, 0x00000000       ; bd00000000

I'm trying to figure out how 0008:0xf010002e is transfered to [0x0010002e].
Based on the transfermation from logic addr. to linear address, I think I should use the base address from the GDT's 8th entry to plus the offset 0xf010002e.
However, I got the GDT's content as follows:
<bochs:6> x /16wx 0x0010f000
[bochs]:
0x0010f000 <bogus+       0>:    0x00000000  0x00000000  0x0000ffff  0x10cf9a00
0x0010f010 <bogus+      16>:    0x0000ffff  0x10cf9300  0xf0000017  0x00000010
0x0010f020 <bogus+      32>:    0x32311b00  0x36353433  0x30393837  0x09083d2d
0x0010f030 <bogus+      48>:    0x72657771  0x69757974  0x5d5b706f  0x7361000a

The 8th entry is:
0x69757974  0x5d5b706f

Based on the entry's format at Fig 5-3, the base address is: 0x730a8d5b.  However, 0x730a8d5b + 0xf010002e  is not 0x0010002e!
Can anyone help me point out where I'm wrong?
Thank you so much in advance!
Answer: 0008 means first segment, not 8th.
Thus, 0x0000ffff  0x10cf9a00 means segment base = 0x10000000, so 0008:0xf010002e overlaps to 0x0010002e.
Edit: (answering the comment)
The lowest bits 0 and 1 of segment selector is used as privilege level (ring) selector, bit 2 - selects between GDT and LDT, all the other bits are used as offset to relevant descriptors table. Thus, 0x0008 to 0x000b means 0x0008 offset in GDT with privilege levels 0..3
Pointer for the explanation: Intel Software Developer Manual, vol.3, ch.3
Comment: Hi @qwm, why 0008 means first segment? could you please explain a little or give me a pointer for the explanation? Thank you so much!
Comment: maybe the 0008 means 8B offset? Then it refers to the first entry of the GDT?


How equality in Fenchel-Young inequality characterizes subdifferential?

Question: I am not able to see why equality in the Fenchel-Young inequality
characterizes subgradients.
As per Fenchel-Young inequality:
\begin{equation}
f(x)+f^*(u) \geq \langle x,u \rangle
\end{equation}
while the definition of subdifferential set says:
\begin{equation}
\partial f(x) = \{u: f(z) \geq f(x) + \langle u, z-x\rangle \}
\end{equation}
Now it holds that $u \in \partial f(x)$ at equality of Fenchel-Young inequality.
Assume whatever is necessary for defining functions involved above.
Thanks.
Answer: We will show that $$f(x)+f^*(u) = \langle x,u \rangle \Longleftrightarrow u \in \partial f(x).$$
Indeed, we have
\begin{align*}
u \in \partial f(x) &\Longleftrightarrow f(z) \geq f(x) + \langle u, z-x\rangle \quad\forall z \\
&\Longleftrightarrow \langle u, x\rangle - f(x) \ge \langle u, z\rangle - f(z) \quad\forall z \\
&\Longleftrightarrow \langle u, x\rangle - f(x) = \sup_z\left\{ \langle u, z\rangle - f(z)\right\} \\
&\Longleftrightarrow \langle u, x\rangle - f(x) = f^*(u) \\
&\Longleftrightarrow f(x)+f^*(u) = \langle x,u \rangle, \text{QED}.
\end{align*}
Comment: Why do we have equality with the supremum on the 3-rd line ?
Comment: @Svetoslav: if $x\in X$ and $f(x) \ge f(y) \quad\forall y\in X$ then obviously $f(x) = \sup_{y\in X} f(y)$, by definition (of $\sup$).
Comment: you are right. I just looked at $\langle u,x\rangle -f(x)$ as some sumber-an upper bound for $\langle u,z\rangle -f(z)$, without realizing that it is the same function.
Comment: Can you tell when the Fenchel-Young has the strict inequality?
Comment: @AlbertChen Sorry I missed your comment. I think the answer to your question is clear from my answer: strict inequality occurs if and only if $u\not\in\partial f(x)$.
Answer: Let $f:X\rightarrow \mathbb R$ and $X^*$ is the dual of $X$.
First recall the definition of $f^*: X^*\rightarrow \mathbb R$
$f^*(u^*)=\sup\limits_{x\in X}{\{\langle u^*,x\rangle - f(x)\}}$, where $u^*\in X^*$ and $\langle .,.\rangle$ is the duality pairing in $X^*\times X$.
Then the definition for subdifferential set is:
$\partial f (x)=\{u^*\in X^*: f(z)\ge f(x)+\langle u^*,z-x\rangle\}$.
Proposition:
$f(x)+f^*(u^*)-\langle u^*,x\rangle =0\Leftrightarrow u^*\in\partial f(x)$.
Proof:
1) Let $f(x)+f^*(u^*)-\langle u^*,x\rangle =0$. From the definition $f^*(u^*)=\sup\limits_{x\in X}{\{\langle u^*,x\rangle - f(x)\}}\Rightarrow$
$0=f(x)+f^*(u^*)-\langle u^*,x\rangle \ge f(x)+\langle u^*,z\rangle -f(z)-\langle u^*,x\rangle\quad \forall z\in X$ which is $f(z)\ge f(x)+\langle u^*,z-x\rangle \quad \forall z\in X$
2) Let $u^*\in \partial f(x)$. By definition $f(z)\ge f(x)+\langle u^*,z-x\rangle\quad \forall z\in X$. Consequently $\langle u^*,x\rangle-f(x)\ge \langle u^*,z\rangle - f(z)\quad\forall z\in X$
$\Rightarrow \langle u^*,x\rangle-f(x)\ge \sup\limits_{z\in X}{\{\langle u^*,z\rangle - f(z)\}}=f^*(u^*)\quad\quad   (1)$.
But from the definition of $f^*(u^*)\Rightarrow f^*(u^*)\ge \langle u^*,x\rangle-f(x)\quad\quad (2)$.
From $(1)$ and $(2)$ follows the equality.


Beginner Trying a complex & tiered if and while statement in Python

Question: New to Python, trying to see why my tiered if and while statements aren't working.  Based off of Trinket, my code is blowing up at my second 'if' statement.
Trinket Code
This is what I have:
MIN_VALUE = 2
MAX_VALUE = 100
input_number = input(
    'Enter a number between {} and {}: '.format( MIN_VALUE, MAX_VALUE )
)

if input_number.isdigit():

    userDigitalNumber = int(input_number)

        if ((userDigitalNumber >= MIN_VALUE) and (userDigitalNumber =< MAX_VALUE)):

            while ( range( 1, ( userDigitalNumber + 1 )  )
                totalSum = totalSum + userDigitalNumber
                userDigitalNumber -= userDigitalNumber

else:
    'I''m sorry but your number is not a whole digital number.  Please try again.'
    sys.exit( 1 )

print(
    'The sum of all integers between 1 and {} is {}.'.format( userDigitalNumber, totalSum )
)

Answer: It's not properly aligned. It should be aligned on the same level as userDigitalNumber = ... statement.
Comment: `=<` should be `<=`. You also have a bunch of parentheses inside the if and while you don't need. You are forgetting `:` at the end of your while. And you never initially declared `totalSum`
Comment: Missing parenthesis. It should be `for amount in range( 1, ( userDigitalNumber + 1 )):`, which actually is equivalent to `for _ in range(userDigitalNumber):`, the`_` is a null variable since you are not using the iterated value anywhere. PS: You really need a python editor :).
Comment: :) I had the same problem when started python with a C background. Also, another hint before you start swearing why, do not mix hard tabs and soft tabs (tabs represented as spaces) on the same file, you will get indentation errors again.
Comment: And if it answers your question you might want to accept it as the answer :).
Comment: wow.... lots of errors.......  ii'm using NotePad++ to write all of this.  i see a ton of errors.  thank you all
Comment: time limit on the accepting of the answer.  have to wait another minute (literally)
Comment: Use a python IDE (like pycharm or spyder) or text editor+python plugin (sublime+anaconda or atom+python plugin). They highlight the errors and help with indentation.
Comment: Thanks!  still throwing an error on my while. https://trinket.io/python/0f8516fea1
Comment: That is now how do a while loop in Python. You want something like  `while i < num: i+=1`
Comment: It fails cause you have no boolean condition on this while loop, just an iterator. And I never used whiles even in C :). A while can be done with a for loop ;) try `for _ in range(userDigitalNumber):`.
Comment: @idjaw That would be inefficient both computationally and memory wise than a for loop with (x)range and a dummy variable :).
Comment: @JohnSmith It was a extremely simplified example on how to structure a while loop in Python. As is, it's an infinite loop. :)
Comment: And for infinite loops do `while True:`
Comment: @KevinFischer The for loop has a syntax error, however, the for loop provided to you is also incorrect. You want `for i in range(1, userDigitalNumber + 1): total_sum += i`.
Comment: Perfect!  Thanks everyone!  I learned a ton, even with such simple code!
Answer: It can not work because Python doesn't handle '=<'!
Change it with '<='.
Fixed:
if ((userDigitalNumber >= MIN_VALUE) and (userDigitalNumber =< MAX_VALUE)):

And yeah, also... It won't work because of its wrong indentation level.


Reflexivity of the relation between strings over language $L$ defined by $xc \equiv L$ and $yc \equiv L $

Question:
Given any two strings, call them $x$ and $y$, over any language $L$ and given property such that  if $xc \equiv L$ and  $yc \equiv L $ (where $c$ is some string), then $x \equiv y$.

I would like to prove that $\equiv$ is reflexive. I tried $x \equiv x \rightarrow x-x \equiv0$ and $y(0) \rightarrow x(0)\equiv0$ Therefore, $\equiv$ is reflexive.
But somehow I don't feel this is right.  Can someone point out what I am doing wrong here?
Comment: There must be some mix-up. Instead of $x,y$ you mean $a,b$? And what does your notation $ac\equiv L$ mean, after all?
Comment: @mathse Yes, sorry I fixed that. the notation means that strings xc and yc are indistinguishable by language L
Comment: Yes, okay, but just as a matter of notational style, should it be something like $x\equiv_L c$?
Comment: @mathse Yes you are right, that would be better style but does what I have as far as the prove make sense or am I missing something?
Comment: Um, rather not. You say $x-x$, how is "$-$" defined on strings?
Comment: Where did you get this question from? Can you try to relate as much information to us as you have been given? I think some assumptions on $\equiv$ are missing ...
Comment: @mathse All I have is if x and y are indistinguishable by L we indicate that with $$x \equiv_L y$$ and with that I am trying to prove that $$\equiv_L$$ is symmetric.
Comment: Symmetric or reflexive? These are different things ...
Comment: @mathse well actually both, but I started with reflexive and tried to prove that it is symmetric with $$yc \equiv xc \rightarrow y \equiv x \rightarrow x \equiv y \rightarrow xc \equiv yc $$, therefore symmetric, but also unsure if I did it right. Also distinguishable is defined as "for some string c, exactly one xc or yc is a member of L".
Comment: Well, I think you should provide all available information for otherwise it makes no sense to reason about this exercise.
Comment: @mathse It basically asks to show that $$\equiv_L$$ is an equivalence relation. So I went about showing reflexive property that is aRa and symmetric if aRb, then bRa and then I will show transitive. This is a hw problem I am working on Intro to Theory of Computation by Sipser number 1.51.
Comment: Alright, the book is online. Why is it that you make so many mistakes in copying this task from the book? I suggest you edit the problem description above, to describe the problem **correctly**.
Comment: @mathse okay I'll do that later, I'm sorry I gotta run now I have class starting
Answer: The relation $\equiv_L$ is defined by: $x\equiv_L y$ iff $xz\in L\iff yz\in L$ for all strings $z$.
Clearly, $x\equiv_L x$ since $xz\in L\iff xz\in L$ for all strings $z$.


How to show that there is a continuous linear transformation?

Question: Let $H$ be a Hilbert space and $M$ closed subspace of $H$, then following:
Suppose that $M$ has codimension 1, which means that $M^\perp  $ have a dimension 1.
Then, how to show that there is a continuous linear transformation $ T: H \rightarrow R$  such that $ M=KerT$?
Should we use orthogonal projection theorem and write $<m,V>=0 $ and then defining $KerT$ ?
Answer: Let $u$ a non zero element of theorthogonal of $M$, define $T(x)=\langle u,x\rangle$, then $kerT=M$.
Comment: Dear Tsemo, can you please a little bit more elaborate your answer.  Because I did not get what you meant(


Inherit/override core module

Question: I have made a single tiny change to a core module. I copied it into my site modules directory. I am curious as to whther I can simply override it's hook_menu() method in my copy so as not to carry over all the additional code which the core version provides?
Similar to theme inheritance, do modules support anything similar?
Answer: There's no inheritance for modules, but much of the functionality they provide can be altered using hooks (search this page for _alter and you'll see the ones core provides).
Specifically for items defined in hook_menu(), you can use hook_menu_alter(), e.g.
function MYMODULE_menu_alter(&$items) {
  // Replace the page callback for the foo/bar path
  $items['foo/bar']['page callback'] = 'MYMODULE_some_function;
}

If I've misunderstood and you mean you literally want to inherit from a module, like subclassing a class, and just change a couple of things, then unfortunately not. Copying the module is the way to go; you'll need to change the names of all the functions so they don't collide with those in the core module, and change paths/cache keys/variables for the same reason.
Comment: If you just need to change a URL like that don't bother with a custom module, just add an alias from forums -> forum, that'll take care of it. `hook_menu_alter()` probably isn't appropriate for that, as links to the original path would need to be changed. You could always use `hook_url_inbound_alter()` for that, but for a path change an alias is much easier
Comment: They shouldn't do - all core methods will use the `l()` function to link to the page, and that handles aliasing for you. So if you (or a core module) have a bit of code like this: `print l('forum', 'Forum');`, the href attribute on the `` tag will be the alias (forums), not the original path (forum)
Comment: Ah sorry I didn't get what you meant, but I think you'll still be ok - the path for forum posts will be defined as something like `forum/%` so it "shouldn't" interfere :)
Comment: I literally copied the forum module so as to change the URI from forum to forums so it's the forum_menu() I would overload -- with my custom module name but how then does Drupal know which menu path to use?
Comment: I thought of that but the forum module uses the singular version when you have selected a topic under it -- which is the desired structure. So wouldn't that conflict?
Comment: ok but the forum module itself uses both the singular and plural form...if I use ONE alias to ensure the default is "forums/" instead of "forum/" but I want to keep the behavior "forum/this-is-a-post" is what I am afraid of...in any case...I just have to try it and find out I guess :)

Inherit/override core module


How can I stop cron from deleting images I need

Question: I have an image that is being deleted by the drupal 7 cron.
This is not good for us and I am trying to figure out how to prevent this.
As I am new to drupal I am not sure even where to begin but I am pretty sure we add the image via the core image module if that helps.
Please if anyone could help I would be most appreciative and sorry if this Q is too noob for here :)
The image is the only one in it's containing folder too.
Answer: Try using
<code><?php
$file->status |= FILE_STATUS_PERMANENT;
$file = file_save($file);
?>
</code>
While you save the file
References
hook_insert


Difficulty deducing derivatives of particular summation formulas

Question: I have difficulty concluding the derivatives of the following:
$$y=\ln\bigg(\sum_{j=1}^ng_j\cdot e^{xE_j}\bigg)$$
and
$$y=x\cdot \sum_{j=1}^n \bigg(g_j \cdot \frac{N}{\sum_{j=1}^ng_j\cdot e^{xE_j}}\cdot e^{xE_j}\cdot E_j\bigg)$$
Note that $x$ does not change during the summation. Are these possible to solve? If so, how?
EDIT: I have made a mistake when copying the second formula, I have corrected it.
Comment: What derivatives are you taking? $\frac{\partial y}{\partial E_j}$, or $\frac{\partial y}{\partial g_j}$, presumably not $\frac{dy}{dx}$ since you're suggesting $x$ is constant. Is this something from statistical mechanics by any chance?
Comment: He is saying that $x$ is the variable to differentiate wrt, but the series index is not $x$.

Here what I'd do is say $e^y = \sum$ and then you can differentiate both sides wrt $x$ (implicit differentiation), giving $\frac{dy}{dx}e^y = \frac{d}{dx}\Sigma$.

To differentiate the series, just differentiate each term and sum them together.
Comment: For the second one I'd guess the answer is just $y=N$ with derivative zero, but seeing as there is probably $N = N_j$ i.e. $N$ varying, what you should do is take $(\sum_{j=1}^n g_j e^{xE_j})^{-1}$ out as a multiple, and use the product rule of differentiation.
Comment: @GeorgeDewhirst For the 1st formula, if $\frac{dy}{dx}e^y = \frac{d}{dx}\Sigma$  then I get $\frac{dy}{dx} = \frac{1}{x} \cdot \sum_{j=1}^n(g_j \cdot E_j \cdot e^{xE_j})$. But a different source is telling me otherwise saying that the derivative of $\ln(g(x))$ is $\frac{g'(x)}{g(x)}$, thus $\frac{dy}{dx} = \frac{\sum_{j=1}^n (g_j \cdot E_j e^{xE_j})}{\sum_{j=1}^n (g_j \cdot e^{xE_j})}$.

For the second formula, I made a mistake; the summation itself should be multiplied by $x$ as well (I corrected it in the OP). The $N$ is a constant and does not vary during the summation.
Answer: If
$y
=\ln\bigg(\sum_{j=1}^ng_j\cdot e^{xE_j}\bigg)
$
then,
since
$(\ln(f(x))'
=\dfrac{f'(x)}{f(x)}
$,
$\begin{array}\\
y'
&=\dfrac{(\sum_{j=1}^ng_j e^{xE_j})'}{\sum_{j=1}^ng_je^{xE_j}}\\
&=\dfrac{\sum_{j=1}^ng_jE_j e^{xE_j}}{\sum_{j=1}^ng_je^{xE_j}}\\
\end{array}
$
For your second $y$,
you need to make the index
in the inner sum
different than
the index in the outer sum.
$\begin{array}\\
y
&=x \sum_{j=1}^n \bigg(g_j \dfrac{N}{\sum_{k=1}^ng_ke^{xE_k}} e^{xE_j}\bigg)\\
&=N\sum_{j=1}^n \bigg(g_j \dfrac{xe^{xE_j}}{\sum_{k=1}^ng_ke^{xE_k}} \bigg)\\
&=N\sum_{j=1}^n g_jy_j(x)\\
\end{array}
$
where
$y_j(x)
= \dfrac{xe^{xE_j}}{\sum_{k=1}^ng_ke^{xE_k}}
$.
Then
$\begin{array}\\
y_j'(x)
&= \left(\dfrac{xe^{xE_j}}{\sum_{k=1}^ng_ke^{xE_k}}\right)'\\
&= \dfrac{(\sum_{k=1}^ng_ke^{xE_k})(xe^{xE_j})'-(\sum_{k=1}^ng_ke^{xE_k})'(e^{xE_j})}{(\sum_{k=1}^ng_ke^{xE_k})^2}\\
&= \dfrac{(\sum_{k=1}^ng_ke^{xE_k})((xE_j+1)e^{xE_j})-(\sum_{k=1}^ng_kE_ke^{xE_k})(e^{xE_j})}{(\sum_{k=1}^ng_ke^{xE_k})^2}\\
&= e^{xE_j}\dfrac{(xE_j+1)\sum_{k=1}^ng_ke^{xE_k}-\sum_{k=1}^ng_kE_ke^{xE_k}}{(\sum_{k=1}^ng_ke^{xE_k})^2}\\
\end{array}
$
Now put this in
$y'(x)
=\sum_{j=1}^n g_jNy_j'(x)
$,
do any possible simplifications,
correct any errors I may have made,
and you are done.
Comment: I think your $x$ in the denominator of $y'_j(x)$ should not be there.
Comment: Thanks a lot. I'm so sorry, I have a mistake in the OP, the second formula within the summation should be multiplied by $E_j$ such that $y=x\cdot \sum_{j=1}^n (g_j \cdot \frac{N}{\sum_{j=1}^ng_j\cdot e^{xE_j}}\cdot e^{xE_j}\cdot E_j)$. Not sure if this would change the whole derivation.
Comment: Nope. Just changes the final summation. The $y_j$ remain the same.
Comment: Such that $y'(x)=\sum_{j=1}^n E_j g_jNy_j'(x)$?
Comment: Yup. If $E-J$ is there, use it.
Comment: Probably right. I'll fix it tomorrow. Thanks.
Comment: I'm not sure if there are any other errors. Could you please recheck this?