How to block parent without blocking child in ublock

Question: I want to be able to block everything on a page but a picture.
Example: https://imgur.com/gallery/wJIyDIF
@@||i.imgur.com/St95Jdv.jpg

imgur.com##.post-pad.left      < this overrides the previous line, order doesn't matter.

Ideally I would love something like this:
imgur.com##html

@@||i.imgur.com/St95Jdv.jpg

Or this:
imgur.com##html > body

@@||i.imgur.com/St95Jdv.jpg

But no idea how to actually make it work
Answer: Pretty sure, it is not possible. Every matching element is blocked with its children. Indeed, where would the children even be placed if their parent is hidden?
Your best hope is to block all siblings of the element you wish to keep...
Comment: I don't see why it wouldn't be possible. I'm looking to do the same thing, with something of the form "block all elements other than X, if its parent is Y", which would block almost everything within the parent, without blocking the parent itself.
Comment: True, but in the case when the parent is just a container for its children, the end result is the same. My point is, the original asker's question is slightly different from their intent; what I'm asking is probably what the original asker should be asking as well. So it's similar to "block all siblings of X" like you said, but with the added conditional of "only do so to instances of X which are children of Y".
Comment: That's different from the asker's question. You're not seeking to block the _parent_ -- you're seeking to block some of its other children -- siblings of the element you want kept.


fastest way to mirror a directory containing millions of small files

Question: I need to copy a 700G ISCSI mounted folder to a folder on the local hard drive, while maintaining the existing permissions and ownership.  The data in the folder consists of about a million mostly small files, and the new directory needs to exactly match the permissions and ownership of the original.
Using

rsync -az /original_folder/ /new_folder

gets all the permissions correct, but it has been over an hour "scanning for files", and has not even started coping over yet.  The data is openvz disk shares, and there have been permission problems in the past when they were copied over using "cp".
Is there a faster way to copy a huge number of small files while exactly preserving the permissions and ownership? Maybe some rsync flags that can avoid the initial scan?  Ideally a tool that can pick up where you left off if the process is interrupted.
Comment: not that you can change it at this moment, but i remember that moving from ext3 to xfs reduced the 'scanning for files' time on a 6TB volume from 23 minutes to less than 15 secs. (now it's at 17TB, and still less than 30secs for scanning)
Answer: Have you considered using tar? Something along the lines of tar -cpOC <sourcedir> . | tar -xpC <targetdir> -f - might do you.
Answer: What version are rsync are you using? Version 3 handles small files quite a bit better.  You can also use -P to get a sense for how far along you are.
As for recovering from partials.. hrm.  You could go into your root dir and run something like..

for i in * ; do rsync -azP $i /newfolder ; done

then skip any subdirs that you've already copied
Answer: In this situation you should probably try to duplicate the volume rather than trying to duplicate the individual files.
Does your iSCSI target have a way to clone the volume?
Answer: cp -aux (as root) should do the trick.


Can I use GhostDoc to add documentation to an entire class or code file?

Question: I love GhostDoc, but I want to be able to "Document This" for an entire file, and not just one member at a time.  Is this possible?
Comment: I did not re-install ghost doc on my recently acquired machine.  I tried it.  Didn't like it.  R# did a better job of "ghost writing" the generic comments AND they pass stylecop formatting.
Comment: You can actually do that now with GhostDoc Pro - it introduces Document File, Document Type commands and flexible T4 based comment templates
Comment: You can't use GhostDoc to add documentation, period. All it does is add pointless file size.
Answer: When I originally answered this question, this was not possible in GhostDoc, or in my (similar) addin, Atomineer Pro Documentation).
(This was an intentional design choice in Atomineer, and presumably also in GhostDoc, because it's a generally bad idea to document everything automatically and move on. Both these addins produce a reasonable starting point for documentation of a method, and sometimes they will provide good enough documentation that you don't need to make any adjustments - but most of the time you will want to tweak the resulting comment. If you auto-generate the entire documentation set, then the docs will be pretty poor, because they will do little more than describing what the code element names already state).
However, both addins now now provide this feature, which is very useful in the following situations:

(in Atomineer) To batch-convert legacy comments between JavaDoc, Doxygen, Qt and XML Documentation formats
(in Atomineer) To update the style/layout of documentation comments after changing the AtomineerUtils formatting options
(in both addins) To quickly add skeleton documentation to a class

In all these situations it is strongly recommended that you review the resulting comments, but automating the update does save a lot of time.
Comment: "sometimes they will provide good enough documentation that you don't need to make any adjustments"  Based on my experience using GhostDoc and using libraries "commented" with it, I think instead of *sometimes* you meant to say *never*.
Comment: Two things. 1) it IS possible in GhostDoc now, and 2) it would be good to state that you are the developer of AtomineerUtils
Comment: @ChaseFlorell - You're quite right on both counts. I normally do try to make that clear. I've edited mny answer to bring it up to date with recent developments.
Answer: No.  I still love it also regardless.
Comment: This is no longer correct. GhostDoc Pro has a 'Document File' menu option.
Answer: Use document File Option:

see the comment added for all members within the file:


call a function on an element with jQuery

Question: I need to call a function on a DOM element automatically. The following code works, but I wonder if there's a better way.
$('#toc > ul > li').first().find('a').each(loadTopic);

My selectors will return exactly one element, so running "each" seems hackish. Is there a better way to call 'loadTopic' on my anchor element?
Comment: with all respect, I don't think it should depend on my layout. The bottom line is that I want to select an element and call a function, not bound to any event (click, etc.). My selectors work. I just wonder if there's a better way.
Comment: It really depends on your HTML layout, but this isn't really the place for this type of question. [Try over here instead](http://codereview.stackexchange.com).
Comment: My point was simply, according to your HTML, there may be a better way to get the selection, however, as it stands, i really see no better way except maybe to shorten it with something like: `$('#toc > ul > li:first a').each(loadTopic);`. The `:first` is same as `.first()` and then the a tag after of course is same as `.find('a')`
Answer: Create simple jquery plugin and call $('#toc > ul > li').first().find('a').myPlugin();
Comment: not a good answer - any well behaving plugin will internally call `.each` anyway...
Comment: If you have one element, each will not be used, but my solution is a little better
Answer: Using .each is about as good as it gets here, not least because it automatically passes the native DOM elements from within the jQuery object, and not wrapped up as jQuery objects themselves.  Heck, it even sets this to be that element for you.
You could implement a .call() plugin that only works on the first element in a jQuery object, but it would be kinda pointless...


How do I create a log/statistics of on page events?

Question: I am using drupal 7, I have seen there are already statistic modules but can't find any for my situation
On my website I am trying to track certain on page activities which site admins can see in a table.
Example of activities are if users engage with certain elements on a page, if certain images load before user leaves, and browser information. Alot of information is only available through JS or Jquery not PHP.
On my site I can build a client side log, so when I go to console I can see the statistics I am looking for, but what is the best way to save this log/statistics to by drupal database.
I was thinking of building a content type called 'page log' with different fields relating to page info I need, which would be loaded on every page and filled/submitted via javascript. But think this would be too resource intensive.
To summarise, I have been building a function in javascript which collects on page activities which currently I can view in my browser console. I am looking for a way to save the log for each page to my drupal site in a way which can be recalled easily. Probably through views.
How can I save this log? Thanks for any help
Answer: Since, you've built everything in js, next thing to do is send the data from the client. You could do that with an endpoint in a custom module and sending everything you want there with ajax.
From there it depends how often you anticipate db writes from these data and you can assess the next step to take. You could:

Create a content type and programmatically save data to it.
Create a custom db table with only the fields you want and implement some db logic to save data.
Use mongoDB and setup a document table to store these data. This is the best option performance wise. You would need to setup the mongoDB module for it.
Comment: Thanks for replying. I would have a db write for each session at least, and theres what I'd consider a lot of data being sent. I think using a content type provides more flexibility. I am concerned about how I would programatically save the content type.
Comment: After you make your content type saving new nodes for it isn't hard at all. Something like this will help you get started: https://drupal.stackexchange.com/questions/230097/programmatically-creating-a-node


Posso chamar uma classe que faz apenas um cadastro de controller?

Question: Tenho uma classe de uma aplicação android que faz apenas o cadastro de usuário e a chamei de UsuarioController. A meu ver controller faz a comunicação entre view e model, mas como a classe só faz um cadastro, creio que ela poderia ser também um DAO. Ainda tenho uma certa dificuldade de entender o que fica em um controller e em um DAO
<code>package com.app.eventos.controllers;
import com.app.eventos.dao.ConfiguracaoFirebase;
import com.app.eventos.dao.ConfiguracaoFirebaseAuth;
import com.app.eventos.model.Usuario;
import com.google.firebase.auth.FirebaseUser;

public class UsuarioController {
    private Usuario usuario;

    public UsuarioController() {}

    public void cadastrarUsuario(String nome, String email
    , String senha, String idUser) {
        usuario = new Usuario(nome, email, senha);

        ConfiguracaoFirebase.getDatabaseReference()
        .child("usuarios").child(idUser).setValue(usuario);
    }
}
</code>
Comment: Juliana, você poderia editar sua pergunta e, em vez de colar uma imagem, colocar a classe em formato texto? Com o tempo, se o link da imagem expirar, sua pergunta vai perder o sentido e dificultar para outros que tenham a mesma dúvida que a sua ;)
Answer: A quantidade de operações que uma classe faz não define o que ela é ou o seu comportamento, uma classe que realiza o cadastro de 5 objetos diferentes não muda seu comportamento porque agora cadastra apenas 3
O controller, como o próprio nome diz, controla a aplicação, recebe as requisições/instruções que o usuário envia, interpreta e devolve o resultado, durante a interpretação ele pode interagir com outras classes, como model e o DAO
O DAO é uma classe que tem apenas uma tarefa, interagir com o banco, quando usado com o Firebase, não é muito útil (comparado a um banco de dados que não seja um baas), já que a ação de escrita e leitura é apenas uma linha
No seu caso, seu controller também é um DAO, já que, aparentemente recebe os dados enviados do usuário, interage com o model e cadastra no banco
O que é MVC(Model, View, Controller)?


C++ count occurence of the word from a file and write to another file

Question: What is the problem in this code?
I am trying to search for the word TID in input.txt
input.txt-
TID TID
 TID:fjkcgbkn
It just shows 0 in output.txt
#include<iostream>
#include<fstream>
#include<string.h>
using namespace std;
int main()
{
int con=0;
ifstream fi;
fi.open("input.txt");
char word[3];

  while(!fi.eof())
  {
     fi.get(word,3,' ');
     if (strcmp(word,"TID") == 0)
        con++;
  }
  fi.close();

ofstream fo;
fo.open ("output.txt");
fo<<con<<"\n";
fo.close();
return 0;
}

