JQuery Datatables click event not working for pages except 1

Question: I am using JQuery Datatable for my application. I have a simple code which displays all my clients and a script which fires on the click of table row. Now, the problem is, this works fine for the first page, however, for all the other pages click event on the row is not identified. Please find below the code for the datatable and the script library.
// viewAllClients.php

        Name
        City

    <?php
    $values = Client::all();
    foreach ($values as $value)
        {?>

name}}" data-id="{{$value->id}}">
        {{$value->name}}
        {{$value->city}}

    <?php }
    ?>

//default.js

$('#view_all_entries').DataTable( {
            "aaSorting": [[ 2, "desc" ]],
            "iDisplayLength": 30,
            "sPaginationType": "full_numbers"
        } );

$('#view_all_entries .options').click(function(){
var id = $(this).closest('tr').data('id');
document.location.href = $('#route_path').val()+'/'+id + '/edit';
});

Any help would really be appreciated. Thanks.
Answer: So, well, based on the answer by Halcyon, I figured out that I needed a minor change for event delegation. I hope the following code helps other stucked with the same problem.
//default.js
$('body').delegate('#view_all_entries .options', 'click', function () {
  var id = $(this).closest('tr').data('id');
  document.location.href = $('#route_path').val()+'/'+id + '/edit';
});

Comment: Ah yea, that's the one I meant. In newer version of jQuery it's been replaced by `on`. So I think `$('#view_all_entries .options').on("click", .. );` does it as well.
Answer: $('#view_all_entries .options') matches DOM Nodes that are currently on the page. Once you go to the next page a new set of DOM Nodes is created. If you also want those to be clickable you must added the click handler.
I think there is a way to automatically do this in jQuery but the straight forward approach is to add the click handler whenever the data changes.
You can bind to the page event to know when a new page is loaded: https://datatables.net/release-datatables/examples/advanced_init/dt_events.html
It's little bit like this row callback exmaple: https://datatables.net/release-datatables/examples/advanced_init/row_callback.html
Comment: Votes up for the answer. Just gave me the right idea. Adding an answer to my question for future references.
Answer: I was facing the same problem and this is my implementation in Asp.Net and Jquery. I have a grid-view and an Edit button inside the Item Template. I'm making an ajax function call. You need to use a delegate.
<asp:GridView ID="GrdRegPeople" runat="server" class="display table table-hover table-condensed" AutoGenerateColumns="False" AllowPaging="True" AllowSorting="True" ClientIDMode="Static" OnPageIndexChanging="GrdRegPeople_PageIndexChanging">
  <Columns>
      <asp:BoundField ItemStyle-Width="50px" DataField="Reg_id" HeaderText="Reg.ID">
          <ItemStyle Width="50px" />
      </asp:BoundField>
      <asp:BoundField ItemStyle-Width="200px" DataField="Name" HeaderText="Name">
          <ItemStyle Width="200px" />
       </asp:BoundField>
      <asp:BoundField ItemStyle-Width="50px" DataField="Reg_email" HeaderText="Email">
           <ItemStyle Width="50px" />
      </asp:BoundField>
      <asp:BoundField ItemStyle-Width="50px" DataField="CompanyName" HeaderText="Company">
           <ItemStyle Width="50px" />
      </asp:BoundField>
      <asp:BoundField ItemStyle-Width="50px" DataField="Reg_position" HeaderText="Position">
           <ItemStyle Width="50px" />
      </asp:BoundField>
      <asp:TemplateField ShowHeader="false">
           <ItemTemplate>
               <asp:Button ID="Button1" class="btn btn-primary activeButton" ClientIDMode="Static" runat="server" Text="Edit" />
           </ItemTemplate>
      </asp:TemplateField>
</Columns>
<PagerStyle HorizontalAlign="Right" />

 $("body").delegate("#GrdRegPeople .activeButton", "click", function (e) {
            //Write Your Code here..
                                }
        });


What are the real-valued functions?

Question: Is $f(x)=\frac{1}{x}$ a real-valued function?
I think the definition of a real-valued function is that the range is in the real numbers. Is that right?
Hence, I think $f(x)=\frac{1}{x}$ is not a real-valued function.
If then, what are the other examples of real-valued functions?
Are polynomial functions the only real-valued functions?
Comment: what non real value does $\frac{1}{x}$ take on?
Comment: By your definition, $f(x)=x^2$ is also not a real function because $-1$ is not in its range.
Answer: A real valued is a function, whose range is $\mathbb{R}$ or some subset of $\mathbb{R}$.
$\frac{1}{x}$ for $x\in\mathbb{R}$ is real valued. We note that its range is $(-\infty,0)\cup (0,\infty)$, which is a subset of $\mathbb{R}$.
Polynomials are real valued, but they are not the only functions who are real valued.
A few examples of real valued functions:
The following are said to be real valued functions since their range is the set of real numbers, or some subset of the real numbers.
$f(x)=2$ ; The range is $\{2\}\subset \mathbb{R}$
$f(x)=11x$ ; The range is $\mathbb{R}$
$f(x)=e^x$ ; The range is $(0,\infty)\subset\mathbb{R}$
$f(x)=\dfrac{1}{x^2}$ ; The range is $(0,\infty)\subset \mathbb{R}$
etc...
Answer: The term "valued" refers to a function's codomain.  real-valued, complex-valued, integer-valued, vector-valued, etc.
Comment: Simple and straightforward.
Comment: I know I am late, but I wish I found this answer in my undergraduate days...
Answer: What is a real-valued function?

A real-valued function is a function that assigns real numbers to each member of its codomain or range.

Is $f(x)=\frac{1}{x}$ a real-valued function?
Yes because each member of the codomain of $f(x)=\frac{1}{x}$ is in fact a real number. Also note that excluding zero from the codomain does not change the fact that every other member is a real number. Symbolically, we have
$$f:\mathbb R\setminus\{0\}\to\mathbb R\setminus\{0\}$$
Since $\mathbb R\setminus\{0\}$ is a subset of $\mathbb R$, then the expression above can be read as $f$ is a real-valued function of a real-valued variable.
Comment: then is cos x is real valued function?
Comment: @aaa, $\cos(x+iy)$ is a real valued function when $y=0$ and also when $x=n\pi$, where $n$ is any integer.
Comment: In the function $f$, you have to exclude zero, right? One cannot have $1/0$.
Comment: @johnny09, Thanks for the correction, please see my edit.
Answer: A function which has either $\mathbb{R}$ or one of its subsets as its range is called a real valued function. Further, if its domain is also either  $\mathbb{R}$ or a subset of  $\mathbb{R}$ it is called a real function.
Comment: Try formatting your responses using MathJax (http://meta.math.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference).

What are the real-valued functions?


Convert object to an array with underscore

Question: I'm trying to covert javascript object to an array using Underscore, but I have some problems with understanding Underscore.
I want to covert this:
{ key1: value1, key2: value2},{key1: value1, key2: value2}

Into this:
[value1, value2],[value1, value2]

Answer: You can use _.map and _.values like this
var data = [{ key1: 1, key2: 2 }, { key1: 3, key2: 4 }];
console.log(_.map(data, _.values));
# [ [ 1, 2 ], [ 3, 4 ] ]

If you fancy generic JavaScript version, you can do
console.log(data.map(function(currentObject) {
    return Object.keys(currentObject).map(function(currentKey) {
        return currentObject[currentKey];
    })
}));
# [ [ 1, 2 ], [ 3, 4 ] ]

Answer: I suppose you're having input as Array of Objects and want the result in Array of Arrays, then you could just use native javascript to do it
var output = input.map(function(obj){ return [obj.key1, obj.key2] });


Como retornar null se não for encontrado nenhum resultado com find_by?

Question: Estou obtendo um retorno como array ([]) de um escopo com find_by e desejo que o retorno seja vazio (null).
Veja abaixo alguns trechos do código:
class Dispute::Conference < ApplicationRecord
  ...
  belongs_to :dispute, counter_cache: true

  scope :scheduled, -> { find_by state: :scheduled }
  ...
end

É um relacionamento has_many, então é normal retornar um array caso não se encontrei nenhum resultado.
class Dispute < ApplicationRecord
  ...
  has_many :conferences, dependent: :destroy
  ...
end

Como estou utilizando um escopo, e espero somente um resultado do filtro, acreditei que retornasse null caso nenhum resultado fosse encontrado.
Existe alguma maneira de retornar null, para este caso específico?
Comment: Um detalhe importante, troquei `find_by` por `where`, por algum motivo que não sei explicar em alguns casos o retorno gera problemas com o `ActiveModel::Serializer`.
Answer: A forma que encontrei para resolver isso foi utilizando um .present? dentro de uma condicional no local onde faço a chamada do escopo scheduled:
class DisputeSerializer < ActiveModel::Serializer
  ...
  has_one :scheduled

  def scheduled
    Dispute::ScheduledSerializer.new object.conferences.scheduled if
      object.conferences.scheduled.present?
  end
end

Um detalhe é que se não fizer este tratamento um erro do ActiveModel::Serializer será apresentado.
#<NoMethodError: undefined method `read_attribute_for_serialization' for #<ActiveRecord::AssociationRelation []>>

Answer: O find_by sempre retorna 1 ou nil. Como você trocou para where, retorna uma coleção ou vazio []. Você pode utilizar

def self.scheduled
  where(state: :scheduled).first
end

para retornar o primeiro resultado ou nil.


Cannot run the socket programs correctly in Centos using Python

Question: I'm currently working on with Sockets using Python.
As a starter, I tried copying first the examples given in this (17.2.2. Example) tutorial
I put the client and the server scripts in two different machines (of course)
Now, I want to try if it works, but I'm kind of lost.
I'm thinking of running the server program continuously so that it will keep on receiving the data sent by the client program. However, when I tried to run the Server program, it is giving me this error

socket.error: (99, 'Cannot assign requested address')

and When I tried running the client program, it doesnt give me errors, however, it is printing random data, which is different from what I'm expecting because I sent the String "Hello World", So im expecting that it will receive and print "Hello World"
Shown below is the server program
# Echo server program
import socket

HOST = '192.168.104.112'                 # Symbolic name meaning all available interfaces
PORT = 50007              # Arbitrary non-privileged port
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((HOST, PORT))
s.listen(1)
conn, addr = s.accept()
print 'Connected by', addr
while 1:
    data = conn.recv(1024)
    if not data: break
    conn.sendall(data)
conn.close()

and the one below is the client program
# Echo client program
import socket

HOST = '192.168.104.111'    # The remote host
PORT = 50007              # The same port as used by the server
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((HOST, PORT))
s.sendall('Hello, world')
data = s.recv(1024)
s.close()
print 'Received', repr(data)

Assuming that the IP of the machine that runs the server program is : 192.168.104.111
while the Client program is : 192.168.104.112
Im not really sure where to get the port number so I just used the port showed in the rpyc in the terminal. how do I get the correct port number anyway?
I know I made a lot of mistakes here. I just don't which part. Could you point me the mistakes that i've done and how to correct them? and how do I run these programs?
BTW, i'm using Centos.
Comment: Is the port not in use by any other application? It seems like that because your server can not bind to that port while the client can connect (indicating that someone is listening to that port). Use a program such as [`netstat`](http://linux.die.net/man/8/netstat) to make sure no other program is using the port.
Answer: On the server, HOST should be either 0.0.0.0 or the server's own IP address. The server needs to bind its listening port to its own interface(s). The client connects to the server.
Your client program doesn't check for errors. So if it can't connect to the server, things go awry.
Comment: I tried changing the Host of the server to 0.0.0.0 / localhost / to it own IP, it gave me this error socket.error: (98, 'Address already in use')
Comment: Wait about two minutes or try a different port. Don't set it to 127.0.0.1 or the client won't be able to connect to it.
Comment: I tried opening a new port and used 0.0.0.0 in the host  of the server program. It works!!! thanks! :D


Perturbation of positive semidefinite matrix

Question: Consider an $n\times n$ matrix $A$ that is positive semidefinite and has rank $n-1$, so there exists exactly one eigenvector $v$ such that $Av=0$. Let now $B$ be a symmetric matrix such that $v^TBv=0$. I'd like to argue that, if the norm of $B$ is small enough, $A+B$ is always positive semidefinite.
Comment: This is correct. This can be proven using standard perurbation results. See the book by Kato for instance.
Comment: Thank you @KBS. Can you please tell me which result you are referring to in Kato's book?
Answer: Assuming we require non-zero $B$, then the claim is False.  Consider the case of $n=2$ with
$A=\begin{bmatrix}1 & 0 \\ 0 & 0\end{bmatrix}$ and $B=\begin{bmatrix}1 & 1 \\ 1 & 0\end{bmatrix}$.
For any $\lambda \in \mathbb R-\big\{0\big\}$
$A+\lambda B = \begin{bmatrix}1 +\lambda & \lambda  \\ \lambda & 0\end{bmatrix}$
which is a real symmetric matrix that has a zero on its second diagonal component but the entire row fails to be zero hence is indefinite. Alternatively just check that the determinant is $\lambda^2 \lt 0$
Answer: The condition that $v^TBv$ is insufficient; we require the stronger condition that $Bv = 0$. As a counterexample, take $n = 2$ and
$$
v = \pmatrix{1\\0}, \quad A = \pmatrix{0 & 0\\0&1}, \quad B = \pmatrix{0&t\\t&0}, \quad t > 0.
$$
For any $t > 0$, we find that $A + B$ fails to be positive semidefinite.

If $Bv  = 0$, then we can argue that $A + B$ is positive semidefinite as follows. Let $\{v_1,v_2,\dots,v_n\}$ be an orthonormal basis with $v_1 = v$. Let $Q$ denote the orthogonal matrix whose columns are $v_1,\dots,v_n$, and break it into the block-matrix $Q = [v\ \ Q_\perp]$. We can replace $A$ and $B$ with the similar matrices
$$
A_0 = Q^TAQ = \pmatrix{v^TAv & v^TAQ_\perp \\ Q_\perp^T Av & Q_\perp^TAQ_\perp}, \quad B_0 = Q^TAQ = \pmatrix{v^TBv & v^TBQ_\perp \\ Q_\perp^T Bv & Q_\perp^TBQ_\perp}.
$$
We note that $Bv = 0$ and $v^TB = (Bv)^T = 0$ and similarly $Av = 0$ and $v^TA = 0$. Thus, we have
$$
Q^T(A + B)Q = A_0 + B_0 = \pmatrix{0& 0\\0 & Q_\perp^TAQ_\perp + Q_\perp^TBQ_\perp},
$$
which is indeed positive semidefinite if the norm of $B$ (and hence $Q_\perp^TBQ_\perp$) is sufficiently small.
With this decomposition, we also see that if $v^TBv = 0$, then $A + B$ will be positive semidefinite only if $Bv = 0$. Otherwise, $Q_\perp^Tv$ will be non-zero, which means that $Q^T(A + B)Q$ will have a $2 \times 2$ principal submatrix that fails to be positive semidefinite.


GWT-Custom Button

Question: I need a gwt widget which has a button and can display a number. The number indicates the number of updates present.
The best example of this implementation which i can think of is facebook. The notification button on the facebook homepage displays a number which indicates the number of notifications from the last login.
I want to implement something like that.
Any suggestions?
Thanks
Comment: Use a button, and set the text to a number?
Answer: you can use button and on every update ,change the label of the button to reflects the number of update , if you wanted it on a server side you can update the button name from a callback function

GWT-Custom Button


Horizontal menu in center

Question: doing this for the first time so please be gentle. :) I am aiming for navigation menu in the centre, horizontal, with image in the middle list item. Image will be much bigger as the bottom half is name of the my company and top of the picture might be touching the top. My first problem is that the li elements are only as big as the text, whitch doesnt serve the center-thing purpouse and the second one related that it stretches the whole menu when hoovered on. Please I'm looking for solution where the text is in the middle of li and img sits down on bottom. Thanks so much for help!

Link 1

Link 2

Link 4

Link 5

body {
width: auto;
background-image: url(blue4.jpg);
background-size: cover;
margin: 2px 0 0 0;
}

#menu {
height:210px;
line-height:36px;
margin:0 auto;
text-align:center;
width:800px;
padding:0;
}

