Is it or should it be possible to modify the GUI of an application after it's compiled?

Question: I'm a Linux user, and I have been very hesitant to use Glade to design GUIs, since the xml files it produces can easily be modified. I know it doesn't sound like a major issue, but what if it's a commercial app that you just don't want people changing?
I use Mac OS X every once in a while, and I figured out that they use files called ".nib"s for GUIs. I think they're essentially the same type used in Nextstep and Openstep (there's even a Linux app which lets you edit these files). Anyway, these files are included in the application bundle, and according to some people, are completely editable. This person claims he even successfully edited Keynote's interface.
Now, why would that be possible? Is it completely okay for the end user to change the interface? Or is it better to have the GUI directly in the compiled application code, like traditional GTK apps?
Comment: Even if it is possible: Why would you prevent it? Moddability is generally a plus (especially if officially supported, but the main point is that it's possible), and even if it isn't what would justify putting any effort or making any tradeoffs in preventing it?
Comment: Even "traditional GTK apps" can be changed by the user's GTK theme settings, or do you want to outlaw that too?
Comment: In OS X, nib files are not editable anymore. Before leopard, they were simply copied into the application at build time. Now, however, there is a different format used which is compiled and then copied to the bundle. These new ones are not editable.
Answer: OS X nib files are one option; the other option is to do things programmatically. For android, XML files can define the GUI or program code can do it. In Windows WPF, the UI is made in XML. Firefox/Mozilla? XUL, another XML-based UI language.
Most modern GUI toolkits have either both of these options or even just defining UIs in files.
But even binaries are modifiable. With a good binary reverse engineering tool, it's wide open. The only way to be really certain is to do what Apple did with iOS, and run signed code; the entire bundle is signed by a key and can't be run if modified.
This isn't a problem for most everyone. Why do you care if the UI is modified? The underlying code isn't, so functionality can't be added or modified.
As a corollary (and a little off-topic) something that you might have a valid concern about is stuff a little more like this.
Answer: I don't really see a problem with it. If a user messes up his UI, then it's his problem. Think of it like moddable games. Users always loved them, and in the end, most games benefit from it. There is usually nothing secret about an application's user interface. If there is, you could always do some sort of encryption.
As others have said, you can also add checksums if you just want to disallow editing.
Answer: The xml specifies little more than what the interface looks like.  Without the compiled-in event handling code, it's pretty much useless.  My opinion is customers change it at their own risk, and you might actually get some free useful improvements out of their hacks.
If you're really paranoid about people changing it, you could always add an MD5 digest verification step or something when you load the xml, or compile the xml string into a header file, but that defeats many of the benefits.
Comment: If you're that paranoid, you should stop coding and get help.
Answer: The theming engine can make substantial-looking changes to your GUI, as can tools like Parasite.  Updating the Glade layout — at their own risk — is much safer than either of those.
What's wrong with users customizing the UI anyway?


How to stop one childrenlistener when other childrenlistener start in firebase android

Question: I have two childrenlistener from firebase in the same activity called from a popup menu that has two options. (two options, two childrenlistener).
I need only to run a childrenlistener, that is, if the user presses "option1" their thread is created, and if the user presses "option2", the thread of "option1" is canceled and it only shows the thread data of "option2" and vice versa
PopupMenu popup = new PopupMenu(Ruta1Manantiales.this, busLocation);
            popup.getMenuInflater().inflate(R.menu.sentidos, popup.getMenu());
            popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
                public boolean onMenuItemClick(MenuItem item) {
                    switch (item.toString()){
                        case "option1":
                            _globalString = "option1";
                            loginToFirebase();
                            break;
                        case "option2":
                            _globalString = "option2";
                            loginToFirebase();
                            break;
                    }
                    return true;
                }
            });
            popup.show(); //showing popup menu

private void loginToFirebase() {
    // Authenticate with Firebase, and request location updates
    FirebaseUser currentUser = mAuth.getCurrentUser();
    if(currentUser!=null){
        if(_globalString == "ida"){
            checkIfChildrenExistIda();
        }

        if(_globalString == "vuelta"){
            checkIfChildrenExistVuelta();
        }
    }
    else{
        Toast.makeText(getApplicationContext(),
                "Firebase auth failed",
                Toast.LENGTH_LONG)
                .show();
        Log.d(TAG, "firebase auth failed");
    }
}

private void checkIfChildrenExistIda(){
    DatabaseReference fbDb = null;
    if (fbDb == null) {
        fbDb = FirebaseDatabase.getInstance().getReference();
    }

    fbDb.child("locations/unidad_1/ida")
            .addListenerForSingleValueEvent(new ValueEventListener() {
                @Override
                public void onDataChange(DataSnapshot dataSnapshot) {
                    // get total available quest
                    int size = ((int) dataSnapshot.getChildrenCount());
                    if (size >= 1){
                        subscribeToUpdatesIda();
                    } else if (size <= 0){
                        Toast.makeText(getApplicationContext(),
                                "No buses available",
                                Toast.LENGTH_LONG)
                                .show();
                    }
                }
                @Override
                public void onCancelled(DatabaseError databaseError) {

                }
            });
}

private void checkIfChildrenExistVuelta(){
    DatabaseReference fbDb = null;
    if (fbDb == null) {
        fbDb = FirebaseDatabase.getInstance().getReference();
    }

    fbDb.child("locations/unidad_1/vuelta")
            .addListenerForSingleValueEvent(new ValueEventListener() {
                @Override
                public void onDataChange(DataSnapshot dataSnapshot) {
                    // get total available quest
                    int size = ((int) dataSnapshot.getChildrenCount());
                    if (size >= 1){
                        subscribeToUpdatesVuelta();
                    } else if (size <= 0){
                        Toast.makeText(getApplicationContext(),
                                "No hay camiones disponibles",
                                Toast.LENGTH_LONG)
                                .show();
                    }
                }
                @Override
                public void onCancelled(DatabaseError databaseError) {

                }
            });
}

private void subscribeToUpdatesIda() {
    DatabaseReference ref = FirebaseDatabase.getInstance().getReference().child("locations").child("unidad_1").child("ida");
    ref.addChildEventListener(new ChildEventListener() {
        @Override
        public void onChildAdded(DataSnapshot dataSnapshot, String previousChildName) {
            setMarkerIda(dataSnapshot);
        }

        @Override
        public void onChildChanged(DataSnapshot dataSnapshot, String previousChildName) {
            setMarkerIda(dataSnapshot);
        }

        @Override
        public void onChildMoved(DataSnapshot dataSnapshot, String previousChildName) {

        }

        @Override
        public void onChildRemoved(DataSnapshot dataSnapshot) {
            removeMarkerIda(dataSnapshot);
            //Toast.makeText(Ruta1Manantiales.this, "child removed", Toast.LENGTH_LONG).show();

        }

        @Override
        public void onCancelled(DatabaseError error) {
            Log.d(TAG, "Failed to read value.", error.toException());
        }
    });
}

private void removeMarkerIda(DataSnapshot dataSnapshot) {
    //Toast.makeText(Ruta1Manantiales.this, "child removed 2", Toast.LENGTH_LONG).show();
    String key = dataSnapshot.getKey();
    HashMap<String, Object> value = (HashMap<String, Object>) dataSnapshot.getValue();

    if (mMarkers.containsKey(key)) {
        Marker marker = mMarkers.remove(key);
        if(marker != null){
            marker.remove();
        }
    }
}

private void setMarkerIda(DataSnapshot dataSnapshot) {
    // When a location update is received, put or update
    // its value in mMarkers, which contains all the markers
    // for locations received, so that we can build the
    // boundaries required to show them all on the map at once
    Bitmap markerBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.bus_marker);
    markerBitmap = scaleBitmap(markerBitmap, 70, 70);

    String key = dataSnapshot.getKey();
    HashMap<String, Object> value = (HashMap<String, Object>) dataSnapshot.getValue();
    double lat = Double.parseDouble(value.get("latitude").toString());
    double lng = Double.parseDouble(value.get("longitude").toString());
    LatLng location = new LatLng(lat, lng);
    if (!mMarkers.containsKey(key)) {
        mMarkers.put(key, mMap.addMarker(new MarkerOptions().icon(BitmapDescriptorFactory.fromBitmap(markerBitmap)).title("Ruta 1 - Unidad-Manantiales").position(location)));
    } else {
        mMarkers.get(key).setPosition(location);
    }

    LatLngBounds.Builder builder = new LatLngBounds.Builder();
    for (Marker marker : mMarkers.values()) {
        builder.include(marker.getPosition());
    }

    if (firstLoad) {
        mMap.animateCamera(CameraUpdateFactory.newLatLngBounds(builder.build(), 13));
        LatLng marker = new LatLng(19.407021,  -102.046595);
        mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(marker, 12.9f));
        firstLoad = false;
    }
}

private void subscribeToUpdatesVuelta() {
    DatabaseReference ref = FirebaseDatabase.getInstance().getReference().child("locations").child("unidad_1").child("vuelta");
    ref.addChildEventListener(new ChildEventListener() {
        @Override
        public void onChildAdded(DataSnapshot dataSnapshot, String previousChildName) {
            setMarkerVuelta(dataSnapshot);
        }

        @Override
        public void onChildChanged(DataSnapshot dataSnapshot, String previousChildName) {
            setMarkerVuelta(dataSnapshot);
        }

        @Override
        public void onChildMoved(DataSnapshot dataSnapshot, String previousChildName) {

        }

        @Override
        public void onChildRemoved(DataSnapshot dataSnapshot) {
            removeMarkerVuelta(dataSnapshot);
            //Toast.makeText(Ruta1Manantiales.this, "child removed", Toast.LENGTH_LONG).show();
        }

        @Override
        public void onCancelled(DatabaseError error) {
            Log.d(TAG, "Failed to read value.", error.toException());
        }
    });
}

private void removeMarkerVuelta(DataSnapshot dataSnapshot) {
    //Toast.makeText(Ruta1Manantiales.this, "child removed 2", Toast.LENGTH_LONG).show();
    String key = dataSnapshot.getKey();
    HashMap<String, Object> value = (HashMap<String, Object>) dataSnapshot.getValue();

    if (mMarkers.containsKey(key)) {
        Marker marker = mMarkers.remove(key);
        if(marker != null){
            marker.remove();
        }
    }
}

private void setMarkerVuelta(DataSnapshot dataSnapshot) {
    // When a location update is received, put or update
    // its value in mMarkers, which contains all the markers
    // for locations received, so that we can build the
    // boundaries required to show them all on the map at once
    Bitmap markerBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.bus_marker);
    markerBitmap = scaleBitmap(markerBitmap, 70, 70);

    String key = dataSnapshot.getKey();
    HashMap<String, Object> value = (HashMap<String, Object>) dataSnapshot.getValue();
    double lat = Double.parseDouble(value.get("latitude").toString());
    double lng = Double.parseDouble(value.get("longitude").toString());
    LatLng location = new LatLng(lat, lng);
    if (!mMarkers.containsKey(key)) {
        mMarkers.put(key, mMap.addMarker(new MarkerOptions().icon(BitmapDescriptorFactory.fromBitmap(markerBitmap)).title("Ruta 1 - Unidad-Manantiales").position(location)));
    } else {
        mMarkers.get(key).setPosition(location);
    }

    LatLngBounds.Builder builder = new LatLngBounds.Builder();
    for (Marker marker : mMarkers.values()) {
        builder.include(marker.getPosition());
    }

    if (firstLoad) {
        mMap.animateCamera(CameraUpdateFactory.newLatLngBounds(builder.build(), 13));
        LatLng marker = new LatLng(19.407021,  -102.046595);
        mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(marker, 12.9f));
        firstLoad = false;
    }
}