Comment: Yeah, you at least need to resize `word` to [4], as there's no room for the NULL terminator '\0'.  Simply adding that and it might just work.
Comment: this code is not very flexible...if you need to change the delimiter to something else your code will not work anymore. you usually implement a state-machine and check character by character :)
Comment: Your code also doesn't finish running for me in VS, it's stuck in an infinite loop. You need to check `fi.good()`, not `!fi.eof()`.
Answer: Is because when you use quotation mark like this:
"TID"

in memory is saved like this
TID\0

where \0 is mark of the end of string.
You could add to your variable word at the end '\0' and it should work (change size to 4:)
Answer: Two things:
First, word must be 4 bytes long in order to hold the null terminator that ifstream::get reads:
char word[4];

Second, the buffer size passed to fi.get() must be updated to match:
fi.get(word,4,' ')

As per documentation, ifstream::get(char*,streamsize,char) will read n-1 characters at most, then append a null terminator. This will let you read the full 3 character string plus its terminator. (Using sizeof(word) instead of 4 is also an option; it will allow you to change the size of word without having to modify anything else.)
Note that you are still going to produce incorrect results for strings like "abTID TID", which will first read "abT" then "ID". Necessary improvements to the algorithm are left as an exercise to the reader.
Answer: Here a way (not tested, but should work):
#include <iterator>
#include <fstream>
#include <iomanip>

using namespace std;

ifstream fin("input.txt");
ofstream fout("output.txt", std::ios::trunc);
fin >> noskipws;
istream_iterator<string> iter(fin), end;
ostream_iterator<string> iter_out(fout);

int count = 0;
copy_if(iter, end, iter_out, [&count](string const & val) -> bool
 { if (val == "TID") {
       ++count;
       return true;
   }
   return false;
});

Comment: This is certainly a way to do it but it does not directly address or explain the errors the OP was seeing.
Comment: @JasonC It addresses the errors by removing them, which is good a good thing: the standard library gives you tools that make it harder to make simple mistakes, it is good to know these. +1 from me.
Comment: I voted you up. Your point is right. But I wanted to illustrate a solution, since what he wants to do after all is this.
Answer: Alernatively to the function get(), you must use the function getline().
It will solve the problem of your \0 null character.
These are the most basics you must have learned in file handling in C++.


Copy data from PyObject to float * using boost

Question: This should be easy I think, but I cannot make it work. I want to call a C++-function from python. As argument I have an np-array. The C++ looks like this:
void foo_python(PyObject *p, const int m, const int n){
    float *data = new float[m*n];
    memcpy(data,PyArray_DATA(p),m*n*sizeof(float));
    delete [] data;
}

When I call this from python using
hello_ext.foo_python(A,A.shape[0], A.shape[1])

I get
  error: cannot convert 'PyObject* {aka _object*}' to 'PyArrayObject* {aka tagPyArrayObject*}' for argument '1' to 'void* PyArray_DATA(PyArrayObject*)'

This used to work but came when I included #include <boost/python/numpy.hpp>
, which is needed in this function where I return ndarrays to python.
np::ndarray test() {
    int *data = new int[5];
    for (int i = 0; i < 5; ++i){
        data[i] = i+1;
    }
    p::tuple shape = p::make_tuple(5);
    p::tuple stride = p::make_tuple(sizeof(int));
    p::object own;
    np::dtype dt = np::dtype::get_builtin<int>();
    std::cout << " Here " << std::endl;
    np::ndarray array = np::from_data(data, dt, shape, stride, own);
    cout<<"Selective Multidimensional array :: "<<std::endl <<
    p::extract<char const *>(p::str(array)) << std::endl;
    // delete [] data;
    return array;
}

This is the module:
BOOST_PYTHON_MODULE(libhello_ext)
{
    using namespace boost::python;
    Py_Initialize();
    boost::python::numpy::initialize();
    def("greet", greet);
    def("sum", sum);
    def("foo_python", foo_python);
    def("test", test);
}

Answer: The solution I came up with was to replace PyObject *p with np::ndarray &p. Then I can create a pointer float *p = reinterpret_cast<float *>(p.get_data()).
p can then be used in Map to create an Eigen::Matrix using Map<FMatrix > A(data, m, n); with
typedef Eigen::Matrix<float, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor> FMatrix;


Android.Widget.TextView

Question: I am trying to change the color of a textview in Android MonoDevelop.
I have tried this:
TextView mapTextView = new TextView(contextOverlay);
mapTextView.Text = overlayDetailsForThisOverlay.stringName;
mapTextView.setTextColor(Color.RED);

I get the following error:

Android.Widget.TextView does not contain a definition for setTextColor.

I have tried to add the following as a using statement:
using `Android.Graphics`;

With no luck.
May I please have some help?
Answer: To change the color of your textview you should use this:
tv.SetTextColor(Resources.GetColorStateList(Resource.Color.textcolor));

But first you must create an xml file(Color.xml) inside the Values folder containing this following code:
<?xml version="1.0" encoding="utf-8"?>
<resources>
  <color name="textcolor">#ffcc33</color>
</resources>

Answer: I can't understand if you want to change the background color or the text color. Anyway, to change the text color you should use this:
TextView tv=new TextView(this);
tv.setTextColor(Color.argb(255, 255, 0, 0));//ARGB 255 255 0 0 is red

And to change the background color:
TextView tv=new TextView(this);
tv.setBackgroundColor(Color.argb(255, 0, 255, 0));//ARGB 255 0 255 0 is green

Don't forget to put this in your imports:
import android.graphics.Color;

Android.Widget.TextView


Passing a linked list as an argument to a function in C

Question: I am writing a program which creates a linked list. Each node of the list stores 4 data about, a patient. This part works. After the user decides to output all the data. The average height of the people within the database is to be calculated. I am able to do this within the main function, but I fail to do that with an outside function
void avr_height(LIST_HEAD *InpList)

My question is what am I doing wrong here?
I suspect that, due to my limited understanding of pointers I mess up something about iterating through the list in the outside function. Or pass the list incorrectly to the outside function.
That's the part that calculates the average within the main function
pTemp = DataBase.pFirst_elmt;

while(pTemp != NULL)
{
    iCurrent = pTemp->Patient.iHeight;
    iSum = iSum + iCurrent;
    pTemp = pTemp->next;
    iNumb++;
}

fAvrageH = ((float)iSum) / ((float)iNumb);
printf("\n\nThe average height of these patients is: %.2f\n\n", fAvrageH);

and this is my outside function which is supposed to do the same.
void avr_height(LIST_HEAD *InpList)
{
    int iNumb = 0;
    int iSum = 0;
    int iCurrent = 0;
    float fAvrageH = 0;

    NODE *pTemp = NULL;
    pTemp = InpList;

    while(pTemp != NULL)
    {
        iCurrent = pTemp->Patient.iHeight;
        iSum = iSum + iCurrent;
        pTemp = pTemp->next;
        iNumb++;
    }

    fAvrageH = ((float)iSum) / ((float)iNumb);

    printf("The average height of these patients is: %f", fAvrageH);
}

To the function void avr_height(LIST_HEAD *InpList) I pass a struct LIST_HEAD Database, as an argument. This is done by the call avr_height(&DataBase)
All of the code looks as follows:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define STRSIZE 80

//List element's data
typedef struct{
    int iID;
    int iAge;
    int iHeight;

    //Defining a character array for storing the name
    char sName[STRSIZE];

} PATIENT;

//Defining the list elements (German: KNOTEN)
typedef struct NODE{

    //Initialising a Patient of the data type PATIENT. Then pointing to the next element
    PATIENT Patient;
    struct NODE *next;
} NODE;

//Defining the list element's head
typedef struct{

    NODE *pFirst_elmt;
    int iNumber;
}LIST_HEAD;

//Function for creating the actual list
void add_patient(LIST_HEAD *List)
{
    //Allocating memory for list elements
    NODE *pTemp;
    pTemp = (NODE*) malloc(sizeof(NODE));

    //Creating new elements of the linked list (and checking input validity)
    printf("\nEnter patient ID:");
    if(scanf("%d", &pTemp->Patient.iID) == 0){
        printf("Invalid input...");
    }

    printf("Enter patient's name:");
    if(scanf("%s", pTemp->Patient.sName) == 0){
        printf("Invalid input...");
    }

    printf("Enter patient age:");
    if(scanf("%d", &pTemp->Patient.iAge) == 0){
        printf("Invalid input...");
    }

    printf("Enter patient height:");
    if(scanf("%d", &pTemp->Patient.iHeight) == 0){
        printf("Invalid input...");
    }

    //Setting the first element of the list AS the the next element, in front of the new element
    pTemp -> next = List -> pFirst_elmt;
    //Designating the new element of the list as the first element of the list. Increase the number of elements in the list
    List -> pFirst_elmt = pTemp;
    List -> iNumber++;

    printf("\n");
}

//Calculating the average height of the patients: i.e. ITERATING OVER A LINKED LIST
void avr_height(LIST_HEAD *InpList)
{
    int iNumb = 0;
    int iSum = 0;
    int iCurrent = 0;
    float fAvrageH = 0;

    NODE *pTemp = NULL;
    pTemp = InpList;

    while(pTemp != NULL)
    {
        iCurrent = pTemp->Patient.iHeight;
        iSum = iSum + iCurrent;
        pTemp = pTemp->next;
        iNumb++;
    }

    fAvrageH = ((float)iSum) / ((float)iNumb);

    printf("The average height of these patients is: %f", fAvrageH);
}

int main()
{
    //Variable initialisation
    int i = 0;
    LIST_HEAD DataBase;
    DataBase.pFirst_elmt = NULL;
    DataBase.iNumber = 0;
    NODE *pTemp = NULL;

    //Variables for the height calculation
    int iNumb = 0;
    int iSum = 0;
    int iCurrent = 0;
    float fAvrageH = 0;

    //Loop for creating list elements if specified by user:
    do
    {
        printf("[0] Output the stored data [1] Enter data\n");
        printf("What do you wish to do?\n");

        //Checking input validity
        if(scanf("%i", &i) == 0){
            printf("\nInvalid input...");
        }

        if(i == 1){
            add_patient(&DataBase);
        }

    } while(i);

    pTemp = DataBase.pFirst_elmt;
    printf("\n\n");

    //Outputting the linked list: i.e. ITERATING OVER A LINKED LIST
    while(pTemp != NULL)
    {
        printf("\nPatient ID: %d  Patient name: %s  Patient age: %d  Patient height: %d", pTemp->Patient.iID, pTemp->Patient.sName, pTemp->Patient.iAge, pTemp->Patient.iHeight);
        pTemp = pTemp->next;
    }

    //Calculating the average height
    pTemp = DataBase.pFirst_elmt;

    while(pTemp != NULL)
    {
        iCurrent = pTemp->Patient.iHeight;
        iSum = iSum + iCurrent;
        pTemp = pTemp->next;
        iNumb++;
    }

    fAvrageH = ((float)iSum) / ((float)iNumb);
    printf("\n\nThe average height of these patients is: %.2f\n\n", fAvrageH);

    //Alternative way of calculating the height with a linked list
    avr_height(&DataBase);

    printf("\n\n");

    return 0;
}