#menu ul {
display: inline;
-webkit-padding-start: 0px;
-webkit-margin-before: 2x;
-webkit-margin-after: 0px;
margin:0;
font-size: 0;
}

#menu ul li {
text-algin:center;
display:inline;
font-family:Arial,sans-serif;
font-size:40px;
padding:0;
margin:0;
text-decoration:none;
background-image:url(../Pics/Buttons/Menu/Menu.gif);
min-width:100px !important;
}

#menu a {
text-decoration:none;
color:#000000;
margin:10px 0;
padding:0;
}

#menu a:hover {
font-weight:bolder;
}

span {
width:100%;
font-size:30px;
}

Comment: Can you make a jsFiddle?
Comment: Two typos for "align"
Comment: is there a value 'bottom' for text-align property?!!
Comment: 1) `` might not be a valid element directly under ``; 2) `bottom` might not be a valid value for `text-align`.
Comment: tilwin Joy is correct - there is no 'bottom' property on text-align...
for vertical-align, there is a 'bottom' property
Comment: Never used jsFiddle, but I'll try, was looking for smthing like that. ; yeah, bottom was just shot in the dark
Comment: http://jsfiddle.net/pmkjj/
Comment: everything is in center here. and you are making text bold on hover which will definitely stretch your menu. one suggestion is DO NOT use `` direct in ``
Comment: Yes, but if the li width will remain the same, it shouldn't do the thing, right?
Comment: Not getting you. You want to give fix width to li ? Cant you give some other effect on hover so that menu will not stretch.
Comment: I'll probably have to do that, but not the solution. Still, if you change li text to some words with different lengh it won't be centered anymore. Li needs to remain same size I guess
Answer: the only option is left is width to  tag : DEMO
I have removed the direct  from UL and have added class 'widthAuto' so that it will not affect your logo.
#menu a {
    text-decoration:none;
    color:#000000;
    margin:10px 0;
    padding:0;
    min-width:100px !important; display:inline-block;
}

Note : Menu will stretch on hover if text exceed min-width.

Horizontal menu in center


Rails outputting two images when just one is wanted

Question: I am currently working on a project that requires me to create a (real) estate agent website. I have imported an XML list with all the properties and created the database, but when I go to create a properties list and insert the first image for each property, it creates two images (one for each property in the list) and assigns both images to each property.
The code is:
<% @properties.each do |property| %>

              <% property.pictures.each do |picture| %>
                  <% if picture.name.eql?('Photo 10') %>
                      <img src="<%= picture.url %>" class="img-responsive center-block"/>
                  <% end %>
              <% end %>

<%= property.advert_heading %>

<%= property.main_advert %>

  <% end %>

The html output is:

Pen Y Bryn, Llanfairfechan

A semi detached three bedroom family home located in a quiet cul de sac in the upper part of the village of Llanfairfechan.  The property benefits from double glazed windows, gas central heating, gardens to front and rear.  This would make an ideal family home or investment property.

33, Pen Y Bryn, Llanfairfechan LL33 0UH

A semi detached three bedroom family home located in a quiet cul-de-sac in the upper part of Llanfairfechan village.  The property benefits from double glazed windows, gas central heating, gardens to front and rear.  Restrictions apply.  Application fees apply. Deposit: &pound;750.

