text:
Q: Make an enum INSTANCE private I am using an enum singletom pattern like this:
public enum LicenseLoader implements ClientLicense {
    INSTANCE;

    /**
     * @return an instance of ClientLicense
     */
    public static ClientLicense getInstance() {
        return (ClientLicense)INSTANCE;
    }

   ...rest of code

}

Now I want to return the Interface and hide the fact that we are actually using an enum at all.  I want the client to use getInstance() and not LicenseLoader.INSTANCE as one day I may decide to use a different pattern if necessary.
Is is possible to make INSTANCE private to the enum?

A: What about making a public interface and private enum that implements said interface, with a singleton INSTANCE constant?
So, something like this (all in one class for brevity):
public class PrivateEnum {

    public interface Worker {
        void doSomething();
    }

    static private enum Elvis implements Worker {
        INSTANCE;
        @Override public void doSomething() {
            System.out.println("Thank you! Thank you very much!");
        }
    }

    public Worker getWorker() {
        return Elvis.INSTANCE;
    }
}

This way, you're not exposing Elvis.INSTANCE (or even enum Elvis at all), using an interface to define your functionality, hiding all implementation details.

A: All enum constants are accessible. For instance through deserialisation or the enum-specific reflective methods.
As always, I strongly suggest avoiding singletons.


text:
Q: Jquery selector : select header, exclude all child anchors Wanted functionality : whenever a user taps on the header of the JQuery Mobile application, the content of the main window should scroll to the top.
However when a user taps on an anchor which is located in the header, the default action should be executed (and not the scroll-action).
I already tried following code :
$(document).on('tap', 'div[data-role=header]' ,function(event, ui) {

 if (event.target.tagName !== 'A') {
    // perform scroll action here
 };
});

This works pretty good, except when I tap following anchor in the header :
Cancel

In this case the default behavior of the anchor is not executed.
Could anyone explain me why ?

redpajama_set_name: RedPajamaStackExchange


text:
Q: Installing ViennaCL on Ubuntu I have successfully built ViennaCL using cmake . and make and run some of its generated tests on Ubuntu 11.04. But how do I install it and how do I include and link it with my application? Shouldn't it generate headers and shared libraries that automatically installs under /usr/local/include and /usr/local/lib? The Makefile doesn't contain any install target.
/Nordlöw

A: ViennaCL is a header/template library. All you need to do is copy the viennacl directory wherever you want to install the headers and you are done. This is clearly explained in the README file that accompanies the distribution:

ViennaCL is a header-only library,
  therefore it is sufficient to copy the
  subfolder ViennaCL/ (holding the
  header files) into you project
  directory or your system include
  directory.

You should note that the subfolder mentioned in the README is actually named viennacl (lower case) in recent versions.


text:
Q: Using constructor function to add methods The classic way to create constructor function is like:
var Obj = function(param){
    this.param = param;
    this.method = function(){ console.log(this.param); }
}

But why i can't do something like this:
Obj.anotherMethod = function(){ //some code }

(I know about Obj.prototype.anotherMethod).
In practical usage i can't understand why use String.prototype.func instead of String.func to define new method. Is it just because String is constructor function and it's impossible to add method to it?

A: Those are different things.
If you add a method to Constructor.prototype, it will be available on all instances of Constructor.
You can also add methods to Constructor itself. However, instances won't inherit them.
For example,

*

*charAt method is defined on String.prototype, so you can use both "abc".charAt(1) and String.prototype.charAt.call("abc", 1).

*But fromCharCode is defined on String, so you can use String.fromCharCode(65), but "abc".fromCharCode is undefined.

A: You can do this with prototypal inheritance. Instead of using constructors, you can have objects inherit from other objects using Object.create(). You can add members to the parent object at any time and they will be available to objects that have the parent as their prototype.
var Base = {a: "a"};
Base.b = "b";
var sub = Object.create(Base); // creates a new object with Base as its prototype
Base.c = "c"; // sub.c will be available because Base is its prototype!
alert(sub.a + sub.b + sub.c); // "abc"

http://jsfiddle.net/kqtm4f8j/
Great article to understand prototypal inheritance patterns:
http://aaditmshah.github.io/why-prototypal-inheritance-matters/

A: Here's a little code that should help. Starting with your constructor:
var Obj = function(param){
    this.param = param;
    this.method = function(){ console.log(this.param); }
}

Now make an instance:
var inst = new Obj("testParam")
//now use it
console.log(inst.param) // logs: "testparam

Now add another parameter to Obj:
Obj.anotherParam = "TestParam2"
console.log(Obj.anotherParam) // <-- Works
console.log(inst.anotherParam) // <-- but this is Undefined on the instance

But if you add it to the prototype:
Obj.prototype.anotherParam = "TestParam2"
console.log(inst.anotherParam) // <-- this now works as expected

The takeaway is that when you add it to the prototype it becomes available to all instances. If you simply add it to the constructor, only the constructor function has the parameter. There are a lot of other ways to do this in Javascript, but understanding the prototype object is a good place to start.


text:
Q: Summing across arrays during aggregation pipeline I've got a model with a few arrays of the same fixed size and I've been trying to work out whether I can sum across the array indices using the aggregation pipeline, but have been having a difficult time finding anything helpful.
For example:
{
    label: "label1",

    A: [0, 0, 0],
    B: [1, 1, 1],
    C: [0, 0, 1],

    etc: ... ,
}

Would need to produce the following summed array during a projection, or another similar array when grouping on the label key further down the pipeline:
{
    Z: [1, 1, 2]
}

Using Mongo 3.2 I can unwind an array and maintain its indices, but I'm still not sure how to rebuild an array using those indices and values.
If anyone has any ideas or suggestions, it would mean a lot. Thanks in advance for any responses.

A: One could use $slice to slice array if it is a small size (3x3 means 9 operations), but unwinding it will generate 27 documents for 3x3 arrays so connecting them back is a kind of pain.
or you could use simpler solution using forEach
var arraySize=3;
var a=[];
db.david.find({label:"label2"}).forEach(function(myDoc) {
      for(var i=0;i<arraySize;i++){
          a[i]=myDoc.A[i]+myDoc.B[i]+myDoc.C[i];
      }
      })
 printjson( a )

edit
I am still not sure how to bite this in more dynamic way - but this is a kind of proposal for 3 arrays of 3 elements each.
var arraySumprojection = {
            $project : {
                col1 : {
                    $let : {
                        vars : {
                            a : {
                                "$arrayElemAt" : ["$A", 0]
                            },
                            b : {
                                "$arrayElemAt" : ["$B", 0]
                            },
                            c : {
                                "$arrayElemAt" : ["$C", 0]
                            },

                        },
                        in : {
                            $add : ["$$a", "$$b","$$c"]
                        }
                    }
                },

                col2 : {
                    $let : {
                        vars : {
                            a : {
                                "$arrayElemAt" : ["$A", 1]
                            },
                            b : {
                                "$arrayElemAt" : ["$B", 1]
                            },
                            c : {
                                "$arrayElemAt" : ["$C", 1]
                            },

                        },
                        in : {
                            $add : ["$$a", "$$b","$$c"]
                        }
                    }
                },
                col3 : {
                    $let : {
                        vars : {
                            a : {
                                "$arrayElemAt" : ["$A", 2]
                            },
                            b : {
                                "$arrayElemAt" : ["$B", 2]
                            },
                            c : {
                                "$arrayElemAt" : ["$C", 2]
                            },

                        },
                        in : {
                            $add : ["$$a", "$$b","$$c"]
                        }
                    }
                },
            }
        }
    ])


text: Q: Verificar se valor já está salvo no sessionStorage É a primeira dúvida que posto e vou tentar passar a informação mais clara possível. Tenho o código abaixo ao qual eu salvo no sessionStorage o valor do elemento clicado, o problema é que se clicar várias vezes, o valor irá se repetir várias vezes também. Como pretendo enviar esse valor posteriormente para o bd, qual a melhor forma de eu limitar que esse valor se repita ao clicar no objeto?


text:
Q: Which algorithm use sorted method in Stream interface When I print the values in the sorted method,
Stream.of("d", "a", "b", "e", "c", "f")
    .sorted((s1, s2) -> {
        System.out.printf("sort: %s - %s\n", s1, s2);
        return s1.compareTo(s2);
    }).forEach(System.out::println);

The output is as follows;
sort: a - d
sort: b - a
sort: b - d
sort: b - a
sort: e - b
sort: e - d
sort: c - d
sort: c - b
sort: f - c
sort: f - e
a
b
c
d
e
f

I could not understand the logic of the sorting algorithm here. Any help will be appreciated.

A: The answer below is relevant to OpenJDK (checked against 10.0.1).
Streams delegate the sorting operations to the relevant Arrays.sort methods (see end methods of various SortingOps).
Sorting streams of objects
For sorting objects, TimSort (basically a merge sort which uses insertion sort when the divisions of the input are small enough) is the preferred method.
The authors credit Tim Peter's implementation of list sort in Python as an inspiration, further attributing the idea to the paper "Optimistic Sorting and Information Theoretic Complexity", Peter McIlroy, SODA (Fourth Annual ACM-SIAM Symposium on Discrete Algorithms), 467-474, Austin, Texas, 25-27 January 1993.
However the user can also request MergeSort (falling back to insertion sort when the arrays are small enough - in OpenJDK 10 it's 32 or fewer elements) to be used by setting the java.util.Arrays.useLegacyMergeSort property to true. This is planned to be removed in future releases.
Sorting streams of primitives
For sorting streams of primitives (byte, char, short, int, long, float, double) - dual pivot quicksort is implemented. The authors (Vladimir Yaroslavskiy, Jon Bentley, and Josh Bloch) do not give any more information about where the inspiration came from.
Sources
To learn more, see OpenJDK code:

*

*SortedOps.java - implementation relevant to the streams

*Arrays.java - implementation of the Arrays helper, see the different sort methods

*TimSort.java - implementation of TimSort

*ComparableTimSort.java - variation for classes implementing Comparable

*DualPivotQuicksort.java - implementation of sorting for primitives


text:
Q: Redirect after download xml file I use the following code to download an xml file
<?php
header('Content-type: text/xml');
header('Content-Disposition: attachment; filename="download.xml"');
echo simplexml_load_file('temp.xml');
unlink('temp.xml');
?>

I would like to redirect to index.php after this. How do I do this?
header('location...) and meta refresh do not work

A: Well because you send the header and content this can't be done.
You have to redirect first and then let the file download on the target site.

A: Make your website change the url two times with javascript:
<script>
  location.href="your_php_file_that_downloads_xml.php";
  location.href="/other/site";
</script>


text:
Q: Can I use aluminum foil for a heat gun as a nozzle? Wanted to desolder a small chip with 48 pins on a PCB.
Since my heat gun didn't come with a small nozzle included, can I use aluminum foil to create a ghetto nozzle for it?
What can I do as an alternative option?

A: Of course, you can use aluminum as the nozzle, even though it's melting point temperature is low, I think aluminum alloy covers the upper limit temperature a chip can bear.
But why your heat gun has no nozzle?

A: I don't see why not. You just need to secure it well and play around til you get a good size nozzle at the end with the airspeed you like. If its blowing too hard you could try cutting some vents in the side to take away some of the pressure.
Like the user in the comments said, it may work better to just shield the rest and use the heat gun as is if its just a one off type thing.

A: You don't necessarily need a nozzle, I  occasionally reflow solder with it off (if I'm doing a panel by hand, for instance, and want to spend less time waiting for my board to heat up between component placements). The main problem is that without one you'll spread heat over a wider area, so you might accidentally shift or desolder components if you're not careful. If you're using an actual heat gun, you might risk high temperatures that could burn your solder mask (although I've used them sucessfully in a pinch).
I do recommend getting a real, temperature controlled rework tool if you're going to be doing more of this in the future but a heat gun with no nozzle should be fine for a one off.