All help is appreciated, thanks in advance!
Comment: `pTemp = InpList->pFirst_element`. Make sure you have compiler warnings turned up, it should have complained about the type mismatch.
Comment: Are you not getting compiler warnings? Should always heed those and fix them up to remove all warnings.
Answer: The compiler should issue a message for the function
void avr_height(LIST_HEAD *InpList)
{
    int iNumb = 0;
    int iSum = 0;
    int iCurrent = 0;
    float fAvrageH = 0;

    NODE *pTemp = NULL;
    pTemp = InpList;
    //...

because the pointers pTemp and InpList have different types.
You need to write
pTemp = InpList->pFirst_elmt;

Also this variable is redundant
int iNumb = 0;

because the list already has the data member int iNumber;.
Comment: Thanks' for the answer. One question though. When declaring the datatypes, do you  think it **is a better practice to do it in one block**, alternatively as few blocks as possible (i.e. the data part and the head). **Or in several smaller blocks**, as I have done it?
Comment: @Mark There is ni general rule.. I think you did all o'k.


404 not found Laravel with route argument

Question: I come to you today because I don't really understand where my problem is coming from. When I try to pass a dynamic argument in my url, I systematically fall on a 404 page. I looked in my db, there is the article, I looked in my model, it points well to this table of the db, I looked at my controller, I specify this article well... I do not understand too much.
My web.php:
Route::get('/article/{article}', 'ArticleController@index');

My controller:
class ArticleController extends Controller
{
    public function index($article)
    {
        $scopedArticle = Article::where('id', $article)->firstOrFail();
        return view('article', compact('scopedArticle'));
    }
}

My model:
class Article extends Model
{
    protected $table = 'articles';

    protected $fillable = [
        'titre', 'image', 'description',
    ];
}

My database:

So I don't really understand...
Comment: what dynamic argument are you trying to pass into your url? also, what error are you getting?
Comment: Btw, You can use `Article::findOrFail($article);` instead of `Article::where('id', $article)->firstOrFail();` if `$article` doesn't match with the `id` then it will raise a 404 error. You can dd the $article  and debug.
Comment: @sta I've already tried to debug by doing multiple things: Trying to output all articles with a ::all(), changing the name of the variable doesn't help.... When I try to make a dd of an article, I still have a 404. I deduce that it doesn't fit in my public function.
No errors occur, except for a 404
Comment: Give the output of `dd($article);` is it `1`?
Comment: @sta I can't make a dd. I've a 404 error before my public function, so I can't pass any code
Comment: Do you have any route group? would you please send your web.php completely
Answer: With route model binding there is no need to add $scopedArticle = Article::where('id', $article)->firstOrFail();
Example usage:
goto http://yourstie.com/article/1
class ArticleController extends Controller
{
    public function index(Article $article)
    {
        return view('article', compact('article'));
    }
}

Comment: No problem, on another note it is good practice to use `show()` instead of `index()`, `index()` would be reserved for viewing all articles and `show()` is used to show a single article
Comment: So, I just updated my code but I still get the same result. A 404 without being able to make dd
Comment: Yes and without reasons, with repeating f5, I've finally my page in front of my eyes... Incredible


local and global exponential stability

Question: I read the book "A Linear Systems Primer" [1] and confused about the differences between the definitions of local and global exponential stability. They are defined as:

\begin{equation} \dot{x}=f(x) \tag{4.8} \end{equation}
  Definition 4.8 (local exponential stability). The equilibrium $x = 0$ of (4.8) is exponentially stable if
  there exists an $\alpha > 0$, and for every $\epsilon > 0$, there exists a $\delta(\epsilon)>0$, such that
  \begin{equation} ||φ(t, x_0 )|| ≤ \epsilon e^{-\alpha t} ~for ~all~ t ≥ 0  \end{equation}
  whenever $||x_0||<\delta(\epsilon) $
Definition 4.11 (global exponential stability). The equilibrium $x = 0$ of (4.8) is exponentially stable in the large if there exists $\alpha > 0$ and for any β > 0, there exists $k(β) > 0$ such that
  \begin{equation}
||φ(t, x_0 )|| ≤ k(β)|| x_0|| e^{−\alpha t} ~for ~all ~t ≥ 0
\end{equation}
  whenever $||x_0|| < β$.

The only major difference I could see is that in the definition of the global exponential stability, there is a $||x_0||$ in the equation. But I just do not understand how definition 4.11 can guarantee that the exponential stability is global since it also restricts the domain of $||x_0||$ by  $||x_0|| < β$ just like that in the definition of the local exponential stability?
References:
[1] Antsaklis, Panos J., and Anthony N. Michel. A linear systems primer. Vol. 1. Boston: Birkhäuser, 2007.
Answer: The important thing you're missing is the restrictions on $x_0$. In the first case you need $\| x_0 \|<\delta(\epsilon)$, and $\delta(\epsilon)$ might be small. More importantly, it might remain bounded as $\epsilon \to +\infty$, so that some $x_0$ don't satisfy the inequality for any choice of $\epsilon$. By contrast, in the second case you need $\| x_0 \|<\beta$ but $\beta$ is arbitrary.
Thus the first one says essentially "if you start close enough to zero, you will decay to zero exponentially fast". By contrast, the second one says "no matter where you start, you will decay to zero exponentially fast; at worst, the speed may slow down if you start further away from zero".

local and global exponential stability


What does DEFINE_IDA mean?

Question: I was going through chipidea usb otg driver code and I see such similar definitions numerous times.

static DEFINE_IDA(ci_ida);

I don't get what it meant in the programming world and its purpose. Can someone please explain the same?
Comment: it's just a macro and means [`struct ida name = IDA_INIT(name)`](https://github.com/torvalds/linux/blob/3e1e21c7bfcfa9bf06c07f48a13faca2f62b3339/include/linux/idr.h#L174) in this case.
Comment: what does ida define/mean exactly. As I see in docs that "IDA - IDR based id allocator, use when translation from id to  pointer isn't necessary.". I didnt get the gist of it. If possible, please explain/
Answer: As already noted, DEFINE_IDE(name) is #defined as struct ida name = IDA_INIT(name). You should check out LXR which is very convenient for browsing kernel source.
IDR is a subsystem in the kernel that provides an efficient way to map ids to pointers. Normally you would use the id as an offset into an array of pointers, but this limits how big your ids are. IDR solves this by using radix trees instead for lookup.
Sometimes you just want unique ids without associating them with pointers and that's what IDA is for.
 /* IDA - IDR based ID allocator
  *
  * This is id allocator without id -> pointer translation.  Memory
  * usage is much lower than full blown idr because each id only
  * occupies a bit.

Comment: Thanks a3f. That helps. https://lwn.net/Articles/103209/ helped me understand the internals. They are simply a replacement for pointers and these are how the minor numbers are addressed by the kernel. These IDs are mapped to the pointers which hold the start location of the memory-the structure that holds all related info. Plz correct me if I am wrong; meanwhile, your answer did answer my question and also helped me with the "IDR" part and I was able to browse and find some indepth information. So, marking it as an answer. Thanks.
Comment: The API changed a bit since the article was released in 2004. There is a more up to date [lwn article on it](https://lwn.net/Articles/536293/). IDA is for IDs _without_ pointer mapping, this is needed for instance ids of the same device in your case.
Comment: While the gist was clearly understood; in the latest changes, we don't need to worry about looping to get a valid memory allocated and thereby getitng valid id. "It is, instead, stored in a single per-CPU array" - This line has generated few more queries. Are different processors allotted different memory spaces in RAM for performing their computation. Please throw some light on this/suggest some links to get a bit deeper understanding of this whole concept. Thanks.

What does DEFINE_IDA mean?


Laravel - Is it possible to pass object|array parameter for authenticating broadcasts in privatechannel?

Question: UserController.php
event(new MyEvent($MyObject));

MyEvent.php
public function broadcastOn()
{
    return new PrivateChannel('check-validity.'.$this->MyObject);
}

channels.php
Broadcast::channel('check-validity.{MyObject}', function ($user, $MyObject) {
    $sameMyObject = MyModel::where('some_id', $MyObject->some_id)
        ->where('state', 1000)
        ->where('user_id', $user->id)
        ->where('some_other_id', $MyObject->some_other_id)
        ->first();

    if($sameMyObject)
    {
        return true;
    }
});

I have a table named MyTable as an example which has some columns.
The more important ones are: some_id, user_id, some_other_id. When a user triggers event(new MyEvent($MyObject)), the content of $MyObject is an object of himself BUT what I want to check here in Broadcast::channel('check-validity... is whether the other user has the same row in MyTable with some differences which could be ->where('state', 1000) or not. If there was, so to send only to that user(the concept of authenticating for that user).
Now my question is that is it possible to pass object|array to Broadcast::channel? if yes how can I pass the other user's data about this $MyObject in Echo? I'm asking this because before this I could pass other user data which was ONLY ONLY user_id that I made an html tag and got the value to pass it through the channel: window.Echo.private('valid-user.' + user_id) but now instead of that user_id I don't know how can I pass a MyObject content to be authenticated due to those sql multiple conditions should be set.
Thanks :)
Answer: Why don't you try serializing your array like so
$a= array("john" => 120,"dave" => 342,"joe" => 553);
print_r($a);
echo "
";
$b=serialize($a);
echo $b."
";
$c=unserialize($b);
print_r($c);

But to send a model do this
use App\Order;

Broadcast::channel('order.{order}', function ($user, Order $order) {
    return $user->id === $order->user_id;
});

https://laravel.com/docs/5.8/broadcasting#defining-authorization-callbacks


How to use an aliased column in a MySQL WHERE clause?

Question: I have a MySQL query like this:
SELECT *, SUM(...some SQL removed for brevety) AS Occurrences FROM some_table AS q
WHERE criterion="value" GROUP BY q.P_id ORDER BY Occurrences DESC LIMIT 10;

I want to restrict the results to rows where Occurrences>0.  This seems very simple to me, but I can't seem to make it work.  No matter what I try, WHEREs or HAVINGs, whenever I try to add this restriction I get NO ROWS in return.  I'm positive that there is data in my table that should be returned.  Does anyone know how to accomplish what I'm doing?

I've tried this, but it still doesn't work.  Any ideas why it still won't work?
SELECT *, SUM(...some SQL removed for brevety) AS Occurrences FROM some_table AS q
WHERE criterion="value" HAVING SUM(...some SQL removed for brevety)>0 GROUP BY q.P_id ORDER BY Occurrences DESC LIMIT 10;

Answer: I am not as familiar with MySQL as I am with SQL Server, but in T-SQL, you can't use aliases in GROUP BY clauses (I originally thought ORDER BY clauses as well, but that has since been shown to be incorrect).  In this case, you want to filter based on the results of a GROUP BY, so I would use a HAVING clause as follows:
SELECT *, SUM(... some SQL removed for brevity ...) AS Occurrences
FROM
    some_table AS q
WHERE
    criterion = 'value'
GROUP BY
    q.P_id
HAVING
    SUM(... some SQL removed for brevity ...) > 0
ORDER BY
    Occurrences DESC
LIMIT 10;

Comment: Ah, that works.  It's working fine to have the results ordered by the alias, though.
Answer: This query works for me...
select order_id, sum(qty_ordered) as total_qty
from sales_flat_order_item
group by order_id
having total_qty > 10
order by total_qty desc

Answer: According to the SQL standard, the column aliases are not available in the body of the query, which is a confounded nuisance.  Given what you have tried, it sounds as though the same is true of MySQL (and some other DBMS).  You'll probably have to repeat the expression in the ORDER BY clause.
Also, the GROUP BY clause should list every column that is in the *, not just the primary key (though, logically, specifying the primary key should be sufficient).
Answer: Ah, I've found the place for it.
The statement is now:
SELECT *, SUM(...some SQL removed for brevety) AS Occurrences FROM some_table AS q
WHERE criterion="value" GROUP BY q.P_id HAVING SUM(...some SQL removed for brevety)>0 ORDER BY Occurrences DESC LIMIT 10;

It seems to be working fine with ORDER BY Occurrences,
Comment: Excellent.  Please be sure to mark one of the answers as correct, even if it is your own answer.
Answer: I believe aggregates should be in the HAVING clause. Though, admittedly, I'm not sure if aliases are accepted.
HAVING (Occurrences > 0)

HAVING (SUM(...some SQL removed for brevety) > 0)

Alternatively, you can use a sub-query:
SELECT *
FROM (
   -- your current query
) AS sub
WHERE (Occurences > 0)


Custom Keyboard on iOS: How do I access the UITextField?

Question: I have a UIView subclass that I assign to a text field as follows:
self.textField.inputView = [[HexKeyboard alloc] initWithFrame:CGRectMake(0, 0, 100, 100)];

and this works (i.e., the keyboard comes up). However, how should the HexKeyboard instance know about the textField?
[Of course I can add a property to the HexKeyboard to achieve this (and call it delegate), but I figure there's a built-in mechanism for this...]
Answer: You don't really need a complex delegate pattern for this. Just create a property of type UITextField on your HexKeyboard class, and make it an unsafe_unretained reference so you don't get a retain loop:
@interface HexKeyboard

@property (nonatomic, unsafe_unretained) UITextField *textField;

@end

Then set it when you set your inputView:
self.textField.inputView = [[HexKeyboard alloc] initWithFrame:CGRectMake(0, 0, 100, 100)];
self.textField.inputView.textField = self.textField;

Comment: Thanks. What's the advantage over `assign`, which also works on iOS4?
Comment: I'm pretty sure it gave me a compiler warning when I tried it, and if you run the ARC conversion tool it changes assign to unsafe_unretained. Good point about calling it delegate though, although that also implies it will be a protocol rather than a concrete class, so may be misleading in another way.
Comment: Why `unsafe_unretained` instead of weak?
Comment: Weak is iOS5 only. If you only plan to support iOS5, use weak instead. If you need to support iOS4, use unsafe_unretained.
Comment: Assign can't be used for object properties if you're using ARC. If you aren't using ARC it makes no difference if you use assign or unsafe_unretained.
Comment: You may use `assign` for objects with ARC just like without ARC. Delegates are typically `assign`, not `unsafe_unretained`, only because the new keyword was introduced with iOS 5 (and whatever on the Mac side), and programming is, by convention, conventional. If you include the word "delegate" in the property name, the user knows that it's not going to be retained, and also what it's for.
Comment: I checked the docs and I think you're right - it's fine to use assign for unretained properties (but not for ivars, that was where my compiler warning came from).
Answer: There seems to be no built-in mechanism for this, as the other answerers have pointed out. As Nick says, you don't need a complex delegate pattern for this. Or rather, you use the delegate pattern, but you get the delegate class for free. In this case it's the UITextInput protocol.
So your keyboard probably looks like this (and has a NIB)
@interface ViewController : UIViewController

// use assign if < iOS 5
@property (nonatomic, weak) IBOutlet id <UITextInput> *delegate;

@end

When you create the keyboard controller, you assign the UITextInput conformer to it, so something like this:
- (void)viewDidLoad
{
    [super viewDidLoad];

    HexKeyboardController *keyboardController = [[HexKeyboardController alloc] initWithNibName:@"HexKeyboardController" bundle:nil];
    self.textField.inputView = keyboardController.view;
    keyboardController.delegate = self.textField;

}

However, I thought, there MUST be a way to define this keyboard just once and get the keyboard to "automatically know" who the UITextInput object that summoned it is. But I've looked around to no avail... you cannot figure out who the firstResponder is unless you troll the view hierarchy yourself or retain your delegates in a list (which would cause a retain loop). Plus, this isn't so bad because the HexKeyboardController will unload, too, when the textField is dealloced.
Comment: Heh, damn iPhone keyboard - too slow to type comments!
Comment: I don't t get the "use assign if < iOS5" comment - iOS5 doesn't protect you from retain cycles if you use retain, and assign under iOS4 is not equivalent to retain under iOS5.
Comment: Hi @NickLockwood, I beat you to the punch by 24 seconds on my edit :) Seriously, my apologies, my code was wrong.
Answer: I dont believe there is a built in mechanism for this, you probably want the a delegate in the hex keyboard that will receive the "keystrokes" from it and then append it to the textfield, or whatever it is you need to do..


How to ajax load, and verify, an mp3 file over a network, without playing it?

Question: We have a lot of problems with our software (which is mostly used in schools) and firewalls:  we use mp3s within our resources, and mp3s are blocked in a lot of school firewalls.  I'm trying to write some js code to detect when this is happening, so we can alert the user (teachers) to speak to their IT department and get it unblocked.
I went down a road initially of trying to play an short mp3 of silence, and detect whether that had happened.  But, you have to jump through so many hoops to play audio automatically, especially on iOS Safari - waiting for user interaction, etc, that the hoop-jumping stuff was just getting in the way of the tests, and making the code think mp3s were being blocked when they were actually just being prevented from being played, by the browser rather than the network.
So, i'm abandoning the idea of playing mp3s.  What I want to do instead is to request a small mp3 file over the network, and then analyse the contents of the response, to make sure that it is actually an mp3 file, and not, say, an html page saying "Sorry, that content is blocked", or whatever other things firewalls may return when someone asks for a blocked file.
I can't actually think what the simplest way to do this is, which will work cross browser.  I'm using jQuery, and I thought that I might be able to do something in the "success" block of a jQuery ajax call, to analyse the data that I get back, to check that it's an mp3 file.
The first thing I thought was to just pull the data into a div on the page, like so:
var url = "/assets/test_media_files/silence.mp3?t="+Math.random();
$("#content-test-file-data").load(url, function(){
  console.log("loaded data");
});

This is working, and I have a load of binary data gibberish in the #content-test-file-data div.  But, how can I tell if this is an mp3 file?  Is there a nicer way to do this?  Do I need to request the data with a mime type, or something like that? thanks
Comment: take a look [to this answer....](https://stackoverflow.com/questions/4260422/javascript-checking-if-file-is-mp3-format)
Comment: Have you tried just creating and preloading an `` element with a small test file and using error handler on it?
Comment: @charlietfl yes, that's what's caused all the wasted time really, trying to use an audio tag.  I couldn't get it to tell the difference between the browser blocking and the network blocking.
Comment: @gaetanoM that looks interesting thanks.  I would worry though that because that test uses a HEAD request, there might be situations where a HEAD request can get through the firewall where a GET would be blocked.  If so then a HEAD request isn't a good test.
Comment: you are right, but another possibility is looking for the ....magic flag (file type).....
Answer: You are generating this mp3 yourself? Add an ID3 tag to the test file and read it. As it is located at the end of the file (128bytes) then it would be sure the file is completely arrived. ID3 org
Second approach would be to read/decode frame header (as done here) but compared to first option it's way more complicated.
Comment: Thanks - in between asking the question and seeing your answer just now, this (the first thing) is exactly what I did.  I made a very small mp3 (only one audio data point) and put a unique string in as the title in the metadata.  Then, I ajax-load the file and write its contents into a hidden div on the page.  The binary parts of this are gibberish but the metadata values are readable text, so it's just a case of checking that the div contains my unique string.  Seems to work perfectly.  I'll mark this as correct since it's the approach I ended up using.  thanks


Installing in a sub-folder of Angular

Question: I have an Angular 2+ application running. I would like to install Drupal in a subfolder and have my Angular application to iframe the contents.
Ideal Folder Structure:
/             - Angular
/content      - Drupal

I have an existing rewrite rule to rewrite all URLs to index.html. Drupal works fine with pages like http://myapp.com/content/admin, but if I am accessing a page like http://myapp.com/en/page, it will be redirected to the index.html file of the Angular application.
How do I configure Drupal to make it add /content to its URLs?
I am hosting them on IIS. These are the rewrite rules I have now.
<rewrite>
  <rules>
    <clear />
    <rule name="HTTPS Redirection" stopProcessing="true">
      <match url="(.*)" />
      <conditions logicalGrouping="MatchAll" trackAllCaptures="false">
        <add input="{HTTPS}" pattern="^OFF$" />
      </conditions>
      <action type="Redirect" url="https://{HTTP_HOST}{REQUEST_URI}" />
    </rule>
    <rule name="Angular Routes" stopProcessing="true">
      <match url=".*" />
      <conditions logicalGrouping="MatchAll" trackAllCaptures="false">
        <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
        <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
      </conditions>
      <action type="Rewrite" url="./index.html" />
    </rule>
  </rules>
</rewrite>

Comment: Or expose JSON endpoints and write Angular services to fetch the data?
Comment: We have thought of that before, but we would like to let our marketing team to manage the contents of those pages, that is why we came to this direction. I will try to remove the clean URL and see how it works.
Answer: Finally got it working, the following are the changes I've made. I am writing this here in case anyone faces the same problem.

I noticed there was another web.config file in root of Drupal folder (/content) and it contains a few rewrite rules.
I've changed the last rewrite rule which rewrite all requests to index.php, it now looks like this:

<rule name="Short URLS" stopProcessing="true">
  <match url="^(.*)$" ignoreCase="false" />
  <conditions>
    <add input="{REQUEST_FILENAME}" matchType="IsFile" ignoreCase="false" negate="true" />
    <add input="{REQUEST_FILENAME}" matchType="IsDirectory" ignoreCase="false" negate="true" />
    <add input="{URL}" pattern="^/favicon.ico$" ignoreCase="false" negate="true" />
  </conditions>
  <action type="Rewrite" url="/content/index.php" />
</rule>

Modified .htaccess file in root of Drupal folder and added this line RewriteBase /content, below this line # RewriteBase /
Modified the web.config file in root folder of Angular App (/) to the following:

<?xml version="1.0" encoding="utf-8"?>
<configuration>

  <system.webServer>
    <rewrite>
      <rules>
        <clear />
        <rule name="Angular Routes" stopProcessing="true">
          <match url="(.*)" negate="false" />
          <conditions logicalGrouping="MatchAll" trackAllCaptures="false">
                        <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
                        <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
                        <add input="{URL}" pattern="^/content/(.*)$" negate="true" />
          </conditions>
          <action type="Rewrite" url="./index.html" />
        </rule>
      </rules>
    </rewrite>
  </system.webServer>

</configuration>

Installing in a sub-folder of Angular


XML attributes deserialization with RestSharp

Question: I have the following xml and I'm trying to deserialize it. I have used the RestSharp library but with this particular response I'm getting an empty list of resources. Do you know if the library has problem with self-closing elements in XML?
<?xml version="1.0" encoding="utf-8"?>
<resourceList xmlns="..." xmlns:xsi="..." xsi:schemaLocation="..." location="...">
    <resourceURL location="../../../campaign/12" metaData1="12" metaData2="ACD Systems" metaData3="CPS" metaData4="Active" metaData5="Public" metaData6="No" metaData7="2005-10-28" metaData8="2020-12-31"/>
    <resourceURL location="../../../campaign/10607" metaData1="10607" metaData2="Aiseesoft" metaData3="CPS" metaData4="Active" metaData5="Public" metaData6="No" metaData7="2013-07-17" metaData8="2033-12-31"/>
    <resourceURL location="../../../campaign/567" metaData1="567" metaData2="AnchorFree Hotspot Shield Elite" metaData3="CPS" metaData4="Active" metaData5="Select" metaData6="No" metaData7="2011-10-03" metaData8="2031-12-31"/>
    <resourceURL location="../../../campaign/384" metaData1="384" metaData2="Avast" metaData3="CPS" metaData4="Active" metaData5="Select" metaData6="No" metaData7="2008-06-30" metaData8="2025-01-31"/>
</resourceList>

C# Classes:
[DeserializeAs(Name = "resourceList")]
public class ResourceList
{
    [DeserializeAs(Name = "resourceURL")]
    public List<ResourceUrl> ResourceURL { get; set; }
}

public class ResourceUrl
{
    public string Location { get; set; }

    public string MetaData1 { get; set; }

    public string MetaData2 { get; set; }
}

Last my call:
var response = _restClient.Execute<ResourceList>(request);

Answer: No, RestSharp doesn't have any problems with self-closing elements in XML.
As you are using their default XML deserialiser (RestSharp.Deserializers.XmlDeserializer),
as can be inferred by the use of the DeserializeAs attribute, you can see in the
library's source code that they use internally the XML parser from System.Xml.
So your XML sample should be deserialised without problems. But for that I recommend a simpler and faster solution:
using System.Collections.Generic;
using RestSharp.Deserializers;

public class ResourceList : List<ResourceUrl> {}

[DeserializeAs(Name = "resourceURL")]
public class ResourceUrl {
    [DeserializeAs(Name = "location")]
    public string Location { get; set; }
    [DeserializeAs(Name = "metaData1")]
    public string MetaData1 { get; set; }
    [DeserializeAs(Name = "metaData2")]
    public string MetaData2 { get; set; }
}

//(...)

request.RootElement = null;
request.XmlNamespace = null;
var response = _restClient.Execute<ResourceList>(request);

However, this solution doesn't work with the current v105.2.3 (the one still on NuGet).
You have to use the version of the class committed at the GitHub repository. Just get the code for the class, change the top namespace statement to your own, save to it disk and add it to you project. Then, just set the RestSharp client to use the new (better) version of the deserialiser:
_restClient.AddHandler("application/xml",new XmlDeserializer());

Comment: Finally this answer helped me. Interesting, that RestSharp web page itself does not explain deserialization easily...


How to map nested JSON in Log-stash HTTP Output

Question: I am using Logstash to output JSON message to an API. I am using "mapping" attribute to map my message. See, following piece of my shipper configurations.
output {
    stdout { }
     http {
        url => "http://localhost:8087/messages"
        http_method => "post"
        format => "json"
        mapping => ["MessageId","654656","TimeStamp","2001-12-31T12:00:00","CorrelationId","986565","MessageType","%{log_MessageType}" ,"MessageTitle","%{log_MessageTitle}","Message","%{log_Message}"]
    }
}

This configuration is working fine and is producing following output:
{
  "MessageId": "654656",
  "TimeStamp": "2001-12-31T12:00:00",
  "CorrelationId": "986565",
  "MessageType": "INFO",
  "MessageTitle": "TestTittle",
  "Message": "Sample Message"
}

Input Log Entry:
TID: [0] [ESB] [2016-05-30 23:02:02,602]  INFO {org.wso2.carbon.registry.core.jdbc.EmbeddedRegistryService} -  Configured Registry in 572ms {org.wso2.carbon.registry.core.jdbc.EmbeddedRegistryService}

Grok Pattern :
TID:%{SPACE}\[%{INT:log_SourceSystemId}\]%{SPACE}\[%{DATA:log_ProcessName}\]%{SPACE}\[%{TIMESTAMP_ISO8601:log_TimeStamp}\]%{SPACE}%{LOGLEVEL:log_MessageType}%{SPACE}{%{JAVACLASS:log_MessageTitle}}%{SPACE}-%{SPACE}%{GREEDYDATA:log_Message}

Problem Statement:
I want following output through mapping of HTTP. I wanted a nested JSON type inside my message, how should I add that in the mapping tag.
Expected Output:
{
  "MessageId": "654656",
  "TimeStamp": "2001-12-31T12:00:00",
  "CorrelationId": "986565",
  "MessageType": "INFO",
  "MessageTitle": "TestTittle",
  "Message": "Sample Message",
  "MessageDetail": {
    "FieldA": "65656",
    "FieldB": "192.168.1.1",
    "FieldC": "sample value"

  }
}

I have tried few options but I am receiving errors.
Comment: omer, please also add input log and grok patteren.
Comment: I added the mentioned information as well.
Answer: It is not possible to do this with the message mapping in the http output. That mapping can only create a single-level JSON.
What you can do, however, is to construct your JSON message before it reaches the http output using the mutate/add_field filter.
filter {
   grok {
       match => { "message" => "TID:%{SPACE}\[%{INT:SourceSystemId}\]%{SPACE}\[%{DATA:ProcessName}\]%{SPACE}\[%{TIMESTAMP_ISO8601:log_TimeStamp}\]%{SPACE}%{LOGLEVEL:log_MessageType}%{SPACE}{%{JAVACLASS:log_MessageTitle}}%{SPACE}-%{SPACE}%{GREEDYDATA:log_Message}" }
   }

   # add additional fields in your event here
   mutate {
      gsub => [
        "log_TimeStamp", "\s", "T",
        "log_TimeStamp", ",", "."
      ]
      add_field => {
        "MessageId" => "654656"
        "TimeStamp" => "%{log_TimeStamp}"
        "CorrelationId" => "986565"
        "MessageType" => "%{log_MessageType}"
        "MessageTitle" => "%{log_MessageTitle}"
        "Message" => "%{log_Message}"
        "[MessageDetail][FieldA]" => "65656"
        "[MessageDetail][FieldB]" => "192.168.1.1"
        "[MessageDetail][FieldC]" => "sample value"
      }
      remove_field => ["@version", "@timestamp", "host", "message", "SourceSystemId", "ProcessName", "log_TimeStamp", "log_MessageType", "log_MessageTitle", "log_Message"]
   }
}
output {
   stdout { codec => "rubydebug" }
   http {
      url => "http://localhost:8087/messages"
      http_method => "post"
      format => "json"
   }
}

You'll get exactly the JSON you expect posted to your HTTP endpoint
{
         "MessageId": "654656",
         "TimeStamp": "2016-05-30T23:02:02.602",
     "CorrelationId": "986565",
       "MessageType": "INFO",
      "MessageTitle": "org.wso2.carbon.registry.core.jdbc.EmbeddedRegistryService",
           "Message": "Configured Registry in 572ms {org.wso2.carbon.registry.core.jdbc.EmbeddedRegistryService}",
     "MessageDetail": {
        "FieldA": "65656"
        "FieldB": "192.168.1.1"
        "FieldC": "sample value"
     }
}

Comment: Thanks for your answer, I have tried this, it is working still there are some fields are going to the API, which are not expected, so can you answer my two questions:
1. How to remove all the attributes and fields except the fields that we mentioned in the "mutate" filter?
2. Like "mapping" element of http output also ensures the sequence of the fields, does this mutate element also ensures the sequence of the fields, because the error I am getting in my api is that the fields sequence is not waht expected?
Thanks in advance
Comment: 1) You can use the `mutate/remove_field` filter in order to remove unwanted fields. 2) By definition a JSON hash is not ordered, so there is no notion of sequence in a JSON document.  What is the error you're getting from your API?
Comment: I've managed to get exactly the JSON you expect with the properties in the exact same order. See my updated answer.
Comment: Thanks a lot for your help.
Comment: If you have time, can u please look into this question too. http://stackoverflow.com/questions/37679108/unable-to-get-the-parse-value-out-of-multi-line-logs-in-logstash


When were dugout railings added in MLB?

Question: I was watching the movie "Major League" with my wife when she asked about the absence of the dugout railings. She assumed it was for the movie.
I explained that they were added fairly recently (early 90s perhaps) but can't find anything to confirm this.
When were dugout railings first used in the MLB?
Answer: This blog about the Angels suggests that fences were added to dugouts shortly after Mo Vaughn's 1999 injury.

It should be noted that after Vaughn's opening day tumble, many
  stadiums around Major League Baseball put fences in front of their
  dugouts to avoid any future injuries of this nature.

This Chicago Tribune article mentions that the process was underway, but not complete league-wide in 2002.

Some teams have put up fences or netting in front of dugouts to
  protect their players...

When were dugout railings added in MLB?


Post request, req.body undefined

Question: My Code
const express = require('express')
const cors = require('cors')
const bodyParser = require('body-parser')

const app = express()

app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json())
app.use(cors())

app.get('/', (req, res)=>{
    res.send("Hello World!")
})

app.post('/', (req, res)=>{

    console.log(req.Body);

    res.send(`Name is`)
})

app.listen(5000, ()=>{
    console.log("Server runing on port 5000");
})

when i send post request it shows error
SyntaxError: Unexpected token n in JSON at position 6
at JSON.parse ()
at parse (E:\Saylani IT Lab\JavaScript\Express-JS\Assignement 1\server\node_modules\body-parser\lib\types\json.js:89:19)
at E:\Saylani IT Lab\JavaScript\Express-JS\Assignement 1\server\node_modules\body-parser\lib\read.js:121:18
at invokeCallback (E:\Saylani IT Lab\JavaScript\Express-JS\Assignement 1\server\node_modules\raw-body\index.js:224:16)
at done (E:\Saylani IT Lab\JavaScript\Express-JS\Assignement 1\server\node_modules\raw-body\index.js:213:7)
at IncomingMessage.onEnd (E:\Saylani IT Lab\JavaScript\Express-JS\Assignement 1\server\node_modules\raw-body\index.js:273:7)
at IncomingMessage.emit (events.js:387:35)
at endReadableNT (internal/streams/readable.js:1317:12)
at processTicksAndRejections (internal/process/task_queues.js:82:21)
Request
Answer: It is a JSON syntax problem in your request:
Try {"name":"Zaman"} instead of {name:"Zaman"}

Post request, req.body undefined


Ajuda com footer desalinhado em flexbox

Question: Gostaria de uma ajuda com o meu footer , que está ficando totalmente desalinhado, já tentei um clear: both , mas sem sucesso, gostaria de uma ajuda pra corrigir este erro. o código original do footer é este:
https://codepen.io/x-gyba/pen/pEmyRk
e o meu projeto atual é este:
https://codepen.io/x-gyba/pen/pNmbEe
Vejam que ele fica totalmente deformado, onde pode estar o erro?
Comment: primeiro, a tag " está com max-width:700px"(pegando do escopo global), por isso o copyright não está alinhado no center corretamente
Comment: Veja aí: https://codepen.io/anon/pen/GrNWaq
Answer: Primeiro, sua tag:   está faltando um >
Segundo, sua classe .footer-infos tem que estar assim:
display:flex;
flex-direction:column;

Ajuda com footer desalinhado em flexbox


Remote Support Software Recommendations

Question:
Possible Duplicate:
Best Windows remote support / screen sharing tools?

What remote support software do you use?
How much of your support is done remotely versus on-site?
Any metrics your company is using to quantify the savings/profit remote support has contributed to your company?
Comment: similar question: http://serverfault.com/questions/155/best-windows-remote-support-screen-sharing-tools
Answer: LogMeIn is the primary way
Secondary way, All computers have remote desktop turned on as the secondary and the network forwards the remote desktop port to one computer.  So I can login via remote desktop to one computer and then remote to any other.  I'll filter the IP for forwarding of that port so it only comes from my IP's
Also since LogMeIn is outbound connections there is nothing to open on the firewall
I do everything remotely unless its actually setting up a new computer or moving hardware or fixing hardware.
Answer: For servers we use RDC, but for workstations, because we may want the user to see what we are doing, we use IntelliAdmin.
I have mentioned IntelliAdmin on here many times.  It lets you directly connect to any machine on your network very easily and quickly...even stealthy if you want.  You can control the users keyboard and mouse and even lock the user out if you want.  Its as if you were physically in front of the remote machine.
It requires no installation of 3rd-party software for the LAN edition.  There is an internet edition that requires 3rd part software on the remote machine.
Comment: I have no real stats, but I use both IntelliAdmin and RDC everyday..many times per day...even on machines that are 2 doors down the hall (would hate to leave my desk).  RDC was obviously free with Windows, but IntelliAdmin costs us about a hundred bucks.
Answer: We use Single Click version of UltraVNC.  Our customers download a small executable from our website and initiate the connection to us.
Single Click can be used on Vista, but it is slow unless you change the theme to Windows Classic
We install the full version of UltraVNC on any terminals we supply, so we can remote provide support.
Answer: I like lots of options...
For my servers, I go RDP or VNC -- or even iLO2 if nothing else works. I love the mRemote app to keep everything in one tabbed window. Worth a look if you spend a lot of time on a lot of systems remotely. Even does SSH.
I use the free LogMeIn app with many remote clients. For interactive sharing/trouble-shooting I'll use CrossLoop instead.
Around the office I'll use ChrisControl (download) to "push" a VNC server and then connect when we need to do screen sharing. Otherwise I'll go RDP there as well.
Answer: We use UltraVNC. Getting through the firewall was a challenge to do, but mostly because I wasn't very familiar with port forwarding. When it works, it works great. But there are issues with Vista, anytime Vista asks for User Account Control, UltraVNC drops the connection. At other times it just seems that UltraVNC won't work at all, for some reason unknown to me. In these cases I've bought day-passes at copilot.com, or used a trial version of some other software.
90 -95% of support is done remotely. An on-site visit for me is very rare.
Unfortunately, I don't have any metrics on savings/profit of remote support. If I base it on about 10 on-site support issues a year (1 day apiece), considering my salary, travel expenses, time away from other issues, etc. we are probably saving around $4000 to $5000 per year.
I also use LogMeIn.com for my personal computers at home.
Comment: Have you tried the latest version of UltraVNC?  We have it installed on a few remote computer and it stays connected when the UNC prompt is displayed.  So far we have had no problems with Vista,
Answer: To "ride along" with the user, we've used RealVNC for years on Windows XP. (We deploy it with an MSI package and an MST to set a per-Customer password.) This is problematic with Windows Vista, but since our Customers have largely skipped Windows Vista (where we have been, grudgingly, using LogMeIn) we have punted on that issue for now.
We've been using LogMeIn on Windows Vista machines, grudgingly, with success. Unless you pay them, however, you don't get an MSI-based installer. (You can do some rather creative hacks with the "free" edition to get an MSI, but it's not worth the trouble.)
Remote Desktop is enabled via Group Policy on every computer (server, client computer, etc). For support issues that don't require seeing what the user sees, we use that.
I had an interest level in solicited Remote Assistance functionality, but I never did the work to get that going. I'd be interested to hear from people who have, because the more I can use built-in Windows functionality the happier I am.
I can't give you a "hard dollar number", but we'd be hard pressed to service the number of Customers (and raw counts of individual PCs) that we do w/o VPNs and remote control tools.
Answer: Almost 100% of support is done remotely. We use Novell's integrated remote desktop support ... or if that's not working for whatever reason, we use CoPilot.
Answer: We use RDP for just about everything but occasionally use www.GoToMeeting.com if the user needs to see we're doing or vice versa.  GoToMeeting is probably not the best solution for lots of support, but we're very happy with it for meetings so it's Convenient for support as well.
Answer: We use ScriptLogic's Desktop Authority.  Remote control as well as login script management, etc. for AD domains.
Answer: We push TightVNC out via group policy to oncampus workstations, and will work with users that way on occasion.     There's only 2 of us to support about 110 users.

Remote Support Software Recommendations


Finding the values of the coefficients $a,b,c$ in the curve $y=ax^2+bx+c$.

Question: The curve $y=ax^2+bx+c$ crosses the $y$-axis at the point $(0,3)$ and has a stationary point at $(1,2)$. Find the value of $a$, $b$ and $c$.
Answer: HINT
By the givens we can easily find that

for crossing $y$ at $(0,3) \implies 3=a\cdot 0^2+b\cdot 0+c$
stationary point at $(1,2) \implies y'(1)=0\implies 2a\cdot 1+b=0$
for crossing at $(1,2) \implies 2=a\cdot 1^2+b\cdot 1+c$

then solve the system of three equations to find $a,b, c$.
Comment: Can you give me a little explanation about the "stationary point"? Please
Comment: @user9602923 By definition of stationary point we have that the derivative at that point is equal to zero then $y'(x)=2ax+b=0$ for $x=1$.
Comment: @user9602923 Let try to solve the system and show your result, I will look to that for check!
Comment: Oh, okay. So I'm expected to always find the derivative of $y$ when at stationary point.?
Comment: @user9602923 Yes for general functions. In this case since it is a parabola, if you were not aware about derivatives, you can use the fact the the coordinate for the vertex (that is the unique stationary point for a parabola) is located at $x=-b/2a=1\implies 2a+b=0$ that is precisely the condition found by the derivative.
Comment: Oh, that's why I wasn't understanding what @Delta-u said. But I think I get it now $x=-b/2a$. Thanks gimusi. Let me try it out and see how it goes.
Comment: I'm quite sure that taken the derivative is much more easier to me coz that's what I'm familiar with.
Comment: @user9602923 ok then proceed in this way!
Answer: @Gimusi, here...
$y=ax^2+bx+c$
At point (0,3),
We have $3=a•0^2+b(0)+c$
=> 3=c
At stationary point (1,2)...we takes the derivative of "y"..and equate it to zero
$=> y^1=2ax + b = 0$
There4,
$2ax + b = 0$ but x=1
$2a + b =0.....(1)$
And also, at point (1,2)
We have,
$2=a+b+3$ since c=3.
$=>a+b=-1.......(2)$
$(1)-(2)$
:•a=1
Put a=1 into (2)...
Then b=-2
Therefore,
a=1,b=-2 and c=3.
So,
$y=x^2-2x+3$.
I'm a right?
Comment: Ah no, I guess it was unexpectedly done, I mean, unknowingly.... I like your answer and it even gives me more understanding.
Comment: Yes it's correct how you can check directly on your final result. Well done! Bye
Comment: Thanks to you. I'm much grateful
Comment: You are welcome! Only for information, why did you unaccepted my answer? It is not a problem of course and the choice is completely up to you. I ask to understand how I we can make my answers more clear in the future. Thanks!
Comment: Ahhhhh I was indeed wondering were was my fault :) Anyway really it is not a problem, you are the only which can choose the aswer to accept! But if it was unexpectedly done I'm happy now it is clear. Thanks! Bye
Comment: Can't I reaccept it?
Comment: Yes now it is ok! and you can change whenever you want!
Answer: Let $f(x)=a x^2 + b x +c$. The value at $x=0$ give $c=f(0)$ and the stationary point is at $1=x_0=-\frac{b}{2a}$ with value $2=a x_0^2 +b x_0 +c$.
That give you as set of $3$ linear equations and $3$ unknowns.
Comment: Thanks Delta-u.


Jquery history.go(-1); não funciona Chrome

Question: Já fiz umas pesquisas até mesmo aqui no stackoverflow sobre criar um botão voltar.
A situação é que eu clico em um registro dinâmico para editar, depois tenho a opção de Cancelar (que é para voltar) no IEca e FF funciona, mas no chrome temos problema.
Já tentei outras alternativas, mas nada deu certo continua a não funcionar.
<button type="submit" name="voltar" value="voltar" id="voltar" class="btn btn-default" style="margin-left: 30px">Cancelar</button>

    $('#voltar').click(function() {

        history.go(-1);
        return false;
    });

Já tentei algo direto inline também em JS, mas não deu! Alguma solução ?
SOLUÇÃO:
Aparentemente o que fiz para dar certo foi só tirar o jquery que estava no final da página e jogar no começo da mesma. Vai entender.
Comment: Esse botão é gerado dinamicamente por javascript/jquery?
Comment: Isso funciona no chrome, acredito que o que deve estar errado é como você vai para a tela de edição. Se for via ajax, lembre-se que é você quem deve [manipular o history do browser](https://developer.mozilla.org/en-US/docs/Web/Guide/API/DOM/Manipulating_the_browser_history).
Comment: Onde o js postado está? Em um script separado? Na própria página?
Comment: Kadu não é não.. é um html normal.
Comment: Guilherme o código js/jquery está na mesma página é tudo simples mesmo!
Comment: Não existe ajax não, eu simplesmente pego registro (pelo id) e levo a outra página e faço edição dos dados.
Answer: Fiz um teste com o seu código da seguinte forma do Chrome e funcionou normalmente:
<button type="submit" name="voltar" value="voltar" id="voltar" class="btn btn-default" style="margin-left: 30px">Cancelar</button>

link

De qualquer forma tente remover o return false, caso ele esteja interrompendo alguma ação da sua página.
OBS: Fique atento se realmente existe alguma página no history para voltar, pois o -1 só volta para a posição anterior, e se for para a mesma, em alguns casos ele ignora, sugiro que coloque um link para a página neste caso (como em breadcrumbs).
Abs


Variable with malloc inside a thread

Question: I have a question about pthread, when I create a variable inside a thread with malloc and then pass its pointer to a shared structure, i.e fifo, is the pointer passed by thread-1 will be accessed by thread2 ?
Please note that I have to code for the question above, I'm just trying to understand threading better, the below is just what I'm thinking about. The environment is pthread, c and linux
As far as I know threads are sharing the memory of their parent process, If that's the case the below should be correct.
void *thread-1(void *pointer)
{
  int *intp = malloc(4);
  send_to_fifo(intp);
}

void *thread-2(void *pointer)
{
  int *iptr;
  iptr = read_from_fifo();
  do_something(iptr);
  free(iptr);
}

Comment: `thread-1`?!? That is not an identifier in c. Use `thread_1` or `thread1`.
Answer:
is the pointer passed by thread-1 will be accessed by thread2 ?

Yes: since all threads operate in a common memory space, this is allowed.
malloc, free, and other memory management functions are thread-safe by default, unless compiled with NO_THREADS.
Answer: Of course you can do this. However you must be careful to not write to variable when it's used by another thread. You need synchronization.
In your case, you have race condition if the threads are run simultaneously (thread2 not waiting for thread1 to finish): thread2 either execute all it's code before thread1 puts anything to fifo or after that.
Comment: I was thinking about that, if read_from_fifo and send_to_fifo have lock then that should be fine, right?
Comment: Not necessarily - if thread2 executes it's code first then `read_from_fifo` will read form empty fifo (or not, depends on rest of the program), which could lead to problems. Memory allocated in thread1 can be never released then. If `read_from_fifo` waits until something is in fifo it should be okay.

Variable with malloc inside a thread


CSS dropdown menu adds scroll bars to header div on hover

Question: I used the following example trying to create my own dropdown menu.
I've tried increasing the z-index but my problem is really not that the sub-menu is behind other content. Rather when I hover over 'Login', scrollbars are added to the header div and I have to use them to view the sub-menu.
<!DOCTYPE html>

<title>Test</title>
<link rel="stylesheet" type="text/css" href="test.css">

[ BETA ]

Login

A

B

C

Register

Events

About

and
#header {
    background: black;
    color: white;
    padding: 10px 10px 10px 10px;
    overflow: auto;
    position: relative;
    z-index: 999;
}

#logo {
    float: left;
    color: #ff8100;
}

#menu_container {
    float: right;
}

#menu ul {
    list-style: none;
    position: relative;
    float: left;
    margin: 0;
    padding: 0;
    z-index: 999;
}

#menu ul a {
    display: block;
    text-decoration: none;
}

#menu ul li {
    position: relative;
    float: left;
    margin: 0;
    padding: 0;
}

#menu ul li.current-menu-item {
    background: #000000;
}

#menu ul li:hover {
    background: green;
}

#menu ul ul {
    display: none;
    position: absolute;
    top: 100%;
    left: 0;
    background:#ffffff;
    padding: 0;
}

#menu ul ul li {
    float: none;
    width:200px;
}

#menu ul ul a {
    line-height: 120%;
    padding: 10px 15px;
}

#menu ul ul ul {
    top: 0;
    left: 100%;
}

#menu ul li:hover > ul {
    display: block;
}

What do I need to do to have the sub-menu appear to be hanging down from the header div and over the rest of the content body? Thanks and I appreciate your help.
Answer: You need to remove overflow: auto from .header and use a clearfix instead:
#header {
   background: black;
   color: white;
   padding: 10px 10px 10px 10px;
   /*overflow: auto;*/ //remove
   position: relative;
   z-index: 999;
}