To me it seems that rails is looping throught the property.picture.each twice (or I'm guessing more if I had more properties) and inserting the output twice but I can't see why.
Many thanks
Comment: Pictures URL's are different, consequently is not the same image and you are not iterating twice. you have stored two images with the same name but different url.
Comment: Pretty sure that property.pictures contains multiple pictures with the name 'Photo 10'. Double check the xml file and your parsing of it.
Comment: Is picture name unique?
Answer: It looks like you have duplicate pictures with a name attribute of 'Photo 10'. Use your rails console to run a query to confirm this.
Picture.where(name: 'Photo 10').count

How many records are returned? Is your expectation that each property would have one picture with a name of 'Photo 10'? If so you you should expect to have as many pictures returned as properties, if not then you have duplicate entries with the name 'Photo 10' for each property. which brings me to my next point.
You should normalize your database. The fact that you are relying on a non unique attribute, and that there are multiple picture entries that point to the same url tells me that. You are also creating a lot of unnecessary picture entries in the picture table. Instead, I'd create a join table between between properties and pictures, maybe called PropertyPictures. For each unique picture url, create one entry in the Picture table. For each property that uses a picture, create an entry in the join table with that property_id and the desired picture's picture_id. This will help in case your pictures change. As you have it now, if one picture url changes it doesn't change in all places, even if it should. As far as your view goes, now that you have a unique and consistent picture_id, use that, it will be impossible to have duplicates. Also, instead of pulling all pictures, just get the one you want. You could write a method in your property model to do this. It might look like this:
def special_picture
   pictures.where(id: 1)
end

And in your view:
<% @properties.each do |property| %>

                      <img src="<%= property.special_picture.url %>" class="img-responsive center-block"/>

<%= property.advert_heading %>

<%= property.main_advert %>

  <% end %>

`
Comment: Thank you for the answer, really helped clear it up and I now have a join table for properties and pictures and it works perfectly. Thanks again
Answer: If you're only wanting the first image for each listing, why are you looping through all pictures for each listing?
You could do this instead:

  <img src="<%= property.pictures.first.url %>" class="img-responsive center-block"/>


Check effect of hook_schema_alter() hook

Question: I want to alter the comment subject field title width.
Core comment module sets it to 64 characters, and I want to change it up to 100 characters.
Now I tried to alter the schema using hook_schema_alter() function. Below is my code snippet, which I tried,
/**
 * Implements hook_schema_alter().
 */
function comment_alter_schema_alter(&$schema) {
    if (isset($schema['comment'])) {
        $schema['comment']['fields']['subject'] = array(
        'type' => 'varchar',
        'length' => 100,
        'not null' => TRUE,
        'default' => '',
        'description' => 'The comment title.',
        );
    }
}

I am confused whether do I have to write some stuff in .install file or not?
Now after installing module how can i check whether the width of subject field is increased or not. If I see the comment table then it is as it is to 64 characters. I could find this in your table structure using PHPMyAdmin.
Answer: This hook is not used to edit the database as such. It is used to alter the schema when using the drupal_get_schema

Gets the schema definition of a table, or the whole database schema.
The returned schema will include any modifications made by any module
  that implements hook_schema_alter().

To do what you want you will have to use the db_change_field and this would go in the .install file.
You can check out the Schema API to get other relavent functions
You have to write db_change_field() in hook_enable() function.
Here is my modified answer:
/**
 * Implements hook_enable().
 */
function comment_alter_enable() {
    db_change_field('comment', 'subject', 'subject', array(
        'type' => 'varchar',
        'length' => 100,
        'not null' => TRUE,
        'default' => '',
        'description' => 'The comment title.',
        )
    );
}

Comment: I have added following code in .install file, but it is still not working.     /**
     * Implements hook_install().
     */
    function comment_alter_install() {
     db_change_field('comment', 'subject', 'subject', array(
      'type' => 'varchar',
        'length' => 100,
        'not null' => TRUE,
        'default' => '',
        'description' => 'The comment title.',
      )
     );
    }
Comment: did you uninstall and then reinstall the module>
Comment: yes. i did all the things..
Comment: can you try it in hook_enable.
Comment: you suggestion for hook_enable() worked...Cheers..Update the answer..
Comment: good it worked. But it should work in the hook install as well. Dont know why it did not :-) Could be because the module is already installed. It only calls it once when you enable the module for the first time. Disabling and enabling again will not call the function.
Comment: I tried to verify it, but couldn't due to time limit..will post you here as i find something interesting


Unable to get a subfolder in directory

Question: Hi I'm trying to load files within different folders for example
-- Main directory
  -- bot folder
    - index.js
    - package.json
    - package-lock.json
    -- commands
        -- fun
            - kick.js
            - ban.js
        -- some other category

However in my code I'm only seem to be able to load the .js files in the Commands folder rather than the sub folders.
Here is the code I'm working with:
const commandFiles = fs.readdirSync("../main/Commands")
        .filter(file => file.endsWith(".js"));

    const commands = commandFiles.map(file => require(`../Commands/${file}`));

    commands.forEach(cmd => {
        console.log(`Command ${cmd.name} loaded`);
        this.commands.set(cmd.name, cmd);
    });

Help appreciated.
Comment: To read from subdir refer `https://stackoverflow.com/questions/5827612/node-js-fs-readdir-recursive-directory-search`
Answer: You can create multiple collections, one for each of your subfolders. Here is what I've done for my bot, and it's perfectly working :
client.commandsAdmin = new Discord.Collection();
client.commandsUser = new Discord.Collection();

const commandsAdminFiles = fs.readdirSync('./commands/admin').filter(file => file.endsWith('.js'));
const commandsUserFiles = fs.readdirSync('./commands/user').filter(file => file.endsWith('.js'));

for(const file of commandsAdminFiles){
  const command = require(`./commands/admin/${file}`);
  client.commandsAdmin.set(command.name, command);
}

for(const file of commandsUserFiles){
  const command = require(`./commands/user/${file}`);
  client.commandsUser.set(command.name, command);
}

When processing the command in your code, you would have to check if it belongs to one of the collections, then get which collection does contain the command, and then use client.commandsFun.get(command).execute(...) for example, if the command belong to the 'fun' subfolder.

Unable to get a subfolder in directory


Mean absolute percentage error with respect to predictions

Question: A friend of mine has suggested that instead of using mean absolute percentage error, i.e.
$$ \frac{1}{N}\sum_{i=0}^N \left| \frac{A_i - P_i}{A_i} \right| $$
(where $A_i$ denotes an actual value, $P_i$ denotes a predicted value, and $N$ the number of observations), to modify it so that the predicted amount is in the denominator, i.e.
$$ \frac{1}{N}\sum_{i=0}^N \left| \frac{A_i - P_i}{P_i} \right| $$
They've said that like this we penalise underforecasting more than overforecasting.
This seems strange to me, though I'm having trouble articulating why. What problems might there be with this latter error metric (as compared with regular MAPE on top)?
Comment: @whuber the latter. Thanks, have edited to clarify
Comment: Which one is "such a"?  The first one looks more problematic because in case $A_i=0$ you're in trouble, whereas any decent prediction procedure in the second case will avoid the possibility of predicting $P_i=0.$  (This is part of an argument for using the absolute logarithm of $A_i/P_i$ as an improvement over either formula.)
Answer: First off, using the prediction in the denominator is a reasonably common idea, see the survey by Green & Tashman (2009). Also, some people use the average of the prediction and the actual, which is commonly called a "symmetric" MAPE (see What is "symmetry" in evaluation metrics).
That said, "we penalize underforecasting more than overforecasting" is an accurate description. Note, though, that an alternative description is that "the optimal forecast under this MAPE variant is higher than the expectation". That is, using this MAPE will reward you for reporting systematically biased forecasts. Of course, this is completely analogous to the situation with the "normal" MAPE, which will reward you for biasing your forecasts low: What are the shortcomings of the Mean Absolute Percentage Error (MAPE)? Our thread on Minimizing symmetric mean absolute percentage error (SMAPE) addresses the bias that the sMAPE induces.
How strong the bias turns out will of course depend on the (unknown) future predictive distribution. I like to simulate stuff like this: randomly generate many iid future outcomes, and find out which point forecast will minimize your MAPE variant in expectation.
I personally would say that a major drawback of all kinds of MAPEs is that we don't know which functional of the future distribution will minimize the error measure. That is, we don't know what we are shooting for. I would say that if we want an unbiased expectation forecast, we should use (a variant of) the MSE, and if we want a given quantile forecast, we should use the appropriate quantile loss function. In other words, we should first figure out which functional of the unknown future density we want to elicit, then tailor or error measure accordingly.


SCVMM 2016 server sending DHCP requests

Question: We have a Hyper-V 2012 r2 cluster and I have just upgraded our SCVMM to 2016. The VMM is installed on a VM in the cluster.
Our DHCP server is a VM in the cluster with filters enabled. We have configured SCOM to email us whenever someone attempts to connect to our network and we either allow or deny it.
My old VMM server was generation 1. I created a new generation 2 VM for the upgrade. I saw an article where you can migrate from one server to another with different names. I removed SCOM integration, Backed the DB from VMM Console, uninstalled VMM with retain DB option checked and shutdown the VM.
After failed attempts at installing on a server with a different name, I reinstalled the operating system on the new VM from scratch and gave it the same name as the old VMM server and started installing VMM. The service should use local system since we are a small business. During the installation, which ran with a domain admin I got an account lockout alert of the user running the installation. Even with the account lockout alert the installation completed successfully (...) Since this happened more than once I checked when the lockout happened and it was during the setspn step of the installation.
My problem is, ever since I installed the VMM server I keep getting DHCP requests. The only reason I say that is because I restarted the server and from the restart it requests DHCP. I even shutdown the server for a day to see what happens and I didn't get any DHCP alerts while the server was down. Every time it is a random address, not vendor specific. And, it sends requests every hour.
Honestly don't know what to do about this...
Rahamim.
Comment: Hope someone still follows this. I ran Wireshark and found that SCVMM sends a DHCP Discover packet. I tried several ways to disable this but it still happenedץ
Answer: Found the culprit!!!
First of all, When installing Hyper-V and using an ISCSI LUNs, the MSiSCSI services is throwing DHCP discover packets when it start. After it finds the NIC that uses the iSCSI targets it uses that NIC and doesn't attempt to search for DHCP until the next reboot \ restart of the service.
Apparently when installing SCVMM server and SCVMM agent several this is what happens: On the SCVMM server the iSCSI initiator service is installed and starts running (like the Hyper-V) which causes the first DHCP discover packets. Than, On all the server that SCVMMAgent service is installed, a DHCP discover packet is broadcasted repeatedly in a constant interval for each server.
The solution: https://download.microsoft.com/download/A/E/9/AE91DEA1-66D9-417C-ADE4-92D824B871AF/uGuide.doc
Although this is for server 2008 and 2003, when Creating the MSiSNS Key and adding the DHCPRetries DWORD with the value 0, it causes iSCSI to stop sending DHCP discover packets.
Hope this helps anyone.
Rahamim.

SCVMM 2016 server sending DHCP requests


Can anyone help me to get valgrind work on Mavericks?

Question: The latest version of valgrind available is 3.9.0 which supports Mac OS X 10.7. I have Mac OS X 10.9.2. I've just begun learning C programming and I need valgrind before I go any further.
Had anyone successfully ran valgrind on Mavericks??
Comment: possible duplicate of [Are there any alternatives to valgrind on Mac OS X Mountain Lion and Mavericks to detect memory leaks for C/C++ applications?](http://stackoverflow.com/questions/19719762/are-there-any-alternatives-to-valgrind-on-mac-os-x-mountain-lion-and-mavericks-t)
Answer: Check here for the work of Frederic Germain:
https://bugs.kde.org/attachment.cgi?id=85889&action=edit


Questionário dinâmico php SQL Server

Question: Olá,
 estou construindo uma ferramenta de calibração (dado um checklist o usuário precisa selecionar os campos que estão de acordo (ou não) com uma ligação ou roteiro.

Ex.:
1)Colaborador inicia o atendimento conforme diretrizes.
a) conforme
b) não conforme
c) não se aplica.

A principio a ferramenta vai permitir selecionar o tipo de campo ( radio,checkbox,select e text).
Atualmente ja tenho boa parte pronta, a questão é: qual a melhor forma de estruturar o meu banco? Como devo relacionar as respostas e as perguntas? atualmente minhas tabelas estao assim:
Tabela Formulário
CREATE TABLE [dbo].[formulario](
    [id] [varchar](13) NULL,
    [nome] [varchar](150) NULL,
    [descricao] [varchar](max) NULL,
    [pergunta] [varchar](150) NULL,
    [resposta] [varchar](150) NULL,
    [tipo] [varchar](100) NULL,
    [iPergunta] [int] NULL,//indice da pergunta
    [iResposta] [int] NULL,//indice da resposta
    [qtdPerguntas] [int] NULL,//total de perguntas
    [qtdRespostas] [int] NULL,
    [responsavel] [varchar](150) NULL,
    [criacao] [datetime] NULL,
    [atualizacao] [datetime] NULL
)

Tabela Resposta:
CREATE TABLE [dbo].[resposta](
    [formulario] [varchar](13) NULL,
    [pergunta] [varchar](150) NULL,
    [resposta] [varchar](150) NULL,
    [respondente] [varchar](150) NULL,
    [data] [datetime] NULL
)

Eu preciso de uma outra tabela para que o adm possa falar quais são as respostas corretas, mas essa estrutura não parece adequada.
Comment: Para que serve  os campos `iPergunta` e `iResposta`? Pelo qe da para entender eles servem para dizer qual a pergunta e respota do formulário. É importante entender isso para que a comunidade possa dar uma resposta mais adequada para você.
Comment: Bom Thiago, eles são o indice da pergunta e da resposta, meio que um contador.
Comment: Pelo que entendi o `iPergunta` iria receber o id da pergunta do formulário. Mas se o formulário tiver várias perguntas, pela modelagem que mostrou, acredito que isso não iria funcionar.
Comment: Não, o iPergunta é o índice. veja bem, suponha que eu inseri 2 perguntas, a primeira com 3 respostas e a segunda com duas,a estrutura seria:
Pergunta 1: iPergunta 0
Resposta a iResposta 0
Resposta b iResposta 1
Resposta c iResposta 2
Pergunta 2 iPergunta 2
Resposta a iResposta 3
Resposta b iResposta 4
Answer: Eu criaria o modelo mais ou menos da seguinte forma:
Formulário
CREATE TABLE [dbo].[formulario](
    [id] [int] NOT NULL, // chave primaria
    [nome] [varchar](150) NOT NULL,
    [descricao] [varchar](max) NOT NULL,
    [tipo] [varchar](100) NOT NULL,
    [responsavel] [varchar](150) NOT NULL,
    [criacao] [datetime] NOT NULL,
    [atualizacao] [datetime] NOT NULL
)

Resposta
CREATE TABLE [dbo].[resposta](
    [id] [int] NOT NULL, // chave primaria
    [id_formulario] [int] NOT NULL, // chave extrangeira
    [id_pergunta] [int] NOT NULL, // chave extrangeira
    [id_opcao] [int] NOT NULL // chave extrangeira
)

Pergunta
CREATE TABLE [dbo].[pergunta](
    [id] [int] NOT NULL, // chave primaria
    [pergunta] [varchar](150) NOT NULL
)

Opção
CREATE TABLE [dbo].[opcao](
    [id] [int] NOT NULL, // chave primaria
    [id_pergunta] [int] NOT NULL, // chave extrangeira
    [opcao] [varchar](150) NOT NULL
)

Fazendo desta forma, você poderia criar uma pergunta com quantas opções de resposta você quisesse. E depois na tabela Resposta, você pode relacionar várias perguntas a um formulário, e registrar a opção marcada pelo usuário.
Comment: Assim fica bem melhor, preciso pensar em uma forma de fazer isso no backend, pois para o meu adm que vai inserir o banco, vai fazer a inserção como se fosse o modelo de criação de formulário do google forms. Imagino que com essa estrutura, se fosse criado cada item de forma separada, seria muito mais trabalhoso.
Comment: Você pode colocar os itens junto as perguntas, mas terá uma quantidade fixa de itens e se você quiser uma quantidade de itens variadas de acordo com a pergunta, terá campos nulos. Da forma que fiz a modelagem, isso não iria acontecer.

Questionário dinâmico php SQL Server


Instagram Public Api ( __a=1 ) is banned. Any alternative?