Answer: When you attach a listener to a reference/query, Firebase returns a reference to that listener. You'll want to hold on to that reference in a member field:
ChildEventListener mActiveListener;

And then when you attach the listener:
mActiveListener = ref.addChildEventListener(new ChildEventListener() {
  ...

Then when you are ready to attach the other listener, first remove the previous one with:
if (mActiveListener != null) {
  ref.removeEventListener(mActiveListener);
}

Comment: Thank you!
your help worked,
I only added "ref" as a global variable so that it was recognized in the other listener
Comment: if I press the active listener again, the app crashes :(. java.lang.NullPointerException: Attempt to invoke virtual method 'void com.google.firebase.database.Query.removeEventListener(com.google.firebase.database.ChildEventListener)' on a null object reference
Comment: That looks like you've set `ref` to `null`.


Calculate the intersection area between a pyramid and plane $\pi$.

Question: Having problem on this one.
I drew it on GeoGebra, and managed to see some congruences, but couldn't prove it. I managed to do it using analytic geometry on $\mathbb{R}^3$, but I also tried using only synthetic geometry, and it got kinda big. Could someone try doing it via synthetic geometry?
Here's the question.

Let $VABCD$ be a regular pyramid whose lateral faces are equilateral triangles of side $1$. Let $P$ be an extension of segment $VA$ such that $A$ is on $VP$ and $AP = \frac{1}{2}$.
  Considering a plane $\pi$ determined by $P$ and the middle points of the segments $BC$ and $AD$, calculate the area of the intersection between the plane $\pi$ and the pyramid.

(a) $\frac{16\sqrt{11}}{7}$
(b) $\frac{7\sqrt{11}}{16}$
(c) $\frac{7\sqrt{11}}{64}$
(d) $\frac{64\sqrt{11}}{7}$
(e) $\frac{32\sqrt{11}}{7}$
Answer: For quick answer, say, in a tight test situation, one could observe  that the intersection is a symmetric trapezoid, which has its one base line across the pyramid base along the middle and the other base line on one side of the pyramid at a moderate angle. So, its area is roughly half that of the pyramid base (which is 1). The closest choice then would be (C); all other answers are far off from 1/2.

Now, let's do it more carefully. First, the height of the pyramid is found to be $\sqrt{2}/2$ from the given of a unit square base and four equilateral sides. All other segments in the diagram are then derived and marked.
The long base length of the intersecting trapezoid is simply 1 and  the short base length is 3/4, which can be obtained from similarly triangles of side ratio 1:3. The derivation of its height can be similarly carried out, from similar triangles of side ratio 1:2 and at $h=\sqrt{11}/8$.
So, its area is,
$$\frac{1}{2}\times \left( 1 + \frac{3}{4}\right) \times \frac{\sqrt{11}}{8}=\frac{7\sqrt{11}}{64}$$


Ancorar um TR é possível?

Question: É possível por fora de um elemento tr linkar algum endereço como abaixo?

Se não é possível, o JavaScript resolveria isto ou é melhor esquecer?
Tenho a seguinte tabela como mostrado na imagem abaixo, e queria que quando o usuário clicasse numa linha fosse direcionado para um endereço X.
Answer: Infelizmente não existe nenhum construção específica para isso. Você terá que fazer "na mão".
Fica relativamente simples fazer com jQuery e data-* attributes. Exemplo:
JavaScript:
$('tr').click(function() {
    window.location.href = $(this).attr('data-href');
});

HTML:

      Empresa

      CEO

       Google

      Larry Page

        Yahoo!

      Marissa Mayer

        Microsoft

      Steve Ballmer

Exemplo mais completo (incluindo estilo).
Comment: +1 Pelo "(incluindo estilo)"
Comment: Verdade @Zignd! Veio completo a resposta. Valeu @talles
Comment: Para evitar comportamentos inesperados é recomendável incluir o `[data-href]` no seletor: `$('tr[data-href]').click(...)`.
Answer: Sim é possivel com javascript.
Inserir links entre table e tr não é sintaxe correcta, por isso a via é mesmo javascript.
Pode adicionar um "event handler" que procura cliques dentro das linhas da tabela. Quando acontecer um clique vai buscar o link dessa linha e abre-o.
Exemplo com jQuery:
var linhaTabela = $('table tr');
linhaTabela.on('click', function (event) {
    var link = $(this).find('a').attr('href')
    link && window.location = link;
});

Exemplo

Se não houver link dentro da linha como eu referí no exemplo acima, pode atribuir via seu php a informação do link num campo data-, aí sim na linha da tabela.
Assim o meu exemplo é
html

javascript
var linhaTabela = $('table tr');
linhaTabela.on('click', function (event) {
    var link = $(this).data('href');
    link && window.location = link;
});

Exemplo
Comment: o link seria por fora da `tr`.
Comment: @Luitame, como por fora? Pode explicar melhor?
Comment: Sim! Eu tenho uma `table` correto? Tenho um loop em PHP para imprimir linhas (`tr`) e por fora dessa `tr` queria colocar um link. Exemplo: `   Conteudo   `
Comment: Fazer como que a linha (`tr`) se torne um hyperlink, certo?
Comment: correto!!! @Zignd
Answer: Se você embrulhar a
 num , seu HTML se tornará inválido. Sugiro que você coloque a URL num attributo data, e use um código muito semelhante ao do Sergio para navegar para o destino.
HTML

        ...

JavaScript (jQuery)
$('table').on('click', 'tr', function() {
    var url = $(this).attr('data-url');
    if(url) window.location = url;
});

Comment: Obrigado ai pela força...
Comment: +1 porque a resposta é util, correcta e porque quero [uma medalha](http://br.stackoverflow.com/help/badges/63/sportsmanship) :)
Comment: Hehe, obrigado @Sergio. Eu tenho o hábito de votar em respostas concorrentes no SO, e já aviso que essa medalha demora um pouco para chegar.
Comment: hehe, sim, por isso é bom ganhar o hábito cedo :P

Ancorar um TR é possível?


Strange Entity Framework behavior

Question: I have 2 models:
public class Office
{
    [Key] public int OfficeId { get; set; }
    public string Brand { get; set; }
    public string Type { get; set; }
    [NotMapped] public IRepository<CarItem> CarsDataBase { get; set; }
    public virtual ICollection<CarItem> Cars { get; set; }
    public Office(string brand, string type)
    {
        Type = type;
        Cars = new List<CarItem>();
        Brand = brand;
    }
}

and
public class CarItem
{
    public CarItem() { } //for serialization
    public CarItem(string brand, string model, uint price, uint stockBalance)
    {
        Brand = brand;
        Model = model;
        Price = price;
        StockBalance = stockBalance;
    }
    [Key] public int ItemId { get; set; }
    public string Brand { get; set; }
    public string Model { get; set; }
    public uint Price { get; set; }
    public uint StockBalance { get; set; }
    public int? OfficeId { get; set; }
    public Office Office { get; set; }
}

and DataBase Context
public class EFDataBaseContext : DbContext
{
    public DbSet<Office> Offices => Set<Office>();
    public DbSet<CarItem> CarItems => Set<CarItem>();
    public EFDataBaseContext()
    {
        Database.EnsureCreated();
    }
    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        optionsBuilder.UseSqlServer("Server=(localdb)\\mssqllocaldb;Database=carstoredb;Trusted_Connection=True;");
    }
    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Office>().HasData
        (
            new Office("Audi", "SQL")
            {
                OfficeId = 1,
            },
            new Office("Scoda", "SQL")
            {
                OfficeId = 2,
            }
        );
        modelBuilder.Entity<CarItem>(entity =>
        {
            entity.HasOne(item => item.Office).WithMany(office => office.Cars).HasForeignKey(item => item.OfficeId).OnDelete(DeleteBehavior.Cascade);
        });
        modelBuilder.Entity<SparePart>(entity =>
        {
            entity.HasOne(item => item.Office).WithMany(office => office.Parts).HasForeignKey(item => item.OfficeId).OnDelete(DeleteBehavior.Cascade);
        });
        modelBuilder.Entity<CarItem>().HasData
        (
            new CarItem { OfficeId = 1, ItemId = 1, Brand = "Audi", Model = "A228", Price = 4, StockBalance = 14 },
            new CarItem { OfficeId = 1, ItemId = 2, Brand = "Audi", Model = "Super", Price = 44, StockBalance = 5 },
            new CarItem { OfficeId = 2, ItemId = 3, Brand = "Scoda", Model = "Logan", Price = 47, StockBalance = 9 },
            new CarItem { OfficeId = 2, ItemId = 4, Brand = "Scoda", Model = "Spider", Price = 78, StockBalance = 3 }
        );
    }

Manually I added an office called BSU.
And in main function I write this:
using (EFDataBaseContext db = new EFDataBaseContext())
{
    Office office = mainOffice.Dealerships.FirstOrDefault(of => of.Brand == "BSU");
    CarItem carItem = new CarItem(office.Brand, "BSss", 2222, 4);
    office.CarsDataBase ??= new EFDataBase(office);
    office.CarsDataBase.Create(carItem);
}

Adding a new CarItem to the BSU somehow magically creates a new office named BSU in my database every time a new CarItem is added to the BSU.
using (EFDataBaseContext db = new EFDataBaseContext())
{
    Office office = mainOffice.Dealerships.FirstOrDefault(of => of.Brand == "Audi");
    CarItem carItem = new CarItem(office.Brand, "AuuuU", 2222, 4);
    office.CarsDataBase ??= new EFDataBase(office);
    office.CarsDataBase.Create(carItem);
}

Adding a new CarItem to an Audi, on the other hand, does absolutely nothing. No new cars with the Audi brand appear in the database, and nothing at all.
Comment: *//for serialization* - avoid serializing EF entity graphs; they contain cycles. Consider dedicated front end DTOs instead
Comment: I don't see your `Dealerships` object. If you inspect your `.FirstOrDefault()` of the returned `office`, does it contain anything? (eg, put a breakpoint on: `Office office = mainOffice.Dealerships.FirstOrDefault(of => of.Brand == "Audi");`)
Comment: What is anything like `[NotMapped] public IRepository CarsDataBase { get; set; }` doing inside a db entity?
Comment: @Caius Jard
I transfer there the office to which my CarItem will be attached. Here is the Create() method that adds a new CarItem to the database:

  public void Create(CarItem item)
        {
            using (EFDataBaseContext DataBase = new EFDataBaseContext())
            {
                item.Office = Office;
                DataBase.CarItems.Add(item);
                DataBase.SaveChanges();
            }
        }`
Answer: Seems like you're over complicating things
Adding a new Car to an existing Office should perhaps looks like:
var ctx = new EFDatabaseContext();
var off = ctx.Offices.FirstOrDefault(o => o.Type == "Main" and o.Brand == "Audi");
off.Cars.Add(new CarItem(off.Brand, "AuuuU", 2222, 4));
ctx.SaveChanges();

Find the office, add a car, save the changes

Strange Entity Framework behavior


Insert a lot of records into database

Question: I have a list with a lot of (500+) codes and I want to insert it into database.
For example: User given codes to textarea and codes are seperated by new line (\n). In PHP it is $_POST['codes']. Of course I can just use explode() function and insert all codes in loop, but I'm thinking it's not a good idea with 500 repeatitions.
So, how can I do this the most optimal?
Comment: Have you tried it? 500 inserts is practically nothing.
Comment: Probably best to use a prepared statement as well to speed it up that little bit.
Comment: it's ok to explode the field
Comment: 500-1000 repeats is nothing for both PHP and MySQL. So just explode and insert...
Comment: Time isn't an issue and `$_POST['codes']` means: data is already in the memory anyway.
Answer: Depending on the size of your data, you could make it all into a single query if you are worried about number of separate inserts:
mysql_query("INSERT INTO mytable(`People`, `Places`, `Ideas`, `things`)
             VALUES ('40', '15', '0',  '0'),
             ('0',  '5',  '10', '0'),
             ('10', '0',  '11', '12')");

(example from: https://stackoverflow.com/a/10286687/486780)
Comment: It's crucial for this question: if you run prepared statements, the SQL interpreter has to interpret the query only once and you can run the same query over and over again at high speed. That's a totally different syntax from yours.
Comment: Don't recommend `mysql_*` functions, they are deprecated (see the [red box](http://php.net/mysql_query)). It's advised to use [prepared statements](http://bobby-tables.com/php.html).
Comment: Of course, you are 100% right about prepared statements. But as a proof of concept, this would be one way of doing it.
Comment: You are totally right. Missed the point of your initial comment a bit. All I can do is agree now.

Insert a lot of records into database


Add a class to a row in a view

Question: i'm trying to create a module that adds a 'new' class to a row based on the date it was published.
So i thought of doing something like
<code>if ($data > 10 days ago){
  $this_row addclass new
}
</code>
But whats the best way to do this? I would like to put this in a module so i can simply turn it on and off and avoid problems with template files from ds.
I can only find a way using hook_views_pre_render to add a class to all the rows, but nothing about adding it to one specific row. Maybe i need to use another hook?
Answer: Writing a view handler would be the perfect way to do this. The handler itself will be almost as simple as your example code.
However getting everything right to get the handler called from views isn't easy. A good example to learn from is the maillog module. It integrates its log table with views and adds a custom handler.

Add a class to a row in a view


Linux execute script based on usb port

Question: Hello I am working on debian system installed on embedded system. The PC has 3 ports usb let's call it A, B, C. I want to execute different script based on the usb port. How can I achieve this?
I found a lot of articles about the udev rules and I have the below rule that it works if I connect a usb.
ACTION=="add", SUBSYSTEM=="block", KERNEL=="sd[a-z]1", SYMLINK+="usb_to_check", RUN+="/usr/local/bin/check-usb1.sh"

How can I extend this rule to work only if I connect a device let's say to usb A??
Comment: This Q is doesn't seem to be about programming as defined for StackOverflow. It **may** be more appropriate on either http://unix.stackexchange.com (Unix & Linux) OR http://superuser.com . Use the `flag` link at the bottom of your Q and ask the moderator to move it. Please don't post the same Q on 2 different sites. Please read  http://stackoverflow.com/help/how-to-ask http://stackoverflow.com/help/dont-ask and http://stackoverflow.com/help/mcve before posting more Qs here. Good luck.
Answer: lsusb outputs the USB bus and USB ports to which devices are attached. in the output some of the USB root hubs are internal USB hubs to that also bluetooth and webcam and so on are attached, see https://unix.stackexchange.com/questions/144029/command-to-determine-ports-of-a-device-like-dev-tty-usb0
you should figure out on which USB bus your external ports are linked. on my computer all external USB ports are linked to Bus 01
to do this check the output of lsusb -t, then attach a usb device and check the output of lsusb -t again. then you know what 'adresses' your three external usb ports have in your devices internal usb structure tree:
internal USB ports:
/:  Bus 04.Port 1: Dev 1, Class=root_hub, Driver=ohci_hcd/5p, 12M
/:  Bus 03.Port 1: Dev 1, Class=root_hub, Driver=ohci_hcd/5p, 12M
/:  Bus 02.Port 1: Dev 1, Class=root_hub, Driver=ehci_hcd/5p, 480M
    |__ Port 1: Dev 64, If 0, Class='bInterfaceClass 0x0e not yet handled', Driver=uvcvideo, 480M
    |__ Port 1: Dev 64, If 1, Class='bInterfaceClass 0x0e not yet handled', Driver=uvcvideo, 480M

external USB ports:
/:  Bus 01.Port 1: Dev 1, Class=root_hub, Driver=ehci_hcd/5p, 480M
    |__ Port 3: Dev 116, If 0, Class='bInterfaceClass 0xe0 not yet handled', Driver=rndis_host, 480M
    |__ Port 3: Dev 116, If 1, Class=data, Driver=rndis_host, 480M

USB stick attached to external port # 2
/:  Bus 01.Port 1: Dev 1, Class=root_hub, Driver=ehci_hcd/5p, 480M
    |__ Port 2: Dev 119, If 0, Class=stor., Driver=usb-storage, 480M
    |__ Port 3: Dev 116, If 0, Class='bInterfaceClass 0xe0 not yet handled', Driver=rndis_host, 480M
    |__ Port 3: Dev 116, If 1, Class=data, Driver=rndis_host, 480M

after this procedure you the 'addresses' of your external USB ports
in dmesg an attached USB device always appears with a line that contains the USB bus and port number:
[186067.360139] usb 1-1: new high-speed USB device number 123 using ehci_hcd  is bus 001 port 001
[186067.360139] usb 1-2: new high-speed USB device number 123 using ehci_hcd  is bus 001 port 002
[186067.360139] usb 1-3: new high-speed USB device number 123 using ehci_hcd  is bus 001 port 003
in your script you grep this line using the command dmesg | grep "usb 1" | tail -1 (the tail -1 greps the last occurence, see http://www.stackoverflow.com/questions/24014194/how-to-grep-the-last-occurence-of-the-line-pattern )
you can get the port number directly using the command
dmesg | grep -o -P 'usb 1.{0,3}' |  tail -1 | head -c 7 | tail -c 1 (if all your external ports are on Bus 001)
( Grep characters before and after match?, http://www.unix.com/unix-for-dummies-questions-and-answers/28542-how-do-i-get-nth-character-string.html )
so with this you get the USB port number to that the latest USB device (your device) was attached and this you can use in your udev script (if ...)

you can also find the USB bus tree structure in the  /dev/bus/usb/ file sytem i.e. Bus 01 Port 1 is /dev/bus/usb/001/001
see http://www.linuxnix.com/find-usb-device-details-in-linuxunix-using-lsusb-command/
Answer: there is a better solution. you can assign a specific /dev/x device node based on vendorID and productID of your stick using udev, see https://askubuntu.com/questions/127695/force-specific-letter-for-usb-drive-in-dev-sd (x is an arbitrary name)
with this fixed device node you can use udevadm to query the USB port to which the device is attached
udevadm info --query=all --attribute-walk --name/dev/x
and grep the USB port number from it (see other answer ...)

Linux execute script based on usb port


cant figure out how to bind 2 drop down list

Question: How to Bind Two Drop DownList in MVC like onchange event of first DropdownList
it load another
    My Model
    public int cat_id { get; set; }
    public string cat_name { get; set; }
    public string cat_img { get; set; }

    2nd Model
    public int scat_id { get; set; }

    [Required(ErrorMessage = "Input field required*")]
    public string scat_name { get; set; }
    public string scat_img { get; set; }
    [Required(ErrorMessage = "Input field required*")]
    public int scat_fk_cat_id { get; set; }

   Controller
     public ActionResult CreateProduct()
    {
        if (Session["ad_id"]!=null)
        {
            List<tbl_shopCategory> lst = db.tbl_shopCategory.ToList();
            List<tbl_subCategory> li = db.tbl_subCategory.ToList();
            ViewBag.cat = new SelectList(lst, "cat_id", "cat_name");
            ViewBag.scat = new SelectList(li, "scat_id", "scat_name");

            return View();
        }
        else
        {
           return RedirectToAction("AdminSignIn");
        }

    }

This is my piece of code unable to bind both dropdowns also searched for the problem couldn't find the proper answer thats why posting this
Answer: Here are the code with your requirement.
You need create a action to filter subcategory, implement change event of drop down in jquery, in change event call AJAX to get data.
Controller:
 public class ProductController : Controller
    {
        private static List<tbl_shopCategory> categories = new List<tbl_shopCategory>
        {
            new tbl_shopCategory
            {
                cat_id = 1, cat_name = "Beverage"
            },
            new tbl_shopCategory
            {
                cat_id = 2, cat_name = "Fruits"
            }
        };

        private static List<tbl_subCategory> subcategories = new List<tbl_subCategory>
        {
            new tbl_subCategory
            {
                scat_id = 1, scat_fk_cat_id = 1, scat_name = "Sub Beverage 1"
            },
            new tbl_subCategory
            {
                scat_id = 2, scat_fk_cat_id = 1, scat_name = "Sub Beverage 2"
            },

            new tbl_subCategory
            {
            scat_id = 3, scat_fk_cat_id = 2, scat_name = "Sub Fruits 1"
        },
        new tbl_subCategory
        {
            scat_id = 4, scat_fk_cat_id = 2, scat_name = "Sub Fruits 2"
        }
        };
        public ActionResult CreateProduct()
        {
            //if (Session["ad_id"] != null)
            //{
            List<tbl_shopCategory> lst = categories;
            List<tbl_subCategory> li = subcategories;
            ViewBag.cat = new SelectList(lst, "cat_id", "cat_name");
            ViewBag.scat = new SelectList(li, "scat_id", "scat_name");

            return View();
            //}
            //else
            //{
            //    return RedirectToAction("AdminSignIn");
            //}

        }

        public JsonResult GetSubCategory(int categoryId)
        {
           return Json(subcategories.Where(c => c.scat_fk_cat_id == categoryId).ToList(), JsonRequestBehavior.AllowGet) ;
        }
    }

    public class tbl_subCategory
    {
        public int scat_id { get; set; }

        [Required(ErrorMessage = "Input field required*")]
        public string scat_name { get; set; }
        public string scat_img { get; set; }
        [Required(ErrorMessage = "Input field required*")]
        public int scat_fk_cat_id { get; set; }
    }

    public class tbl_shopCategory
    {
        public int cat_id { get; set; }
        public string cat_name { get; set; }
        public string cat_img { get; set; }
    }

CreateProduct.cshtml
@using System.Collections

@{
    ViewBag.Title = "CreateProduct";
}

CreateProduct

@Html.DropDownList("Category", (IEnumerable<SelectListItem>)ViewBag.cat, string.Empty, new {})

@Html.DropDownList("SubCategory", (IEnumerable<SelectListItem>)ViewBag.scat, string.Empty, new { })

Comment: Thank You So Much
Comment: Please check your code in GetSubCategory may be exceotion in that method
Comment: jquery.3.2.1.min.js:4 GET http://localhost:50045/Admin/GetSubCategory?categoryId=1419 500 (Internal Server Error)
Getting this error in console
Comment: The controller name is Product controller or AdminController? I tried jquery.3.2.1.min.js it worked well, 500 error is not related jquery
Comment: AdminController also changed url with
url: '@Url.Action("GetSubCategory","Admin")',
Comment: Did you debug in action? If not success, Please post your code here


Percorrer array e localizar um caracter diferente de um numero

Question: A ideia é receber um numero de 4 digitos e depois realizar uma variedade de contas mas existe uma condição de entrada:
Caso no meio dos 4 digitos esteja um caracter que não um numero então necessito de o imprimir.
Sem utilização de metodos.
Não consigo realizar o seguinte código:
Receber uma entrada exemplo: 3?56

Guardar {3, ?, 5 ,6} num array sem saber qual é a entrada.
Verificar se alguma das posições do array não está entre 0 e 9.

Neste caso ? não é um numero então imprime.
Eu queria guardar nas 4 posições do array.
    int i;
    char [] digitos = new char[3];
    digitos [0] =
    digitos [1] =
    digitos [2] =
    digitos [3] =
    for(i=0; i<digitos.length; i++);{
        if(digitos[i]<(char)0||digitos[i]>(char)9) System.out.println("Digito "+digitos[i]+" invalido");
        System.exit(0);

Comment: O que você já tentou? Que linguagem está usando?
Comment: Linguagem Java.
Comment: Já está peço desculpa
Comment: Alguém pode ajudar?
Answer: Tem vários problemas no trecho de código. Vamos lá:
1 - char [] digitos = new char[3];
Se você quer um array com 4 elementos, seu tamanho precisa ser quatro, seu índice máximo é 3, pois começa do índice 0.
2 - for(i=0; i<digitos.length; i++);{
Esse ; faz com que o i extrapole o tamanho do vetor, dessa forma você deve removê-lo.
3 - if(digitos[i]<(char)0||digitos[i]>(char)9) System.out.println("Digito "+digitos[i]+" invalido");
   System.exit(0);
Aqui existem 2 problemas. O primeiro é que a condição de comparação dos caracteres está incorreta pois o casting não vai resultar numa verificação válida da natureza dígito do caractere. Aqui você deve comparar char com char, pois fazendo esse casting você está comparando o código ascii com o char. O segundo problema é que teu exit está fora do if, fazendo assim que o programa encerre logo após a primeira iteração.
Então, com base nos problemas apresentados, a solução final seria algo como:
int i;
    Scanner scanner = new Scanner(System.in);
    String numero = scanner.nextLine();
    char [] digitos = numero.toCharArray();
    for(i=0; i<digitos.length; i++){
        if(digitos[i]<'0' || digitos[i]>'9') {
            System.out.println("Digito "+digitos[i]+" invalido");
            System.exit(0);
        }
    }

Comment: @BFR essa informação deveria estar na pergunta, por isso é importante adicionar o maximo de informações, senão acaba ocorrendo isso.
Comment: Pronto, editei a resposta. Usa o scanner para ler e depois converter para o array de chars a string. Aí corrige a comparação dos chars sem utilizar métodos.
Comment: Não posso utilizar metodos.
A questão é que como é que:
Guardo a entrada de maneira a separa-la em caracteres para depois serem introduzidos no array?
Comment: @diegofm Já corrigi. Vou estar mais atento a esse tipo de situações. Obrigado
Comment: Muito obrigado.


Bloquear envio de formulário quando clicar em voltar

Question: Pode parecer uma pergunta besta mas estou abismado que quando clico no botão voltar, o formulário é enviado.
O código é similar a este:
<code><form id="idform" method="post" onsubmit="return funcaodevalidacao(this);">
    <!-- conteúdo do form -->
    <input type="submit" value="Enviar"> <button onclick="window.location.href = 'URL'">Voltar</button>
</form>
<script>
    $('form').submit(function (ev) {
        ev.preventDefault();
        $(window).unbind('beforeunload');
        return false;
    });
</script>
</code>
O que acontece é o seguinte: quando clico em Voltar, que deveria me redirecionar para uma URL desejada, o formulário é ENVIADO, e logo em seguida é redirecionado para a URL, o que não estou entendendo é o porque do formulário estar sendo enviado.
Já tentei a forma descrita acima para usar o preventDefault, desabilitar o beforeunload, retornar false, mas o formulário ainda assim é enviado.
Como faço para bloquear este comportamento? estou testando no firefox.
PS:  a função: funcaodevalidacao(this) está retornando false por questões de teste.
A solução paliativa que encontrei foi remover o elemento 'form', mas acredito que essa não seja a alternativa correta. Verifiquei no link http://www.w3.org/TR/html401/interact/forms.html#h-17.12 que desabilitar o elemento  também não é possível.
Answer: Na verdade a forma que estava utilizando no exemplo acima adiciona uma segunda chamada de submit onde na verdade impede o envio formulário mas mesmo assim ainda chama a função de validação.
A solução mais correta que pensei neste caso foi adicionar este script ao botão voltar:
<code>$('form').attr('onsubmit','return false;');window.location.href='URL'
</code>
Desta forma sobrescreve a função de validação que dava a impressão que o formulário estava sendo enviado.


After the first answer, Prolog shows the error "char_code/2: Cannot represent due to 'character_code'"

Question: In normal situation, we can use ";" to show the next answer if there is one.
But if I do this, it shows me
error: char_code/2: Cannot represent due to 'character_code'

In stead of ";", I use "shift + ;", and prolog gives me a prompt
Unknown action: : (h for help)   Action?

then if I input ";", the designable answers will be shown one by one.
What is the problem?
Comment: Please show us the code.
Comment: Does your program do a `read`?
Comment: What happens if you use the spacebar instead ? Also my keyboard need shift to emit ';' .
Answer: Use swipl-win.exe instead of swipl.exe can solve this problem.(I tried 6.x and 7.x)
By the way, swipl works well under MacOS.


How are groups created in maxout units when dividing the set of inputs  into groups of  values?

Question: I don't get $G^(i)$the set of indices into the inputs for group $i$, $\{(i −1)k+ 1, \ldots , ik\}$ when creating a maxout units/function, these thing that outputs the maximum element of groups: $$g(z)_i= \max_{[j∈G^{(i)}]}z_j$$

Maxout units(Goodfellow et al., 2013a) generalize rectified linear
units. Instead of applying an element-wise function $g(z)$,
maxout units divide $z$ into groups of $k$ values. Each maxout unit
then outputs the maximum element of one of these groups:
$$g(z)_i= \max_{[j∈G^{(i)}]}z_j$$
where $G^{(i)}$is the set of indices into the inputs for group
$i$,$\{(i −1)k+ 1, \ldots , ik\}$.
This provides a way of learning a piecewise linear function that
responds to multiple directions in the input $x$ space. A maxout unit
can learn a piecewise linear, convex function with up to $k$ pieces.
Maxout units can thus be seen as learning the activation function
itself rather than just the relationship between units. With large
enough $k$, a maxout unit can learn to approximate any convex function
with arbitrary fidelity. In particular, a maxout layer with two pieces
can learn to implement the same function of the input $x$ as a
traditional layer using the rectified linear activation function, the
absolute value rectification function, or the leaky or parametric ReLU,
or it can learn to implement a totally different function altogether.
The maxout layer will, of course, be parametrized differently from any
of these other layer types, so the learning dynamics will be different
even in the cases where maxout learns to implement the same function
of $x$ as one of the other layer types.
Deep Learning, Bengio and al. page 190

I tried to work it out with a concrete example:
Let's take a concrete example with k = 3. In this case, the groups would be as follows:
$$G^{(1)} = {(1 - 1)3 + 1, \ldots, 1 * 3} = \{1, 2, 3\}$$
$$G^{(2)} = {(2 - 1)3 + 1, \ldots, 2 * 3} = \{4, 5, 6\}$$
$$G^{(3)} = {(3 - 1)3 + 1, \ldots, 3 * 3} = \{7, 8, 9\}$$
And so on...
So, in this example, if we have 9 inputs, we'd have 3 maxout units, and each maxout unit would use 3 inputs to calculate its output, choosing the maximum from these 3 values.
Suppose we want to model the cost of producing a certain number of units of military weapons as a function of the quantity produced. We can use a piecewise linear function for this.
So let's imagine that the production cost is defined by a convex function with three pieces (k = 3):

For the first 100 units produced, the cost is \$10,000 per unit.
For 101 to 200 units, the cost is \$8,000 per unit.
For 201 units and above, the cost is \$7,000 per unit.

So here, I guess each maxout unit would take as input the quantity produced, and each group $G^(i)$ would be associated with one of the pieces of the function.
For example, if we wanted to calculate the cost of production for 150 units, I'm not sure but I guess we'd have :
$G^{(1)} = \{1, 2, 3\}$ corresponding to the first part of the function (\$10,000 per unit).
$G^{(2)} = \{4, 5, 6\}$ corresponding to the second part of the function (\$8,000 per unit).
I don't get what are $\{1, 2, 3\}$ and $\{4, 5, 6\}$ standing for, concretely
If I apply the maxout function for each group, I guess it means that maxout unit 1 will select the maximum of the values associated with $G^{(1)}$, and maxout unit 2 will select the maximum of the values associated with $G^{(2)}$, and so on ... but then it doesn't make any sens
Indeed, for 150 units, I guess maxout 1 would give a value of \$10,000 per unit, and maxout 2 would give a value of \$10,000 per unit, ... I don't know how I am expected to calculate the total cost of production then ...
I am a slow but passionate learner in math and deep learning. Don't hesitate to explain it to me as if I was a teenager.
Answer: Your example function does not really have multiple inputs in the same sense as max-out functions have multiple inputs.
Your example function is in essence just a scalar function ($\mathbb{R} \to \mathbb{R}$).
The max-out non-linearity, on the other hand, is actually a vector function ($\mathbb{R}^N \to \mathbb{R}^{N/k}$).
Take the following six-dimensional vector (i.e. $N = 6$) as an example input: $\boldsymbol{x} = (1, 3, -2, -4, -1, 3)$.
Applying the max-out non-linearity with $k = 2$ to $\boldsymbol{x}$ would result in
$\operatorname{max-out}(\boldsymbol{x}) = (3, -2, 3) = \big(\max(1, 3), \max(-2, -4), \max(-1, 3)\big).$
Similarly, using max-out non-linearity with $k = 3$, we would obtain
$\operatorname{max-out}(\boldsymbol{x}) = (3, 3).$
If $k$ does not divide $N$, this just does not work.
The only thing to make things work is to either crop the input vector (ignore the last few outputs) or pad the input vector with $p$ zeros such that $k$ divides $N + p$.
Finally, the max-out non-linearity should not be thought of as a function that models something useful.
It was conceived as an activation function for hidden representations in neural networks.
Typically, these hidden representations are hard to interpret.
Therefore, it is not really important that these activation functions are easily interpretable.
The only thing we care about is that the non-linearity is effectively non-linear.


ModelMap and @Controller in spring webflow

Question:
Is there something like ModelMap in spring webflow ?
In spring webflow I would like to put multiple objects into map under different keys
and then display them in jsp page. How should I do it ?
How can I get @Controller functionality in spring webflow - preparing data for jsp page?
Comment: Check this example here:
http://stackoverflow.com/questions/23342621/web-flow-add-model-attribute-for-binding-with-form-values/23344985#23344985

DispatcherServlet forwards the requests to "ClassForThisFlow" class to process each of your request.
Also, you can use any data type(map, list, etc.,) in the form "Client". Depending on you requirement, you can put this form in View scope or flow scope and use this through that flow cycle.
Answer: 1.) More read here
ModelMap subclasses LinkedHashMap.
addAttribute can be called with just a value, and the map key is then inferred from the type.
The addAttribute methods all return the ModelMap, so you can chain method called together, e.g. modelMap.addAttribute('x', x).addAttribute('y',y)
The addAttribute methods checks that the values aren't null
The generic type of ModelMap is fixed at Map<String, Object>, which is the only one that makes sense for a view model.
2.) Need to access ModelMap values through expression language
// At controller layer
modelMap.put("result",myResult);

/At Jsp layer

   <title></title>

{result}

3.) The @Controller annotation is used to mark any java class as a controller class.
Also you can add <mvc:annotation-driven /> for enabling the Spring MVC annotations.
detailed information here
Comment: Ankur-Singhal how can I access modelMap in spring webflow ? I would like @Controller functionality, but with spring webflow, not regular spring mvc - how is it possible ?


loading nodes with Ajax/jQuery

Question: Assume that we have a list of titles on the left and a div on the right side of the page that displays posts. when I click one of the titles it first removes content of that div and then loads node content. how can I do this? is there any module or function to do that?
Answer: You could look at the Quick Tabs and Vertical Tabs modules.  Otherwise you could write your own custom module if you had super specific needs and are proficient with drupal menu callbacks and php and of course jQuery.

loading nodes with Ajax/jQuery


How "Hello World" works in C

Question: I am searching for a month for blog posts about "how C program works". Most of them go like

Compilers do these things
Linkers do these things
Program is put into memory; and stacks, heaps, etc.

I thought I would first read about how compiler works to understand the flow of the program into the machine. Dragon Book seems to be universally preferred. But truthfully, it's too intensive. I am not good enough now to go through it all.
So I began to read about hardware. But There too, they explain about buses, I/O signals, structure of memory, writing cache-friendly code etc. But with no proper examples.
But still I could not find myself satisfied or being able to completely visualize the process.
2 hours ago  I decided to ask this question.(Since I am scared of It might be not useful to SO community, or off-topic question or other down-votable categories) and I did not find out any post relating to this exactly. There was one about "how compiler does the compilation", but the answers showed that it's too broad a question.
My question is this:
I would like to know how, in depth, a C program works. If you cannot tell me explicitly, please redirect me to a book or another post on another website that can give me the answer to this.
I am here until I get a response. If you have any suggestions regarding this post, tell me. And It is not my first language, so please take all my sentences as being soft and polite.
Thanks.
UPDATE:
Along with the accepted answer, there are some very nice links as well as suggestions which give partial answers or the way to proceed further to understanding what I am trying to understand.
Comment: This is a useful question and it's great that you're asking it.  Too many beginners ignore how things work under the hood.  BTW, "Hello" and "World" would not be tokens from the lexer's POV.
Comment: It must be black magic!
Comment: @humble_fool: I didn't mean you should change it.  You asked the question, I wouldn't expect you to already know the answer. :)
Comment: "_I am unable to continue with programming like this_" - Please don't treat this too seriously, **especially** if you've been learning CS/programming for just 2 years. I bet majority of programmers don't know half of the answer to this. It's good that you even want to know, it just happens that your question is quite complex. Don't see this as your failure just because it might take quite some time to learn and feel confident about understanding the whole process.
Comment: Then the magicians here must be able to explain the trick to me :)
Comment: This borders on "too broad". I think you're basically asking how CPU instructions produce screen output; I think you seem to have a pretty good idea of how C is converted into those instructions, just not how they move through the system to produce something like characters on a screen?
Comment: You're asking for about 12 credit hours worth of information
Comment: The answer can be as broad as the person who is answering wants. I don't think this question is too broad.
Comment: check out [Code: The Hidden Language of Computer Hardware and Software](http://www.amazon.com/Code-Language-Computer-Hardware-Software/dp/0735611319/)
Comment: The best way to get an answer is to *study* computer science. This takes several years (e.g. learning at university), after which you'll be able to write a book to answer your question.
Comment: One great link that explains how a program gets executed on a linux-based system is [this](http://linuxgazette.net/84/hawk.html)
Comment: It would take way to long for me to attempt to answer for each of these, nor could I create a great example for every single one. But your general compilation will have some stages:
1. Lexical Analysis
2. Syntax Analysis
3. Type Checking
4. Intermediate Code Generation
5. Register Allocation
6. Machine Code Generation
7. Assembly and Linking.  A decent read on the topic is http://www.diku.dk/~torbenm/Basics/basics_lulu2.pdf .  Its a little long but its not too hard to digest.
Comment: See [this answer](http://stackoverflow.com/a/9495727/841108) to a similar question.
Comment: I changed it, is it okay now Ed?
Comment: @BasileStarynkevitch Its related but it is not solving my problem. I want a explaination using example.
Comment: @meagar I think he is asking how everything starting from the CPU, source code, compiler, linker, loader etc fit together and produce the effect they do.
Comment: It's like I know some bits from here and there. But unable to connect all that stuff. But it's not like I want to ask you what are the drawing algorithms or that stuff. But yea, I would like if you explain that "it happens through this module in linux kernel which you can see here"
Comment: @BasileStarynkevitch Yeah, I am going through the process of learning. But If someone who has studied it and written a book , and he could show me how he/she visualizes it, I can atleast know what I am dealing with.
Comment: I don't think it's an unreasonable question to wonder how a simple application runs from start to finish and I do believe there is someone(not me >.>) on SO able to answer this question. I think the answer should be at least [this detailed](http://stackoverflow.com/a/11227902/2033671)
Comment: @humble_fool: I believe I know enough to write such a book, but I also believe that not much people actually would be interested in it. So it is not worth the effort writing it. Also, you can find partial answers and mix them yourself. On Linux, you could write a `helloworld.c` program, compile it to a `hello-world-bin`, then `strace ./hello-world-bin` and try to understand all of that trace.
Comment: @BasileStarynkevitch I am completely sure that it would be a best-seller.
Comment: This is a great, broad and off-topic question.
Comment: @OtávioDécio I am sorry sir. Can I ask it on some other stackexchange network site which would handle these kinds of topics. Beside I have already mentioned that you can have links supplementing your answer.
Comment: And one point of advice.  When you're looking for a fundamental explation of computer architecture, just to demystify it. You'll know you're in the right place when you're reading about `and gates` and `not gates` and `or gates`, and eventually half-adders and multiplexers and latches and flip-flops, and other circuit-level stuff
Comment: @fotanus Exactly. Thanks. I wanted to say it but couldn't find words.
Comment: I have edited my question, will it still remain marked too broad to answer???
Comment: I think it will take a few days to get it unhold. Thanks for all your help guys.. Starters like me respect all of you computer-lover-programmers a lot. And I wish that there should be a Like button on Top of SO , so that I could like it everyday.Good night.
Comment: Someone has narrowed it down for me.Thanks a lot for that. Though it's not exactly going to serve my initial purpose. But it will do it more than half way. :)
Comment: I think it has been narrowed down, So why they are still keeping it on hold...???
Answer: The best answer to this question by far comes from the book "The Elements of Computing Systems," by Noam Nisan and Shimon Schocken. This book starts from the simplest possible electronic components, assembles them into a working processor, invents a simple assembly language for it, writes an assembler for that, and ultimately shows you how high-level languages can be compiled onto it. Reading the book, and working all the examples (which use a simulator for the hardware, so no workshop required!), will forever change the way you look at computers; he will literally understand everything from the lowest to the highest levels, and see how they work together. See the book's website for more info.
Comment: Correct link: http://www.nand2tetris.org/
Comment: www.nand2tetris.com , it is opening a gaming-site. ??
Comment: Someone pasted the wrong link... I hate it when that happens.
Comment: I will definitely see it.
Comment: I think that's the best answer to the current question... :)
Answer: It's too broad a question (as you have observed).
If you really want to understand from bottom up - buy an OLD computer from the 80's off ebay. Sinclair Spectrum/BBC it really doesn't matter but make sure you get plenty of books and manuals that go with it.
You will learn plenty because these machines were well documented and what wasn't documented was discovered and then documented :)
They are also sooooo much simpler than a modern quad core multi-gigabyte memory job. It will all fit inside your head easily
or for a modern start, Arduino or Raspberry pie maybe.
Comment: I disagree. Old machines (unless physical machines before 1940) will not reveal the inner workings any more than AMD64 based machines, for example. In fact they may hide more, since one can easily download the Intel developer manuals and learn the theory of its architecture, whereas you have fewer options for understanding a Z80 to the same extent.
Comment: The Z80 (not used in the BBC Micro actually) is probably one of the most documented processors. It took me 1 (one) google to get the entire manual & architecture in detail direct from Zilog. Nothing is hidden. 1 (one) google to find a C compiler and assembler. It's all so much simpler and  the resources are all out there.
Comment: @Vortico: The thing about the Speccy/BBC is that they didn't really have an OS, so you were generally dealing directly with the hardware. The CPUs were conceptually much simpler than modern ones - there was no caching, no memory managers, no uops translations and superscalar architectures. They just read an instruction, did something, then read the next instruction and so on. That is the one drawback to the RasPi - the hardware is really complex.
Comment: Yeah, doing something like this is my wish too. But it's very much time consuming and might not be possible before holidays.

How "Hello World" works in C


Building on netty-tcnative for solaris?

Question: I have been using netty-tcnative-1.1.33.Fork17 for my web server program on solaris since 2016. (JDK1.7 32bit, netty-4.0.25, solaris11).
It is good ssl provider for me who develop java program on solaris sparc.
Then, I will update netty and netty-tcnative version on solaris sparc.
There are many updated netty and netty-tcnative after I used.
Now, netty major version is 4.1.x ,   netty-tcnative major version is 2.0.x. I think I have to use this version.
However, over netty-tcnative 2.0.2~8 package used not supported string function(strndup) on solaris sparc in jnilib.c.
Finally, I comple and package netty-tcnative-2.0.1 with netty 4.1.13.Final on solaris sparc.(JDK1.8 64bit)
Question1. There are anyother reason not support solaris sparc after netty-tcnative-2.0.2?
           I'm concerned about my netty-tcnative package for running.
Question2. Can you change or include string function(strndup) on further version for solaris..?
Thanks..
Answer: No there are no real reasons to not also allow to compile it on Solaris Sparc, we just not do it as part of the release process and testing. This means if there is something not working please open an issue and we will try to fix it. Or even better provide a PR with a fix. I opened

https://github.com/netty/netty-tcnative/issues/349
https://github.com/netty/netty-tcnative/pull/350/

Building on netty-tcnative for solaris?


Problem with sets using $n$-balls in $\mathbb{R}^n$

Question: How can I prove if this subset is open, closed or neither?
$$S \subset \mathbb{R}^2, \quad S=[1,2] \times [1,2]$$
Answer: If you can show that $[1, 2]$ is closed, then it is straightforward to show that in a metric space $M$, the Cartesian product of two closed subsets is itself a closed subset of $M \times M$.
First show that $[1, 2]$ is closed by showing it contains all its limits. Then suppose that $A \subset M$ is closed, where $M$ is a metric space. Let $p \in M \times M$ be the limit of a sequence $(p_n)$ where for each $n$, $p_n \in A \times A$. Show that $p \in A \times A$. Finally, conclude that $S$ is closed.
Answer: $[1,2]$ is a closed interval, so $[1,2]\times[1,2]$ is also closed under product topology.
$[1,2]$ is closed because $\mathbb{R}\setminus[1,2]$ is open by ball test.


lost password "user-pass" form no more redering

Question: We didn't touch our templates and the "lost password" form is no more rendering. here is my template code working fine with $login_form.

<?php echo t('Pour vous connecter, veuillez indiquer votre adresse email (login) et votre mot de passe')?>

    <?php
      $login_form['name']['#attributes']['placeholder'] = t('Login');
      $login_form['pass']['#attributes']['placeholder'] = t('Mot de passe');
      print drupal_render($login_form);
    ?>

<?php echo t('Indiquez votre adresse e-mail de connexion, et vous recevrez un nouveau mot de passe')?>

    <?php
      $reset_pass_form['name']['#attributes']['placeholder'] = t('Addresse e-mail');
      //print drupal_render(drupal_get_form('user_pass'));
      print drupal_render($reset_pass_form);
    ?>

I also tried directly the following :
print drupal_render(drupal_get_form('user_pass'));

Here is the result of print_r($reset_pass_form); so, the it exists :
Array
(
    [#form_id] => user_pass
    [#type] => form
    [#build_id] => form-na8Ow30ky69azZcTP7vQ_BijkXKobSuPFtmsajrNveM
    [form_build_id] => Array
        (
            [#type] => hidden
            [#value] => form-na8Ow30ky69azZcTP7vQ_BijkXKobSuPFtmsajrNveM
            [#id] => form-na8Ow30ky69azZcTP7vQ_BijkXKobSuPFtmsajrNveM
            [#name] => form_build_id
            [#parents] => Array
                (
                    [0] => form_build_id
                )

            [#input] => 1
            [#process] => Array
                (
                    [0] => ajax_process_form
                )

            [#theme] => hidden
            [#defaults_loaded] => 1
            [#tree] =>
            [#array_parents] => Array
                (
                    [0] => form_build_id
                )

            [#weight] => 0
            [#processed] => 1
            [#required] =>
            [#attributes] => Array
                (
                )

            [#title_display] => before
            [#ajax_processed] =>
            [#sorted] => 1
        )

    [form_id] => Array
        (
            [#type] => hidden
            [#value] => user_pass
            [#id] => edit-user-pass
            [#parents] => Array
                (
                    [0] => form_id
                )

            [#input] => 1
            [#process] => Array
                (
                    [0] => ajax_process_form
                )

            [#theme] => hidden
            [#defaults_loaded] => 1
            [#tree] =>
            [#array_parents] => Array
                (
                    [0] => form_id
                )

            [#weight] => 0.001
            [#processed] => 1
            [#required] =>
            [#attributes] => Array
                (
                )

            [#title_display] => before
            [#name] => form_id
            [#ajax_processed] =>
            [#sorted] => 1
        )

    [#id] => user-pass
    [#method] => post
    [#action] => /login
    [#theme_wrappers] => Array
        (
            [0] => form
        )

    [#tree] =>
    [#parents] => Array
        (
        )

    [#validate] => Array
        (
        )

    [#submit] => Array
        (
        )

    [#theme] => Array
        (
            [0] => user_pass
        )

    [#processed] =>
    [#defaults_loaded] => 1
    [#required] =>
    [#attributes] => Array
        (
        )

    [#title_display] => before
    [#array_parents] => Array
        (
        )

    [#sorted] => 1
    [#attached] => Array
        (
            [js] => Array
                (
                    [0] => Array
                        (
                            [type] => setting
                            [data] => Array
                                (
                                    [urlIsAjaxTrusted] => Array
                                        (
                                            [/login] => 1
                                        )

                                )

                        )

                )

        )

)

Is it an update issue or anonymous user rights issue?
I'm on 7.58
Can you help me?
Answer: actually the user/password is accessible for everyone (unless some custom code changes this behaviour)
if the form elements are present in DOM but are not displayed, i would check if there is some custom css that hides it somehow.
Comment: I was thinking of the CSS `display:none`or soething like that bue, if I look for source code (with Firebug console) there's nothing! https://i.imgur.com/RjXFHdX.png
Comment: Here is the only code I have in `

`


Find the total number of combinations of suits of card from a deck of 52 cards.

Question: There are 4 suits (spades, hearts, diamonds and clubs) and 13 cards for each suit in a deck of 52 cards. A player randomly draw 13 cards. We do not distinguish the cards 1, 2, ..., Q, K.
(a) Find the total number of combinations of suits for the player.
(b) Find the number of combinations of suits that the player has 6 clubs.
(c) Find the number of combinations of suits such that the player has 4 or more spades and 3 or more hearts.
I tried to tackle this question using multinomial distribution but I actually don't really know how to solve it.
Comment: For (a), you need to count the number of ways to write $13$ as a sum of $4$ non-negative numbers.
Comment: So it should be C(16,3)=560?
Comment: Yep!!! And equivalently for (b), you need to count the number of ways to write $13-6$ as a sum of $4-1$ non-negative numbers. But please wait for other users here to verify this.
Comment: "We do not distinguish the cards 1, 2, ..., Q, K"? What does that mean?
Comment: That means that the digits on the cards are ignored, only suits are counted.
Answer: $(a),(b)$ have been resolved in the comments. For $(c)$ you can let the number of clubs, diamonds, hearts, spades picked be $c,d,h+3,s+4$ respectively. So we have
$$
c+d+(h+3)+(s+4)=13\implies c+d+h+s=6
$$
Number of non-negative integer solutions of the above equation is $$\binom{6+4-1}{4-1}=\binom{9}{3}=84$$
which is the required number of combinations.


Erro ao pegar valor do input

Question: Estou tentando capturar o valor do input e mandar para o script do js, onde se a nota do aluno for >= 7 exibe na tag p "Aprovado" e caso contrario exibe "Reprovado", mas estou travado na lógica do js, não consigo exibir o resultado.
<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>College FX</title>

    <link rel="stylesheet" href="style.css">

COLLEGE FX

Welcome student, this is your grading portal, together we will check if you pass or fail

            <form class="form" action="">
                <input type="text" name="name" id="name" placeholder="enter you name">
                <input type="number" name="note1" id="note1" placeholder="enter test grade 1">
                <input type="number" name="note2" id="note2" placeholder="enter test grade 2">

                <select class="city" value="college">
                    <option value="sp">São paulo</option>
                    <option value="sp">Toronto</option>
                    <option value="sp">New york</option>
                    <option value="sp">Sydney</option>
                </select>

                <input  onclick="" type="submit" value="Calcular" class="Calcular" id="btn">

            </form>

let btn = document.querySelector("#btn")

btn.addEventListener("click",function(e){

    e.preventDefault()

    const n1 = document.querySelector("#note1").value
    const value1 = n1.value
    const n2 = document.querySelector("#note2").value
    const value2 = n2.value

    const media = parseInt((value1)) + parseInt((value2)) /2
            if (media >=7){
                    document.getElementById("#result").innerHTML = "Aprovado"
            } else{
                    document.getElementById("#result").innerHTML = "reprovado"
            }

})

Answer: Isso está acontecendo porque você está tentando
document.getElementById("#result").innerHTML

Mas o id do seu elemento é id="result", portanto basta substituir por
document.getElementById("result").innerHTML

A # só é utilizada no querySelector para especificar que se trata de um id, assim como o . no querySelector indica se tratar de uma classe. Como você está fazendo o uso do getElementById para selecionar o elemento no qual deseja exibir o resultado, o uso da # torna-se errôneo, a menos que seu id seja id="#result".
Além disso, quando você escreve
const n1 = document.querySelector("#note1").value

você já está pegando o valor do input, assim quando você escreve novamente
const value1 = n1.value

sua variável value1 possuirá valor undefined, pois n1 já é o valor que estava armazenado no input, e esse valor não possui um atributo value.
Ainda, ao parsear os valores, não é necessário
parseInt((value1))

apenas
parseInt(value1)

Erro ao pegar valor do input


EF está dando Timeout em uma query que deveria ser instantânea

Question: Quando rodo o SQL gerado pelo EF direto no SQLServer ele roda com menos de 1 segundo.
Quando roda pela aplicação ele da timeout pois demora mais de 30 segundos. Tenho visto muito desse problema na internet com chamadas de procedure, mas quando se fala em rodar um SQL eu não acho muita coisa.
Banco de dados SQLServer 2012, Entity Framework 6.
Segue tudo que eu tenho de informação:

(from v in _db.VIDEO.AsNoTracking()
                      join cv in _db.VIDEO_CATEGORIA.AsNoTracking() on v.ID equals cv.ID_VIDEO
                      where cv.ID_CATEGORIA == codcat
                      orderby v.DT_INCLUIDO_BD descending
                      select

                      new VideoModel
                      {
                          ID = v.ID,
                          DURATION = v.DURATION,
                          SCREENSHOT = (v.ID_ORIGEM == NUMERO_4_TIPO_LONG) ? v.ScreenShotServer : v.SCREENSHOT,
                          URL = v.URL,
                          VIDEO_TITLE = v.VIDEO_TITLE,
                          DATE = v.DT_INCLUIDO_BD,
                          origemlong = v.ID_ORIGEM,
                          totalclicks = v.TOTALCLICKS
                      });

Isso é usado depois com o PageList, filtrando paginas de 120 linhas, então ele vai receber uma parte a mais no SQL:
Pego o SQL usando o log do proprio EF: db.Database.Log = s => log.Debug(s);

2015-08-24 15:02:44,035  SELECT
[Project1].[C1] AS [C1],
[Project1].[ID] AS [ID],
[Project1].[DURATION] AS [DURATION],
[Project1].[C2] AS [C2],
[Project1].[URL] AS [URL],
[Project1].[VIDEO_TITLE] AS [VIDEO_TITLE],
[Project1].[C3] AS [C3],
[Project1].[ID_ORIGEM] AS [ID_ORIGEM],
[Project1].[TOTALCLICKS] AS [TOTALCLICKS]
FROM ( SELECT
    [Extent1].[ID] AS [ID],
    [Extent1].[VIDEO_TITLE] AS [VIDEO_TITLE],
    [Extent1].[DURATION] AS [DURATION],
    [Extent1].[DT_INCLUIDO_BD] AS [DT_INCLUIDO_BD],
    [Extent1].[ID_ORIGEM] AS [ID_ORIGEM],
    [Extent1].[URL] AS [URL],
    [Extent1].[TOTALCLICKS] AS [TOTALCLICKS],
    1 AS [C1],
    CASE WHEN (4 = [Extent1].[ID_ORIGEM]) THEN [Extent1].[ScreenShotServer] ELSE [Extent1].[SCREENSHOT] END AS [C2],
     CAST( [Extent1].[DT_INCLUIDO_BD] AS datetime2) AS [C3]
    FROM  [ricardocorpore].[VIDEO] AS [Extent1]
    INNER JOIN [ricardocorpore].[VIDEO_CATEGORIA] AS [Extent2] ON [Extent1].[ID] = [Extent2].[ID_VIDEO]
    WHERE [Extent2].[ID_CATEGORIA] = @p__linq__0
)  AS [Project1]
ORDER BY [Project1].[DT_INCLUIDO_BD] DESC
OFFSET 0 ROWS FETCH NEXT 120 ROWS ONLY
2015-08-24 15:02:44,035

2015-08-24 15:02:44,035  -- p__linq__0: '28' (Type = Int64, IsNullable = false)

2015-08-24 15:02:44,035  -- Executing at 24/08/2015 15:02:44 -03:00

2015-08-24 15:03:14,081  -- Failed in 30041 ms with error: Timeout expired.  The timeout period elapsed prior to completion of the operation or the server is not responding.

2015-08-24 15:03:14,081

2015-08-24 15:03:14,081  Closed connection at 24/08/2015 15:03:14 -03:00

O [Extent2].[ID_CATEGORIA] que é usado no where é bigint , a variável que chega no EF no código é long. Por isso descartei problemas de tipos deferentes de variável com coluna.
A coluna de [DT_INCLUIDO_BD] tem um index criado só para ela.
Alguém tem alguma sugestão?
Comment: Hoje a tabela de Video tem um milhão e meio de registros, a de video_categoria 4 milhões de registros.
Comment: Qual o tamanho de cada tabela? A princípio não há qualquer problema com o código.
Comment: Se a consulta demora para ser executada quando vêm da aplicação, tenta fazer o [SQL Server Profiler](http://stackoverflow.com/a/7359705/2387977) dela para descobrir a causa. Este problema de você não conseguir reproduzir rodando a consulta diretamente pode estar relacionada com cache do banco (tem [como limpar também](http://stackoverflow.com/a/1873064/2387977) e testar novamente a consulta)
Comment: O plano de acesso do SQL é ótimo, eu já fiz o teste, usa os índices e a PK. Nenhum problema nele.
Comment: Mas se está demorando no banco a consulta, alguma coisa existe de problema. Quem vai te ajudar a mostrar isto é o SQL Server Profiler.
Comment: Então, eu verifiquei o plano de acesso pegando a query e colocando no Management Studio, e ele diz que o plano está bom, tanto que eu rodo ela lá e ela roda instantaneamente. Eu uso um servidor compartilhado, por isso não tenho acesso a tabela `sys.dm_exec_cached_plans` que eu acredito seria onde ver o que foi executado pela aplicação (Não tenho certeza se seria isso).
Comment: Veja o [link que passei, método 3](http://stackoverflow.com/a/7359705/2387977): _If you can't run your query directly (or your query doesn't run slowly when you execute it directly - remember we want a plan of the query performing badly), then you can capture a plan using a SQL Server Profiler trace._ Chegou a limpar o cache e testar a consulta novamente, só para garantir que não é cache?
Comment: Tentei colocar o comando de limpar o chace em uma procedure, mas mesmo assim não tenho acesso para rodar, quando ao Server Profile eu nem consigo logar nele por falta de acesso tb...
Comment: Não pode falar com o DBA/pessoa que tem privilégios para te ajudar? Há um limite claro onde pode ir, sem privilégios suficientes, para investigar este problema. Se não conseguir acesso a todas as ferramentas necessárias para realizar o seu trabalho, fica complicado achar a causa. Você poderia mostrar o plano de execução que já conseguiu?
Comment: Já tem um dia que eu mudei a paginação para 130 linhas, agora ele executa o SQL no servidor em 2ms, mesmo SQL só que no lugar de 120 está 130... Se resolver assim vou deixar dessa forma. Se voltar o problema vou tentar conversar com o DBA.
Answer: A solução para o caso apresentado na pergunta foi a troca da coluna que está sendo ordenada.
De:
ORDER BY [Project1].[DT_INCLUIDO_BD] DESC

Para:
ORDER BY [Project1].[ID] DESC

O que eu pude entender é que o plano de acesso usado pela aplicação ou pelo management são diferentes.
Por isso alterei o SQL em uma tentativa de fazer ele executar o mesmo plano de acesso das duas maneiras.
Comment: Obrigado pela resposta. Esta informação será valiosa para os demais usuários. +1.


Export View results to CSV

Question: I have a listing view with filters and a button to export the results to a CSV file. How can I send the view's arguments to my export callback after a user applies some filters?
Answer: Have you looked at Views Data Export. I've wired in a view to export on button click. You just build or modify a FAPI form to contain a button and give it the url of the view you want to output as csv.
In your case you'd pass the selected arguments into the view. You could use FAPI and Javascript to properly build the url and button action.
Comment: yes, use hook_form_alter ... your approach seems good. you add a button like `$form['mybtn']=array('#type'=>'button', '#submit' => array('your_submit_function'));` just be sure to add the button to the exposed form (which your logic should take care of as you described in hook_form_alter.
Comment: I've managed to create the view for my export but I would like to add my button in the "exposed_form" $form and I'm not sure how can I achieve this.
Comment: whats the name of the View you want to add the button to the exposed_filter (?) $form. What is your export view called?, does it have a page path url, what is that path ?
Comment: The path to my export view is /export. And I was thinking that I can add the button through _form_alter() on views_exposed_form case, but I can't manage to find out how can I add a new button to the form.
Comment: Thanks, this works just great. I was sure I couldn't find how to set the button, with #type, #submit and all attributes.

Export View results to CSV


Solve the sequences inequality

Question: If $a_1=1$ and $a_n=a_{n-1}+\dfrac{1}{a_{n-1}}$ for $n≥2$ , then prove that $12 < a_{75} < 15$ ?
I have tried solving this by:
 $$a_{75} - a_1 = \frac{1}{a_1}+\frac{1}{a_2}....+\frac{1}{a_{74}}$$
Comment: Hint: Use $a_n^2$.
Answer: Let $b_n=a_n^2$. Then $b_1=1$ and:
$$ b_{n+1} = b_n + 2 + \frac{1}{b_n}, $$
hence $b_n\geq 2n-1$ holds by induction, so $a_{75}\geq \sqrt{149}>12$.
On the other hand, $b_n\geq 2n-1$ also gives:
$$ b_{n+1} \leq b_n + 2 + \frac{1}{2n-1}, $$
hence:
$$ b_n \leq (2n-1)+\sum_{k=1}^{n-1}\frac{1}{2k-1} $$
holds by induction and we get $a_{75}\leq 13$ as well.
Comment: I see we can prove ≥2−1, but do we motivate this statement? Was it just an intuition?
Comment: @Supersusha22: any solution of $b_{n+1}=b_n+2$ is of the form $b_n=2n+k$.
Answer: Use the hint given by Did:
We have that $a_n^2=a_{n-1}^2+\frac{1}{a_{n-1}^2}+2$. Thus $a_n^2\geq a_{n-1}^2+2$ for all $n\geq 2$. Hence $a_n^2\geq 2\cdot (n-1) +1$. Hence $a_{75}\geq \sqrt{2\cdot 74+1}\geq \sqrt{2\cdot 72}=\sqrt{144}=12$.
For the other inequality, use the following reasoning:
$$a_n^2=a_{n-1}^2+\frac{1}{a_{n-1}^2}+2\leq a_{n-1}^2+\frac{1}{2(n-2)+1}+2.$$
Here we used the inequality $a_{n-1}^2\geq 2\cdot (n-2) +1$ in the denominator. Now replace $a_{n-1}^2$ by $a_{n-2}^2+\frac{1}{a_{n-2}^2}+2$ and again use the inequality in the denominator. Continue in this fashion to obtain the result. (Do this yourself, it requires a bit of work).
All credits go to @Did for his brilliant hint!
Comment: I hadn't been taught recursive series yet but I used the hint given by @Did to get the result.
Comment: how exactly did you get ()^2≥2⋅(−1)+1? (I understood the previous step but not this one)
Answer: Prove using induction that for all $n \geq 2$
$$ \sqrt{2n} \leq a_n \leq \sqrt{3n}.$$
Comment: Sure. you are right. Thanks.

Solve the sequences inequality


iOS get Keyboard Window

Question: So in iOS 7 I always got the Keyboard Window like this:
- (UIView *)keyboardView
{
    UIWindow* tempWindow;

    //Because we cant get access to the UIKeyboard throught the SDK we will just use UIView.
    //UIKeyboard is a subclass of UIView anyways
    UIView* keyboard;

    NSLog(@"windows %d", [[[UIApplication sharedApplication]windows]count]);

    //Check each window in our application
    for(int c = 0; c < [[[UIApplication sharedApplication] windows] count]; c ++)
    {
        //Get a reference of the current window
        tempWindow = [[[UIApplication sharedApplication] windows] objectAtIndex:c];

        //Get a reference of the current view
        for(int i = 0; i < [tempWindow.subviews count]; i++)
        {
            keyboard = [tempWindow.subviews objectAtIndex:i];
            NSLog(@"view: %@, on index: %d, class: %@", [keyboard description], i, [[tempWindow.subviews objectAtIndex:i] class]);
            if([[keyboard description] hasPrefix:@"(lessThen)UIKeyboard"] == YES)
            {
                //If we get to this point, then our UIView "keyboard" is referencing our keyboard.
                return keyboard;
            }
        }

        for(UIView* potentialKeyboard in tempWindow.subviews)
            // if the real keyboard-view is found, remember it.
            if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0) {
                if([[potentialKeyboard description] hasPrefix:@"<UILayoutContainerView"] == YES)
                    keyboard = potentialKeyboard;
            }
            else if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 3.2) {
                if([[potentialKeyboard description] hasPrefix:@"<UIPeripheralHost"] == YES)
                    keyboard = potentialKeyboard;
            }
            else {
                if([[potentialKeyboard description] hasPrefix:@"<UIKeyboard"] == YES)
                    keyboard = potentialKeyboard;
            }
    }

    NSLog(@"view: %@, on index: %d", [keyboard description]);
    return keyboard;
}

But in the iOS 8 beta 1 & 2 the window/view that is returned is the main App window. Any idea what is the the problem in my code? On my test device with iOS 7 it works great...
Answer: I also had this problem and found the solution.
Below is the code which will work for iOS 8.0 and also for below versions.
I have tested it on iOS 7 and 8.0 (Xcode Version 6.0.1)
- (void)addButtonToKeyboard
{
    // create custom button
    self.doneButton = [UIButton buttonWithType:UIButtonTypeCustom];
    self.doneButton.frame = CGRectMake(0, 163+44, 106, 53);
    self.doneButton.adjustsImageWhenHighlighted = NO;
    [self.doneButton setTag:67123];
    [self.doneButton setImage:[UIImage imageNamed:@"doneup1.png"] forState:UIControlStateNormal];
    [self.doneButton setImage:[UIImage imageNamed:@"donedown1.png"] forState:UIControlStateHighlighted];

    [self.doneButton addTarget:self action:@selector(doneButton:) forControlEvents:UIControlEventTouchUpInside];

    // locate keyboard view
    int windowCount = [[[UIApplication sharedApplication] windows] count];
    if (windowCount < 2) {
        return;
    }

    UIWindow* tempWindow = [[[UIApplication sharedApplication] windows] objectAtIndex:1];
    UIView* keyboard;

    for(int i = 0 ; i < [tempWindow.subviews count] ; i++)
    {
        keyboard = [tempWindow.subviews objectAtIndex:i];
        // keyboard found, add the button

        if([[keyboard description] hasPrefix:@"<UIPeripheralHost"] == YES){
            UIButton* searchbtn = (UIButton*)[keyboard viewWithTag:67123];
            if (searchbtn == nil)//to avoid adding again and again as per my requirement (previous and next button on keyboard)
                [keyboard addSubview:self.doneButton];

        }//This code will work on iOS 8.0
        else if([[keyboard description] hasPrefix:@"<UIInputSetContainerView"] == YES){

            for(int i = 0 ; i < [keyboard.subviews count] ; i++)
            {
                UIView* hostkeyboard = [keyboard.subviews objectAtIndex:i];

                if([[hostkeyboard description] hasPrefix:@"<UIInputSetHost"] == YES){
                    UIButton* donebtn = (UIButton*)[hostkeyboard viewWithTag:67123];
                    if (donebtn == nil)//to avoid adding again and again as per my requirement (previous and next button on keyboard)
                        [hostkeyboard addSubview:self.doneButton];
                }
            }
        }
    }
}

>

    -(void) removedSearchButtonFromKeypad{

    int windowCount = [[[UIApplication sharedApplication] windows] count];
    if (windowCount < 2) {
        return;
    }

    UIWindow* tempWindow = [[[UIApplication sharedApplication] windows] objectAtIndex:1];

    for(int i = 0 ; i < [tempWindow.subviews count] ; i++)
    {
        UIView* keyboard = [tempWindow.subviews objectAtIndex:i];

        if([[keyboard description] hasPrefix:@"<UIPeripheralHost"] == YES){
            [self removeButton:keyboard];

        }else if([[keyboard description] hasPrefix:@"<UIInputSetContainerView"] == YES){

            for(int i = 0 ; i < [keyboard.subviews count] ; i++)
            {
                UIView* hostkeyboard = [keyboard.subviews objectAtIndex:i];

                if([[hostkeyboard description] hasPrefix:@"<UIInputSetHost"] == YES){
                    [self removeButton:hostkeyboard];
                }
            }
        }
    }
}

-(void) removeButton:(UIView*)keypadView{
    UIButton* donebtn = (UIButton*)[keypadView viewWithTag:67123];
    if(donebtn){
        [donebtn removeFromSuperview];
        donebtn = nil;
    }
}

Hope this helps.
Comment: Pure awesomeness!  You saved me lots of extra hassle.  And what's more... Our original code must have been from same boilerplate example, because this almost dropped right in place.  Nice! Thanks!
Comment: I have used the same code for adding done button, it worked for me, but when default keyboard appeares I can see that done button behind the keyboard even If I have removed it from superview. plz help. Thanks
Comment: please tell me how to remove the done button and predictive text bar from the keyboard.
Comment: I have edited my code which supports removing done button from the keyboard. Please have a look on the complete code.
Comment: please see this question am doing same like this http://stackoverflow.com/questions/26213708/remove-back-drop-accessory-bar-of-keyboard-in-iphone-5s-with-ios-8
Comment: I have not yet upload the app to the app store with this code. Have you found any restriction?
Comment: Yes! I am able to add the button but not able to interact with that. I can see only image which I placed on the keyboard.
Answer: What i use to get the window for the keyboard is
- (void)findKeyboardWindow
{
    for (UIWindow *window in [[UIApplication sharedApplication] windows])
    {
        if ([NSStringFromClass([window class]) isEqualToString:@"UITextEffectsWindow"])
        {
            _keyboardWindow = window;
            break;
        }
    }
}

From my logs on iOS8 this contains one view
UIInputSetContainerView: 0x190d4430; frame = (0 0; 320 568); autoresize = W+H; layer = CALayer: 0x190d4630

Which contains another view
UIInputSetHostView: 0x190d4820; frame = (0 352; 320 216); layer = CALayer: 0x190d49c0

Since those dimensions are 216.0f height i guess that is the keyboard.
Was this what you where looking for?
Comment: This is the best solution!
Answer: On iOS 13, we can get keyboard window like this:
let windows = UIApplication.shared.windows
if let keyboardWindow = windows.first(where: { NSStringFromClass($0.classForCoder) == "UIRemoteKeyboardWindow" }) {
  return
}

Answer: In the first iOS 8 beta, the system keyboard is the UIInputSetHostView subview of the UIInputSetContainerView subview of one of the application windows.

iOS get Keyboard Window


Additional tab in custom module's admin configuration page

Question: Can't figure out why two admin pages of my custom module are not showing in different tabs. I've disabled and re-enabled the module, cleared cache, however while both pages are accessible and I see the "Leads" link in the menu, unfortunately they are not aligned into tabs. Can anyone help me to get my tabs?
<code>/**
 * Implementation of hook_menu().
 */

function leads_menu() {
  $items = array();

  $items['admin/commerce/leads'] = array(
    'title' => 'Leads',
    'access arguments' => array('administer leads'),
    'page callback' => 'leads_active',
  );
  $items['admin/commerce/leads/subscribed'] = array(
    'title' => 'Subscribed Leads',
    'page callback' => 'leads_subscribed',
    'type' => MENU_DEFAULT_LOCAL_TASK,
    'weight' => -10,
  );

  return $items;
}
</code>
Answer: It seems that first main path 'admin/commerce/leads' needs to be defined, and then other two items added.  The first item inherits the properties of the main menu item, and the second defines its own callbacks. Far from obvious, but it works for me now:
<code>  function leads_menu() {
  $items = array();

  $items['admin/commerce/leads'] = array(
    'title' => 'Leads',
    'access arguments' => array('administer leads'),
    'page callback' => 'leads_active',
  );
  $items['admin/commerce/leads/active'] = array(
    'title' => 'Active',
    'type' => MENU_DEFAULT_LOCAL_TASK,
    'weight' => -10,
  );
  $items['admin/commerce/leads/subscribed'] = array(
    'title' => 'Subscribed',
    'page callback' => 'leads_subscribed',
    'type' => MENU_LOCAL_TASK,
    'access arguments' => array('administer leads'),
  );

  return $items;
}
</code>
Comment: This is correct. When in doubt, look at what Drupal core modules do. The Node module defines node, node/%node/view, and node/%node/edit.


Comet with uwsgi and nginx, how to turn off the output buffer?

Question: How can I prevent Nginx from buffering the output of my uwsgi app? For my comet style application I'm using long polling and the requests are now buffered.
I tried to reduce the size of the buffers, but I'm not allowed to put uwsgi_buffer_size and uwsgi_buffers on 0. Also uwsgi_max_temp_file_size does not work (eventhough the manual suggests that).
How can I do this?
Answer: Until a few minutes ago this was not possible. nginx would always buffer all uwsgi and scgi responses, and no configuration would change that.
I have submitted a patch for nginx (and it was accepted) and from the next version on there are two methods to disable buffering for uwsgi requests:

put uwsgi_buffering off in the nginx config
send a X-Accel-Buffering 'no' header in the response

uwsgi never buffers the response, so no configuration is required on that end.
Comment: 10 years later! The X-Accel-Buffering is an excellent solution! thanks!
Answer: Why don't you use the uwsgi-embedded http-router/load-balancer directly ? It does no-buffering expecially for comet/websockets app. You can use nginx for static files mapping them to another domain.
Comment: In that case I could also http proxy the requests through nginx, as for proxying there are specific buffering flags. The thing I'm doubting is that uwsgi http server is able to give me a good performance and security.
Answer: Try with uwsgi_max_temp_file_size = 0
Comment: As I wrote in the question, this does not work.
Answer: Nginx "proxy" module has a directive for that, it's called proxy_buffering on|off, which does exactly what you want, it turns buffering off and proxies upstream output synchronously. But AFAIK neither FastCGI nor UWSGI modules have it.
BTW even when proxy_buffering is off, you may notice small delays because of OS TCP stack buffering.
Comment: Please don't take the downvote personal. A downvote means "This answer is not useful". So I downvoted it as it was not useful to me, because it does not give an answer to my question.
Comment: Indeed, if I would use proxy_pass then this would be useful. But as I mentioned I use uwsgi so this does not work.
Comment: Ok, I'll tell you plainly: there is no solution.

Is downvoting your motivation for people? Good luck.


Proof that $SupA$ = $SupB$

Question: Let $A,B\subseteq \mathbb{R}$ be unempty and bounded from above.
Also: $\forall a\in A$ $ \hspace{2mm}\exists b \in B \hspace{2mm} a\leq b$
and $\forall b\in B$ $ \hspace{2mm}\exists a \in A \hspace{2mm} b\leq a$
I need to proove that $SupA$ = $SupB$.
It is kind of appernt to the eye, but im having a trouble proving that.
My intuition tells me that I need to prove that $A=B$ but I need to do it formally. I know that theyre both bounded and have their supremums.
I was thinking that maybe I should argue that $\exists\hspace{2mm} b_0\in B$ such that this $b_0\geq a \hspace{2mm}\forall a\in A$ and the same for
$a_0\geq b \hspace{2mm}\forall b\in B$
Comment: Do you mean "bounded from above"?
Comment: @Dave Yes! im so sorry!
Comment: Btw, you can use `\sup` to get $\sup$.
Answer: Let $m_A$, $m_B$ be the suprema of $A$ and $B$, respectively.
Given $a\in A$, there exists $b\in B$ such that $b\ge a$ and since $m_B\ge b$ for all $b\in B$, $m_B\ge a$ for all $a\in A$. Therefore, $m_B$ is an upper bound for $A$ and since $m_A$ is the least upper bound, $m_B\ge m_A$.
The exact same argument can be used to show that $m_A\ge m_B$. Therefore, $m_A=m_B$.
Answer: We know that $\sup(A)$ is an upper bound for $A$, i.e. $\forall a\in A,~a\leq\sup(A)$. Thus, for each $b\in B$, there exists $a\in A$ such that $b\leq a\leq\sup(A)$. Hence, $\sup(A)$ is an upper bound for $B$. Thus, by definition of supremum for $B$, we have $\sup(A)\geq \sup(B)$. Apply the argument symmetrically for $B$ and compare the inequalities at the end.
Answer: The two sets need not be equal.
In fact they can be disjoint.
Ex:
A=] 0;1[ inter Q
B=]0;1[ inter I
I:=irrational numbers
inter:=intersection
Comment: You're not wrong, but this would be better left as a comment since you're not really offering a full answer (i.e. addressing how the OP *should* solve it, then). Also, here's [a reference for MathJax](https://math.meta.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference) you might find useful, which is preferred for writing up and rendering your math text on this site.

Proof that $SupA$ = $SupB$


How to display cck node fields' values at the search result page?

Question: I need to display some specific cck fields such as Telephone Number, Address, etc. at the search result page.
As I see the search-result.tpl.php, there is no $node->... So how can I get the node fields into search result page?
Answer: In your theme, you can use template_preprocess_search_result()
function YOURTHEME_preprocess_search_result(&$variables) {
  if ($variables['type'] == 'node') {
    $node =& $variables['result']['node'];
    //Do something here
  }
}

Or, you can also implement hook_nodeapi() in a custom module for $op = 'search result'. The result of hook_nodeapi($node, 'search result') is available in $info_split in the search-result.tpl.php template.
Answer: We had to create a custom search once. We created a custom module that allowed not only writing a custom query to the database but also choose the kind of amount that gets displayed. We hooked into hook_search with the module. To give you an idea:
function yourmodule_search($op = 'search', $keys = NULL) {

switch ($op) {
   //some code, basically a stripped version from what the API shows us
    case 'search':

      $find = do_event_search($keys); //the actual search

      // Load results.
      $results = array();

      foreach ($find as $item) {

        //iteration and adding certain elements to $resuls needned by Drupal
      }
      return $results;
  }
}

The interessting part for you is the retrival of the search results as done by do_event_search:
//all data comes from a queries to the database
$search_result[] = array ('link' => trim($link),
                    'snippet' => trim_text(i18n_get_lang() == "en" ? $row->description_en : $row->description_de),
                    'head' => trim_text(i18n_get_lang() == "en" ? $row->title_en : $row->title_de),
                    'type' => $type
                );

As you can see, snippet holds the text that should be displayed on the search pages and we select a certain $row from a custom database. The API example shows all fields that are needed for displaying the results properly.
Answer:
[SORTED]
wow, that simple :)
search-result.tpl.php
<?php if ($result['node']->field_name[0]['value']): ?>

<?php print($result['node']->field_name[0]['value']); ?>

<?php endif; ?>

Comment: It seems there's risks with this method? —http://www.computerminds.co.uk/articles/rendering-drupal-7-fields-right-way
Answer: Another possibility is to use Display Suite, it allows you to override the node indexing as well as the display of the search results
Answer: you could use the template_preprocess_search_result(&$variables) function (copy it from the search module and place it in your theme's template.php file) -
and use the $variables variable (var_dump it) to retrieve your node info and print it