#header:after{
   content: "";
   display: block;
   clear: both;
}

FIDDLE
overflow:auto is being added to clear the floated items (i prefer overflow:hidden) but what it also does is hide the overflow and add scroll bars to view more. Typically that's a good approach except in this case you actually want the subnav to overflow the header.
Answer: Add this to your code:
#header {
    overflow: hidden;
}

That oughta' do the trick.
Simple and clean.
Comment: I no longer have the scrollbar problem but now I've arrived at the common dropdown behind other content issue. I added z-index: 999; all over trying to get the menu item on top but with no luck. Where should it go?


What is the terminology for a piece of guitar played in the following cases

Question: Songs
1. Metallica : Master of Puppets - Duration:  3:33 - 5:15
2. Led Zeppelin: Stairway to Heaven - Duration : 5:35 - 6:35
3. Avenged Sevenfold : So Far Away - Duration : 3:29 - 4:25
What I intend to ask is what is the term for the unique non recurring "tune" of the guitar played within the above mentioned duration.. I don't think it can be called as a "riff". Because, from what I have read riff is something what the entire song's music is built up on.
Forgive me for my poor choice of words.
@NeilMeyer
Here are the links . Man ! I was not aware about an existence of such a feature in youtube.

@Dr. Mahyem. Could you suggest me some artists whose music contains this interlude stuff. Also thanks for the reply.
Comment: Thanks for editing in those links Todd. Croissant - the majority of bands I'd class as classic heavy metal or prog rock will have things like this. Follow suggested videos on YouTube after watching these and you'll discover loads.
Answer: A riff doesn't have to be a sequence that the whole song is built on, in fact Metallica are rather famous for having songs built up from a large number of associated, but different riffs, time sequences, concepts etc.
That section you mention from Master of Puppets is effectively an interlude between two heavier riffs, again, something they commonly do, providing a wide dynamic range across the whole song (and giving all the headbangers time to catch their breath before the next fast and heavy bit)
Answer: That's called a "solo" or a "guitar solo". The word "solo" means alone, and of course in these cases there are other instruments playing, but as it is used in music today "solo" doesn't mean alone, it just means a single instrument that is playing a separate melody that is the main focus of the music for part of the song.
When a solo is being played, there is almost always no singing. In rock music, a solo is usually in the same part of the song where a bridge might be. Sometimes the solo is part of the bridge, sometimes there is a separate solo and bridge, and sometimes there is no bridge, just a solo instead of singing for a verse section. Of course, sometimes there is no solo.
There are solos that are not played on the guitar. They are still called "solos", and sometimes the instrument used in the solo might be added to the term. So you might hear of "a piano solo" or a "keyboard solo", "bass solo", "drum solo", "theremin solo", "harmonica solo", etc.