Question: I used Instagram public API (adding __a=1 to parameters of an URL) to get a post detail (caption ,imageUrl, postType, likes, comments , viewsCount). But it seems that Instagram banned that recently and returned a 403. It also asks for login when I try to directly open a post by its usrl.
I tried to use the Instagram private API (https://mgp25.github.io/) for getting post details, but after some requests Instagram banned that too:

"throttled by instagram because of too many api requests"

Do you have any offer for an alternative?
Comment: Looks more like they just banned you for spamming their API
Comment: yes, but I was using this API for more than one year at the same rate of requests and there were no problem. Maybe there is a new limit
Comment: `__a=1` is a public endpoint API. How did he notice you and banned you? This API `__a=1` is also not found in instagram documents! How long have you been using this API `__a=1`?
Comment: Maybe by my ip or something (since it is also banned when I use psihpone proxy on my own pc, but it allows me when I try without proxy)
Comment: I was using it for about tow years
Answer: Actually it is not really banned but now redirects with 302 to auth page. It seems like auth is required when Instagram account and query geoIPs are different. Alternative is to use official API. No scraping can be done, because the profile link now also requires authentication. You can do authenticated scraping but you are limited to 200 queries ( that Instagram sends to get data) per hour.
Comment: When I open a direct link, it works. If I try to load json using the program - it does not work.
Comment: Is there any reference for 200 query per hour limit? or any document about instagram app limits
Comment: @Saeed https://developers.facebook.com/docs/graph-api/overview/rate-limiting#platform-rate-limits
Comment: It also does not work in Russia, Belarus and Kazakhstan.
Comment: Faced the same issue. When performing a request from heroku server I'm getting login page. But from my personal Russian IP everything works. However if I'm adding cookie into the headers then it works even from US IP but it's not a stable solution.
Comment: It seems like Instagram makes a desicion upon  geoIP of your request and your Instagram account. So if u registered and accesssed it in one country and town, but then trying to get data via public grap api from the server located in another country - it will require to be authenticated
Answer: Instagram blocked all public endpoints with some limitations and hit rate. Now you need to send the user's session to get the response.
Did you notice the same endpoint returning the JSON response when you are logged in on Instagram in the same browser? Yes, that because whenever you are hitting the URL like "https://www.instagram.com/anything/?__a=1", your browser sending the live and valid sessionid to Instagram. Since you are logged in hence Instagram served you well.
Ever you wonder why the same endpoint started to work again after changing the Internet connection from Wifi to Mobile hotspot or try with another internet service provider.
It's because your IP got blocked and no more free hot babes for you until you are logged in.
Below is the PHP code to give a try with sessionid.
<?php
// keyword or user name
$hashtag = $username = "msevylynch";
// $endpoint = "explore/tags/$hashtag"; // hashtag search
$endpoint = $username; // user search
// login in insta account and copy session from browser's cookie tab
$sessionid = '<YOU-SESSION-ID-PICK-FROM-BROWSER-AFTER-LOGIN>';

$ch = curl_init();
https://www.instagram.com/explore/tags/msevylynch/?__a=1
curl_setopt($ch, CURLOPT_URL, "https://www.instagram.com/{$endpoint}/?__a=1");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
    'Cookie: ds_user='.$username.'; igfl='.$username .'; sessionid=' . $sessionid,
    'User-Agent: Instagram 7.16.0 Android'
));
$response = curl_exec($ch);

header('Content-Type: application/json');
echo $response;
?>

Still no luck then it means Instagram blocked you or your IP for some time due to

hitting endpoint too early or very fast programmatically
denied the presented challenge
seems it's an automated hit
password is changed
you are logged out
or your internet bill is over due .. ha ha ha