A: I don't know how well it will work, but you need to consider that aluminium has rather low melting point temperature(660.32 °C). You probably wont have that temperature near PCB, but temperature will be higher near heat gun.


text:
Q: Angular 2 Radio Button not Initializing Correctly with Reactive Form I am starting with Angular 2 and am currently using version 2.2.2
I am writing a reactive form, but I am not able to initialize the selected radio button. The page should load with a radio button selected, but this is not occurring.
I have been unable to locate the source of the problem. From code samples on the Web, I think this should be working. Here is a snippet of my code.
<form [formGroup]="consultaSolicitudesINETELForm"  (ngSubmit)="consulta(consultaSolicitudesINETELForm)">
<input type="radio" formControlName="criterio" value="1"  />
<input type="radio" formControlName="criterio" value="2"  />
<input type="radio" formControlName="criterio" value="3"  />
<input type="text" formControlName="folio" placeholder="folio" required>
 </form>

for the component
import { Component, OnInit } from '@angular/core';
import { FormGroup, FormBuilder, Validators } from '@angular/forms';
@Component({
moduleId: module.id,
selector: 'my',
templateUrl: 'my.component.html',
styleUrls: ['my.component.css']
})
export class My implements OnInit {

myForm: FormGroup;

constructor(private fb: FormBuilder) {

}

ngOnInit(): void {
  this.buildForm();
}

buildForm(): void {

  this.consultaSolicitudesINETELForm = this.fb.group({
    criterio: ["2"],
    folio: ["TEST"],

  });

  this.myForm.valueChanges.subscribe(data => this.onValueChanged(data));
  this.onValueChanged();

}

EDIT:
 Here is a plnkr   I forked from an example where I added radio that does not run in my environment. The only difference I see there are version numbers.
EDIT2:
OK, I found it has something to do with ng-bootstrap.  If I use NgbModule.forRoot() then the radio buttons are not initialized and don't work as expected, if I disable ng-bootstrap then they work, but as I use ng-bootstrap elsewhere I can't do that.
I went around it by using ng-bootstrap's own radio button group and re-designing the web page. I had the radio buttons placed inside a legend of various fieldsets and all content always visible.
Now the radios  work kind of like tabs, displaying a different div depending on the current selection.
The original purpouse of the radio buttons was to select a working fieldset where all it's elements would be enabled and all others fieldsets' content disabled.

A: This issue is with ng-bootstrap and is tracked at https://github.com/ng-bootstrap/ng-bootstrap/issues/1125
It's high priority for them.


text:
Q: Inserir no banco conforme os dados encontrados Estou com um certo problema em "lógica", onde eu devo inserir os registros de dois arrays em uma table do BD. Ai eu tenho a seguinte situação:
No primeiro if eu verifico se a tabela_p não contém dados. Caso não contenha, ela adiciona null na tabela_p e insere conforme quantos dados tiver a tabela_s;
if(count($tabela_p) == 0){
    $tabela_p = null;
    for( $i = 0; $i < count( $tabela_s); $i ++ ) {

        $w_querybusca="insert into sai_cad_patr_seri (fk_seq_cara_peri,tx_num_patr,tx_num_seri)
                  values ('$arr_w_param[17]','$tabela_p[$i]','$tabela_s[$i]');";

        $w_queryresultado = f_class_conecta_bd($w_querybusca);
    }
}
else
{
    for( $i = 0; $i < count($tabela_p); $i ++ ) {
        $w_querybusca="insert into sai_cad_patr_seri (fk_seq_cara_peri,tx_num_patr,tx_num_seri)
                  values ('$arr_w_param[17]','$tabela_p[$i]','$tabela_s[$i]');";
        $w_queryresultado = f_class_conecta_bd($w_querybusca);
    }
}

Logo no else eu insiro conforme a tabela_p; O problema é:

*

*Caso tenha um valor na tabela_p ele cai no else e ira executar o for somente uma vez. Mas tem a possibilidade de conter 2 ou mais dados na tabela_s ai ele não vai inserir eles.

Como eu deveria fazer para arrumar essa lógica?

A: Você usa o p como parâmetro do for. Use o s, já que você quer que o s defina o loop.
Troque
for( $i = 0; $i < count($tabela_p); $i ++ )

por
for( $i = 0; $i < count($tabela_s); $i ++ )

A: Você pode fazer 2 algo parecido com:
Caso você sempre tenha certeza que irá existir valor na variável $tabela_s, então basta apenas 1 foreach.
foreach ($tabela_s as $key_s => $value_s){
        foreach ($tabela_p as $key_s=> $value_p){
            $w_querybusca="insert into sai_cad_patr_seri (fk_seq_cara_peri,tx_num_patr,tx_num_seri) values ('$arr_w_param[17]',$value_p,'$value_s;";
            $w_queryresultado = f_class_conecta_bd($w_querybusca);
        }
    }


text:
Q: C++ classes variables declaration and usage sequence? I'm new to programming, and I'm currently learning C++. I came across this in the tutorials I am using.  My question: How can the variable 'name' be used in the getName and setName functions before it is even declared which happens later under private? Isn't C++ a top to down sequential language?enter image description here

A: It works, because the C++ compiler is clever and initially loads the entire class declaration (together with any definitions it might have) "separates" the class members, builds up internal structures about the class and its content, and at a later stage the class methods are being compiled, when the entire class structure is already known. For example this is also how the parent class's methods and variables are accessible ... without full knowledge of the class and its entire hierarchy this would not work.
Since you are just beginning to learn C++, I'm not going to bore you with compiler internals, however a good book on this subject is https://en.wikipedia.org/wiki/Compilers:_Principles,_Techniques,_and_Tools or "Modern Compiler Implementation in C" (https://www.cs.princeton.edu/~appel/modern/c/)


text:
Q: TSP vs. Word Unscrambler Would the task of outputting whether or not a given scrambled word is a real english word be an equivalent problem to the traveling salesman problem? A well known strategy is to generate all permutations of a given word and compare all of them to all the words in the English dictionary. This algorithm would have a time complexity of O(N!). I could imagine that the two differ in an important aspect: once you find a permutation that matches a word, you can stop generating permutations, whereas with the TSP you have to try out every combination of routes regardless. However, I wrote an algorithm which, instead of generating all permutations of a given word with length n, it instead sorts the letters in the given word and performs the same algoritm on the words of the dictionary, then compares the two sorted strings (this method works 100% of the time). My algorithm uses the default Java sort, and after researching, I found that it runs at O(n log n). In total, my program runs at O(n log n) because this term grows the largest as n approaches infinity. This algorithm runs in less than polynomial time.
So, if the problems are equivalent, couldn't you use a similar method to solve the TSP problem? How would this relate to P vs. NP?
Sorry if any of this didn't make sense or I wasn't using the terminology correctly, I'm not that experienced in this field

A: The fact that there exist algorithms of the same complexity for solving two problems doesn't necessarily mean that the problems have the same complexity, because there could exist more efficient algorithms for one of the problems but not for the other.
The proper way of relating the complexities of different problems is reduction: If you can show that any instance of problem A can be transformed into an instance of problem B in such a way that the answer to the transformed instance is the same as the answer to the original instance, then problem B is at least as complex as problem A (because the algorithm that solves B also can solve A). If you can show a reduction in the opposite direction too, A and B are equally complex.
In your case, there is no currently known way to transform an arbitrary TSP problem to an equivalent unscrambling problem, so it is (to the best of our knowledge) not the case that the problems have the same complexity.


text:
Q: Turf.js Check if polygon "Contains" another polygon I am using turf.js for geometrical operation on openlayers3 features but i think it lacks support for "contains" operation.
There are these within and inside operations, but they return "false" when i check it with the polygon. Is there any other way to do this "contains" operation with turf.js or do i have to use the JSTS?

A: You should be able to use the turf/boolean-contains module, noting that this only returns a true or false answer. Hope that helps


text:
Q: Infinite loop after dividing in assembly NASM I'm trying to write a program in NASM assembly that convert a decimal number to binary.
So far I wrote some code that take the input number, divide it by 2 and display the remainder. But I have a problem, I get an infinite loop after division, in fact I'll always have in eax a number greater than 0.
; ----------------------------------------------------------------------------------------
; nasm -felf decbin.asm && gcc decbin.o -o decbin
; ----------------------------------------------------------------------------------------
section .data
    in_message  db  "Enter a number in decimal:",0 ;input message
    out_message db  "The binary number is:%d",10,0 ;output message
    integer times 4 db  0                  ;32bits integer
    formatin    db  "%d",0
    binary      db  2;used for div
section .text
    global  main
    extern  printf
    extern  scanf
main:
;;; Ask for integer
    push    in_message
    call    printf
    add esp,4       ;remove parameters

    push    integer     ;address of integer where number will be stored
    push    formatin    ;%d parameter, arguments are right to left
    call    scanf
    add esp,8       ;remove parameters