back-propagation derivatives

Question: In the 10th video of week3 of Ng course on Deep Neural Networks in coursera, there is a slide that i attached. Why he used elementwise product (vs normal matrix product) in this slide? Is it only for match-up of matrices for other products?
Answer: I made a youtube video where I go through some backprop at https://www.youtube.com/watch?v=ppJwiv1qtlE&t=12s
Basically you chain-rule everything. And $g$ is the activation function, which is per-element.
In detail, the above net is two layers with mse loss. So, the forward direction would be something like, in code:
z1 = g(W1 @ x + b1)
z2 = g(W2 @ z1 + b2)
loss = MSELoss(z2, y)

... where:

g is an activation function, like tanh, or sigmoid, or ReLU
x is the input to the network
z is the output of each layer, after activation
W is weight matrix of a layer, and
b is bias of a layer

Mathematically, this is:
$$
\def\z{\mathbf{z}}
\def\W{\mathbf{W}}
\def\b{\mathbf{b}}
\def\y{\mathbf{y}}
\def\x{\mathbf{x}}
\z_1 = g(\W_1 \x + \b_1) \\
\z_2 = g(\W_2 \z_1 + \b_2) \\
\mathcal{L} = \text{MSELoss}(\z_2, \y)
$$
When we chain-rule this, we can do bit by bit. So, we can take the second layer output $\z_2$, and derive with respect to the input $\z_1$:
$$
\frac{\partial \z_2}{\partial \z_1} = \frac{\partial}{\partial \z_1} (g(\W_2\z_1 + \b_2))
$$
Let's substitute $h(\z_1) = \W_2 \z_1 + \b_2$, so we have:
$$
\frac{\partial \z_2}{\partial \z_1} = \frac{\partial}{\partial \z_1} (g(h(\z_1))
$$
By chain rule this is:
$$
\frac{\partial}{\partial \z_1} (g(h(\z_1)) =
\frac{\partial g}{\partial h}
\frac{\partial h}{\partial \z_1}
$$
... which doesnt itself involve any matrix multiplication. The partial derivative $\frac{\partial h}{\partial \z_1}$ will involve differentiating matrices, but the two partial derivatives themselves are simply multiplied together.

back-propagation derivatives


Prove that $\frac{\sqrt{\prod_{i=1}^n}x_i}{n-1} \geq 1998$

Question: Let $n \geq 2$, $x_1,x_2,x_3....x_n \in R^+$ such that $$\sum_{i=1}^n\frac{1}{x_i+1998} = \frac{1}{1998}.$$  Prove that $$\frac{\sqrt{\prod_{i=1}^n x_i}}{n-1} \geq 1998$$
Comment: Use AM-GM inequality.
Comment: I am not sure but I think it should be that $$\frac{\sqrt[n]{\prod_{i=1}^n x_i}}{n-1} \geq 1998.$$
Comment: I suggest you explain what you already tried. Otherwise, it will be difficult to help without knowing your efforts and where you are stuck.
Answer: I'll try from $\sum\limits_{i=1}^n\frac{1}{x_i+1998}=\frac{1}{1998}$.
For all $i$ by AM-GM we have $\frac{1}{1998}-\frac{1}{x_i+1998}=\sum\limits_{k\neq i}\frac{1}{x_k+1998}\geq\frac{n-1}{\sqrt[n-1]{\prod\limits_{k\neq i}(x_k+1998)}}$.
Thus, $\frac{1}{1998^n}\cdot\frac{\prod\limits_{k=1}^nx_k}{\prod\limits_{k=1}^n(x_k+1998)}\geq\frac{(n-1)^n}{\prod\limits_{k=1}^n(x_k+1998)}$, which gives $\sqrt[n]{\prod\limits_{k=1}^nx_k}\geq1998(n-1)$.


Node Acess User Reference and Organic Groups permissions

Question: I am using Organic Groups to give group-specific content to users.
The groups' permissions do not allow simple group members to edit group content.
By using the Node Acess User Reference module I wanted to grant permission to specific group members to edit specific nodes on an ad-hoc basis.
The devel information that I get is that allthough that rule works, it is being overriden by OG's permissions thus still not allowing the user to edit the node.
Answer: Nevermind, http://drupal.org/node/1171834#comment-6019078 answers it.


How to determine the date a package was installed or updated?

Question: Is there a way to determine the date a package was installed or updated?  What's the proper syntax for both rpm and dpkg?
Answer: Red Hat based distro:
<code>$ rpm -q --last <pkg>
$ rpm -qi <pkg>
</code>
Debian based distro:
<code>$ ls -lt /var/lib/dpkg/info/<pkg>.list
</code>


How to extract the content between 2 sibling nodes in an XML document using Java

Question: sample xml document:

    ...
    xyz
    <c>...</c>

Is there a way to extract the content xyz placed between the tags b and c using Java code (through DOM parsing)?
Comment: Is this the fixed fomat?
Comment: Please, formulate a correct question. What is your problem?
Answer: Iterate over the nodes of root element (). In your example the second node (with index 2, since nodes are indexed from 1) will be the text node.
Document document = ...; // create org.w3c.dom.Document instance from XML
document.getDocumentElement().getChildNodes().item(2).getTextContent();

Answer: Assuming that element refers to tag 'a' following code should extract what you want and work also if you have content before and after the 'b' and 'c' tags
    NodeList content = element.getChildNodes();
    StringBuilder textContent = new StringBuilder();
    int cntLength = content.getLength();
    for ( int i = 0; i < cntLength; i++ ) {
        Node paramValue = content.item( i );
        short type = paramValue.getNodeType();
        if ( ( type == Node.TEXT_NODE ) || ( type == Node.CDATA_SECTION_NODE ) ) {
            textContent.append( ((CharacterData) paramValue).getData() );   //  Both Text and CDATASection nodes are SubType of CharacterData
        }
    }


Unwanted resizing of forms in C#

Question: I'm and a friend are working on a training project. My friend's laptop monitor is full HD and my monitor is HD.
This difference in resolution has caused the project to change its size when it is transferred back to my system when it is transferred from my system to my friend's system.
To be clear, we are working on Visual Studio and suppose we have a form 1080 by 720 which in my system is OK when we edit the form. But when we save the project and move that on my friend's system to continue the project, because the monitor has a higher resolution, the size of the form becomes 1124 by 812, and this disrupts the whole design work.
The point is that the forms that we do not open on my friend's system remain in the same dimensions of 1080 by 720 and there is no change in them.
What is the way to solve this problem?
Thanks a lot
Comment: Is the DPI different on the two monitors?
Comment: What dpi do you each run?
Comment: My friend monitor is 1,920 x 1,080 and my monitor is 1366 x 768
Comment: yes DPI is different.
Answer: Under the Layout section of your Form's properties set the AutoScaleMode to None.
Alternatively, if your AutoScaleMode is currently set to Font (the typical setting), then make sure that your system fonts are the same size.
Answer: What you need is responsive design. if you design your program responsive, so every element of your app in any resolution load correctly.
I suggest reading this link to figure out how to do that
Dynamically Resizing Controls On Windows Forms
Comment: This appears to be the opposite of what the OP requested and needs.
Comment: Thanks, But is not my problem. my forms are responsive

Unwanted resizing of forms in C#


How to prove $\mathbb Z^2 \ast \mathbb Z$ is quasi isometric to $\mathbb Z^2 \ast \mathbb Z^2$?

Question:
How to prove $\mathbb Z^2 \ast \mathbb Z$ is quasi isometric to $\mathbb Z^2 \ast \mathbb Z^2$? Here $\ast$ is the free product of groups.

I am thinking of proving they are commensurable. In other words, proving they share a finite index subgroup. $\mathbb Z^2 \ast \mathbb Z$ is the fundamental group of $T \vee S^1$, and $\mathbb Z^2 \ast \mathbb Z^2$ is fundamental group of $T \vee T$ (here $\vee$ is wedge sum). So we can also turn the problem into finding compact cover of each space such that the two covers have the same fundamental group. My problem right now is the only compact cover of a torus is torus itself, so I'm not sure how to find such a compact cover?
Answer: $\mathbb Z^2 * \mathbb Z^2$ is indeed commensurable to $\mathbb Z^2 * \mathbb Z$, in fact they each have an index 2 subgroup isomorphic to $\mathbb Z^2 * \mathbb Z^2 * \mathbb Z$.
You can see this with covering spaces if you choose the correct spaces.
For the first group $\mathbb Z^2 * \mathbb Z \approx \pi_1(X)$, take $X$ to be a torus $T$ with an arc $A$ attached by identifying its endpoints to two different points of $T$.
For $\mathbb Z^2 * \mathbb Z^2 \approx \pi_1(Y)$, take $Y$ to be two disjoint toruses $T_i$ ($i=1,2$), and an arc $B$ with endpoints attached to $p_i \in T_i$ ($i=1,2$).
Define a double covering space $Z$ of $Y$ consisting of disjoint toruses $\widetilde T_i \subset Z$ ($i=1,2$), such that $\widetilde T_i$ double covers $T_i$ with two points $\tilde p'_i,\tilde p''_i \in \widetilde T_i$ covering $p_i$, and with two arcs $\widetilde B', \widetilde B'' \subset Z$ that each cover the arc $B$, where $\widetilde B'$ has endpoints attached to $p'_1,p'_2$, and $\widetilde B''$ has endpoints attached to $p''_1,p''_2$.
But there is also a double covering map $Z \to X$ taking each $\widetilde T_i$ homeomorphically to $T$ and taking each of $\widetilde B', \widetilde B''$ homeomorphically to $A$.
By the way, as a consistency check one can do a quick Euler characteristic calculation: $\chi(X)=\chi(Y)=-1$, and $\chi(Z)=-2$. My first, now overwritten construction failed this check :-/
Notice finally that $\pi_1(Z) \approx \mathbb Z^2 * \mathbb Z^2 * \mathbb Z$.
Comment: Okay, I fixed it but it required a serious change to the construction. Thanks @Jacob for spotting that.
Comment: Thank you for the answer! Could you specify a bit more on what this degree 2 covering map looks like?
Comment: @LeeMosher I don't think this is a valid double cover, since you are only single covering the circle. And wrapping the arc twice around the circle would triple cover the wedge point.
Comment: Oops, you're right... not sure I can fix this...
Answer: We can show that these groups are quasi-isometric by showing that these are both q.i. to $\mathbb{Z}^2*\mathbb{Z}^2*\mathbb{Z}$.

Consider, as you mention in the question, the space $T\vee S^1$, whose fundamental group is $\mathbb{Z}^2 * \mathbb{Z}$. Using the standard double cover of this space, $T\vee T\vee S^1$, we see that $\mathbb{Z}^2 * \mathbb{Z}$ is quasi-isometric to $\mathbb{Z}^2*\mathbb{Z}^2*\mathbb{Z}$.

Express $\mathbb{Z}^2 * \mathbb{Z}^2$ as $\langle a,b,c,d~|~aba^{-1}b^{-1},cdc^{-1}d^{-1}\rangle$. Then $\mathbb{Z}^2 * \mathbb{Z}^2 * \mathbb{Z}$ is realized as the subgroup $\langle a^2,b,c^2,d,ac^{-1}\rangle$. (The map is the obvious one: $a^2$ and $b$ generate the first $\mathbb{Z}^2$, and so on.) Then you can show this has index 2 by showing that $1$ and $a^{-1}$ are the only left cosets.
Comment: Thanks for the answer! 1 totally makes sense, but for 2, could you maybe argue why they are q.i the same way you did in 1
Comment: @VSMASH I have expanded on point 2, although it should be said that the way I was able to generate this explicit group homomorphism was by inducing it from the map in Lee Mosher's answer. :)


Exterior derivative of a two-form with conditions

Question: With the use of this formula
$$d\omega(X_1, \dots, X_{r+1}) = \sum_{i=1}^{r}(-1)^{i+1}X_i\omega(x_1,\dots,\hat{X}_i,\dots,X_{r+1})+\sum_{i<j}(-1)^{i+j}\omega([X_i,X_j],X_1,\dots,\hat{X}_i,\dots,\hat{X}_j,\dots,X_{r+1}) $$
where the term under $\hat{}$ is removed, I want to get:
$$3d\sigma(X,Y,Z)=-\sigma([X,Y],Z).$$
For the specific case when $X,Y\in V_K(M)$ and $Z\in V(M)$, with $M$ a smooth manifold and $K$ is the characteristic distribution of $\sigma$. And $V_K(M)$ denote all vectors fields that are tangent to $K$.
With all the information of the problem, here is what I have done: the only Lie bracket that should remain is $[X,Y]$ as (for some reason) the Lie bracket of a vector field that is tangent to the other field is zero. And the same is true(?) for the two-forms.
This yields
$$3d\sigma(X,Y,Z)=X_3\sigma(X_1,X_2)-\sigma([X_1,X_2],X_3).$$
Obviously I have misunderstood something fundamental with both differential forms and Lie bracket. From this I can at least conclude that I lack the knowledge why a Lie bracket of a vector field tangent to the other field is zero. And why the same two vector fields in a two-form should be zero.
I would be grateful if someone could answer these questions of mine and perhaps guide me towards the correct reasoning for this problem.
Comment: What is the "characteristic distribution of $\sigma$"?
Comment: It satisfies $$K_M=\{X|\iota_X\sigma=0 \}\subset T_mM$$
Answer: If $X \in K_M$, then $\iota_X\sigma = 0$, so for any $Z \in V(M)$, $0 = (\iota_X\sigma)(Z) = \sigma(X, Z)$. Also note that $\sigma(Z, X) = -\sigma(X, Z) = 0$. So if $X \in K_M$ appears as either argument of $\sigma$, then that term is zero.
Note that
$$d\sigma(X, Y, Z) = X\sigma(Y, Z) - Y\sigma(X, Z) + Z\sigma(X, Y) - \sigma([X, Y], Z) + \sigma([X, Z], Y) - \sigma([Y, Z], X).$$
As $X, Y \in K_M$, any term in which $X$ or $Y$ appears as an argument is zero. The only term which doesn't is $\sigma([X, Y], Z)$. Therefore, $d\sigma(X, Y, Z) = -\sigma([X, Y], Z)$.
I believe the missing $3$ is due to a different convention for the exterior derivative.
Note that the distribution $K$ is involutive (closed under Lie bracket), and hence integrable, if and only if $d\sigma = 0$.


Do I need to nest observation windows in each trial as a random effect?

Question: The study is as follows:

Participants are observed at three ages.
Observations at each age involves 10 trials (i.e., stimuli they are presented with while their eye gaze is measured).
Each trial is split into 3 time windows.

Would it be correct to use a nested random effects structure, with windows nested within trials, trials nested within age, and age nested within participants?
Answer: Very often the correlation structure in the data is simpler than the one the design of the study suggests. Hence, I would suggest that you start with a simple random intercept term per participant, include then a random slope for age, and then a nested random effect for trials. At each step, you can use likelihood ratio tests to see if the additional random effects improve the model.