Thank you for the reading this long, much apriceated.
Comment: I'm able to hit the endpoint from a private browser with no session data just fine, I don't think this is correct.
Comment: Hi @CWSites, sooner or later you will be asked to solve captcha or do log in or would see the error. It may be an IP block too.
Answer: Instagram is getting very strict with __a=1 endpoint. Your best bet in 2021 to get Instagram profile info is to use clean residential proxies
Comment: would you please name some other cloud proxy services ?
Answer: try using "?__a=1&__d=dis"
thank me later.
Comment: This does not provide an answer to the question. Once you have sufficient [reputation](https://stackoverflow.com/help/whats-reputation) you will be able to [comment on any post](https://stackoverflow.com/help/privileges/comment); instead, [provide answers that don't require clarification from the asker](https://meta.stackexchange.com/questions/214173/why-do-i-need-50-reputation-to-comment-what-can-i-do-instead). - [From Review](/review/late-answers/34080430)
Answer: Use /channel page to get JSON data of the user profile.
https://www.instagram.com/imvickykumar999/channel/?__a=1&__d=1
Comment: I still can not access this in an incognito window. `{"message":"Please wait a few minutes before trying again.","require_login":true,"status":"fail"}`


Generating function for number of integer solutions, no computer

Question:
How do you solve a Generating function for the number of integer solutions with no computer?

Use  a generating function to solve the number of integer solutions for $$x_1+x_2+x_3=17$$
Where $2\leq x_1 \leq 5, 3\leq x_2 \leq 6, 4\leq x_3 \leq 7$
Now all this takes is doing:
$$(t^2+\dots+t^5)(t^3+\dots+t^6)(t^4+\dots+t^7)$$
and looking at the coefficient of  $t^{17}$. In the assignments they always asked us to just comute this using Mathematica/Maple/Matlab etc. This is no problem.
But here it is a highly marked (past)final exam question and obviously I won't have a computer.
Is there some method I don't know for solving this by hand, that explains why it is worth so many marks.
Otherwise I can't see why I am not just doing this by hand for a few minutes.
Answer: In $$(t^2+\dots+t^5)(t^3+\dots+t^6)(t^4+\dots+t^7)$$ you can notice that is $$t^2(1+t+t^2+t^3)\times t^3(1+t+t^2+t^3)\times t^4(1+t+t^2+t^3)=t^9(1+t+t^2+t^3)^3$$ which simplifies a lot the problem as Gerry Myerson answered. Moreover,  $$1+t+t^2+t^3=(t+1)(t^2+1)$$ can help.
Answer: It's also the coefficient of $t^8$ in $(1+t+t^2+t^3)^3$. $$(1+t+t^2+t^3)^3=(1-t^4)^3(1-t)^{-3}=(1-3t^4+3t^8+\dots)(1+3t+6t^2+10t^3+\dots)$$ where the coefficient of $t^r$ in the last bracket is $t+2\choose2$. It shouldn't be too hard for you to pick out the coefficient of $t^8$ now.


Bijective $\mathcal{O}_X$-Module Homomorphisms

Question: Let $(X,\mathcal{O}_X)$ be a ringed space, $\mathcal{F}$ and $\mathcal{G}$$\,\,\,$$\mathcal{O}_X$-modules, and $\varphi:\mathcal{F}\to\mathcal{G}$$\,$ an $\mathcal{O}_X$-module homomorphism.
If $\varphi$ is both injective and surjective, then how do we go about constructing an inverse $\varphi^{-1}:\mathcal{G}\to\mathcal{F}\,$?

For $U\subseteq X$ open, we have a map $\varphi(U):\mathcal{F}(U)\to\mathcal{G}(U)$ and we set$$\begin{align*}\text{Im}(\varphi)(U)=\{s\in\mathcal{G}(U):&\forall x\in U,\exists V\subseteq U\text{ open such that}\\&x\in V,s\hspace{-0.13cm}\mid_V\in\text{Im}(\varphi(V))\}\end{align*}$$
Since $\varphi$ is surjective we have $\text{Im}(\varphi)(U)=\mathcal{G}(U)$, so given $s\in\mathcal{G}(U)$ we can find $U=\cup_{i\in I}V_i$ for some open $V_i\subseteq U$, with $t_i\in\mathcal{F}(V_i)$ such that $\varphi(V_i)(t_i)=s\mid_{V_i}$.
I'd like to patch the $t_i$ together to get some $t\in\mathcal{F}(U)$, so we can then set $\varphi(U)^{-1}(s)=t$. I imagine this is where we need to use the injectivity of $\varphi$, but I can't seem to spot how.
Any help would be much appreciated.
Comment: Apologies, I've only just met $\mathcal{O}_X$-modules and I'm not familiar with what that means in this context, have I somewhere assumed that for sufficiently small $U$ we have $\mathcal{F}(U)=\oplus\mathcal{O}_X(U)$?
Comment: I'm just saying most sheaf of $O_X(U)$-modules you want to consider in scheme theory are locally free in which case the injective+surjective implies invertible is easy
Answer: Given $t_i,t_j$, we would have that $\varphi(V_i\cap V_j)(t_i\hspace{-0.13cm}\mid_{V_i\cap V_j})=\varphi(V_i\cap V_j)(t_j\hspace{-0.13cm}\mid_{V_i\cap V_j})=s\mid_{V_i\cap V_j}$, and so by the injectivity of $\varphi$ we have $t_i\hspace{-0.13cm}\mid_{V_i\cap V_j}=t_j\mid_{V_i\cap V_j}$ for all $i,j\in I$, and so we can glue the $t_i$ to construct $t$.


$f:\mathbb R \to \mathbb R$ be twice differentiable , $f(x)+f''(x)=-xg(x)f'(x) , g(x) \ge 0 , \forall x \in \mathbb R$ , then $f$ is bounded?

Question: Let $g:\mathbb R \to [ 0,\infty)$ be a function and $f:\mathbb R \to \mathbb R$ be a twice differentiable function such that
$f(x)+f''(x)=-xg(x)f'(x) , \forall x \in \mathbb R$ , then is it true that $f$ is bounded i.e. $\exists M \ge0 $ such that
$|f(x)| \le M , \forall x \in \mathbb R$ ?
Answer: Here is my answer. The function $f$ is indeed bounded on $\mathbb{R}$. From
$$
f(x)+f^{\prime \prime }(x)+xg(x)f^{\prime }(x)=0,\ x\in \mathbb{R}
$$ multiply by $2f^{\prime }(x)$ the equation, we get $$
2f(x)f^{\prime }(x)+2f^{\prime }(x)f^{\prime \prime }(x)+2xg(x)\left[
f^{\prime }(x)\right] ^{2}=0,\ \ \ \ for\ all\ x\in
\mathbb{R}
$$ then
$$
\left[ f^{2}(x)\right] ^{\prime }+\left[ \left( f^{\prime }\right) ^{2}(x)%
\right] ^{\prime }+2xg(x)\left[ f^{\prime }(x)\right] ^{2}=0,\ \ \ \ for\
all\ x\in
\mathbb{R}
$$ Now, integrate
$$
\int \left( \left[ f^{2}(x)\right] ^{\prime }+\left[ \left( f^{\prime
}\right) ^{2}(x)\right] ^{\prime }+2xg(x)\left[ f^{\prime }(x)\right]
^{2}\right) dx=C,\ \ \ \ for\ all\ x\in
\mathbb{R}
$$ then%
$$
f^{2}(x)-f^{2}(0)+\left( f^{\prime }\right) ^{2}(x)-\left( f^{\prime
}\right) ^{2}(0)+\int_{0}^{x}2tg(t)\left[ f^{\prime }(t)\right] ^{2}dt=0,\ \
\ \ for\ all\ x\in
\mathbb{R}
$$ therefore%
$$
f^{2}(x)+\left( f^{\prime }\right) ^{2}(x)+\int_{0}^{x}2tg(t)\left[
f^{\prime }(t)\right] ^{2}dt=f^{2}(0)+\left( f^{\prime }\right) ^{2}(0),\
\ \ \ for\ all\ x\in
\mathbb{R}
$$ Assume that $f$ is not bounded on $\left[ 0,+\infty \right) ,$ then there
exists a sequence $(x_{n})$ such that $\lim_{n\rightarrow \infty
}x_{n}=+\infty $ and $\lim_{n\rightarrow \infty }f^{2}(x_{n})=+\infty .$
Then, $\lim_{n\rightarrow \infty }f^{2}(x_{n})+\left( f^{\prime }\right)
^{2}(x_{n})=+\infty $ (because $f^{2}(x_{n})+\left( f^{\prime }\right)
^{2}(x_{n})\geq f^{2}(x_{n})\overset{n\rightarrow \infty }{\rightarrow }%
\infty $). Since the right hand side is constant, then we should have%
$$
\lim_{n\rightarrow \infty }\int_{0}^{x_{n}}2tg(t)\left[ f^{\prime }(t)\right]
^{2}dt=-\infty
$$
which is impossible since the integrand function is completely positive on $%
\left[ 0,+\infty \right) .$ It follows that $f$ is bounded on $\left[
0,+\infty \right) .$ The same idea allows one to show that $f$ is bounded on
$\left( -\infty ,0\right] .$ In fact,
Assume that $f$ is not bounded on $\left( -\infty ,0\right] ,$ then there
exists a sequence $(x_{n})$ such that $\lim_{n\rightarrow \infty
}x_{n}=-\infty $ and $\lim_{n\rightarrow \infty }f^{2}(x_{n})=+\infty .$
Then, $\lim_{n\rightarrow \infty }f^{2}(x_{n})+\left( f^{\prime }\right)
^{2}(x_{n})=+\infty $ (because $f^{2}(x_{n})+\left( f^{\prime }\right)
^{2}(x_{n})\geq f^{2}(x_{n})\overset{n\rightarrow \infty }{\rightarrow }%
\infty $). Since the right hand side is constant, then we should have%
$$
-\infty =\lim_{n\rightarrow \infty }\int_{0}^{x_{n}}2tg(t)\left[ f^{\prime
}(t)\right] ^{2}dt=-\lim_{n\rightarrow \infty }\int_{x_{n}}^{0}2tg(t)\left[
f^{\prime }(t)\right] ^{2}dt
$$
then%
$$
\lim_{n\rightarrow \infty }\int_{x_{n}}^{0}2tg(t)\left[ f^{\prime }(t)\right]
^{2}dt=+\infty
$$
which is impossible since ($x_{n}<0)$ and the integrand function is
completely negative on $\left( -\infty ,0\right] $ (there is $t$ inside). It
follows that $f$ is bounded on $\left( -\infty ,0\right] .$ Therefore, $f$
is bounded on the whole $
\mathbb{R}$
Comment: Do we have to use Integration ??
Comment: NO integration ! You have only to know that the integral of a positive function is a positive number, with no integral calculation. If it looks long, it is because it includes all the details, otherwise it is only two or three lines....
Comment: This argument, as does mine, uses integration in the most abstract sense--fundamental theorem of calculus, integral of a positive function is positive, etc.  No nasty integrals to evaluate, however!
Answer: Given that
$f(x)+f''(x)=-xg(x)f'(x), \tag{1}$
we may multiply through by $f'(x)$:
$f(x)f'(x) + f'(x)f''(x) = -x g(x) (f'(x))^2, \tag{2}$
and since
$\dfrac{1}{2}((f(x))^2 + (f'(x))^2)' = f(x)f'(x) + f'(x)f''(x), \tag{3}$
(2) becomes
$\dfrac{1}{2}((f(x))^2 + (f'(x))^2)' = -x g(x) (f'(x))^2. \tag{4}$
Taking $x \ge 0$ for the moment, we may integrate (4) 'twixt $0$ and $x$, thusly:
$\dfrac{1}{2}((f(x))^2 + (f'(x))^2) - \dfrac{1}{2}((f(0))^2 + (f'(0))^2) = \dfrac{1}{2}\int_0^x ((f(s))^2 + (f'(s))^2)' ds$
$=  -\int_0^x s g(s) (f'(s))^2 ds, \tag{5}$
or
$\dfrac{1}{2}((f(x))^2 + (f'(x))^2) = \dfrac{1}{2}((f(0))^2 + (f'(0))^2) - \int_0^x s g(s) (f'(s))^2 ds. \tag{6}$
It will be observed that, for $s \ge 0$, $s g(s) (f'(s))^2 \ge 0$, whence
$\int_0^x s g(s) (f'(s))^2 ds \ge 0, \tag{7}$
and so from (6) and (7) we have
$\dfrac{1}{2}((f(x))^2 + (f'(x))^2) = \dfrac{1}{2}((f(0))^2 + (f'(0))^2) - \int_0^x s g(s) (f'(s))^2 ds \le \dfrac{1}{2}((f(0))^2 + (f'(0))^2); \tag{8}$
indeed, since $(f(x))^2 + (f'(x))^2 \ge 0$, we may write
$0 \le \dfrac{1}{2}((f(x))^2 + (f'(x))^2) = \dfrac{1}{2}((f(0))^2 + (f'(0))^2) - \int_0^x s g(s) (f'(s))^2 ds \le \dfrac{1}{2}((f(0))^2 + (f'(0))^2), \tag{9}$
for all $x \ge 0$.  Thus
$0 \le (f(x))^2 \le (f(x))^2 + (f'(x))^2 \le (f(0))^2 + (f'(0))^2, \tag{10}$
showing $f(x)$ is bounded for $x \ge 0$; indeed,
$\vert f(x) \vert \le \sqrt{f(0))^2 + (f'(0))^2} \tag{11}$
for all non-negative $x$.  For $x \le 0$, we integrate from $x$ to $0$, viz.,
$\dfrac{1}{2}((f(0))^2 + (f'(0))^2) - \dfrac{1}{2}((f(x))^2 + (f'(x))^2) =  -\int_x^0 s g(s) (f'(s))^2 ds; \tag{12}$
re-arranging:
$\dfrac{1}{2}((f(x))^2 + (f'(x))^2) = \dfrac{1}{2}((f(0))^2 + (f'(0))^2) + \int_x^0 s g(s) (f'(s))^2 ds; \tag{13}$
for $s \le 0$, $s g(s) (f'(s))^2 \le 0$, whence $\int_x^0 sg(s)(f'(s))^2 ds \le 0$ and we again conclude
$0 \le \dfrac{1}{2}((f(x))^2 + (f'(x))^2) \le  \dfrac{1}{2}((f(0))^2 + (f'(0))^2), \tag{14}$
which as before leads to the conclusion that
$\vert f(x) \vert \le \sqrt{(f(0))^2 + (f'(0))^2} \tag{15}$
for all $x \le 0$ as well.  $f(x)$ is bounded by $\sqrt{(f(0))^2 + (f'(0))^2}$ for all $x$.
Hope this helps.  Cheers,
and as ever,
Fiat Lux!!!
Comment: @user123733:  by "LMVT" you mean some form of the mean value theorem, right?  I guess such a proof could be constructed; it's just that I'm more familiar with integration-based techniques so that's what first popped into my mind, and so I went with it!  But I must say this is a very nice question!  Cheers!
Comment: Since since $-xg(x)(f'(x))^2$ is non-positive for non-negative $x$ and non-negative for non-positive $x$ , from $((f(x))^2+(f'(x))^2)'=-2xg(x)(f'(x))^2$ I think we can at once say  $(f(x))^2+(f'(x))^2 \le (f(0))^2+(f'(0))^2$ for any $x$
Comment: If you say that, which is OK with me, you are, if I am not mistaken, using assertions like: if $f'(x) < 0$ for all $x \ge x_0$, then $f(x) \le f(x_0)$ for all $x \ge x_0$.  Well, how do you prove that?  I think the argument based on elementary integration is the easiest way.  Otherwise, you have to set up a more delicate argument using the definition of derivative and limits, if I am not mistaken.  I just though using integrals was easier.  Why not use arguments based on integrals?   Integrals are ***good***; nicer than derivatives.  Anyway, I see your point . .  . I think.  Cheers!
Comment: Actually you know I learned derivatives first , so it's kinda habit to use LMVT and all those when you can but off-course I am not saying Integrals are not okay :)
Answer: @user123733, You are right, it is possible to avoid completly the intergration. Here is an answer using your the idea in your comment which uses only
derivatives from Calculus 1.
Multiply the equation
\begin{equation*}
f(x)+f^{\prime \prime }(x)+xg(x)f^{\prime }(x)=0,\ x\in
\mathbb{R}
\end{equation*}
by $2f^{\prime }(x)$, we get
\begin{equation*}
2f(x)f^{\prime }(x)+2f^{\prime }(x)f^{\prime \prime }(x)+2xg(x)\left[
f^{\prime }(x)\right] ^{2}=0,\ \ \ \ for\ all\ x\in
%TCIMACRO{\U{211d} }
%BeginExpansion
\mathbb{R}
%EndExpansion
.
\end{equation*}
Then
\begin{equation*}
\left[ f^{2}(x)\right] ^{\prime }+\left[ \left( f^{\prime }\right) ^{2}(x)%
\right] ^{\prime }+2xg(x)\left[ f^{\prime }(x)\right] ^{2}=0,\ \ \ \ for\
all\ x\in
%TCIMACRO{\U{211d} }%
%BeginExpansion
\mathbb{R}
%EndExpansion
.
\end{equation*}
So,
\begin{equation*}
\left[ f^{2}(x)+\left( f^{\prime }\right) ^{2}(x)\right] ^{\prime }=-2xg(x)%
\left[ f^{\prime }(x)\right] ^{2},\ \ \ \ for\ all\ x\in
%TCIMACRO{\U{211d} }%
%BeginExpansion
\mathbb{R}
%EndExpansion
.
\end{equation*}
it follows that the derivative of the function definied by
\begin{equation*}
h(x)=f^{2}(x)+\left( f^{\prime }\right) ^{2}(x),\ for\ all\ x\in
%TCIMACRO{\U{211d} }
%BeginExpansion
\mathbb{R}
%EndExpansion
\end{equation*}
is of opposit $x^{\prime }s$ sign$;$ it is nonnegative for $x<0$ and
nonpositive for $x>0.$ This implies that the function $h$ is increasing in
the interval $\left( -\infty ,0\right) $ and is decreasing in the interval $%
\left( 0,+\infty \right) .$ Therefore, it admits a unique absolut maximum value at $x=0$
So,
\begin{equation*}
h(x)\leq h(0),\ for\ all\ x\in
%TCIMACRO{\U{211d} }
%BeginExpansion
\mathbb{R}
%EndExpansion%
\end{equation*}
so
\begin{equation*}
f^{2}(x)+\left( f^{\prime }(x)\right) ^{2}\leq f^{2}(0)+\left( f^{\prime
}(0)\right) ^{2},\ \ \ \ for\ \ all\ x\in
%TCIMACRO{\U{211d} }%
%BeginExpansion
\mathbb{R}
%EndExpansion%
\end{equation*}
but,  $\left( f^{\prime }(x)\right) ^{2}\geq 0,$ for all $\ x\in
%TCIMACRO{\U{211d} }%
%BeginExpansion%
\mathbb{R}
%EndExpansion%
,$ then
\begin{equation*}
f^{2}(x)\leq f^{2}(x)+\left( f^{\prime }(x)\right) ^{2},\ \ \ \ for\ \ all\
x\in
%TCIMACRO{\U{211d} }
%BeginExpansion%
\mathbb{R}
%EndExpansion%
\end{equation*}
therefore
\begin{equation*}
f^{2}(x)\leq f^{2}(0)+\left( f^{\prime }(0)\right) ^{2},\ \ \ \ for\ \ all\
x\in
%TCIMACRO{\U{211d} }%
%BeginExpansion
\mathbb{R}
%EndExpansion%
\end{equation*}
which implies that
\begin{equation*}
\left\vert f(x)\right\vert \leq \sqrt{f^{2}(0)+\left( f^{\prime }(0)\right)
^{2}},\ \ \ \ for\ \ all\ x\in
%TCIMACRO{\U{211d} }
%BeginExpansion
\mathbb{R}
%EndExpansion%
.
\end{equation*}
The proof that $f$ is bounded on $
%TCIMACRO{\U{211d} }
%BeginExpansion
\mathbb{R}%
%EndExpansion%
$ is complete.


Statistical analysis of two same experimental measurements

Question: Say I have two blood samples (Sample A and Sample B).
Now, I want to do a measurement (dependent variable, let's call it D) on both samples, at 5 different levels of mechanical stress (independent variable, let's call it I). However, since some calculations is involved to get D and I, and also since the devices have some uncertainty, both dependent and independent variables are reported as: I+/-U1   and  D+/-U2, where U1 and U2 are the total uncertainties for independent and dependent variables, respectively.
U1 is composed of device uncertainty only (which is actually the error propagation).
U2 is composed of device uncertainty and repeated measurement uncertainty.
Say, we want to do 10 measurements at each of the 5 different stress levels (for both samples A and B).
Note that, when I plot D vs. I, there will be both vertical and horizontal bars for the uncertainty.
Now, I want to see if the difference between D in sample A is significantly different than that in the sample B at each stress level.
What kind of statistical test should I use?
Regards,
Answer: This problem is unsolvable, unless you can make some prior assumptions. You need to know

The probability distributions of your measurement and device uncertainties
If these distributions are independent, or otherwise, what exactly the dependence relation is

If you can assume the most simple case, namely

Both distributions are normal, where $U_1$ and $U_2$ are standard deviations of the distributions
The probability distributions are independent

Then you could use chi-squared test to determine if your data is likely under the assumption that both samples $A$ and $B$ share the same mean. Namely, you would compute
$$
\chi^2 =
\bigl(\frac{I_A - \mu_I}{U_{1A}}\bigr)^2
+ \bigl(\frac{I_B - \mu_I}{U_{1B}}\bigr)^2
+ \bigl(\frac{D_A - \mu_D}{U_{2A}}\bigr)^2
+ \bigl(\frac{D_B - \mu_D}{U_{2B}}\bigr)^2
$$
then find the $\mu_I$, and $\mu_D$ that minimize the above expression and plug them back into the expression for $\chi^2$. Finally, the resulting expression can be compared with the tabulated value for $\chi^2$ of dimension $2$ to determine the p-value.
Comment: Thanks for the info! How can I know if the device uncertainty has normal distribution?
Comment: And also how I know the distributions are independent?
Comment: The easiest way to check is to measure D and I for one and the same sample like 100 times and plot the marginal and joint probability distributions of D and I. If the joint distribution is equal to the product of the marginal distributions, then they are independent, otherwise not. Also, you can directly compare your marginal distributions to gaussian distributions and see how well they match. Then, I would repeat the same process of measuring a few different samples like 100 times each. This is necessary because errors could be dependent on the mean values of D and I
Comment: You don't have to do this procedure every time you measure D and I, it is only necessary to determine the probability distribution of errors and calculate U1 and U2. Afterwards a single measurement per sample might be sufficient, if your errors are not too large. Also, the number 100 I said is arbitrary, it depends on how confident you want to be on in your conclusions


Xamarin tem alguma limitação para criação de APP para Android

Question: Estou começando a estudar programação mobile, especificamente Android no momento, e estou com uma dúvida.
Comecei a estudar o Android Studio que usa a linguagem JAVA, mas é possível desenvolver também para Android utilizando o Visual Studio com Xamarin e a linguagem C# (IDE e linguagem que já tenho uma experiencia boa).
Aplicação criada com Xamarin tem alguma limitação técnica? Alguma limitação de versão de Android ou algo que seja diferente de um app criado com Android Studio?
Obrigado a todos.
Comment: Deve usar o Xamarin, claro. De qualquer forma não dá para comparar as duas coisas, afinal Xamarin é uma tecnologia, Android Studo é um IDE. http://pt.stackoverflow.com/q/101691/101 Se a pergunta for reformulada não pedindo opiniões ou comparações amplas e de coisas não comparáveis, dá para reabrir.
Comment: Obrigado pelo feedback, alterei a pergunta, espero que tenha ficado adequada. E obrigado também pela resposta.
Comment: Não, continua pedindo uma opinião. Respostas puramente opinativas não são permitidas já que elas não ajudam ninguém de fato. Eu dei minha opinião como comentário. Se você acha que deve tomar uma decisão de vida baseado no que uma pessoa aleatória na internet que não te conhece disse, aí é algo que só você pode decidir se é bom. Mas o sistema não foi criado para suportar respostas oficiais sobre isso.
Comment: Não estou tomando decisão de vida baseado em alguém aleatório da internet. Estou procurando pessoas que estão na área e saibam sobre o assunto (que pra mim é totalmente novo) e que me mostram alguns pontos sobre as tecnologias em questão para então eu ter o que pesquisar a respeito e tirar minha conclusão. Mas entendo completamente que se esta não é o sistema correto para fazer isso meu post deve ser removido. Peço desculpas por ter postado minha questão na plataforma sem ter lido atentamente os termos.
Comment: Por isso que perguntas baseadas em opiniões não são permitidas aqui. A pessoas acham exatamente o que você acha, que as opiniões postadas aqui vão ajudar, mas elas não vão. As pessoas experientes sabem disto. As iniciantes ainda não perceberam como isso não ajuda. Perguntas mais objetivas ou que tenha um pequeno grau de subjetividade podem ser feitas, essa não pode ser respondida, pelo menos na forma atual. Ainda é possível reformular para salvá-la. Pode ler a [help] para ver se te ajuda. Ou ainda: http://meta.pt.stackoverflow.com/q/486/101 ou http://meta.pt.stackoverflow.com/q/488/101
Comment: Entendi completamente a questão. Dei uma modificada na pergunta, veja se ela esta adequada agora. Obrigado pelo toque.
Comment: Reabri, vamos ver o que a comunidade acha e se podem responder.
Answer: Sua pergunta é muito importante para entendimento do Xamarin.
Muitos acreditam que a plataforma Xamarin não seja nativa, ai que eles se enganam, pois Xamarin é nativo, sendo possível realizar absolutamente tudo que você faria em Android Studio.
Exemplo: Se uma API especifica, como por exemplo, câmera, possuir um problema, esse mesmo problema reproduzido no Android Studio(Java) será reproduzido no Xamarin(C# ou F#), pois ambos utilizam o NDK para acessar as api's nativas.
Lembrando que será necessária uma curva de aprendizagem para desenvolver aplicações Mobile, porém, uma vez já familiarizado com a linguagem, tende a ser menor essa curva.
Espero ter exclarecido sua dúvida.
Comment: Legal, muito obrigado pela resposta. Era isso que queria saber, se tem diferença utilizando um ou outro, mas pelo visto não.
Estou entrando de férias mês que vem da faculdade e começarei a estudar xamarin.


PRACTICE Script To Quickly Halt CPU

Question: I am trying write a script to halt CPU right after powerup (for example we install a faulty code to flash of S32K144 device and make the chip stuck in reset. Other than the basic functions like SYSTEM.UP, BREAK, SYSTEM.MODE.ATTACH , is there any other way to stop the CPU before it executes the main function. I have come across a Lauterbach reference about GLOBALON event, such as POWERUP and POWERDOWN. If there is possible way, please provide kind guidance  and example on the creating the script for halt command repeatedly before it go main function. based on the info from the pdf.
I have tried the execution using demo script given by Lauterbach on LCP1768 on board MCB1700.
This is my script:
<code>  SYStem.RESet
  SYStem.CPU LPC1768
  SYStem.CONFIG SWDP    ON
  SYStem.Option EnReset OFF
IF UTRACE()||COMBIPROBE()
(
  SYStem.CONFIG.CONNECTOR MIPI20T
)
  SYStem.up

; Load the demo code into the SRAM
  Data.LOAD.Elf ~~~~/demo.axf
  symbol.sourcepath.set C:\T32\demo\arm\compiler\gnu\src
  Register.Set PC 0x10000748
  Register.Set R13 0x10005000

  IF hardware.COMBIPROBE()||hardware.UTRACE()
  (
    ; Enable Trace
    Data.Set 0x4002C028 %Long 0x00000008

    ETM.ON
    ITM.ON

    ETM.PortMode Continuous
    ETM.PortSize 4.

    Trace.METHOD CAnalyzer   ; Using CombiProbe
    Trace.OFF                ; Enable the trace and turn it off
  )

ENDDO`
</code>
Answer: If it will have success depends a little bit on the used hardware. There isn't yet native support for your use case inside the debugger, but the PRACTICE script language should be fine to solve it.
The idea is to keep the board in reset after power up and let the debugger automatically execute a SYStem.Up. This will let the debugger connect to the core and halt it without having any code being exectuted on it:
<code>// System settings
RESet
SYStem.CPU S32K144
//... other system settings

// Make sure the board is powered down
IF STATE.POWER()
(
  PRINT "Power down the board!"
  WAIT !STATE.POWER()
)

// Keep reset asserted on the debug connector
JTAG.PIN ENable
JTAG.PIN NRESET Low

// Now the board can be powered again
PRINT "Power up the board!"
WAIT STATE.POWER()

// Connect to the core and stop on the reset vector
PRINT "Connecting..."
SYStem.Up

PRINT "Done!"

//... continue with the rest of the script

ENDDO
</code>
There exists hardware, that is not able to keep the reset being asserted during the power-up. This is for example the CombiProbe HS whisker. But if your board has a reset button, then you can keep it pressed while powered down and realease it after power up as soon as "Connecting..." is shown inside the status line of the debugger.
The sequence should work on other controllers, too. I could not test the LPC1768 itself, because I currently do not have access to a board like this.
Best Regards,
Steffen.

PRACTICE Script To Quickly Halt CPU


Command line, problems after the last windows update (1903)

Question: enter image description hereIt has always worked but now it has stopped.
Maybe there is a problem with java path.
I tried various solutions but I couldn't.
The problem emerged after formatting and reinstalling windows 10.
Without the command line everything works regularly
I installed weka 3.8(weka-3-8-3jre-x64.exe; 120.3 MB) on a new factory PC.(1903)
Same problem
thanks a lot
Comment: Is the typo in your classpath "%CLASPATH%" accidental?
Comment: to remove the doubt I tried in a new pc, with clean installation
Answer: See parallel discussion on the Weka mailing list:
https://email@example.com/thread/NSLPULS7EWNJDIJAH452S67CAHMJ5RGJ/
Answer: After your Windows/Weka reinstall, did you also reinstall the Weka package for libsvm?


Android set Service state

Question: I'm trying to turn off the android radio programmatically. I'm trying to use the ServiceState class, but it wont work. I added the permission CHANGE_NETWORK_STATE and MODIFY_PHONE_STATE. Still no luck. any ideas?
Comment: See http://stackoverflow.com/a/5533943/165674
Comment: Airplane mode will disable radio and wifi, i simple want to turn off just the radio
Answer: Permission MODIFY_PHONE_STATE is a system permission, thus, you cannot use it in your application.
EDIT:
Ok. I'll try to explain. The service method to turn on and turn off radio programatically is protected with MODIFY_PHONE_STATE permission. This permission has signature type, thus, only applications that have the same signature can invoke this method. Thus, so as your application is not signed with the system certificate you cannot use this permission in your application. But without this permission you also cannot change the state of the radio.
Comment: Not at all! I'm glad I could help you!

Android set Service state


haskell : How to report an error for my function

Question: this is an expansion to my last question here: basic haskell : Copying elements
however when an invalid input is added then I want it to print out an error message saying "negative value" or something similar. Is this possible in haskell?
working code:
copy :: Int->a->[a]
copy 0 _ = []
copy y a = [a]++(copy (y-1) a)

final line:
copy b c  = error "negative value"

Comment: Define "invalid input". (Also, the answer to the only actual question you asked is "yes".)
Comment: Calling `error` will abort your program with the error message, which is probably not what you want. You'll need to encode the error in the function's return type (ie: `Either String [a]` or `Maybe [a]`), and then check for a `Left err` or `Nothing` respectively in the function that calls `copy`.
Answer: Because partial functions make me sad, I'd suggest doing something more along the lines of
copy :: Int -> a -> Maybe [a]
copy 0 _ = Just []
copy n a | n < 0 = Nothing
         | otherwise = fmap (a:) (copy (n-1) a)

We've swapped out that if for a "guard"
foo bar | baz = quux
        | ...

is just
 foo bar = if baz then quux else ...

Note that I also changed your code a little,
 [a] ++ copy (y-1) a ====> fmap (a:)  (copy (y-1) a)

You can think of (:) as append.
 1 : [2, 3] ==> [1, 2, 3]

It's the preferred alternative to [1] ++ [2, 3]. Say it out loud as "cons", like "construct". We can write this with an operator section
(a:) ==> \x -> a : x

Next we use this wonky fmap function. Think of fmap like this
fmap f Nothing = Nothing
fmap f (Just x) = Just (f x)

So it unwraps a Just and applies a function before rewrapping the result. So our final code returns Nothing if our number is negative, otherwise, just the list.
Why aren't I recommending error? Well because error will blow up your whole program with pretty minimal information and it's a bad idea to try to catch it. Haskell doesn't even mandate that it's possible to do so, GHC just implements error in such a way that it's possible. In other words, you have little chance to recover.
This isn't a big deal for 10 lines of code, but I've spent upwards of 6 hours searching for the offending call to a function using error. It's much faster to debug and more idiomatic haskell.
Comment: +1 For the newbie-friendly step by step explanation.
Answer: You can do this with guards
copy :: Int -> a -> [a]
copy n x
    | n < 0 = error "negative value"
    | n == 0 = []
    | otherwise = x : copy (n - 1) x

However, if this fails then it will likely crash your program.  A better way is to use the Maybe type:
copySafe :: Int -> a -> Maybe [a]
copySafe n x
    | n < 0 = Nothing
    | otherwise = Just (copy n x)

Then you can use it as
main = do
    putStrLn "Enter a number:"
    nStr <- getLine
    let n = read nStr :: Int
        maybeXs = copySafe n n
    case maybeXs of
        Nothing -> putStrLn "You entered a negative number!"
        Just xs -> print xs

This style forces you to consider both cases of copySafe, either it can fail on a negative value or it can return a valid list.  It doesn't crash your program and the error handling is enforced by the type system.
Comment: I'd suggest defining `copy` in terms of `copySafe`, rather than the other way round.
Comment: @LambdaFairy I would too, but I wanted to stay away from `fmap` in this example.
Answer: look at http://www.haskell.org/haskellwiki/Error_vs._Exception
for example
copy b c = if c > b then error "negativ value"

Comment: I don't understand why this is the accepted answer. The example isn't valid syntax; and `b` and `c`, which are different types, cannot be compared with each other.
Comment: Note that the `else` part of the `if` expression is not optional. Also, you should use `c :` rather than `[c] ++`.
Comment: @LambdaFairy and 'negative' is spelled incorrectly for christ's sake


C# Sql Client: ALTER Table doesn't work

Question: I have a code that is used to add some lines to SQL but it won't work. Select and Delete are working but not the ALTER TABLE command.
If I copy and paste just my console output into Microsoft Management Sql Query, it works. (tmp1 gets filled with some Name, tmp2 gets filled for Example CHAR(50))
Edit: I dont get any Error, in the logs of my SQL server i dont see any command called "Alter" to be excuted.
 string tmp1, tmp2;
 tmp1 = addfrm.getTableName();
 tmp2 = addfrm.getType();

 string constring = @"Data Source=" + adr + ";Initial Catalog=" + dat + ";User ID=" + user + ";Password=" + pwd;
 try
 {
     using (SqlConnection con = new SqlConnection(constring))
     {
         string tmp = @"ALTER TABLE " + tbl + " ADD " + tmp1 + " " + tmp2;
         Console.WriteLine("Mein Befehl lautet: " + tmp);

         using (SqlCommand cmd = new SqlCommand(tmp, con))
         {
             cmd.CommandType = CommandType.Text;
             using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
             {
             }
         }
     }
 }

 catch (SqlException)
 {
     MessageBox.Show("Fehler");
 }

Comment: What error you are getting? Post your error as well.
Comment: This command sounds like you are trying to add some columns to the table not to add lines.
Comment: You never executed SQL Query to database. Use `ExecuteNonQuery` on `SqlCommand`.
Comment: Make sure your application have a permission to alter the table and please post error message as comment above suggested.
Comment: @Damien_The_Unbeliever let me edit back to `SQL`
Answer: You don't send SQL query to database. Use ExecuteNonQuery on SqlCommand. Instead of:
using (SqlCommand cmd = new SqlCommand(tmp, con))
{
    cmd.CommandType = CommandType.Text;
    using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
    {

    }
}

use
using (SqlCommand cmd = new SqlCommand(tmp, con))
{
    cmd.ExecuteNonQuery();
}

Adapter will not execute query until adapter.Fill is called.
Comment: Can you also explain why it will not work with `SqlDataAdapter`. Is there any changes can be done, so that it works with `SqlDataAdapter `
Comment: `SqlDataAdapter` is intended to work with CRUD operations. No need to use it when DDL is performed.
Comment: It dosent do anything for me. I dont get any errors or Exception.
Comment: What do you expect as return value? `ALTER TABLE [Tab] ADD [Col] [Type]` syntax just adds column. No rows are returned.
Comment: No, it should just add it but it wont do it. Only over sql management with same command it works. After he is finished with adding he starts the BindGrid Method where he gets the table out database and binds it again on the datagriedview.
Answer: You are not setting the values properly. Try this it should work.
string tmp1, tmp2;
                tmp1 = addfrm.getTableName();
                tmp2 = addfrm.getType();

                string constring = @"Data Source=" + adr + ";Initial Catalog=" + dat + ";User ID=" + user + ";Password=" + pwd;
                try
                {
                    using (SqlConnection con = new SqlConnection(constring))
                    {
                        string tmp = @"UPDATE TABLE " + tbl + " SET Col1 = '" + temp1 +"',Col2='" + tmp2 +"'";

                        Console.WriteLine("Mein Befehl lautet: " + tmp);

                        using (SqlCommand cmd = new SqlCommand(tmp, con))
                        {
                            cmd.CommandType = CommandType.Text;
                            using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
                            {
    cmd.ExecuteNonQuery();
                            }
                        }
                    }
                }
                catch (SqlException) { MessageBox.Show("Fehler"); }

Comment: That didnt worked :/ same result for me (you forget + and wrote temp, i fixed that hope thats okay)
Comment: should be UPDATE  rather than alter i have updated the answer please check now.
Comment: Now he has some problems with ur Excute NonQuerry. The programm stops with error that the connections is still closed.
I tried to open it with con.Open(); and closed it afer the sqlnonquerry but that i get a SQL Exception with "System.Data.SqlClient.SqlException" in System.Data.dll.
Answer: i just avoided it now with Fill. Its bit messy but ok. Thanks to Pawel who said it.
                            using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
                        {
                            DataTable dt = new DataTable();
                            sda.Fill(dt);
                        }

C# Sql Client: ALTER Table doesn't work


What is meant by "scale" in the 2008 t-SNE paper?

Question: I am trying to understand the use of the term "scale" in the 2008 van der Maaten and Hinton t-sne paper.
I'm not sure I exactly understand what they mean by their use of the term "scale", for example - when they say the t-sne map

reveals structure at many different scales.

Is this term used in the same sense when they also talk about the crowding problem and discuss data in 2D that may be linear on a small scale, but are embedded in a higher D space?
Does "scales" have the same meaning in this sentence?

The volume of a sphere centered on datapoint $i$ scales as $r^m$, where $r$ is the radius and $m$ the dimensionality of the sphere.

I'm a psychometrician by training and I'm wondering if what I think of as scale may not correspond to what computer scientists mean by scale.
Answer: Different scales in this case is referring to different orders of magnitude. During dimensionality reduction, t-SNE tries to conserves structure you would see looking at the data on a high level, but at the same time tries to keep structures that only appear if you would "zoom in".
Consider for example two clusters of points in 3D space:
When reducing to 2D, t-SNE would keep the circle structure of the elements in the second cluster, while separating the two main clusters as well. This is a trivial example but the same would be true in higher dimensionality and much bigger differences of size between different structures.
The second meaning is different. Here it means "how fast does it grow", in reference to big O notation:

Big O notation characterizes functions according to their growth rates: different functions with the same growth rate may be represented using the same O notation.


Parsing every file in a directory in python?

Question: So I have this code:
import xml.etree.ElementTree as ET
tree = ET.parse('test.xml')
root = tree.getroot()

for segment in root.iter("s"):
    for word in segment.iter("w"):
        print word.text,
    print "\n"

That will parse the xml file test.xml and print the parsed output. However, I have a huge number of these xml files that need parsing in a directory. How can I modify the code so that it goes through every file in the directory and applies this function to it?
Thanks!
Answer: This should work:
def printParsed(filename):
    tree = ET.parse(filename)
    root = tree.getroot()

    for segment in root.iter("s"):
        for word in segment.iter("w"):
            print word.text,
        print "\n"

if __name__ == "__main__":
    from os import listdir
    from os.path import isfile, join
    mypath ='path/to/your/xml/files'
    onlyfiles = [ f for f in listdir(mypath) if isfile(join(mypath,f)) ]
    for f in onlyfiles:
        # only does stuff if the file ends in xml
        if f[-3:] = '.xml':
            printParsed(f)

You would save the file, say as parser.py, and then run it like python parser.py. You can also drop the if __name__ == "__main__" section if you want.
Comment: When I run this, I get the following: `Traceback (most recent call last):
  File "xmlparse.py", line 20, in
    printParsed(f)
  File "xmlparse.py", line 6, in printParsed
    tree = ET.parse(name)
NameError: global name 'name' is not defined
O` I removed the `if f[-3:] =  '.xml' ": ` line because all the files are xml anyway.
Answer: Use os.listdir(path)
It returns a list of all files in the dir.
Code:
import xml.etree.ElementTree as ET
import os
listofxml = os.listdir("./")
    for xml in listofxml:
        tree = ET.parse(xml)
        root = tree.getroot()

        for segment in root.iter("s"):
                for word in segment.iter("w"):
                        print word.text,
                print "\n"

And if not all the files are xml, then you can split and check:
import xml.etree.ElementTree as ET
import os
listofxml = os.listdir("./")
    for xml in listofxml:
        format = xml.split('.')
        if format[-1] == 'xml':
            tree = ET.parse(xml)
            root = tree.getroot()

            for segment in root.iter("s"):
                    for word in segment.iter("w"):
                            print word.text,
                    print "\n"


How to keep rhythm

Question: I was taught to tap my foot when counting the notes, so an 8th note would become a tap to the ground, and a 4th note goes to the ground and back again.
However I seem to get confused when encountering a group of complex notes. For instance I will lose my rhythm when playing an 8th (quaver) and a half note followed by two sixteenth notes (semiquaver), as my foot would need to go down to the ground then back to half it's original position then up and back at the middle.
If I play on my own I will eventually master it by setting the tempo gradually, however I recently joined an orchestra and sometimes it's hard to be in sync with all the other guys.
I have also found that if I am tapping my hands or playing and become aware of myself counting the rhythm I will almost immediately make a mistake.
Some have told me to learn the melody and then intuitively play it, however my teacher has told me it is a bad practice.
I am an intermediate player
Is there a better way to count rhythm?
Comment: Please ask your teacher why it's bad practice. The ears are as important as the eyes. Not everything is written down.
Comment: Though he was and no longer is my teacher, his reasoning was that by learning the melody you are then playing from memory and if the conductor or someone else introduces changes to the piece, like for instance: Changes in tempo, or you otherwise learn it erroneously you will have to relearn it and break out of the habit of playing the piece as you do, so you are much slower to respond to changes.
Comment: Fair enough, except that I dep quite frequently, and have to play the same piece at different tempos with different bands, different arrangements - some to read, others to busk, and the response time has to be counted in nanoseconds. You can't go onto autopilot, you have to think on your feet. It ain't easy, but it certainly keeps you on your toes ! I guess the rhythm/tempo for a piece just has to get locked into yourself somehow, probably it's down to experience. And there's only one way to get that !!
Comment: I agree with your teacher,. Anyone else you play with will likely be counting the notes exactly and your "intuitive" playing of the piece may not be right. Once you've committed it to muscle memory its hard to change to fit in with others. I have the same issue as you and the only solution that works for me is to play the part very slowly and exactly, carefully making sure timing is exactly right and without mistakes. Then speed it up gradually.
Answer: The approach you are using now is to learn play the rhythm by seeing it visually. You can also come at the problem from the other direction: learn to play the rhythm by ear, then learn what that pattern looks like on the page. For me, the second approach is much, much easier for complex or off-beat rhythms.

Find or make a recording of the challenging section. Your teacher
should be able to help you with this. I often ask my teacher to play
bits I'm struggling with, and record them on my phone. If she can
tap out the beats loudly enough the be heard on the recording, it
might make things easier.
Put away the sheet music.
Tap along to the recording. Tap out the main beats, not the
    actual rhythm being played.
Now that you know where the beats are, start speaking along in
    the rhythm you're trying to play. Just say da-da-da rather than
    trying to match the notes on the staff.
At this point, the rhythm should be in your head. Take the sheet
    music back out, and see if you can play it. Try to match up the
    rhythm in your head to the rhythm on the page: that way, if you run
    into a rhythm like that again, you'll know both what it looks like,
    and what it sounds like.

I'm not sure what you mean when you say "intuitively" play, but if you mean learning to play by listening, rather than reading, there is nothing intrinsically wrong with that approach. It is an extremely valuable skill that will allow you to play a much larger body of music than if you limit yourself exclusively to sheet music. But being able to both read music and learn it by ear will give you more available music than either approach along.  If you're teacher is arguing against it, it is probably because she works in classical music, where reading sheet music is just as important as playing it. It's worth learning to do well, because it's a skill you can use in any genre, but in other types of music, techniques like this one are equally common, because learning by ear is given more importance.
Answer: Your teacher was right. You do have to count. It is essential because as the music becomes more complex or more parts are added your ear can deceive you. I hate to say it but until you can read without tapping you are probably going to have to put yourself in beginner mode. I'm intimately familiar with this because I played the cello for 20 years, played with amateur orchestras and sort of read music, but I didn't know how to count. I started over with beginner books. So, get a sight reading book. Clap the rhythm before you try playing it and count out loud. Follow the counting guide that Ely suggested. I have also found some useful youtube videos for counting. When I search on youtube I usually will type "dotted eighth sixteenth", something specific like that will give good results. Take your time with each exercise. It's difficult and should be treated like a riddle. Maybe you can crack the piece by starting on an easier measure just to get a feel for the rhythm and then go back to the top.
Answer: Count each beat with your mouth. In a 4/4 measure you would say 1 2 3 4. For eighths, add an and (+) in between, counting 1 + 2 + 3 + 4 +. Then, add sixteenths. The second sixteenth is e and the fourth one is a, counting 1 e + a 2 e + a 3 e + a 4 e + a. Triplets are 1 + a 2 + a etc. For more complex tuplets, find a word with that number of syllables (hippopotamus is a good one for 5-tuplets). Count with the smallest denomination for each beat, and clap on each subdivision that the note falls on. Always practice with a metronome. Most digital ones come with functions that will play the subdivisions for you. When you practice, always count out loud. Eventually you will get good enough to where you don't have to, but if you ever cannot figure out a rhythm, count out loud again. As with everything in music, the best thing you can do is go slowly and practice often.

How to keep rhythm


adding up the elements from all of the nested lists

Question: I am  adding up the elements from all of the nested lists, so far what I have is

for i in range(len(b)) :
    for j in range(len(b[i])):
        total = total + b[i][j]

But this will not work when an integer value exists in the nested list like,
b = [[1,2], [3,4], [5,6], 1]

In this case i am getting an error message that object of type 'int' has no len().
what should i do in this case?
Comment: Does this answer your question? [sum of nested list in Python](https://stackoverflow.com/questions/14917092/sum-of-nested-list-in-python)
Answer: First of all, you are showing a common anti-pattern for Python programmers, don't loop over indices, loop over the objects themselves. E.g:
for item in b:
    do_something(item)

Rather than:
for i in range(len(b)):
    do_something(b[i])

It is clearer, simpler and faster.
That said, the main problem you are having is that one of the items isn't a list, so it doesn't have a length.
A better option here is to flatten the list with a generator expression and itertools.chain.from_iterable(), and then use the sum() builtin function to sum the elements.
>>> import collections
>>> import itertools
>>> b = [[1,2], [3,4], [5,6], 1]
>>> list(itertools.chain.from_iterable(item if isinstance(item, collections.Iterable) else [item] for item in b))
[1, 2, 3, 4, 5, 6, 1]
>>> sum(itertools.chain.from_iterable(item if isinstance(item, collections.Iterable) else [item] for item in b))
22

We need the generator expression as itertools.chain() won't handle non-iterable items, so we place any into a list to work around this.
An alternative would be to make your own generator:
def chain_mixed(iterable):
    for item in iterable:
        try:
            for subitem in item:
                yield subitem
        except TypeError:
            yield item

Then you could simply do:
sum(chain_mixed(b))

Comment: @Dan If you are new to list comps and generator expressions, I suggest you give [my tutorial video](https://www.youtube.com/watch?v=t85uBptTDYY) a watch.
Comment: Nicely done - I'd write it like that except I would use `item if isinstance(item, collections.Iterable) else [item]`
Comment: I am new in Python world so I didn't get half of your code, but Thanks a lot for marking anti pattern used by me and introducing me to generator expression and list comprehension :)
Comment: @JonClements Good idea, changed.
Comment: @Lattyware : Thanks a lot for the video tutorial.
Answer: try something like this,
use sum() only when the element is an list or tuple, else simple use the number.
>>> b = [[1,2], [3,4], [5,6], 1]
>>> sum(sum(x) if isinstance(x,(list,tuple)) else x for x in b)
22

improving your solution:
total=0
b = [[1,2], [3,4], [5,6], 1]
for i in range(len(b)) :
    if isinstance(b[i],(list,tuple)):
        for j in range(len(b[i])):
            total += b[i][j]
    else:
        total +=b[i]
print total  #prints 22

Comment: but it would still fail if there was another layer of lists in one of the sublists (ie `b= [[1,2,[1]],[3,4],[5,6],1]`)
Comment: @JoranBeasley as you can see from OP's approach he's only concerned with list of lists, not list of lists of lists.
Comment: @JoranBeasley That's a different problem. The question did not ask for arbitrarily nested lists and the solution given gives no indication of a need for such.
Comment: yeah I know I was just pointing it out... not saying it was incorrect or anything else( I gave both this and @Lattyware's solution +1)
Comment: Thanks Ashwini, isinstance() solves the problem. I should have remembered it at the very first place.
Comment: @ Joran, Thanks for adding one more level.
Comment: It's worth noting that checking `isinstance()` of the `tuple` and `list` classes is a bad idea as these are not the only iterables, making the solution less likely to work elsewhere. It's not wrong, but it's not as neat a solution, and, as type checking, it's unpythonic (for this reason).
Answer: a generator-based solution
>>> b = [[1,2], [3,4], [5,6], 1]
>>> def sum_up(x):
...     for i in x:
...             if isinstance(i, int):
...                     yield i
...             else:
...                     for j in sum_up(i):
...                             yield j
...
>>> sum(sum_up(b))
22
>>> b = [[1,2], [3,4], [5,6,[3,[6,7]]], 1]
>>> sum(sum_up(b))
38

Answer: one way to do it would be
def calc_sum(the_list):
    sum = 0
    for item in the_list:
        if isinstance(item,(list,tuple)):
           sum += calc_sum(item)
        else:
           sum += item
    return sum

not that pythonic ... but it should work
Answer: Another way to do this
This will work if the list contains nested list and integers/floats
Here I've used python inbuilt function 'sum' to add all the elements of a list
def add(nested_list):
    temp=[]
    for i in nested_list:
        if isinstance(i,list):
            temp.append(sum(i))
        else:
            temp.append(i)
    print sum(temp)


Sparse projection onto a single half-space

Question: Let $x \in \mathbb{R}^n$ and $0 \neq a \in \mathbb{R}^n$ be a given vector and $b$ be a scalar such that the half-space defined by $a^{\top}x \leq b$ always include $0$.
Question
1- Is there any relationship between $z=\arg\min_{a^{\top}v \leq b}\|v-x\|^2$ and
$y \in \text{Argmin}_{a^{\top}v \leq b \text{ and } \|v\|_0 \leq s} \|v-x\|^2$ for a given integer $1 \leq s < n$ where $\|v\|_0$ is the number of non-zero elements in $v$?
My try
I can write $z=x -\frac{a^{\top}x-b}{\|a\|^2}$. I can see from the picture that the sparse solution is either on the intersection of the hyperplane and the axis $y^{(2)}$ or just on the axis $y^{(1)}$ . If this is right, how can I rigorously show it? Is there any connection between my observation and $z$?
Answer: Let's call:
$H$ the hyperplane $a^{\top}x=b$,
$H^-$ the half-space $a^{\top}x \le b$,
$S$ the set $\{v, \|v\|_0 \le s \}$ for a given $s$. $S$ is the union of all vector subspaces generated by any $s$ principal axes among $n$; there are $n \choose s$ such subspaces.
(Note that $S(\text{for }s=1) \subset S(\text{for }s=2) \subset S(\text{for }s=3) \dots$).
So the question is to study $\arg\min_{v \in H^- \cap S} \|v-x\|^2$ and its relationship with $z = \arg\min_{v \in H^-} \|v-x\|^2$.
Define $p(x) = \arg\min_{v \in S} \|v-x\|^2$, i.e. projection of $x$ on the closest point in $S$, which may be one or more points. $p(x)$ is actually $x$ where its $s$ largest (in absolute value) coordinates have been kept and the other coordinates put to $0$.
Let's look at cases.
We could try distinguishing $x \in H^-$ (where $z=x$), from $x \notin H^-$, but it makes no real difference.
Now we distinguish between $p(x) \cap H^- \ne \emptyset$, and $p(x) \cap H^- = \emptyset$:

If $p(x) \cap H^- \ne \emptyset$, $\arg\min_{v \in H^- \cap S} = p(x) \cap H^-$ by definition of $p(x)$ (closest points of $S$ from $x$).
Your drawing is in this case.

If $p(x) \cap H^- = \emptyset$, let's decompose $S \cap H^-$.
$H^-$ is convex.
$S$ is the union of subspaces $C_k$, $k = 1 .. {n \choose s}$. Each of them is convex.
So $S \cap H^- = \bigcup_k (C_k \cap H^-)$ where each $C_k \cap H^-$ is convex.
So the closest point of $C_k \cap H^-$ from $x$ is unique. It is either$^{(*)}$ the orthogonal projection of $x$ on $C_k$, if it is inside $H^-$, or $C_k \cap H$, intersection of the hyperplane with $C_k$.
Then we take the closests of those points to get p(x).
(*) If the orthogonal projection of $x$ on $C_k$ (let's call it $w$) $\notin H^-$, then call $u$ the closest point of $C_k \cap H^-$ from $x$. In the 3-dim plane $P$ defined by $(x, w, u)$, $H$ separates $w$ from $u$ (as $w \notin H^-$ and $u \in H^-$). As $\|w-x\| < \|u-x\|$, and $\|w-x\|$ is minimum distance from $x$ of all points on line $w-u$, $u$ is on $H$ otherwise the point on $H$ would be closer to $x$ than $u$.

In this second case, it is possible that $\arg\min_{v \in H^- \cap S} \|v-x\|^2$ consists in more than one point, some of which are orthogonal projections of $x$ on some subspace $C_k$ of $S$ (and they are in $H^-$), some of which are on some $C_k \cap H$.
Example in $\mathbb R ^2$: $x=(3,5), a=(1,4), b=4, s=1$, closest points from $H^- \cap S$ to $x$ are $(0,1)$ on $H$ and $(3,0)$ inside $H^-$.
There is no significant relationship between $\arg\min_{v \in H^- \cap S} \|v-x\|^2$ and $z = \arg\min_{v \in H^-} \|v-x\|^2$, at least none that I see.
In the (rather simple) example above, $z=(\frac {32} {17}, \frac 9 {17})$ has no relationship with $(0,1)$ and $(3,0)$.


correlation of two features, which test?

Question: I have the following table as pandas dataframe with features feat1 and feat2:
testframe = pd.DataFrame(columns = ['feat1', 'feat2'])
testframe['feat1'] = [1,0,1,0,1,0,1,1,0,1]
testframe['feat2'] = [1,0,1,0,0,0,1,1,0,0]

where the index is the number of observation (e.g people).
I want to find out, if there are any correlation between feat1 and feat2. I thought about chi2, but I am not quite sure if it is applicable  in this case.
My real observation has the shape (43,2), so it is quite small I would say.
Are there any tests for correlation (or independency) you can recommend? If so, how would be the implementation in python?
I am happy for every hint on this!
Thanks!
Comment: A chi-squared test in this 2 by 2 table should work fine.
Answer: You can test for association between the two columns, so you build a contingency table like:
tab = pd.crosstab(testframe['feat1'],testframe['feat2'])
tab

feat2   0   1
feat1
   0    4   0
   1    2   4

If there is correlation between you two variables, the counts will populate the diagonal. Like @whuber suggested, you can first try chi-square test:
import pandas as pd
from scipy.stats import fisher_exact, chi2_contingency
chi2_contingency(tab)

(2.100694444444445,
 0.14723225536366139,
 1,
 array([[2.4, 1.6],
        [3.6, 2.4]]))

The first value is the chi-square statistic, 2nd is the p-value, degree of freedom and last is the table of expected values. If none of your expected counts is the array is < 5, you can use the chi-square.
In the situation some of the expected has <5, use a fisher test:
fisher_exact(tab)
(inf, 0.0761904761904761)

The first value is odds ratio (inf because you off diagonal gives 0), and the second is the p-value.
The manual for the test:
https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.chi2_contingency.html#scipy.stats.chi2_contingency
https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.fisher_exact.html