    mov eax,[integer]
    jmp loop
    ;;; terminate if zero
    mov al,1
    mov ebx,0
    int 80h
loop:
    xor edx,edx
    mov ebx,[binary]    ;mov binary to ebx
    div ebx
    push    edx
    push    formatin
    call    printf
    add esp,8
    cmp eax,0       ;compare the quotient with 0;
    jnz loop

A: A common calling convention is to place the return value from function calls into eax and, since printf returns the number of character printed, it will usually always be non-zero for a "%d" format string (unless you have an output failure of some type).
So, the call itself will probably be what's setting eax to a non-zero value.
To fix this, you need to save eax before calling printf, and then restore it afterwards, by changing:
push      edx
push      formatin
call      printf
add esp,  8

into:
push      eax        ; save here
push      edx
push      formatin
call      printf
add esp,  8
pop       eax        ; restore here

This will ensure that whatever printf does to eax will be irrelevant, since you're saving and restoring it yourself.


text:
Q: What is the maximum sum of squares of two non-attacking rooks placed on a matrix? There is a m x n matrix given each with integer elements. The problem says that we have to place two rooks on that matrix, such that they don't attack each other and the sum of the elements on which the rooks are placed is maximum.
Example:
Let's say matrix is
2 5
1 3

Then non-attacking rooks can be placed only on 2,3 or 1,5 element positions. But the maximum sum is found in case of 1,5, so the function should return 1 + 5 = 6.
I thought that we could go through all the pairs of the array one by one and then return the maximum sum that we found, but I can't seem to find a better or efficient approach for this. My solution would be O(m * m * n * n) in terms of complexity.
What would be a better approach? I would appreciate any help.

A: *

*For each row, find the top 2 values and remember the column where they were found. O(mn)

*For each column, find the top 2 values and remember the row where they were found. O(mn)

*The the remaining operations, we only use the two lists built above. We will not look at the matrix again:

*

*For each row, pretend to place a rook in that row and in the column with the highest value. For each column, sum that top value with the top value for the column, except for the column where the rook is, where we sum with the second highest value. Remember the row of the pretend rook and the column with the highest sum. O(mn)

*Repeat, but use the second highest value. O(mn)
Operation complete. O(mn) + O(mn) + O(mn) + O(mn) = O(mn)

A: based on @Andreas comment above here is the code :

int solution(vector<vector<int>>& board) {
    int n = board.size();
    int m = board[0].size();

    vector<vector<int>> row(n);
    vector<vector<int>> col(m);

    for (int i = 0 ; i < n ; i++) {
        int mx = 0  , mxc  , smx = 0  , smxc;
        for (int j = 0 ; j < m ; j++) {
            if (board[i][j] >= mx) {
                smx = mx ;
                smxc = mxc;

                mx = board[i][j];
                mxc = j;
            }
            else if (board[i][j] >= smx){
                smx = board[i][j];
                smxc = j;
            }
        }
        row[i].push_back(mxc);
        row[i].push_back(smxc);
    }
    for (int j = 0 ; j < m ; j++) {
        int mx = 0 , mxr  , smx = 0  , smxr ;
        for (int i = 0 ; i < n ; i++) {
            if (board[i][j] >= mx) {
                smx = mx ;
                smxr = mxr;

                mx = board[i][j];
                mxr = i;
            }
            else if (board[i][j] >= smx) {
                smx = board[i][j];
                smxr = i;
            }
        }
        col[j].push_back(mxr);
        col[j].push_back(smxr);
    }
    int ans = 0 ;
    for (int i = 0 ; i < n ; i++) {
        int r = i  , c =  row[i][0];
        for (int  j = 0 ; j < m ; j++) {
            if (j != c) {
                if (col[j][0] != r)
                    ans =  max(ans , board[r][c] + board[col[j][0]][j]);
                else
                    ans =  max(ans , board[r][c] + board[col[j][1]][j]);
            }
        }
    }
    for (int j = 0 ; j < m ; j++) {
        int c = j  , r = col[j][0];
        for (int i = 0 ; i < n ; i++) {
            if (i != r) {
                if (row[i][0] != c)
                    ans = max(ans , board[r][c] + board[i][row[i][0]]);
                else
                    ans = max(ans , board[r][c] + board[i][row[i][1]]);
            }
        }
    }
    return ans ;
}


text:
Q: Einstein metric for simply connected Riemannian manifold, diffeomorphic to 3-sphere? If we can construct an Einstein metric for a simply connected Riemannian manifold, why does it necessarily follow it is diffeomorphic to the $3$-sphere?

A: Firstly, without the hypothesis that the manifold is compact, this is not true, with hyperbolic space and Euclidean space being the only other complete examples.  Moving on, in three dimensions an Einstein metric has constant sectional curvature (this is just linear algebra).  Hence, any complete Einstein metric on a simply connected 3-manifold is isometric to the sphere, hyperbolic space or Euclidean space by the classification of space forms which you can find in any text on Riemannian geometry.  If the manifold is assumed compact and $1$-connected, then the only option is that the manifold is isometric, hence diffeomorphic, to the $3$-sphere since the others are non-compact.


text:
Q: BASH Script - SCP - Permission denied (publickey,gssapi-keyex,gssapi-with-mic,password) I was requested for work to have a server that kinda acts like a backup for specific files mostly around 30 (cannot bind them together to a folder) they are scattered  all over the server
need to reach them individually.
Before I'm inserting to the production environment - I have decided to try it at home
I have generated and copy the keys between both servers.
I have changed folder and files permissions to the maximum required - even did 760 for testing purposes
I have chmod 0770 to the all .ssh folder  and still, get this annoying error
also for both servers
I'm not using a Kerberos method or another programming interface - that requires me the GSSAPI - just a simple SCP
when I'm doing a manual SCP from test-server to  linuxproject server it succeeds with no interruptions
So I believe  it has something to do with the second SSH process that comes from the SCP
As when I'm accessing to test server for example - I'm able to execute commands before the SCP like creating a file (so issue happen I believe, when test-server tried to connect with the linuxproject server)
Below ERRORS I'm getting
Command:
[linuxproject@sysadmin ~]$ sshpass -p "abc12345" ssh test-server@192.168.1.26 " touch longlist.txt && scp longlist.txt linuxproject@192.168.1.18:/home/linuxproject"

ERROR:
Permission denied, please try again.
    Permission denied, please try again.
    linuxproject@192.168.1.18: Permission denied (publickey,gssapi-keyex,gssapi-with-mic,password).
    lost connection

Some verbosity logs from the SCP command
debug3: receive packet: type 6
debug2: service_accept: ssh-userauth
debug1: SSH2_MSG_SERVICE_ACCEPT received
debug3: send packet: type 50
debug3: receive packet: type 51
debug1: Authentications that can continue: publickey,gssapi-keyex,gssapi-with-mic,password
debug3: start over, passed a different list publickey,gssapi-keyex,gssapi-with-mic,password
debug3: preferred gssapi-keyex,gssapi-with-mic,publickey,keyboard-interactive,password
debug3: authmethod_lookup gssapi-keyex
debug3: remaining preferred: gssapi-with-mic,publickey,keyboard-interactive,password
debug3: authmethod_is_enabled gssapi-keyex
debug1: Next authentication method: gssapi-keyex
debug1: No valid Key exchange context
debug2: we did not send a packet, disable method
debug3: authmethod_lookup gssapi-with-mic
debug3: remaining preferred: publickey,keyboard-interactive,password
debug3: authmethod_is_enabled gssapi-with-mic
debug1: Next authentication method: gssapi-with-mic
debug1: Unspecified GSS failure.  Minor code may provide more information
No Kerberos credentials available (default cache: FILE:/tmp/krb5cc_1000)

debug1: Unspecified GSS failure.  Minor code may provide more information
No Kerberos credentials available (default cache: FILE:/tmp/krb5cc_1000)

debug2: we did not send a packet, disable method
debug3: authmethod_lookup publickey
debug3: remaining preferred: keyboard-interactive,password
debug3: authmethod_is_enabled publickey
debug1: Next authentication method: publickey
debug1: Offering public key: /home/oren/.ssh/id_rsa RSA SHA256:tguZWskKp6IFsqdZ5cb/AqzFBd7hzsMXRhjd02wGqko
debug3: send packet: type 50
debug2: we sent a publickey packet, wait for reply
debug3: receive packet: type 51
debug1: Authentications that can continue: publickey,gssapi-keyex,gssapi-with-mic,password
debug1: Trying private key: /home/oren/.ssh/id_dsa
debug3: no such identity: /home/oren/.ssh/id_dsa: No such file or directory
debug1: Trying private key: /home/oren/.ssh/id_ecdsa
debug3: no such identity: /home/oren/.ssh/id_ecdsa: No such file or directory
debug1: Trying private key: /home/oren/.ssh/id_ed25519
debug3: no such identity: /home/oren/.ssh/id_ed25519: No such file or directory
debug1: Trying private key: /home/oren/.ssh/id_xmss
debug3: no such identity: /home/oren/.ssh/id_xmss: No such file or directory
debug2: we did not send a packet, disable method
debug3: authmethod_lookup password
debug3: remaining preferred: ,password
debug3: authmethod_is_enabled password
debug1: Next authentication method: password
debug1: read_passphrase: can't open /dev/tty: No such device or address
debug3: send packet: type 50
debug2: we sent a password packet, wait for reply
debug3: receive packet: type 51
debug1: Authentications that can continue: publickey,gssapi-keyex,gssapi-with-mic,password
Permission denied, please try again.
debug1: read_passphrase: can't open /dev/tty: No such device or address
debug3: send packet: type 50
debug2: we sent a password packet, wait for reply
debug3: receive packet: type 51
debug1: Authentications that can continue: publickey,gssapi-keyex,gssapi-with-mic,password
Permission denied, please try again.
debug1: read_passphrase: can't open /dev/tty: No such device or address
debug3: send packet: type 50
debug2: we sent a password packet, wait for reply
debug3: receive packet: type 51
debug1: Authentications that can continue: publickey,gssapi-keyex,gssapi-with-mic,password
debug2: we did not send a packet, disable method
debug1: No more authentication methods to try.
linuxproject@192.168.1.18: Permission denied (publickey,gssapi-keyex,gssapi-with-mic,password).

Please Please help me - I'm stuck for over 4 days with this (100 bad words) you know what- and can't get it solved

A: From my experience 0770 are the wrong permissions. SSH is somewhat picky about permissions. You should use it like this
user@server:~$ ls -la .ssh
total 28
drwx------  2 user group 4096 Nov 30 17:34 .
drwxr-xr-x 59 user group 4096 Jan  8 08:00 ..
-rw-r--r--  1 user group  394 May  5  2016 authorized_keys
-rw-------  1 user group 1675 May 10  2016 id_rsa
-rw-r--r--  1 user group  390 May 10  2016 id_rsa.pub

This is also stated in the SSH Documentation

~/.ssh/
This directory is the default location for all user-specific configuration and authentication information. There is no general requirement to keep the entire contents of this directory secret, but the recommended permissions are read/write/execute for the user, and not accessible by others.

~/.ssh/id_rsa
Contains the private key for authentication. These files contain sensitive data and should be readable by the user but not accessible by others (read/write/execute). ssh will simply ignore a private key file if it is accessible by others.


text:
Q: How does this program to calculate Armstrong numbers between two intervals work step by step? class Armstrong {
  public static void main(String[] args) {

    int low = 999, high = 99999;

    for(int number = low + 1; number < high; ++number) {
      int digits = 0;
      int result = 0;
      int originalNumber = number;

      // number of digits calculation
      while (originalNumber != 0) {
        originalNumber /= 10;
        ++digits;
      }

      originalNumber = number;

      // result contains sum of nth power of its digits
      while (originalNumber != 0) {
        int remainder = originalNumber % 10;
        result += Math.pow(remainder, digits);
        originalNumber /= 10;
      }

      if (result == number)
        System.out.print(number + " ");
      }
  }

How does this program work? It would be very helpful. Program to find Armstrong between two intervals? Can someone explain step by step? Help me out.

A: Steb-by-step Explanantion
Initialize the start and end of the interval with 999 and 9999
You can change these numbers but ensure that low is always lesser than high:
int low = 999;
int high = 99999;

for (int number = low + 1; // Create a variable number and assign it one number greater than low
    number < high;         // This loop should keep repeating until number is less than high(end of the interval)
    ++number               // After each repetition, increment the value of number by 1
    ) {

Create a variable digits to store the number of digits in number.
For example, if number is 100, this will be later set as 3 as the algorithm proceeds:
  int digits = 0;

Create a variable result that will store the sum of powers of numbers:
  int result = 0;

Copy the value of number to a local variable originalNumber because it has to be modified:
  int originalNumber = number;

The logic of calculating number of digits in a number is keep dividing it by 10 until the number is 0.
Every time you divide any number by 10, the last digit is stripped out. So every time the last digit is stripped out, increment digit by 1 (digit++)
  // number of digits calculation
  while (originalNumber != 0) // Continue this while loop till originalNumber is not 0
  {
    originalNumber /= 10;     // Divide the number by 10. Dividing a number by 10 removes its last digit.
    ++digits;                // One digit was removed in the above step, which means it has to be counted, so increment digit by 1
  }
  // For example, for originalNumber = 423,
  // 423 / 10 = 42 : digits = 1 (first loop)
  // 42 / 10 = 4 : digits = 2   (second loop)
  // 4 / 10 = 0 : digits = 3    (third loop)
  // Now originalNumber has become 0, so the while loop condition originalNumber != 0 will be false and the loop will stop.
  // Now we have digits = 3, which is the number of digits in 423

  // When program reaches here, digits will have the number of digits in the
  // number "originalNumber"

Copy number again to originalNumber because we want to modify the number
again and originalNumber has become 0 because of the digit counting loop above:
  originalNumber = number;

An Armstrong number is a number which is equal to the sum of digits to the power of its number of digits.
e.g.: in 153, (1^3) + (5^3) + (3^3) = 153. We are obtaining the cube of each digit(1, 5, 3) because 153 has 3 digits 1, 5, 3.
If it was say 50, we would check ( 5^2 + 0^2) because 50 has 2 digits (50 is not Armstrong, because 25 + 0 = 25 which is not equal to 50)
We saw above dividing a number by 10 removes the last digit (423 / 10 = 42)
Similarly, if we only want this last digit, we can get it by modulus 10 (% 10): (423 % 10 = 3) (42 % 10 = 2) (4 % 10 = 4)
  // Let's assume originalNumber is 153
  while (originalNumber != 0) // Same as above, keep looping till the originalNumber is not 0(i.e. all digits have been removed)
  {

Extract the last digit to remainder, (for 153: 153 % 10 = 3) (for 15: 15 % 10 = 5)
    int remainder = originalNumber % 10;

Now we have the last digit, we need to raise this digit to the number of
digits i.e. 3(for 153): (3^3) = 27. We do this using Math.pow(3, 3). Add this number to result. In the end after each loop's number's power is added, at the end of the loop, result will contain their sum:
    result += Math.pow(remainder, digits);
    originalNumber /= 10; // Remove the last digit (same as above, for 153: 153 / 10 = 15)
    // After this line finishes, one rightmost digit will be removed, this will keep
    // happening till originalNumber = 153 becomes 15, then 1, then 0.
    // When originalNumber is 0, loop stops and we will have the total sum in result
  }

For an Armstrong number like 153, result will also contain 153. For a non-Armstrong number it will contain something else.
  if (result == number) // For 153, both will be equal.
    System.out.print(number + " "); // This will only execute if result is equal to number, or in other words, only if the number is Armstrong
}

Improvements
As per single responsibility principle, each function or class must exactly do one thing. You have a monolithic main() method that:

*

*Defines the interval

*Counts the digit of each number in the interval

*Calculate the sum of powers of digits

*Check if number is Armstrong and print it.

I would prefer breaking down each operation to a separate method, so that it improves readability and maintainability while respecting single-responsibiliy principle:
class Armstrong {

   public static int countDigits(int number) {
      int digits = 0;
      while (number != 0) {
        number /= 10;
        ++digits;
      }
      return digits;
   }

  public static int digitPowerSum(int number, int power) {
    int result = 0;
    while (number != 0) {
      int remainder = number % 10;
      result += Math.pow(remainder, power);
      number /= 10;
    }
    return result;
  }

  public static boolean isArmstrong(int number) {
    int digits = countDigits(number);
    int sum = digitPowerSum(number, digits);
    return sum == number ; // will return true if both numbers are equal else false
  }

  public static ArrayList<Integer> armstrongNumbersBetween(int low, int high) {
      ArrayList<Integer> numbers = new ArrayList<>();
      for(int number = low + 1; number < high; number++) {
        if (isArmstrong(number)) {
          numbers.add(number);
        }
      }
      return numbers;
  }

  public static void main(String[] args) {
    int low = 999, high = 99999;

    ArrayList<Integer> numbers = armstrongNumbersBetween(low, high);

    for(int number : numbers) {
      System.out.print(number + " ");
    }

  }
}

Here, each method does exactly one thing and this helps in better reusability. You just have to call the required methods to perform a specific operation.
If something is unclear, let me know.


text:
Q: What is best monitoring tool for Tornado as Async container? Tornado web can be used wth WSGI or ASYNC container. There are numerous solutions for WSGI container.
Most appealing solution by now is RPM Lite, but it requires Tornado to run in wsgi mode which I do not want. I need solution that will fully monitor Tornado Async application.
EDOT: Thanks @Graham for reading between lines, I've been expecting people that understand topic would have an answer.

A: The question is a bit obscure but the assumption here is that you are asking what web application performance monitoring tools exist. In this case you are asking for one that will work with the Tornado ASYNC API vs the WGSI container that sits on top of Tornado web server.
You mention 'RPM Lite' which would interpret as being New Relic web application performance service. For that, as you found, only WSGI applications running on Tornado are currently supported and not the ASYNC API of Tornado. Some investigation of support for ASYNC Python web frameworks has been done but Tornado API wasn't used as test case for that and so not known when/if the ASYNC API may be supported.
As for alternatives, it depends on what you want to get out of this and is where you need to expand on the question. If you are more after tracking web traffic then you can alway using Google analytics or tools that extract details from web server logs.
If you are specifically after tools which can instrument the actual web application and tell you what is going on inside of it, including show time taken in database, web externals, etc, like New Relic does, then there isn't currently any other options that I know of for ASYNC systems and in particular Tornado ASYNC API.


text:
Q: Node.js SyntaxError: Unexpected identifier while setting Forge Viewer i want to run autodesk forge viewer and setting Node.js based on Autodesk tutorial, but got this error:
SyntaxError: Unexpected identifier

How can i fix this?
Thanks!

A: In Node.js console, you have to use JavaScript syntax and not some shell or bash code. You are executing set VAR=xx here which is not JavaScript syntax.
Since you want to set environment variable you should exit from Node.js terminal and open plain cmd terminal first, execute these set commands and then open Node.js terminal with command node and then do what you want to do.


text:
Q: ASP.NET MVC + Oracle: samples and how-to While reading NerdDinner, and browsing other examples on the internet regarding ASP.NET MVC with LINQ To SQL.
In my ASP.NET MVC project I have to connect to an Oracle database. The main goal of the application is to display, edit, and update data.  I am uncertain if ASP.NET MVC can work with an Oracle database.

*

*Has anyone ever done an ASP.NET MVC project with Oracle as the database?

*Are there any articles with sample code that you'd recommend?

*What are some easy ORMs or data access strategies that you'd recommend an ASP.NET (webforms or MVC) project use to communicate to an Oracle database?

A: You can use Nhibernate to get access to your DB.

A: ASP.NET MVC can certainly support Oracle or any other data source behind the scenes.
MVC is not tied to Linq to SQL in any way.  It's just one convenient way (among many) to get data from a datasource into your models.
As Sly pointed out, NHibernate is one ORM framework that will work for you.


text:
Q: How to dynamically add and scale with Private Data Collections? Scenario:
I have 3 organizations (O1-O3). O1 is an org of an applicant and O2/O3 administrate his public and private data shared with them. O1-O3 have private data shared with each other and O1-O2 have private data shared. The network is running, collections are already distributed and everything works fine.
When i now want to add more organizations (in terms of thousands, O4-O1000) of type applicant (O1)  and each of them should have shared private data with Organization 2 (O2) and Organization 3 (O3), how do i approach this when the network is already live and running? Is it scalable? How would i add dynamically private data collections between those newly added organizations and the 2 established ones (O2 and O3)?
I already encountered this but it is not a solution to my problem.


text:
Q: Script not firing when window's ready I have a script that resize a text .div (.block-left), to make room for a large picture. The picture width and height are determined by the user window. Depending on this parameters the text .div adapts itself.
To make do, the script runs twice, when the window is ready and when resized.
On most browsers the script works properly when the window is ready, but they are some hiccups on refresh, especially with Safari. The resize script, however, never encounters any bugs.
Here is the script (the same is used when on window resize) :
<script>
$(document).ready(function() {
var imgWidth = ($(".picture img").width()+ 20 + "px");
  $(".block-left").css("margin-left", imgWidth);
});
</script>

You can see what it is supposed to accomplish on this screenshot :

What can I do to force the script to load first thing?


text:
Q: What is the alternative to HtablePool for pooling tables in Hbase I am going through many examples and blogs for hbase connection pooling.
I tried using Htablepool which the compiler shows its depreciated (using cloudera cdh 5.4.0, Hbase version - 1.0.0-cdh5.4.0)
And also Htable class is not Thread safe so instead of directly instantiating Htable i am trying to use HtableInterface by getting a connection from HConnectionManager but this is also depreciated.
It says to use ConnectionFactory.
Please can i get a complete optimised and best way to do connection pooling with having pools of tables  Alternate to HTablePool

A: Even Hconnectionmanager is now deprecated. New way is to use ConnectionFactory.
I was also puzzled to to find no connectionpooling in new client as compared to HTablePool in old APIs. But the new way is to pass executor service to ConnectionFactory.createConnection in the 2nd param. Look at this code for more reference
https://hbase.apache.org/xref/org/apache/hadoop/hbase/client/example/MultiThreadedClientExample.html
If you do not pass the executor service, it creates a default pool which will eventually as many threads as the number of region servers.
I did a perf test to see how passing different sized executor service does against not explicitly passing any executor service and believe me the default method (not passing executor service) did as good as passing service with thread pool more than 20 in my case ( i had 10 region server).
So in my opinion, you can use it without passing executor service explicitly.


text:
Q: AngularJS: Replace an element using Transclude: 'element' but not the deprecated 'replace'? I am trying to create a directive that can create multiple elements an replace the calling element with the multiple. Specifically I want to set the directive on a single list-item and have it create multiple list items w/o a wrapping element. (Using the
 for the directive works but prevent me from including 'static' items.) Here is the markup:

static first

static last

In my controller I'll define myVar:
$scope.myVar = ['one', 'two', 'three'];

And my directive looks like this:
myApp.directive('myRepeater', function () {
    return {
        restrict: 'A',
        transclude: 'element',
        replace: true, //<--- DEPRECATED
        scope: {
            val: '=myRepeater'
        },
        template: '
{{item}}
'
    };
};

In AngularJS v1.2.26 this works UNLESS you remove 'replace', then you get nothing. Is this just not possible? I did note that in the docs for v1.3.4 that they feel:

There are very few scenarios where element replacement is required for the application function, ...

But my case above seems to be a clear example of the need for this, unless there is a 'better way'!...?

A: If you don't have to do it as an attribute, then you can do it using an element:

static first

            <my-repeater var="myVar"></my-repeater>

static last

And the directive
    .directive('myRepeater', function () {
    return {
        restrict: 'E',
        scope: {
            val: '=var'
        },
        template: '
{{item}}
'
    };
    })

I updated the fiddle to show it http://jsfiddle.net/6rjr8nq5/1/
Since unknown tags are just ignored, it works fine.
And if you need the attribute, you could stick it on the ul, transclude, and use the link function to properly place the static data, assuming you know where it goes.


text:
Q: how to avoid undefinedfilename error when piping a2ps output to ps2pdf I am trying to write a bash function to convert a text file to PDF using a combination of a2ps and ps2pdf. To convert exc.cpp I have the following command:
a2ps -M a4 -B -1 -o - exc.cpp | ps2pdf  -sPAPERSIZE=a4 -o exc.pdf -

But I get an error indicating undefined filename the following error output:
GPL Ghostscript 9.04 (2011-08-05)
Copyright (C) 2011 Artifex Software, Inc.  All rights reserved.
This software comes with NO WARRANTY: see the file PUBLIC for details.
[exc.cpp (C++): 2 pages on 2 sheets]
[Total: 2 pages on 2 sheets] sent to the standard output
Error: /undefinedfilename in (.setpdfwrite)
Operand stack:

Execution stack:
   %interp_exit   .runexec2   --nostringval--   --nostringval--   --nostringval--   2   %stopped_push   --nostringval--   --nostringval--   --nostringval--   false   1   %stopped_push
Dictionary stack:
   --dict:1160/1684(ro)(G)--   --dict:0/20(G)--   --dict:77/200(L)--
Current allocation mode is local
Last OS error: 2
GPL Ghostscript 9.04: Unrecoverable error, exit code 1

Is there some way to specify to ps2pdf a value for the filename to avoid this error? Or is there a simpler way to convert a text file to PDF?

A: a2ps and ps2pdf do not share the same syntax.
According to UNIX man pages : ps2pdf (1), the basic syntax of ps2pdf is
ps2pdf  [options...] {input.[e]ps|-} [output.pdf|-]

This will work:
a2ps -M a4 -B -1 -o - exc.cpp | ps2pdf -sPAPERSIZE=a4 - exc.pdf


text:
Q: Question about Color Sensors Can a color sensor detect more than one color at once WHILE distinguishing them?
For example: Say I wanted a program to activate only if both red and violet are detected at the same time. Is that possible? How could I do that?

A: Think of a colour sensor as a single pixel camera. If you held up a red and blue object to this sensor it would detect both of those as a combined signal, purple. If you want to differentiate with more detail, you need more resolution.
There are tons of cheap camera modules available which you can use for various tasks. OpenCV makes extracting useful data much less of a hassle.


text:
Q: Callback to map function in Angular2 service In my service.ts file I have a function (getQuestions) that calls a HTTP service that returns a JSON. With this returned JSON (data) I want to call another function (buildQuestions) so that the result of buildQuestions is returned in getQuestions.
How do I have to call the functions to return the result of buildQuestions or guarantee, that the result of buildQuestions is defined when returning it in getQuestions.
data:any;
questions : QuestionBase<any>[] = [];

getQuestions() {
    let result = this.http.get(this.questionUrl)
        .map(res => res.json())
        .map(data => {
            this.data = data;
            return this.buildQuestions(data);
    });
    return result; //should actually return "this.buildQuestions(data)" (or "this.questions.sort((a, b) => a.order - b.order);")
}

buildQuestions(data){
    for (let key in data) {
        //push Objects in this.questions array
    }
    return this.questions.sort((a, b) => a.order - b.order);
}

A: You can try this.
    data:any;
    questions : QuestionBase<any>[] = [];

    getQuestions() Observable<QuestionsBase[]> {
        return this.http.get(this.questionUrl)
            .map(res => res.json())
            .map(data => {
                this.data = data;
                this.buildQuestions(data);
    )};

    buildQuestions(data){
        for (let key in data) {
            //push Objects in this.questions array
        }
        return this.questions.sort((a, b) => a.order - b.order);
    }


text:
Q: Are there existing electronic sensors that can sense if underwater or not? My goal is to to be able to read the water level percent in a small water tank. I was thinking  wiring sensors going up the side that read whether they are currently touching water. My plan is to wire the sensors into my Arduino and then calculate the percent full by the sensors that are touching water and the sensors that are not.  Are there existing sensors with this functionality? (are they cost effective?) Is there an alternative solution? Thanks so much!

A: There are a few types of water sensors, with varying levels of applicability to the purpose stated in the question.
At the simplest level are electro-conductive sensors, essentially a pair of zig-zagging exposed conductive traces along a PCB, with a small gap between the traces. If the device is submerged in water, there is conduction between the traces, which would indicate presence of water. Of course, the traces must not be covered by solder mask.

From this site
Since the conduction of electricity through the water is dependent on electrolyte / ion content in the water, results vary depending on the water quality. Further, due to corrosion and oxide build-up, the longevity of these sensors is very limited.
If the water tank in question contains somewhat impure water, then a long strip, or several short strips, of such sensors made of standard PCB may serve the purpose. Since the "sensor" is inexpensive to make, regular replacement is an easy recommendation.
A variant on this theme is the use of microstrip antennas, essentially the same concept of PCB traces, but designed to be energized via a radio frequency signal. As the dielectric between the two conductors varies with humidity, moisture and of course submersion, the resultant change in antenna load can be used for detection. See this publication for additional information.

More sophisticated sensors use a stack of hygroscopic material, and a limit micro-switch, to detect water. The hygroscopic material expands in moisture / water, tripping the limit switch. Such sensors may falsely trigger in high humidity, such as in an enclosed water tank.
Even more advanced sensors exist for the type of function described, but they are typically for industrial use, and are very expensive, if at all sold in small numbers.

Although this is not the question asked, an alternative approach is to use an ultrasonic or infrared proximity sensor to sense the water level from above, and thereby determine how full a tank is.
Similarly, there is the classic float sensor, which consists of a floating ball attached to a lever, that acts upon a flex sensor or absolute rotation sensor, to determine the level of water.
These approaches may well be more reliable to implement, than the submersible sensor approach.
See also: All the answers to This question, and this other one.
Suggestion: Research Rain Sensors for other options.

A: VDO sell water-tank sensors & gauges for boats, or you could possibly get away with using a standard resistive float sensor from a car fuel tank as long as you protect it from corrosion. These will give a varying resistance (typically 0-240 Ohms) in proportion (NOT always linear, note!) to the float position. You can bend/extend/shorten the arm to suit your tank.
Something like this:
http://www.brit-car.co.uk/product.php?xProd=90015

A: Another option is a floating magnet (for example embedded in a ping pong ball) rigged up to the edge of the tank and a series of hall effect sensors (or reed switches) up the outside of the tank. You can detect the water level by reading the state of the reed switches.

A: Surprisingly I stumbled on the image of our water sensor (I'm the owner of TempGP). Just to add to comments about our sensor plate, their galvanization (transfer of ions from one side to another) to avoid that variable/ alternative current can be used there. Also in our V3.0-B version we planing to use an ultrasonic sensor to detect distance to the water source, this will allow corrosion resistance and the sensor can be adjusted to tank specs.


text:
Q: Android SimpleCursorAdapter Update when database updates I have an application that uses SyncService and SyncAdapter. Within the application, I have an activity using a SimpleCursorAdapter. How do I go about updating the list when the database updates?
I have read that I should use adapter.changeCursor() or notifyDataSetChanged(), but where do I call it? And how would I know when the database is updated?
Also, I have heard that I could use a ContentProvider instead of a direct database access and the list would update automatically, is that true?
EDIT:
I update the database in the method onPerformSync() in my SyncAdapter class

A: You can use notifyDataSetChanged() like:
mListView.setAdapter(someAdapter);
someAdapter.notifyDataSetChanged();


text:
Q: Problems with JRuby debug IDE I am trying to get the debugger to work for JRuby 1.7.3:
I installed the ruby-debug / base / ide gems. I then tried to run a basic Ruby script on Aptana and NetBeans. In both cases I get the following trace:
Fast Debugger (ruby-debug-ide 0.4.17.beta16, ruby-debug-base 0.10.5.rc3) listens on 127.0.0.1:55687
Hello World
10432: Exception in DebugThread loop: Bad file descriptor - Bad file descriptor
Backtrace:
org/jruby/RubyIO.java:2052:in `close'
  from: C:/jruby-1.7.3/lib/ruby/gems/shared/gems/ruby-debug-ide-0.4.17.beta16/lib/ruby-debug-ide/interface.rb:44:in `close'
  from: C:/jruby-1.7.3/lib/ruby/gems/shared/gems/ruby-debug-ide-0.4.17.beta16/lib/ruby-debug-ide/ide_processor.rb:102:in `process_commands'
  from: C:/jruby-1.7.3/lib/ruby/gems/shared/gems/ruby-debug-ide-0.4.17.beta16/bin/../lib/ruby-debug-ide.rb:121:in `start_control'
  from: org/jruby/RubyProc.java:261:in `call'
  from: org/jruby/RubyProc.java:213:in `call'

I am now using the prerelease versions but I get the same error when using the release build.
A note: I successfully debugged using the built-in Ruby interpreter in NetBeans (not JRuby).


text:
Q: Comparison of the mean of a binary variable from two independent sets I have two sets of data, one is akin to high performing companies, and the other contains low performing companies.
I want to compare the mean of a binary value. For instance, "CEO has a bachelor degree".
Let's say the high performing companies have these values for this variable
[1 0 1 0 1 1 0] => µ = 4 / 7 = 0,57

The low performing companies could have something like
[1 0 1 0 1 0 0] => µ = 3 / 7 = 0,43

Now if I would like to know if these means are statistically different from each other what test should I use? My first thought would be to use a t-test, but I assume this is no option due to the fact my data is not normally distributed. I'm intending to use SPSS for analysis.

A: To compare the means of two samples one would use a t-test. NOTE: a t-test makes no assumptions on the distribution of the data, it only assumes the residuals of the model (differences in case of a two sample t-test) are normally distributed.
If this does not hold then you can use a non-parametric version of the t-test, such as Mann Whitney U test.
NOTE2: yours is a binary variable, so by taking the mean you are estimating the proportion (proportion of people with degree), so for this you can use a proportion test as well.


text:
Q: Generating UUids in a web farm environment I am planning on using sequential guids as primary keys/uuids as detailed in the post below
What are the performance improvement of Sequential Guid over standard Guid?
I am wondering if there are any gotchas as far as generating these guids across multiple web servers in a web farm environment.  I suspect the chances of collision are impossibly low but the fact that the mac address of the web server/timestamp would
doubtless be involved in generating these guids gives me pause.  I wonder if the possibility exists in a high traffic website the ordering would be messed up and the benefit of using sequential guids might be lost.
Please let me know what your experience is.
For what it is worth, my environment is ASP.NET 3.5, IIS 7 using Oracle 11g.
Incidentally, what is the data type I should use for guids in Oracle?  I know that Sql Server has "uniqueidentifier"
Thanks for your advice
-Venu

A: Because I was the creator of the post you're referring to I can answer to it.
We're using the C# code shown in the post (without the modification of ordering detailed in one of the reply, that I feel could improve performance another little bit) in web farms with from 2 to 8 application servers and never had problems of concurrency, I believe that the SequentialGuid function implemented in the Windows core DLLs already takes care of creating different guid on different machines.
In database operation having different machines inserting different Guids means that each different application server in the web farm will write data that will reside on specific regions of the database (i.e. an application server will write guid starting with 12345 and the other one with guid starting with 62373) and so the update of indexes still works efficiently because page splits do not happens very frequently (or never).
So, from my experience, no specific problem happens if you use the same strategy to generate Guids that I outlined in my original message also if you're working in web farm enviviroment if you use the proper method to generate the Guids.
I would avoid in any way to create Guid from code and also to create Guid in a central manner.
Regarding data type we used char(36) because we like to waste a lot of space! Joke aside we decided to use a long and verbose way to write data because having data in a clear format ease a lot the maintenance, but you can use Oracle GUID or simply a RAW(16) data type (they're basically the same) and spare 20 bytes of for each row. To make browsing and editing of data easier you can provide your customer a couple of function to code and decode raw guid data so that the textual representation of the guid is seen.

A: Guid  for Oracle

A: You might want to take a look at how NHibernate's Guid Comb generator works. I have never heard of a collision.

A: To ensure that you have unique GUIDs only 1 server can be the creator of said GUIDs.
If memory serves, Oracle doesn't support the creation of MS's "Guid for OLE" but you should be able to generate something highly similar utilizing this: RAWTOHEX(SYS_GUID())
Alternatively, you could have a separate application residing on a single server that is solely responsible for generating GUIDs (for example, call a web service located at a specific server, whose sole purpose is to generate and return GUIDs.
Finally, GUIDS are not sequential.  Even if you generate one right after another, they won't increment in the exact same fashion as an integer (i.e. that last digit won't go from C-D in one step).  Sequencing requires integers or some other numeric data type.


text:
Q: How to return a record with the lowest distance from a point using geodjango? I am using geodjango and have a collection of points in my database. To get a queryset of points within a certain area I use this:
queryset = Spot.objects.filter(point__distance_lte=(origin, distance_m))

My question is how can I return only one point(the point with the lowest distance)from the point I have passed it?
EDIT
I should mention that I am passing in coordinates and wanting to create a Point object with them. Then pass that point in as the origin and filter against that.
For example I have tried:
from spots.models import *
from django.contrib.gis.geos import *

origin = Point(28.011030, -26.029430)
distance_m = 1000

queryset = Spot.objects.filter(point__distance_lte=(origin, distance_m))
for q in queryset:
    print q.distance

This snippet of code gives me this error:
Traceback (most recent call last):
  File "<console>", line 2, in <module>
AttributeError: 'Spot' object has no attribute 'distance'

Interestingly enough if I do the following:
origin = Spot.objects.get(name='Montecasino').point
distance_m = 1000

for city in Spot.objects.distance(origin):
    print(city.name, city.distance)

(u'Design Quarter Parking', Distance(m=677.347841801))
(u'Montecasino', Distance(m=0.0))
(u'Fourways', Distance(m=1080.67723755))

A: Finally a solution gathered from clues from GeoDjango distance filter with distance value stored within model - query which lead me to this post. From this information I was able to gather that you MUST SPECIFY the measure parameter in your distance query.
You will see in the below snippet, I import measure as D. Then use it in the query.
If you don't specify it you will get this error:
ValueError: Tuple required for `distance_lte` lookup type.

To take just the point with the lowest distance I used order_by('distance')[:1][0]
from spots.models import *
from django.contrib.gis.geos import *
from django.contrib.gis.measure import D

distance_m = 20000
origin = Point(28.011030, -26.029430)

closest_spot = Spot.objects.filter(point__distance_lte=(origin, D(m=distance_m))).distance(origin).order_by('distance')[:1][0]

A: queryset = Spot.objects.distance(origin).filter(distance__lte=distance_m)
point = queryset.order_by('distance')[:1][0]

https://docs.djangoproject.com/en/dev/ref/contrib/gis/geoquerysets/#distance

A: I was looking for an example on how to sort results against a location with geodjango, so my use case was very close to this one. Though the accepted solution worked, performances was very bad for a big data set (more than 140000 rows).
Short story: the distance_lte function must calculate distance to origin for each row of the table and can't make use of geo indexes. It appears that the dwithin function can make use of such indexes and don't need to actually calculate the distance to origin for each row before before the restriction is done, so it's way more efficient:
origin = Point(28.011030, -26.029430)
closest_spot = Spot.objects.filter(point__dwithin=(origin, 1)) \
    .distance(origin).order_by('distance')[:1][0]

The dwithin function works with geographical data in degree (the "1" in the query).


text:
Q: How to define a page number showing the current ((sub)sub)section? I try to print the section (with (sub)subsections) in the page foot. For this I
defined a new page number. It works fine on the first four, but not on the last
page... The goal is to have ``Section x'' printed on every page, where x is
precisely the number of the enclosing ((sub)sub)section.
\documentclass{scrartcl}

\usepackage{scrpage2}
\pagestyle{scrheadings}
\clearscrheadfoot

% page number (omitting trailing zeros)
\newcommand{\mypagenumber}{%
  \ifnum\value{subsubsection}=0
    \ifnum\value{subsection}=0
      \ifnum\value{section}=0
        % nothing
      \else
        Section~\thesection% e.g. 2
      \fi
    \else
      Section~\thesubsection% e.g. 2.1
    \fi
  \else
    Section~\thesubsubsection% e.g. 2.1.3
  \fi
}

\ofoot{\mypagenumber}

\begin{document}
\section{Section}
\clearpage
\subsection{Subsection}
\clearpage
\subsubsection{Subsubsection}
\clearpage
\subsubsection{Subsubsection}
\clearpage
\section{Section}
This page should only show ``Section 2'' (not ``Section 2.0.2'')
\end{document}

Here is an update that takes care of the problem that Christian addressed. Still, it requires that sections are not directly followed by subsubsections.
\newcommand{\mypagenumber}{%
  \ifnum\value{subsubsection}=0
    \ifnum\value{subsection}=0
      \ifnum\value{section}=0
        % nothing
      \else
        Section~\thesection% e.g. 2
      \fi
    \else
      Section~\thesubsection% e.g. 2.1
    \fi
  \else
    \ifnum\value{subsection}=0
      Section~\thesection% e.g. 2
    \else
      Section~\thesubsubsection% e.g. 2.1.3
    \fi
  \fi
}

A: The following is taken from Only show header if section number > 0. You can use
\renewcommand{\sectionmark}[1]{%
  \markright{#1\ \thesection}%
}
\renewcommand{\subsectionmark}[1]{%
  \markright{#1\ \thesubsection}%
}
\renewcommand{\subsubsectionmark}[1]{%
  \markright{#1\ \thesubsubsection}%
}

\ofoot{\rightmark}

This will display the sectional unit (passed as #1 above). If you want only Section, then substitute all #1 for Section.
The use of \rightmark avoids a problem when the page-breaking algorithm is called into play at the start of the sectional unit. This could cause counters to be incremented on the page where the section does not end up eventually. Using \rightmark with the included sectional representations (\thesection, \thesubsection and \thesubsubsection) circumvents this issue.

A: I switched from \ifnum style to use \ifnumexpr from etoolbox
\documentclass{scrartcl}

\usepackage{scrpage2}
\usepackage{etoolbox}
\pagestyle{scrheadings}

\clearscrheadfoot

% page number (omitting trailing zeros)

% This uses the direct counter formatting, but should not be applied,
% The checking of counter values is the same as in \mypagenumber, where
% the formatting commands \the... are used.

\newcommand{\myotherpagenumber}{%
Section~
\ifnumequal{\number\value{subsubsection}}{0}{% subsubsection = 0 then remove subsubsection counter from output
\ifnumequal{\number\value{subsection}}{0}{% subsection = 0, then remove subsection from output
  \arabic{section}}{% No, subsection \neq 0
  \arabic{section}.\arabic{subsection}
}{% No subsubsection \neq 0, now check again for subsection = 0
\ifnumequal{\number\value{subsection}}{0}{% Yes, subsection = 0, remove it from output
  \arabic{section}}{% No, subsubsection \neq 0, show all three counter values.
  \arabic{section}.\arabic{subsection}.\arabic{subsubsection}}}
}% End of outer \ifnumequal{subsubsection}...
}% End of command.

\newcommand{\mypagenumber}{%
Section~
\ifnumequal{\number\value{subsubsection}}{0}{%
\ifnumequal{\number\value{subsection}}{0}{\thesection}{\thesubsection}%
}{\ifnumequal{\number\value{subsection}}{0}{\thesection}{\thesubsubsection}}
}% End of command

\ofoot{\mypagenumber}

\begin{document}
\section{Section}
\clearpage
\subsection{Subsection}
\clearpage
\subsubsection{Subsubsection}
\clearpage
\subsubsection{Subsubsection}
\clearpage
\section{Section}
This page should only show ``Section 2'' (not ``Section 2.0.2'')
\end{document}

Edit
\documentclass{scrartcl}

\usepackage{scrpage2}
\usepackage{etoolbox}
\usepackage{xcolor}

\pagestyle{scrheadings}

\clearscrheadfoot

% Save old \thesubsubsection command

\let\LaTeXStandardTheSubSubsection\thesubsubsection
\renewcommand{\thesubsubsection}{%
\ifnumequal{\number\value{subsection}}{0}{% sub = 0
\arabic{section}.\arabic{subsubsection}}{%
\LaTeXStandardTheSubSubsection}%
}%

% Save old \thesubsection command
\let\LaTeXStandardTheSubsection\thesubsection
\renewcommand{\thesubsection}{%
\ifnumequal{\number\value{subsection}}{0}{% drop sub = 0
}{%
\LaTeXStandardTheSubsection}%
}%

\newcommand{\myotherpagenumber}{%
Section~
\ifnumequal{\number\value{subsubsection}}{0}{% subsubsection = 0 then remove subsubsection counter from output
\ifnumequal{\number\value{subsection}}{0}{% subsection = 0, then remove subsection from output
  \arabic{section}}{% No, subsection \neq 0
  \arabic{section}.\arabic{subsection}
}{% No subsubsection \neq 0, now check again for subsection = 0
\ifnumequal{\number\value{subsection}}{0}{% Yes, subsection = 0, remove it from output
  \arabic{section}}{% No, subsubsection \neq 0, show all three counter values.
  \arabic{section}.\arabic{subsection}.\arabic{subsubsection}}}
}
} % End of command.

\newcommand{\mypagenumber}{%
Section~
\ifnumequal{\number\value{subsubsection}}{0}{%
\ifnumequal{\number\value{subsection}}{0}{\thesection}{\thesubsection}%
}{\ifnumequal{\number\value{subsection}}{0}{\thesection}{\thesubsubsection}}
}% End of command

\ofoot{\Huge \mypagenumber}

\begin{document}
\tableofcontents

\section{Section Number \textcolor{blue}{1}}
\subsubsection{ \textcolor{red}{I am actually a subsubsection and not a subsection ;-) -- my number is 1.1}}
\clearpage
\subsection{True first Subsection \textcolor{green}{1.1}}
\clearpage
\subsubsection{\textcolor{yellow}{True first subsubsection below 1.1}}
\clearpage
\subsubsection{\textcolor{yellow}{True second subsubsection below 1.1}}
%\subsubsection{Subsubsection}
\clearpage
\section{Section}
This page should only show ``Section 2'' (not ``Section 2.0.2'')
\end{document}


text:
Q: Visual Studio 2019 C# highlighting not working? Just randomly all syntax highlighting in C# just stopping working and everything looks white and ugly. I've been putting up with it for awhile but it's just really starting to get on my nerves, it's only for C# projects (old and new). Any other language works fine, like C++. I'm really confused to why this is happening in the first place, any ideas? I've tried updating and reinstalling packages, resetting the the fonts and colors options in environment. Here's some screenshots of C# vs C++ as an example, they are just random code from some of my projects to show the highlighting difference.
C#: https://i.imgur.com/gpnEPkY.png
C++: https://i.imgur.com/HIpcQ06.png

A: It's a bug.
Should be solved in the future by MS.
I uninstalled VS2017 last week to install VS2019. I ran it and next I imported my VS2017 settings with black background and yellow/green colors for the editor. And after 2 minutes and tried to restore default settings without success, I uninstalled it and rollbacked the partition and said to me to retry in one to five years...


text:
Q: Wordpress site with footer that is covering content on one page. I really don't know much about coding and my developer has gone dark so I really need some advice on how to fix this problem.  The footer on one of my pages won't stay at the bottom and is covering up some of the content.  Below is the code.  How can I make the footer stay at the bottom of the page?  Here is the page:  http://www.halfmoonbaymeetings.com/hot-dates-hot-rates/
<?php
/*
Template Name: Hot Dates Hot Rates
*/
?>

<?php get_header(); ?>

    <?php $my_query = new WP_Query('page_id=76'); while ($my_query->have_posts()) : $my_query->the_post(); $do_not_duplicate = $post->ID; ?>

<?php the_title(); ?>

        <?php $subtitle = get_post_meta($post->ID, 'subtitle', TRUE); if($subtitle != '') { ?>

<?php echo $subtitle; ?>

        <?php } ?>
        <?php the_content(); ?>
    <?php endwhile; ?>
    <?php $my_query = new WP_Query('showposts=1000&post_type=featured-hotels'); while ($my_query->have_posts()) : $my_query->the_post(); $do_not_duplicate = $post->ID; ?>
        <?php if ( get_post_meta( get_the_ID(), '_hotdates', true ) ) { ?>

            <?php echo get_post_meta($post->ID, "_hotdates", true); ?>

        <?php } ?>
    <?php endwhile; ?>

<?php get_sidebar(); ?>

<?php get_footer(); ?>

And here is the footer code from the Stylesheet:

.footerwrap {
background: #F9F9F9;
float: left;
margin: 0;
padding: 0;
position: relative;
width: 100%;

}

.footerwrap .col12 { text-align: center; }

.footerwidgets {
background: #eee;
border-top: 5px solid #e0e0e0;
float: left;
margin: 0;
padding: 20px 0 0 0;
position: relative;
width: 100%;

A: You need to add margin-bottom: 289px; to the .contentwrap div because the footer is 289px high so you need to add 289px bottom of the .contentwrap div to offset that.
.contentwrap
{
float: left;
margin: 0;
padding: 0;
position: relative;
width: 100%;
margin-bottom: 289px;
}


text:
Q: Unable to add pattern to anyURI field in xsd I am trying to add a pattern to anyURI such a way that I could eliminate leading/trailing and spaces in between, because copy paste errors are creating a lot of issues.
So far I was able to come up with this
<element name="randomUri">
   <simpleType>
     <restriction base="anyURI"><pattern value="\S(.*\S)?"/></restriction>
   </simpleType>
</element>

but when I try to validate it against an xml it looks like like it's not matching the pattern and I could give leading/trailing and spaces in between. This pattern worked perfectly if I used it against a string i.e when I made base="string" in my restriction. Is there some unique property of anyURI that doesn't allow me to do this?
P.S :I did not go the pattern value = "http://.* way because I wanted to accommodate for custom schemes like sample.app://sampleapp.for e.g
Just to make things clear...I want to eliminate leading/trailing and spaces in between for a url. The pattern I used above works totally fine if it randomUri was a string but it isn't working when I make randomUri an anyURI.

A: The xs:anyURI type has a whiteSpace facet of collapse, which means that leading and trailing spaces are stripped from the value before testing it against the pattern facet. This basically means that leading and trailing spaces are always allowed (and considered ignorable) and cannot be prevented using the pattern facet.

A: I tested your code with the (small) sample you provided and one of the problems with it seems to be that you didn't specify the quantity on the xs:element. So it didn't fail on the xs:pattern, it did fail on the first xs:pattern. So you should have specified a quantifier on the xs:element:
<element name="randomUri" maxOccurs="unbounded">
...

Another simple suggestion may be to specify zero or more SPACE characters before and after the URI by using \S* instead of \S. Maybe that will improve the matching.


text:
Q: How to get a value of column 'b' from a 2d array where column 'a' matches a single array in javascript New to javascript. Need some guidance on the problem below:
I have these arrays:
array1 = [['a1'], ['a2'], ['a3']];

array2 = [['a1',4], ['a3',3], ['a6',2]];

How can i get the matching arrays whereby array1 first col = array2 first col?
Example expected result:
[['a1',4], ['a3',3]]

I hope the question makes sense. Not really sure how to approach this since the structure of these two arrays are different.

A: You can use filter to filter out the elements. Inside filter method check if elements exist in array1. You can flat array1 to check effeciently.
let flatArr1 = array1.flat(); //["a1", "a2", "a3"]

const result = array2.filter(([x,y]) => flatArr1.includes(x));

console.log(result) // for instance

A: This is my solution for your problem:
    const compare = (array1, array2) => {
    let matched = [];
    const keys = [].concat(...array1);

    for(let i = 0; i < array2.length; i++) {
        for(let j = 0; j < array2.length; j++) {
            let result = array2[i][j];
            if(keys.includes(result)) {
                matched.push(array2[i])
            }
        }
    }

    console.log("matched: ", matched);
};


text:
Q: Combine two lists to make a factor of two levels I have two lists as so:
t1.visit.attendance
[1] 77 74 71 62 59 56 55
t2.visit.attendance
[1] 37 34 33 31 27 26 24
I want to make a factor, with the levels being t1.visit.attendance and t2.visit.attendance. Please note: t1 and t2 are two different treatment types.
I then want to make a scatter plot of the data against the numbers 1 to 7 (which correspond to the nth visit) on the same plot, where each treatment type is colour coded.

A: The lattice library has a helper function for this called make.groups. For example
t1.visit.attendance<-c(77,74,71,62,59,56,55)
t2.visit.attendance<-c(37,34,33,31,27,26,24)

lattice::make.groups(t1=t1.visit.attendance, t2=t2.visit.attendance)
#     data which
# t11   77    t1
# t12   74    t1
# t13   71    t1
# t14   62    t1
# ...
# t26   26    t2
# t27   24    t2

A: Another way, just to show some options, involves the reshape2::melt function:
t1.visit.attendance <- c(77,74,71,62,59,56,55)

t2.visit.attendance <- c(37,34,33,31,27,26,24)

df <- data.frame(t1 = t1.visit.attendance,
                t2 = t2.visit.attendance)

newdf <- melt(df, measure.vars = c("t1", "t2"), variable.name = "visits")

> newdf
   visits value
1      t1    77
2      t1    74
3      t1    71
4      t1    62
5      t1    59
6      t1    56
7      t1    55
8      t2    37
9      t2    34
10     t2    33
11     t2    31
12     t2    27
13     t2    26
14     t2    24

To show a plot, other than a scatterplot, here is another way using a dotplot
ggplot(newdf) +
    aes(x=value, color = visits) +
    geom_dotplot() +
    theme(axis.text.y=element_blank())

yielding


text:
Q: Height of binary tree I'm trying to implement a recursive method to calculate the height of a binary tree. Here is the "height"-code:
def height(self):
    if self.root==None:
        return 0
    return max(height(self.root.left), height(self.root.right))+1

When I try to call the function, I get the following error msg:
NameError: name 'height' is not defined

Does anybody see the problem?

A: This is a method of your class, hence you must call it from an instance (self) or the class itself. Though it won't work as you think, unless you define it as a staticmethod or change your call, e.g.
def height(self):
    return 1 + max(self.left.height() if self.left is not None else 0,
                   self.right.height() if self.right is not None else 0)

or
@staticmethod
def height(self):
    return 1 + max(self.height(self.left) if self.left is not None else 0,
                   self.height(self.right) if self.right is not None else 0)

Notice, that you shouldn't use == to compare with None (kudos to timgeb). And you must check whether child-nodes exist, too. And your algorithm doesn't work, so I've changed it slightly.
Example:
class Node:
    def __init__(self, root=None, left=None, right=None):
        self.root = root
        self.left = left
        self.right = right

    def height(self):
        return 1 + max(self.left.height() if self.left is not None else 0,
                       self.right.height() if self.right is not None else 0)

# Create a binary tree of height 4 using the binary-heap property
tree = [Node() for _ in range(10)]
root = tree[0]

for i in range(len(tree)):
    l_child_idx, r_child_idx = (i + 1) * 2 - 1, (i + 1) * 2
    root_idx = (i + 1) // 2
    if root_idx:
        tree[i].root = tree[root_idx]
    if l_child_idx < len(tree):
        tree[i].left = tree[l_child_idx]
    if r_child_idx < len(tree):
        tree[i].right = tree[r_child_idx]

print(root.height())  # -> 4

A: I am not sure of how you define your binary tree. But on a tree node you usually have only one root and multiple sons. I have the feeling that this method leads to an infinite loop. self.root.left and self.root.right are exactly my brother and me...
Here you probably have to call the method from the instances self.root.left and self.root.right with no extra argument :
def height(self):
    if self.root==None:
        return 0
    return max(self.root.left.height(), self.root.right.height())+1


text:
Q: Uncountability of real numbers (proof with nested intervals property) I found the proof of uncountability of real numbers, but I have one question. Why can we not use the same logic to prove, that the set of natural numbers is also uncountable? So proof of uncountability of real numbers.
Proof: We will prove that the unit interval $I:=[0,1]$ is an uncountable set. This implies that the set $\mathbb R$ is an uncountable set. The proof is by contradiction. If we assume that $I$ is countable, then we can enumerate the set as $I:=\{x_1,x_2,x_3...x_n...\}$. We first select a closed subinterval $I_1$ of $I$ such that $x_1 \notin I_1$, then select a closed subinterval $I_2$ of $I$ that $x_2 \notin I_2$ and so on. In this way, we obtain nonempty closed intervals $$I_1\supseteq I_2 \supseteq...\supseteq I_n \supseteq...$$ such that $I_n \subseteq I$ and $x_n \notin I_n$ for all $n$. The Nested Intervals Property implies that there exists a point $\xi \in I_n$ for all $n$. Therefore $\xi \neq x_n$ for all $n \in \mathbb N$, so the enumeration of $I$ is not a complete listing of the elements of $I$, as claimed. Hence, $I$ is an uncountable set.
The question is, why can we use the same argument to prove that the set of natural numbers is also uncountable? Thank you for help!


text:
Q: 'events_statements_summary_by_digest table' is missing In my MySQL 5.6.27 default installation the 'events_statements_summary_by_digest' table is missing in the 'performance_schema' database.
In fact, I think more tables are missing. Did I something wrong during the installation? How can I fix this?
use performance_schema;
show tables;
+----------------------------------------------+
| Tables_in_performance_schema                 |
+----------------------------------------------+
| cond_instances                               |
| events_waits_current                         |
| events_waits_history                         |
| events_waits_history_long                    |
| events_waits_summary_by_instance             |
| events_waits_summary_by_thread_by_event_name |
| events_waits_summary_global_by_event_name    |
| file_instances                               |
| file_summary_by_event_name                   |
| file_summary_by_instance                     |
| mutex_instances                              |
| performance_timers                           |
| rwlock_instances                             |
| setup_consumers                              |
| setup_instruments                            |
| setup_timers                                 |
| threads                                      |
+----------------------------------------------+
17 rows in set (0.00 sec)

A: The changelog for 5.6.9 says
"If you upgrade to this release of MySQL from an earlier version, you must run mysql_upgrade (and restart the server) to incorporate this change into the performance_schema database. (Bug #14075527)"
events_statements_summary_by_digest was added in 5.6.5.


text:
Q: Botão "Gostei/Like" Quero fazer um botão no meu site com um contador ao lado e gostaria que a cada clique o contador aumentasse 1 número. Mas eu queria que ficasse salvo esse número de cliques num ficheiro .txt no servidor, e que todos pudessem clicar e ver esse contador.
Um botão Like, que só poderia ser clicado 1 vez por computador. Entendem?
Quero que os usuários avaliem o conteúdo do meu site com esse botão.

A: Serão utilizado tres arquivos:
1 - principal.php, que exibirá o link para download e o numero de downloads
2 - download_arquivo.php - Este aumentará o contador em 1, fará o download do arquivo e redirecionará para o principal.php
3 - contador_arquivo.txt - Armazenará o numero de downloads
ARQUIVO 1 - PRINCIPAL.PHP:

DOWNLOAD AQUI

N. de Downloads: <? include "contador_arquivo.txt"; ?>

ARQUIVO 2 - DOWNLOAD_ARQUIVO.PHP

">Voltar
<?php
//Abre o contador de downloads e acrescenrta em 1
$fp = fopen("contador_arquivo.txt","r");
$visitas = fgets($fp,255);
$visitas++;
fclose($fp);
$fp = fopen("contador_arquivo.txt","w+");
fwrite($fp, $visitas);
fclose($fp);
?>

ARQUIVO 3 - CONTADOR_ARQUIVO.TXT
(escreva o numero 0 e salve o arquivo)

Fonte: Contador Clicks


text:
Q: Why don't more villains die/become crippled? In the superhero genre heroes fight the bad guys daily. Not everyone is blessed with super-toughness and the like, so there will be casualties.
Even if everyone is fighting with the best intentions, someone is bound to get hurt.
Yet I rarely see a villain die or become critically injured, and put out of action.
The only example I know of is Doc Oc who after years of 'gentle brawling' with the webbed wall crawler, who is more than happy to lock Octavius up, without resorting to deadly force, ends up crippling him instead.

Why don't more villains end up like this? It seems both likely in universe and a good plot point to use out of universe.

A: Because creating a "good" villain is far from easy, and it takes great skill to write one. Yet they are crucial to the story, making the difference between a good and a great story (e.g. Darth Vader, The Joker).
So when you have one you keep it as long as you can. In movies or books you kill them at the very end, but in comics there is no end, so you never kill them.

A: All of the other answers seem pretty good, but they miss something.  In-universe, dramatically speaking, there's one additional reason:  Villains play for keeps, Heroes, by their very nature, tend to allow for redemption.
Heroes have many origin stories, and not all of them are good; often, a back-story involves the hero being a villain (or on his way to becoming one), until an even 'brought him to his senses' and caused the change to heroic behavior.  Sometimes it's not even villainy that was in the heroes path, but simple self-serving behavior.  (Look at Peter Parker, for example, until Uncle Ben died.)
The villain tends to kill; he doesn't really care about the state of his target's moral compass (well, excepting situations where the villain sees a possible tool/ally/whatever that can be turned to evil.)  The hero, on the other hand, only wants to destroy (kill) totally unchangeable evil, and as a rule, doesn't believe that describes most villains.  The hero always wants to leave an option open for the bad guy to become one of the good guys.  So, while the villain uses deadly force, with the intent to kill, the good-guy is always trying to not quite foreclose future redemption.
Take a look at TvTropes page one 'Heel Face Turn' to see many, many examples of the villain becoming a good guy.  This is why bad guys keep their phasers on kill, and the good guys keep them on stun.
(That being said, it's also common for lesser evils to be 'clearly unredeemable' and thus fair game for instant slaughtering; commonly done with zombies, demons, etc.  But they don't tend to be the 'villain', but just a tool the villain uses.)

A: The main reason is the symbiotic relationship between hero and villain.  Without super-villains, there would be no heroes.  Without heroes, there would be no villains.  It's the symbiotic relationship and the need for each other that causes the hero to show mercy and merely capture and and imprison the villain, while the villain will monologue long enough to allow the captured hero to escape and foil their plans.
It is the circle of superhero life which allows both to continue in a more or less endless spiral.  Villain threatens world.  Villain captures hero.  Villain monologues.  Hero escapes.  Hero foils villain's plan.  Hero captures villain and turns him over to the authorities.  Bumbling authorities allow villain to escape.  Rinse and repeat.

A: Because most comics are essentially for kids/juveniles. Hence no real blood, no real violence and no death.

A: If a villain can stand against superheroes, it means that he/she isn't normal. Either he/she is intelligent, powerful in front of superheroes or super lucky. Mind it, real-world Laden can easily die or heavily injured. In fact, villains in comics are "Super Villains".
Not all, but most of superheroes have motto of not to harm anyone even if target are bad guys. They let laws to do their work.
Out of Universe: To challenge a superhero, you need a special villain. And, establishment of new character isn't easy.


text:
Q: Why square wave-form output is higher than a sin or a triangle wave-form output? I'm working on a digital audio synthesiser and I'm facing out an issue about the amplitude level.
I'have a sinusoid signal which have a max amplitude of $-1 / +1$ and a square signal which have a max amplitude of $-1 / +1$ too.
My problem is about the output level. With the same settings on my audio device, the square signal is about $3$ times higher (in the speakers) than the sinusoid or the triangle signal.
Did this phenomenon cames from the fact than the square doesn't smoothly switch from $-1$ to $1$ ?
[EDIT]
Here is how I measured my outputs (don't pay attention to the LFO on amplitude):
The blue signal is the sinusoid one. The green signal is the triangle one. The pink signal is the square one.
As we can see, the two first signal max is around $-0.1 / +0.1$. For the square signal the max is around $-0.3 / +0.3$.
In decibel, it means the $2$ first signals are at $-10$dB and the square one is at $-5$dB.
These measures came from a built-in mic.


text:
Q: ApolloClient Caching does not store every item I have a problem with ApolloClient Caching. There are a few items that are not stored in the cache.
Env: React Native
Packages:

*

*@apollo/client

*@react-native-async-storage/async-storage

*apollo3-cache-persist

Result (without Caching):
contentElements: [{
  __typename: "My_Stage",
  cta: {label: "Test", link: "mylink", __typename: "CTA"},
  id: "0123234234234234234234",
}]

Result (with Caching: strategy: cache-first)
contentElements: [{
  __typename: "My_Stage",
}]

I dont think this is a problem with normalization because the element has an id and __typename.
I have also tried to disable normalization with keyFields: false for Stage but this did not work.
Let me know if i did not deliver enough information. Thank you for your help!


text:
Q: Left outer join? Row numbering issue I have three tables, one table having subject, one table for user data, and one table for storing user subscription.
A user may/not be subscribed its optional, so to get all user list with their subscription status, I use left join as
SET @rnum = 0;

SELECT (@rnum :=@rnum + 1) AS rn, user.user_name, subs.status
FROM user_tbl LEFT JOIN subs_tbl ON user.uid = subs.uid LIMIT 0, 10;

I was using output of this as whole at a time, but now as data has grown high, I have implemented paging of this output in my application.
For paging I created a row_num mechanism, I will store the last row_num displayed and on next page will display from last_num.
Now I want sorting of user with subscribed first or last, so I used
SELECT (@rnum :=@rnum + 1) AS rn, user.user_name, subs.status
FROM user_tbl LEFT JOIN subs_tbl ON user.uid = subs.uid ORDER BY subs.status LIMIT 0, 10;

which is giving row numbers but not as I wanted, it gives row number first then do sorting, so I don't get result as desired.
So I need help on following,

*

*Is any better way of paging ?

*Is there any substitue of Left Join (I want null values also, because I want all user info).

*Is there any other method of numbering the SQL result.

*Is there any PHP regarding function or anything that can help me in this case.

[ This is sample created from my actual problem, in my actual problem, I have a huge query with multiple joins and sub_queries, so nesting of this query and numbering it is not possible ]

A: Perhaps you are looking for something like this:
(Removed as not meeting the OP's requirements, as reminded by a comment.)
Alternatively, you could also try parametrisation of LIMIT. As of MySQL 5.0.7, LIMIT is parametrisable when used in a statement that is part of a stored procedure or a prepared statement:
PREPARE stmt FROM
'SELECT
...
LIMIT ?, ?';

EXECUTE stmt USING @offset, @limit;

It's worth noting that for this method it would make most sense to have as unambiguous sorting order as possible.