text:
Q: leaflet marker popup opening and immediately closing In my leaflet map, clicking on a marker opens its popup and immediately closes it.
Logging of map events reveals that instead of firing just a popupopen event, the click on the marker triggers 2 events - popupopen followed by popupclose of the same marker.
This behavior is semi-consistent:

*

*Open+close happens when you just click on the marker without dragging the mouse at all. But if you click the marker and move the mouse by just few pixels (< ~30px) while at it, the popup now opens just fine (and only a popupopen event is fired, without popupclose following it).

*Open+close happens reliably only in Safari on Mac and iPhone. It also happens sometimes in Chrome on Mac, and when it does - it's consistent during the testing session.

*This only happens in one of my 2 map pages, which use a common map component (one for mobile, one for desktop). Obviously this is a good place to start debugging, but despite many hours of debugging I haven't been able to narrow down the relevant difference between them.

I debugged the source of the popupclose event, and was suprised to discover that the _openPopup function in src/layer/Popup.js:473 is invoked twice. This method ends up calling this.closePopup() on the second invocation.
Note sure it if's related, but looking at click events on the map, I see in Safari two such events per mouse click, both having an original event of type MouseEvent. In Chrome, when things work correctly, there is just a single event with an original event of PointerEvent.
I suspect that this could be related to #7255, however unfortunately the recommended workaround of setting tap to false didn't help.
Any ideas what could be the cause and how to work around it?
Using Leaflet 1.7.1 through react-leaflet 3.2.1.

A: Update:
It turns out that setting tap to false actually did resolve this!
Not sure how I missed this previously. Definitely one of the more frustrating third-party issues I encountered recently!


text:
Q: Can't use Linq with nested class List on MongoDb Very similar to this question, however the answer provided does not solve this case.
I have the following class
public class Company
{
   [BsonId]
   public string dealerId = null;

   public List<string> dealers = new List<string>();
}

I am trying to query with the following query
collection.AsQueryable<Company>()
          .Where(cpy =>
                 cpy.dealers.Where(dlr =>
                         dlr.ToLower.Contains("dealer1")).Any());

Doing this results in the following

Unable to determine the serialization information for the expression:
  Enumerable.Where(cpy.dealers, (String dlr) =>
  dlr.ToLower().Contains("dealer1"))

I believe it is possible to create a wrapper around the string and use Any with a predicate however that's not a very elegant solution. Is there a simple way of doing this that I have completely missed?
I am using mongodb 2.6.4 with C# driver 1.9.2
Edit:
I want the above linq query to be converted to either of the following native mongo queries,
db.Company.find({dealers: {$regex: /dealer1/, $options: "is"}})

or using elemMatch
db.Company.find({dealers: {$elemMatch: { $regex: /dealer1/, $options: "is"}}})

redpajama_set_name: RedPajamaStackExchange


text:
Q: What Permissions Are Needed for Selecting Data and Viewing All Schema? I'm attempting to create a role in Azure SQL such that the user can perform Select operations, view all schema (but not modify schema) but not perform any writes or execute stored procs. Granting a user Select permission gets me close. However, the user cannot see any stored procs or scalar functions.
So, I want to allow the user to see all schema definitions, not modify any schema objects and perform Selects. Is this possible?

A: Assign the VIEW ANY DEFINITION securable to the user.
That will allow them to see SP and view definitions but not allow them to change it.
https://technet.microsoft.com/en-us/library/ms175808(v=sql.105).aspx


text:
Q: How to add both search bar and tab buttons in react-native using react-navigation
I have a login Screen, when the user login they are brought to a screen similar to the one shown above.
In this screen, I have a tabNavigator containing tabs to 5 screens, similar to the one shown in the image above. It also has a header kinda thing with search bar in it. This header is only supposed to be shown in 4 of the 5 tabs and there is a different header i need to display in the 5th tab.
Is there a way to do this? I know i can add a view in 4 of the 5 tabs that render same header and a view in the 5th screen that renders a different header, But I was wondering if there is a way I could do this without having to render the same view in all the 4 tabs again and again.
P.S It should work on both iOS and Android

A: You can configure header of TabNavigator by navigationOptions:
const TabNav = TabNavigator({
  First: { screen: FirstPage },
  Second: { screen: SecondPage },
  Third: { screen: ThirdPage },
  Fourth: { screen: FourthPage },
  Fifth: { screen: FifthPage }
}, {
  navigationOptions: {
    header: <SearchHeader />
  }
})

And then custom navigationOptions in FifthPage:
class FifthPage extends Component {
  static navigationOptions = {
    header: <FifthPageHeader />
  }
}

I just created a demo on Expo Snack: https://snack.expo.io/rJDGpmPHZ, the 5th screen has a blue header, and the others have a red one.
In the document of TabNavigator at https://reactnavigation.org/docs/navigators/tab#Screen-Navigation-Options, it hasn't list the header option, I think it will be pass to StackNavigator.


text:
Q: how can i delete the 1st string from each line in array in php? I read a text file and add the value to array, then I match a string to that array.
If it matches, I want the last value of each line to show.
There are two value separated by comma, I want to show the last value.
$lines = file("D:/CameraName.txt");
foreach ($lines as $line_num => $line) {
    if(strpos($line, $dev) !== false) {
        !$found = true ;
        $dispname=  //here iwant the code to see the last value of each line
        echo $dispname ;
    }
}

Contents of the file:
1234,abcd11
1235,avce21

A: You can use explode() to split the line at the comma and array_pop() to get the last item.
$lines = file("D:/CameraName.txt");
foreach ($lines as $line_num => $line) {
    if(strpos($line, $dev) !== false) {
        !$found = true;
        $lineValues = explode(',', $line);
        $dispname = array_pop($lineValues);
        echo $dispname;
    }
}


text:
Q: Pass PHP string variables to Javascript function via button click I'm creating multiple buttons dynamically and I need to pass some PHP variables to a JavaScript function via the onclick method.
The code below works fine for the most part but if the variables contain double or single quotes, it fails to call the function.
I tried using htmlspecialcharacters with ENT_QUOTES which fixed the issue with the double quotes but the single quotes is still causing it to fail.
<button id="modalBtn" type="button" onclick="ShowProduct('<?php echo $title ?>', '<?php echo $description ?>', '<?php echo $img ?>');">View Details</button>

Any suggestions on how to fix this or is there a better way to do this?

A: I suggest you to create json object from your vars and pass it as argument, something like:
<button
    id="modalBtn"
    type="button"
    onclick="ShowProduct(<?php echo json_encode(array($title, $description, $img))?>);">
        View Details
</button>

Or (for more readable keys)
<button
    id="modalBtn"
    type="button"
    onclick="ShowProduct(<?php echo json_encode(array('title' => $title, 'descr' => $description, 'img' => $img))?>);">
        View Details
</button>

And your ShowProduct function you can define like:
function ShowProduct(params) {
    console.log( params );

    // do other stuff
}

Update:
if your vars are already in array you can:
// pass this array:
ShowProduct(<?php echo json_encode($your_array)?>)

// fill new array with required keys only
ShowProduct(<?php echo json_encode(array($your_array['title'], $your_array['description'], $your_array['img']))?>)

A: I would suggest the best way of passing variables to javascript from button click or any other event.
Add the passing argument as data-attributes in button.
Example:
<button id="b1" type="button" data-id="123" data-name="xyz" data-size="m" onClick="doSomething()">

And in php script or in ajax request you can get the attributes like:
var id   =  $("#b1").attr("data-id");
var name =  $("#b1").attr("data-name");

And use those in ajax call for php script.
Hope this is what you were looking for.


text:
Q: Why should the real numbers interact with number fields and Galois theory? When I wanted to show $\mathbb{Q}(2^{1/3})/\mathbb{Q}$ is not Galois, my argument was it's a real field, while the normal closure clearly contains complex numbers. However I'm unsatisfied with this argument, suppose someone who never met $\mathbb{R}$ asks this, he just innocently takes $x^3-2$ and wonders if adjoining one root gives a Galois extension. How would he come up with the $\mathbb{R}$ argument? It feels unmotivated- it seems he'd need to say something like the algebraic closure of $\mathbb{Q}$ has an order two automorphism, and understand its interaction with the roots of $x^2 - 3$.
** There is an argument that avoids $\mathbb{R}$, namely that $\phi(3)=2$ so this divides the splitting field index, but it's a different argument and requires $\phi(n) \nmid n$.
Thus my question is:

*

*Are there more arguments for why $\mathbb{Q}(2^{1/3})/\mathbb{Q}$ is not Galois

*Is there a better motivation to how and why $\mathbb{R}$ is helpful, and how one naturally arrives at it?

*Are there more striking examples of $\mathbb{R}$ playing an 'algebraic' role? (I'm familiar with the geometry of numbers, but that's not the type of examples I'm looking for, there it plays an analytic role).

A: I'm not quite sure what you want to see, but here are a number of special "algebraic"  properties of the field $\Bbb{R}$. They are highly interdependent and, of course, do rely on the topological properties of the real numbers (completeness mostly).

*

*Every odd degree polynomial with real coefficients has a real zero, and hence $\Bbb{R}$ has no odd degree extensions.

*The field $\Bbb{R}$ has no non-trivial automorphisms.

*The field $\Bbb{R}(i), i^2+1=0$, happens to be algebraically closed.

*The (associative) division algebras over $\Bbb{R}$ are few, and have degrees $1,2,4$ only.

*In class field theory (algebraic number theory on steroids) we look at behavior of primes of a number field $K$ in its finite extensions. To get a complete and coherent picture of the situation we need to include "the infinite prime", which means that we also look at real/complex embeddings of $K$ (and the extension).

Items 1-3 are obviously connected, but don't really need the topological completeness of $\Bbb{R}$. In fact, they also hold for (define, even) so called real closed fields, see here for a local explanation of item 3. Furthermore, a theorem due to Artin and Schreier tells us that if an algebraically closed field $\overline{K}$ is a finite extension of its subfield $L$, then we are in characteristic zero and $\overline{K}=L(i)$.
Items 4 and 5 are also connected, but I don't know if the topological completeness of $\Bbb{R}$ is necessary or not. Some approaches/proofs rely on analytical techniques, so ostensibly need completeness. But I am too ignorant to say whether completeness is absolutely necessary there.

A: I think there should be two kind of separate questions here: can we avoid arguments based on the order on $\mathbb{Q}$, and can we avoid the use of the "non-algebraic" real numbers $\mathbb{R}$.
The answer to the second question is definitely yes. In fact, for basically any algebraic/arithmetic application, you can completely safely replace $\mathbb{R}$ by the real closure of $\mathbb{Q}$, which is an algebraic extension. You can describe it as the intersection of $\mathbb{R}$ and the algebraic numbers in $\mathbb{C}$, but it can be constructed with no mention whatsoever to $\mathbb{R}$ or $\mathbb{C}$. Jyrki's answer highlights some properties of real closed fields that can be useful. In particular, the algebraic closure of $\mathbb{Q}$ is obtained from this real closed field by adjoining a square root of $-1$, so you can mimic all arguments based on the complex conjugation.
The first question is more delicate. The first answer that comes to my mind is "but why would you want to, though?". The fact that $\mathbb{Q}$ is (uniquely) ordered is an interesting algebraic property, and there is no reason not to use it. There is a whole theory of field orderings, with connections with quadratic forms, valuation theory, algebraic geometry, etc. Using it as an argument to show that (for instance) some extension is or is not Galois should not be seen as "abandoning" the use of "purely arithmetic" arguments (whatever that means). There is no universal catch-all method for dealing with Galois extensions of $\mathbb{Q}$, and using the fact that $\mathbb{Q}$ is an ordered field, with a real closure, and that some number fields can be embedded in this closure while some cannot should be part of the standard toolkit.

A: We can show $K = \mathbb{Q}(\sqrt[3]{2})$ is not Galois using only computations over $\mathbb{Q}$, as follows:
We want to show the only root of $f=T^3 - 2$ in $K$ is $\alpha=\sqrt[3]{2}$. Suppose that $\beta \in K$ is a root of $f$, and write $\beta = x + y\alpha + z\alpha^2$. Compute the coefficients of $\beta^3 - 2$ w.r.t the basis $(1,\alpha,\alpha^2)$, by hand or like this in SageMath:
sage: K.<a> = NumberField(x^3 - 2)
sage: A.<x,y,z> = PolynomialRing(K)
sage: v = sum(vector(c)*m for (c,m) in (x+y*a+z*a^2)^3 - 2)
sage: show(v)

$$\left(x^{3} + 2 y^{3} + 12 x y z + 4 z^{3} - 2,\,3 x^{2} y + 6 y^{2} z + 6 x z^{2},\,3 x y^{2} + 3 x^{2} z + 6 y z^{2}\right)$$
These three polynomials define an ideal $I$ in the ring $\mathbb{Q}[x,y,z]$:
sage: B.<x,y,z> = PolynomialRing(QQ, order='lex')
sage: I = B.ideal(list(v))

Computing a Gröbner basis of $I$ w.r.t lexicographic ordering shows that $V(I)$ is finite:
sage: I.groebner_basis()
[x^3 + 2*y^3 + 3240/7*z^9 - 216*z^6 - 26/7*z^3 - 2,
 x*y - 270/7*z^8 + 18*z^5 + 9/14*z^2,
 x*z - 54*y^2*z^6 + 9*y^2*z^3,
 y^4 - 108*y*z^6 - 2*y*z^3 - y,
 y^3*z + 27/7*z^7 - 2*z^4 + 1/28*z,
 y*z^7 + 1/108*y*z,
 z^10 - 1/2*z^7 + 1/108*z^4 - 1/216*z]

The last element gives the equation $216z^{10} - 108z^7 + 2z^4 - z = 0$ which, by the rational root theorem, has $z=0$ as its only root in $\mathbb{Q}$. The fourth element then yields $y^4 - y = 0$, hence for $y \in \mathbb{Q}$ we get $y=0$ or $y=1$. If $y=0$ then the first element yields $x^3 - 2 = 0$ which is a contradiction for $x \in \mathbb{Q}$. So $y=1$, and the second element shows $x=0$. In summary $(x,y,z) = (0,1,0)$, which means $\beta=\alpha$, so we are done.
In general there are algorithms to compute a Gröbner basis, the radical of a zero-dimensional ideal, the intersections with the univariate polynomial rings, and rational roots of univariate polynomials. This may be not the most efficient way, but it works and uses only arithmetic in $\mathbb{Q}$.

A: Your question is equivalent to showing that $x^3 -2$ does not split into linear factors over $\mathbb{Q}(\sqrt[3]{2})$. You can show that it splits into a linear and a quadratic factor over it, and all you need to do is to show that quadratic factor is irreducible over $\mathbb{Q}(\sqrt[3]{2})$. From this point of view, it's quite natural to consider $\mathbb{R}$, as $\mathbb{Q}(\sqrt[3]{2})$ embeds into it, and we have a simple condition for irreducibility of degree two polynomials over $\mathbb{R}$. I'm not sure if it answers your question though.


text:
Q: Firefox - Huge Cursor I have a contentEditable div on which if a cursor is placed it's displayed as a huge cursor!
Here's the code:

You can see it here: http://jsfiddle.net/yW62h/
Here's what it looks like in my browser (FFX3.5)

This problem also appears in FFX3.6 and 4.0b6
Is this a bug or am I doing something wrong here?

A: Not declaring 100% height and it works fine:
http://jsfiddle.net/nS3X8/
Caret height is based on height in Firefox (which seems like a bug to me).
Though it based on line-height in Webkit.
When setting the height of an input element use padding instead of height and Firefox will behave.

A: Try adding a
 inside the editable div.
That worked for me: http://jsfiddle.net/66A2h/

A: It's a Firefox bug https://bugzilla.mozilla.org/show_bug.cgi?id=537475 :(


text:
Q: Cannot find why Stack Overflow error appears I am trying to make an octree for randomly distributed set of particles. I have been trying to find where Stack Overflow Error appears whole day, but it was in vain. Could you please help me? The problem should be somewhere in (c == [0]) && (a > 0) part, however, I have no idea where. Thank you in advance!
type particle
  R::Vector{Float64}          # coordinates of the particle
  m::Float64                  # mass of the particle
  a_tree::Float64             # acceleration of particle calculated from tree
  a_exact::Float64            # acceleration of particle calculated by exact summation
end

type node
  parent::Int64               # node's parent number
  children::Vector{Int64}     # set of childrens' numbers
  l::Float64                  # size of the node
  R::Vector{Float64}          # radius of geometric center
  m::Float64                  # total mass of the node
  ptcl::Int64                 # pointer to the particle in it
end

function problem3_2(N::Int64)
particles = Vector{particle}(N)                 # Basically, our system
tree = Vector{node}(1)                          # Initial tree (root)
tree[1] = node(0,[0],1.0,[0.0,0.0,0.0],0.0,0)

for i in eachindex(particles)
  particles[i] = particle([rand() - 1/2, rand() - 1/2, rand() - 1/2], 1.0, 0.0, 0.0)
  tree = InsertParticle(i,1,tree,particles)
end

return tree
end

function InsertParticle(i::Int64,k::Int64,tree,particles)
  c = tree[k].children
  a = tree[k].ptcl
  if (c == [0]) && (a == 0)
    tree[k].ptcl = i
  elseif (c == [0]) && (a > 0)
    j_1 = length(tree) + DetermOctant(particles[tree[k].ptcl],tree[k])
    j_2 = length(tree) + DetermOctant(particles[i],tree[k])
    tree[k].children = [x for x in length(tree)+1:length(tree)+8]
      for p = 1:8
        push!(tree,node(k,[0],tree[k].l/2,[0.0,0.0,0.0],0.0,0))
        if (p == 1) || (p == 4) || (p == 5) || (p == 8)
          tree[k+p].R[1] = tree[k].R[1] + tree[k+p].l/2
        else
          tree[k+p].R[1] = tree[k].R[1] - tree[k+p].l/2
        end
        if (p == 1) || (p == 2) || (p == 5) || (p == 6)
          tree[k+p].R[2] = tree[k].R[2] + tree[k+p].l/2
        else
          tree[k+p].R[2] = tree[k].R[2] - tree[k+p].l/2
        end
        if (p == 1) || (p == 2) || (p == 3) || (p == 4)
          tree[k+p].R[3] = tree[k].R[3] + tree[k+p].l/2
        else
          tree[k+p].R[3] = tree[k].R[3] - tree[k+p].l/2
        end

        end

    InsertParticle(tree[k].ptcl,j_1,tree,particles)
    InsertParticle(i,j_2,tree,particles)
    tree[k].ptcl = 0
  elseif (c != [0])
      j = DetermOctant(particles[i],tree[k])
      InsertParticle(i,tree[k].children[j],tree,particles)
  end
return tree
end

function DetermOctant(x::particle,y::node)
  c1 = y.R[1]; c2 = y.R[2]; c3 = y.R[3]
  x1 = sign(x.R[1] - c1); x2 = sign(x.R[2] - c2); x3 = sign(x.R[3] - c3)
  if (x1 > 0) && (x2 > 0) && (x3 > 0)
    n = 1
  elseif (x1 < 0) && (x2 > 0) && (x3 > 0)
    n = 2
  elseif (x1 < 0) && (x2 < 0) && (x3 > 0)
    n = 3
  elseif (x1 > 0) && (x2 < 0) && (x3 > 0)
    n = 4
  elseif (x1 > 0) && (x2 > 0) && (x3 < 0)
    n = 5
  elseif (x1 < 0) && (x2 > 0) && (x3 < 0)
    n = 6
  elseif (x1 < 0) && (x2 < 0) && (x3 < 0)
    n = 7
  else
    n = 8
  end
return n
end

Basically, I do know that the error should be somewhere here:
function InsertParticle(i::Int64,k::Int64,tree,particles)
  c = tree[k].children
  a = tree[k].ptcl
  if (c == [0]) && (a == 0)
    tree[k].ptcl = i
  elseif (c == [0]) && (a > 0)
    j_1 = length(tree) + DetermOctant(particles[tree[k].ptcl],tree[k])
    j_2 = length(tree) + DetermOctant(particles[i],tree[k])
    tree[k].children = [x for x in length(tree)+1:length(tree)+8]
      for p = 1:8
        push!(tree,node(k,[0],tree[k].l/2,[0.0,0.0,0.0],0.0,0))
        if (p == 1) || (p == 4) || (p == 5) || (p == 8)
          tree[k+p].R[1] = tree[k].R[1] + tree[k+p].l/2
        else
          tree[k+p].R[1] = tree[k].R[1] - tree[k+p].l/2
        end
        if (p == 1) || (p == 2) || (p == 5) || (p == 6)
          tree[k+p].R[2] = tree[k].R[2] + tree[k+p].l/2
        else
          tree[k+p].R[2] = tree[k].R[2] - tree[k+p].l/2
        end
        if (p == 1) || (p == 2) || (p == 3) || (p == 4)
          tree[k+p].R[3] = tree[k].R[3] + tree[k+p].l/2
        else
          tree[k+p].R[3] = tree[k].R[3] - tree[k+p].l/2
        end

        end

    InsertParticle(tree[k].ptcl,j_1,tree,particles)
    InsertParticle(i,j_2,tree,particles)
    tree[k].ptcl = 0
  elseif (c != [0])
      j = DetermOctant(particles[i],tree[k])
      InsertParticle(i,tree[k].children[j],tree,particles)
  end
return tree
end

However, I cannot see where the infinite loop appears. Sorry for bringing these all here in a such form, I just want to avoid XY-problem.
Thank you in advance!


text:
Q: Saltos de linea en Java B dias! he creado un programa que crea un txt, seleccionando el nombre y el contenido, y me funciona perfectamente. He añadido saltos de línea y todo, pero debería terminar el bucle al escribir "q" y NO lo hace, alguien sabe por qué?
Os paso código de lo que tengo hecho.
public class practicas04 {

static InputStreamReader isr = new InputStreamReader (System.in);
static BufferedReader br = new BufferedReader (isr);

public static void main(String[] args) throws IOException {
    //crear archivo

    String ruta = System.getProperty("user.dir")+File.separator;
    String salt = System.getProperty("line.separator");
    System.out.print("Introduzca el Nombre del Archivo: ");
    String file = br.readLine();

    System.out.print("Introduzca el Contenido del Archivo: ");
    String text = br.readLine();
    FileWriter fw = new FileWriter (ruta+file+".txt");
    BufferedWriter bw = new BufferedWriter (fw);
    bw.write(text+salt);
    bw.flush(); //obliga al buffer a escribir en el archivo.

    while (text != "q") {
        text = br.readLine();
        bw.write(text+salt);
        bw.flush();
    }//end while

    bw.close();
    System.out.print("El Archivo "+file+".txt se ha Creado con Éxito! en\n "+ruta);

}//end main

}//end class

A: Dentro del while, en la línea br.write(textAr+salt);), que es textAr? ¿No debería de ser text?
    while (text != "q") {
    text = br.readLine();
    bw.write(text+salt);
    bw.flush();
}//end while

He probado cambiando el while y ahora funciona, siempre y cuando la "q" sea la primera letra de una línea.
 while (!text.equals("q")) {
     text = br.readLine();
     bw.write(text+salt);
     bw.flush();
 }//end while


text:
Q: How to put ngFor and ngIf in MAT-Table I have a mat-table where I am displaying name.
However, I have an array of name and I want to put condition where if name type is equal to primary name then show that name on the table.
How can I achieve that?
Code for HTML:
<mat-table [dataSource]="customerSearchRecordList" matSort>
  <ng-container matColumnDef="index">
    <mat-header-cell *matHeaderCellDef> Number </mat-header-cell>
    <mat-cell *matCellDef="let element; let i = index">{{ i + 1 }}</mat-cell>
  </ng-container>
  <!-- First Name Column -->
  <ng-container matColumnDef="firstName" >
    <mat-header-cell *matHeaderCellDef>First Name</mat-header-cell>
    <mat-cell *matCellDef="let element">{{ element.individualCustomer.individualName[0].firstName }}</mat-cell>
  </ng-container>

  <!-- Last Name Column -->
  <ng-container matColumnDef="lastName">
    <mat-header-cell *matHeaderCellDef>Last Name</mat-header-cell>
    <mat-cell *matCellDef="let element">{{ element.individualCustomer.individualName[0].lastName }}</mat-cell>
  </ng-container>

  <!-- Date of birth Column -->
  <ng-container matColumnDef="dateOfBirth">
    <mat-header-cell *matHeaderCellDef>Date Of Birth</mat-header-cell>
    <mat-cell *matCellDef="let element">{{ element.individualCustomer.dateOfBirth | date: 'MM/dd/yyyy' }}</mat-cell>
  </ng-container>

  <!-- Gender Column -->
  <ng-container matColumnDef="gender">
    <mat-header-cell *matHeaderCellDef>Gender</mat-header-cell>
    <mat-cell *matCellDef="let element">{{ element.individualCustomer.gender }}</mat-cell>
  </ng-container>
  <!-- Status Column -->
      <!-- View Button -->
  <ng-container matColumnDef="actions">
    <mat-header-cell *matHeaderCellDef> Actions </mat-header-cell>
    <mat-cell *matCellDef="let element; let index = index">
      <button mat-icon-button color="#b71c1c" matTooltip="View" (click)="transferIndCustData(element)">
        <!-- <mat-icon aria-label="Delete"
          >delete</mat-icon
      > -->
        <i class="material-icons large" style="font-size: 50px">
          pageview
        </i>
      </button>
    </mat-cell>
  </ng-container>

  <mat-header-row *matHeaderRowDef="displayedColumns; sticky: true"></mat-header-row>
  <mat-row *matRowDef="let row; columns: displayedColumns; let i = index"></mat-row>
</mat-table>

Typescript Code:
 this.customer360Service.getCustbyLastName("'" + this.lastNameValue + "'").subscribe(
  data => {
    this.sampleData = data;
    this.customerSearchRecord = this.sampleData;
    this.customerSearchRecordList = new MatTableDataSource<Customer>
    (this.customerSearchRecord);
 });

A: As I understand, in this case we need a filtered data to be displayed on HTML.
Hence filtering the customerSearchRecordList from typescript code before rendering on HTML would be an ideal solution.


text:
Q: Read a table row input values after editing them and clicking somewhere else in jquery I have this simple code:

1	<input type="text" value="20" readonly="readonly"/>	<input type="text" value="3" readonly="readonly"/>

2	<input type="text" value="22" readonly="readonly"/>	<input type="text" value="3" readonly="readonly"/>

3	<input type="text" value="23" readonly="readonly"/>	<input type="text" value="3" readonly="readonly"/>

4	<input type="text" value="24" readonly="readonly"/>	<input type="text" value="3" readonly="readonly"/>

or http://jsfiddle.net/x9CMC/ for more reliability.
I did a function which at double click, the readonly attribute was removed from all input from that row.
I want to read values (from every cell, no matter if that cell contains input or not) with blur function (means if I click somewhere else, I want to show an alert with all values from that row and add readonly to input).
I binded a blur action but it doesn't work properly, something is wrong ...
If I edited the 4th row and I click somewhere else, I want to show alert like this 4, new value edited by me, new value edited by me.
How ?
Thank you

A: http://jsfiddle.net/ZcMCg/1
The blur action didn't work because it was the inputs that had focus, not the row.
Unlike mouseenter/mouseleave focus and blur events do not bubble (but don't take my word for it, I just woke up).
As your table gets bigger you may want to have a look at jQuery's event delegation (delegate(), or on() with an extra selector passed in the 1.7 API) by the way.

A: You should work with custom events here, this makes your life much easier.
Consider this jQuery code:
$(function() {
    $("#sme table tr")
    .hover(function() {
        $(this).toggleClass("hl");
    })
    .bind("lock", function() {
        $(this).removeClass("open")
        .find("input").attr("readonly", "readonly");
    })
    .bind("unlock", function() {
        $(this).addClass("open")
        .find("input").removeAttr("readonly")
        .first().focus();
    })
    .dblclick(function() {
        $(this).trigger(
          $(this).is(".open") ? "lock" : "unlock"
        )
        .siblings("tr.open").trigger("lock");
    });
});

(see it in action in this jsFiddle)
What's happening here is:

*

*I've created two custom events that "lock" and "unlock" an individual row.
They handle changing the
 CSS class and making the <input> elements in a row read-only or not

*I've hooked triggering these events to the double click on a row. Double-clicking a locked row unlocks it and vice-versa (that's what trigger() does).

As you can see, the code becomes much cleaner once you separate the steps involved in editing a row from each other.
Note:

*

*There is no need to repeat the same selector (in your case $("#sme table tr") and $(this)) again and again. Just chain more methods to a single selector, like I did.

*There is no blur event for
 elements. Only form elements that can have focus can blur.

*There is no need to call each() on a selector. Everything you do to it will automatically be done to all selected elements. For example: $("a").hide() will hide each  on the entire page.

*The event that catches mouseenter and mouseleave is called hover in jQuery.

*There is no need to call bind(), most jQuery events have native handlers. For example bind("click", function() {}) is equivalent to click(function() {})


text:
Q: log in when I click a button I think this problem easy but there is something I can not figure out
here is a xml file has some widjet and there is an comment button and I want to check when the user click the button if he has an account , if it's not I want to take him to sing in activity ,
I know that I should check for an id or something
sorry for this silly question I will appreciate
    <?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="life.insomnia.inception.movie_Detailes">

        <ImageView
            android:id="@+id/poster"
            android:layout_width="400dp"
            android:layout_height="400dp"
            android:layout_weight="1"
            app:srcCompat="@drawable/split" />

        <TextView
            android:id="@+id/title"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="TextView"
            android:layout_alignBottom="@+id/poster"
            android:layout_alignParentStart="true"
            android:height="60dp"
            android:textAlignment="center"
            android:textSize="20sp"
            android:padding="15dp"
            android:textStyle="bold"
            android:textColor="#fff"/>
        <TextView
            android:id="@+id/tag_line"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_below="@+id/poster"
            android:layout_margin="20dp"
            android:textStyle="italic"
            android:textSize="20sp"
            android:text="mdfxvcmvcbnjxmk,x.,cmvbvncmx,;x,cmvncm,;zlx,cmvncmx,zlxkcmvnbvncmx,jzlfjfksdhmjkhfdsdhfkjjslknscnfgskjdpodjakdksjflkfuiweroihjszfdlkfhsoifhsdkgushfjdfkgh"
            />
        <EditText
            android:id="@+id/commenttxt"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:hint="comment here"
            android:layout_below="@+id/tag_line"
            android:layout_margin="15dp"
            />
        <Button
            android:id="@+id/commentbtn"
            android:layout_width="140dp"
            android:layout_height="45dp"
            android:layout_below="@+id/commenttxt"
            android:layout_centerHorizontal="true"/>
</RelativeLayout>

A: You add an ID to the button:
android:id="@+id/someId"

And then in code:
Button b = (Button) findViewById(R.id.someId);
b.setOnClickListener(this);//Make sure the class implements onClickListener

then in onClick(View v)
switch(v.getId()){
    case R.id.someId:
        //login here
    break;
}


text:
Q: Custom UITableViewCell accessoryView button invisible on REAL device In my UITableView I want to add custom accessoryView button for the rows in the table; this is the code, added in the UITableViewCell cellForRowAtIndexPath method:
    UIImage *image = [UIImage imageNamed:@"icon.png"];
    UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 28, 28)]; // tested also initWithFrame:CGRectMake(0, 0, image.size.width, image.size.heigth)
    [UIButton buttonWithType:UIButtonTypeCustom];
    [button setBackgroundImage:image forState:UIControlStateNormal];
    button.backgroundColor = [UIColor clearColor];

    cell.accessoryView = button;
    [button addTarget:self action:@selector(accessoryButtonTapped:event:) forControlEvents:UIControlEventTouchUpInside];

This perfectly works on the iOS simulator (iOS 5.1 and iOS 6.1), I can see the custom UIButton with icon.png image on the right of each row of the table and I can also call the accessoryButtonTapped event tapping on the custom image. But if I test my app on REAL device (iPhone 4 with iOS 5.1 or iPad 3rd with iOS 6.1) I cannot see the custom button, it is invisible, in fact tapping on the right of each rows still calls the accessoryButtonTapped event. I have deleted and re-installed app too, what can I do?

A: if your method is getting called, it means the button is there. the problem is with your image. While running on device, check if the image is nil or not, and whether the image has been added to the build target.


text:
Q: Flash Debugger on Slackware 64 Given a fresh install of Slackware64, how can I install the 32-bit Flash Plugin content debugger in Firefox and Chrome?
Reading through this question, I've got pretty close, but I'm stuck with with the error: nspluginwrapper: no appropriate viewer found. Unfortunately, there's no SlackBuild for the Debug version of the flash plugin.

A: An option that I use is to install 32-bit Firefox along side 64-bit Firefox and drop the debug version of libflashplayer.so into /usr/lib/mozilla/plugins/. Then use a 32-bit instance to do the flash debugging.


text:
Q: Biblatex: multiple citation numbers all within same bracket with the ieee style I'm using the ieee style for biblatex and when inserting citations I want

[1,2,6-10]

Right now I'm getting

[1],[2],[6-10].

How can I change this?

A: You should be OK by simply using the ieee style for the bibliography but the standard numeric-comp for the citations. For example
\RequirePackage{filecontents}
\begin{filecontents*}{\jobname.bib}
@book{IEEEexample:bookwitheditor,
  editor        = "J. C. Candy and G. C. Temes",
  title         = "Oversampling Delta-Sigma Data Converters Theory,
                   Design and Simulation",
  publisher     = "{IEEE} Press.",
  location      = "New York",
  year          = "1992"
}

@article{IEEEexample:articlelargepages,
  author        = "A. Castaldini and A. Cavallini and B. Fraboni
                   and P. Fernandez and J. Piqueras",
  title         = "Midgap Traps Related to Compensation Processes in
                   {CdTe} Alloys",
  journaltitle  = "Phys. Rev. B.",
  volume        = "56",
  number        = "23",
  year          = "1997",
  pages         = "14897-14900"
}

@article{IEEEexample:TBPmisc,
  author        = "M. Coates and A. Hero and R. Nowak and B. Yu",
  title         = "Internet Tomography",
  journaltitle  = "IEEE J. Selected Areas Commun.",
  month         = 05,
  year          = "2002",
  note          = "to be published"
}
\end{filecontents*}•

\documentclass{article}
\usepackage[backend=bibtex,bibstyle=ieee,citestyle=numeric-comp]{biblatex}
\bibliography{\jobname}

\begin{document}

\cite{IEEEexample:bookwitheditor, IEEEexample:TBPmisc, IEEEexample:articlelargepages}

\printbibliography

\end{document}

(I've included some bibliography data purely to create a self-contained demo.)
Notice that for citations that should be bracketed together, compressed into a range and so on you should use one \cite command and a comma-list of keys within the argument.

A:
Note that this answer is only for non-biblatex users, since biblatex is
  incompatible with the cite package! Thanks to @moewe for pointing that out.

What worked for me is simply adding
\renewcommand\citepunct{, }

to the preamble, as hinted in the cite.sty package documentation.
Here is a screenshot of the result
Before:
After:
But note that I just tested this in conjunction with
\documentclass[10pt,final,journal,compsoc,a4paper]{IEEEtran}


text:
Q: UILabel is not resizing when table cell appears I have a custom table view cell that display a few labels and a image.
The main label that has a variable height won't always resize.
When the table view is first displayed then the labels of the visible cells won't resize but after they will be redisplayed the label will have the correct size.
Table view cell height is set to automatic.
I tried the solution from here: http://www.appcoda.com/self-sizing-cells/ but with no success.
The label has number of lines = 0;
i called sizeToFit() / setNeedsLayout() but nothing changes.
let title = (self.posts[indexPath.row] as JSON) ["title"].stringValue as NSString;
cell.postTitleLabel.preferredMaxLayoutWidth = cell.frame.size.width - 20;
cell.postTitleLabel.text = title as String;
cell.setNeedsLayout();

A: I've read here (great article btw) that you shouldn't perform data binding in cell for row at index. But in my case because i was a loading a part of the data in cell for row and another part in will display cell the frames were resizing how i was the expecting.
So i've moved all the cell data binding in cell for row and now everything works great.


text:
Q: Jest testing stencil JS slot text on button I have a pretty simple button web component written with stenciljs
import { Component, h, Prop, State } from '@stencil/core';

@Component({
  tag: 'ss-button',
  styleUrl: 'button.scss',
  shadow: true,
})
export class Button {
    @State() keyFocus: boolean;
    @Prop() disabled?: boolean;
    @Prop() props: string = 'primary normal responsive';
    @Prop() type: string = 'button';
    @Prop() icon?: string = '';
    @Prop() iconAlt?: string = '';

    render() {
        return (
            <button class={this.props} disabled={this.disabled} type={this.type} id="button" role="button">
                <div class={`slot ${this.disabled ? 'disabled' : ''}`}>

                    <slot/>

            </button>
        );
    }
}

I want to be able to write a test in Jest that can test a text value put into the slot:
describe('ss-button', () => {
  let pageProperties: SpecPage;

  beforeEach(async () => {
    pageProperties = await newSpecPage({
      components: [Button],
      template: () => (<ss-button disabled={true} iconAlt={'add'} icon={'add'}>Testing</ss-button>),
    });
  });

  it('displays slot text', async () => {
  expect(pageProperties.root.shadowRoot.querySelector('slot').innerText).toEqual("Testing");
  });

I have seen this stackoverflow post but when I run:
pageProperties.root.shadowRoot.querySelector('slot').assignedNodes();
I get a TypeError: pageProperties.root.shadowRoot.querySelector(...).assignedNodes is not a function
can someone help me understand what I am missing?


text:
Q: DMARC reports: why Google submitting the reports? I configured DMARC in an email gateway solution and received the DMARC reports. My question is: why Google submitting the reports?

A: The aggregate reports show you how your domains are being used or abused without your knowledge or participation. If you do not want to receive the reports, you can omit the rua field in your DMARC record(s).


text:
Q: Move data between different servers I'm working on a project where I need to automatically run an insert statement to insert a result set - problem is that I need it to go from a SQL Server over to a DB2 server. I can't create a file or script and then import it or run it on the other side. I need to insert or update the DB2 side from the SQL Server side.
Is this possible? I need this to run all by itself as part of a stored procedure in SQL Server.

A: You're looking for the linked server feature.

Typically linked servers are configured to enable the Database Engine to execute a Transact-SQL statement that includes tables in another instance of SQL Server, or another database product such as Oracle. Many types OLE DB data sources can be configured as linked servers, including Microsoft Access and Excel. Linked servers offer the following advantages:

*

*The ability to access data from outside of SQL Server.

*The ability to issue distributed queries, updates, commands, and transactions on heterogeneous data sources across the enterprise.

*The ability to address diverse data sources similarly.

(I believe most of the major RDBMSs have a similar feature)
For the most part, this essentially allows you to treat tables or sources in the other database as if they were part of the SQL Server instance - an INSERT statement should just work "normally".

A: As mentioned you can use a linked server on the SQL Server side to perform operations between two servers.  I haven't done much with running DML on DB2 from SQL Server, but from my experience SSIS performs far better than linked servers for transactions pulling data from DB2 to SQL Server using an OLE DB connection.  You can read more about OLE DB connections in SSIS here and you'll want to reference the DB2 documentation for the specific DB2 type (Mainframe, LUW, etc.) that's used for details on setting up the connection there.  If you setup the SSIS catalog you can run packages using SQL Server stored procedures, which you can either use directly or execute from an existing user stored procedures.


text:
Q: The im- prefix in the word immigrate So I know that, generally speaking, the prefix "im-" means "not" or "the opposite of" which is fine in words like immobile, impolite, impossible etc. However, while helping my wife with her uni work I came across an interesting one: immigrate.
My research into my original query (whether emigrate or immigrate was the correct term to use for her essay) brought me to an interesting point: the word immigrate, from the definitions I've read, means something along the lines of

to enter and usually become established; especially :  to come into a country of which one is not a native for permanent residence

Taking away the prefix, you get migrate, which means

(of an animal, typically a bird or fish) move from one region or habitat to another according to the seasons.

Obviously in context this would mean a human moving from one place to another. My question is this: is the prefix still being used for negation in the word immigrate? Logic would dictate that the definition of it, given the definition of migrate, would be "not moving from one region or habitat to another" but isn't this exactly what you're technically doing when immigrating?
Is there another root/etymology for this word that differs from the usual im- words?

A: In this case, im- is a variation of in-. It gives the meaning of 'migrate in'. For a similar use of im-, compare with implosion.


text:
Q: Ember.js correct syntax for passing closure actions to nested components When passing a closure action down through some nested components, is there a difference between passing the action down using the action helper (First image), and simply passing the action down as a property (Second image)?

A: TLDR; no.
The former was the original and documented implementation of closure actions in Ember. However, the latter works just as well in Ember 2.10 or later and is compatible with the future simplified Glimmer component proposal.
There are some gotchas using the latter syntax, however, you might accidentally override some important Component methods like destroy().
For more background information, see Actions best practices
You may also be interested in the Events deep dive which will explain all the differences between various ways of handling events in Ember.
This answer was written at the time of Ember 3.1, and should work for versions 2.10 - 3.x.


text:
Q: ssh: how to connect a intranet machine outside the intranet I have a machine running my computing tasks in the intranet, and I want to connect the machine outside the intranet via ssh. But I don't know how to do it. Since ssh can only connect machines in LAN or machines with private ip.

A: You can use a NAT (Network Translating Address) to redirect a port from internet IP + port to your computer internal IP + port
For example you can use  externalIP:777 from internet to connect on 192.168.0.100:22 intranet machine
To connect with ssh on different port using ssh command : ssh ${IP_or_Domain} -p ${Port}


text:
Q: AWS S3 Logs: AccessDenied I created an empty bucket and enabled logging via the web GUI with my aws root user. I created a second bucket to store these logs. The logfiles are generated but all of them look like the following:
<Error>
AccessDenied
<Message>Access Denied</Message>
<RequestId>FCD6DC91A5BB8503</RequestId>
<HostId>
ROH2ON84Ef4x3DjcQJnJsE6Jz5h/Ke25sJoHy9hUmrMGo9Qi0eybWcS1ypTvt7r8Xny+mEwDlFw=
</HostId>
</Error>

Do I need to configure something else to receive logs?

A: Try clicking the "Download" or "Open" buttons rather than clicking the hyperlink under "Link"

A: This to me looks like an error with the request you are sending, and not the logging feature. Are you sure that the requester has the correct permissions for the bucket? Check to make sure that the the requester has either the correct IAM privileges and/or the bucket allows access.


text:
Q: How to fetch multiple values from the table based on foreign key? I have two tables,
#table 1 contains the following data structure
NO category_name    category_code   amount   type
1  provident_fund       PF           1000   Deduction
2  Home Allowance       HM           12000  Earning
3  Basic_pay            BP           35000  Earning

#table 2 contains the following data structure
NO group_name         payroll_cat_name
1  permanent          PF,HM,BP,TX
1  visiting           HM,BP

from the table 2, I can get the value of payroll_cat_name using the query
$a = "Select payroll_cat_name from table_2";
using the above query, I'm getting the value PF,HM,BP,TX.
Now, I have to use this multiple values PF,HM,BP,TX in order to get the sum amount from table 1.
Following is my code that I have tried,
include "../db.php";
$a = "Select payroll_cat_name from table_2";
$b = mysqli_query($con,$a);
$c = mysqli_fetch_array($b);
$d = $c["payroll_cat_name"];
echo "$d";
    $myArray = explode(',', $d);

print_r($myArray);
$tr = "select SUM(amount) as am from table_1 where category_code in ($d)";

$rt = mysqli_query($con,$tr);
$new = mysqli_fetch_array($rt);
$gh = $new["am"];

A: That's a poor data model. There should be a separate table to store the relation between groups and categories, which each tuple on a different row. The linked commented by sticky bit on the question gives great explanation on how and why.
For your current structure, one option using uses find_in_set() and a subquery:
select t2.*,
    (
        select sum(t1.amount)
        from table_1 t1
        where find_in_set(t1.category_code, t2.payroll_cat_name)
    ) as t1_amount
from table_t2 t2


text:
Q: Data synchronization in Offline First applications With all the buzz around Offline First applications, one of the firsts things that comes up is the data synchronization between the client and the server.
There are several posts and questions about this subject and during my research I found a very interesting "standalone library for data access and synchronization" called Orbit.js.
Until now I could not find any post or question about the integration between Orbit.js and AngularJS, all the reference I found is integrating with Ember.js and Foundation.
I'd like to know if someone has already tried both in the same project.
Is there any limitation/restriction? Orbit.js as the documentation says:

Orbit.js has no specific external run-time dependencies, but must be used with a library that implements the Promises/A+ spec, such as RSVP.

Could this be a restriction for integrating it with AngularJS?

A: The two seem like they might play nice together, but I have not myself put together an application with these two. However, another option is to use a different data sync library.  A few months back I stumbled on Pouch DB and it does indeed have an angular module.
Here are the links to do some digging. Hope it helps!
PouchDB - http://pouchdb.com
Angular Module - https://github.com/wspringer/angular-pouchdb


text:
Q: Display most recent posts in category with Twenty Ten theme widget I am fairly new to WordPress, and I would like to have a list of the most recent posts in a certain category appear in a right-hand panel (I can do this with all posts, but not specific categories)
I am using the Twenty Ten theme, on wordpress.com. I have found the following code, but unsure if or where this can be added:

<?php $recent = new WP_Query("cat=10&showposts=5"); while($recent->have_posts()) : $recent->the_post();?>

<a href="<?php the_permalink() ?>" rel="bookmark"><?php the_title(); ?>

    <?php endwhile; ?>

A: The fastest way, a plugin:
http://wordpress.org/extend/plugins/category-posts/

A: You are using wordpress.com. You cannot modify your Theme template files, or upload Plugins. You are limited to the Plugins available via Dashboard -> Plugins.


text:
Q: Fill drop down list and append assigned product count to each I have two tables:

I want to fill an ASP.NET server control drop down list with all of the authors that have books assigned to them and additionally append the number of items for each author to the list.
I have successfully done so. However it is slow with just this one and I plan to add 3 or 4 more drop down lists doing the same thing. Is there a better way to reform the following code?
using (myDataContext db = new myDataContext())
        {
            //ddlAuthors
            var authors = db.Authors.OrderBy(x=> x.text).Select(x => new
            {
                authorText= x.text,
                authorId = x.authorID,
                authorCnt = x.ItemAuthors.Count()
            });

            ddlAuthor.DataSource = authors;
            ddlAuthor.DataTextField = "authorText";
            ddlAuthor.DataValueField = "authorId";
            ddlAuthor.DataBind();
            foreach (ListItem item in ddlAuthor.Items)
            {
                foreach (var n in authors)
                {
                    if(item.Value == n.authorId.ToString())
                    item.Text += string.Format(" ({0})", n.authorCnt);
                }
            }
        }

A: This code might be part of the problem.
foreach (ListItem item in ddlAuthor.Items)
            {
                foreach (var n in authors)
                {
                    if(item.Value == n.authorId.ToString())
                    item.Text += string.Format(" ({0})", n.authorCnt);
                }
            }

If ddlAuthor has 10 items, you're going to go through this loop 100 times (1 time for each item in ddlAuthor.Items in the outer loop, and then 1 time for each author in the inner loop).
How about if in your query you did:
var authors = db.Authors.OrderBy(x=> x.text).Select(x => new
            {
                authorText= string.Format("{0} ({1})", x.text, x.ItemAuthors.Count()),
                authorId = x.authorID
            });

Then it's bound in the query, you don't have to loop through each item and append the count.
I just tried out something similar in LinqPad and it formatted the results like I wanted.


text:
Q: Levenshtein algorithm in Java I am trying to implement Levenshtein's algorithm in Java, inspired from this Wikipedia article
public static int indicator(char a, char b) {
    return (a == b) ? 0 : 1;
}

public static int levenshtein(String token1, String token2) {
    int[] levi = new int[token2.length() + 1];
    int[] levi_1 = new int[token2.length() + 1];

    // initialize column i=0
    for (int j = 0; j <= token2.length(); j++)
        levi_1[j] = j;

    // columns i=1 -> i=len(token1)
    for (int i = 1; i <= token1.length(); i++) {
        // lev_a,b(i,0) = i
        levi[0] = i;
        // update rest of column i
        for (int j = 1; j <= token2.length(); j++) {
            levi[j] = Math.min(Math.min(levi_1[j] + 1, levi[j - 1] + 1),
                               levi_1[j - 1] + indicator(token1.charAt(i - 1), token2.charAt(j - 1)));
        }

        // save column i to update column i+1
        levi_1 = levi;
    }

    return levi[token2.length()];
}

But testing this on string "Maus" and "Haus" gives me an incorrect answer of 4. Can you help me with what I am doing wrong?

A: The problem comes from this line:
levi_1 = levi;

This line doesn't change every value from the levi_1 array, it only changes its reference; the values are still the same when you call levi_1[0], levi_1[1], etc.
I would suggest you to write those lines instead:
for (int k = 0; k < levi.length; k++)
    levi_1[k] = levi[k];


text:
Q: How can I loop through excel pivot slicers using python win32? I am trying to loop through all the slicers and then export it to PDF. I am having trouble looping through the Slicer Items.
I have tried the following,
items = ['abs', 'abc', 'abd', 'cdc', 'dvd']

for each in range(0, len(items)):

    itemSlicer = items[each]
    print(itemSlicer )
    workbook.SlicerCaches("Slicer_items").ClearManualFilter()

    workbook.SlicerCaches("Slicer_items").SlicerItems().Selected = True

    workbook.ActiveSheet.ExportAsFixedFormat(0, path + label)

I get the error on workbook.SlicerCaches("Slicer_items").SlicerItems().Selected = True
The error,
com_error                                 Traceback (most recent call last)
<ipython-input-33-a48809dba26f> in <module>
      8
---> 10     workbook.SlicerCaches("Slicer_age").SlicerItems().Selected = True
     11

~\AppData\Local\Temp\1\gen_py\3.8\00020813-0000-0000-C000-000000000046x0x1x9\SlicerItems.py in __call__(self, Index)
     59         # Default method for this class is '_Default'
     60         def __call__(self, Index=defaultNamedNotOptArg):
---> 61         ret = self._oleobj_.InvokeTypes(0, LCID, 2, (9, 0), ((12, 1),),Index
     62             )
     63                 if ret is not None:

com_error: (-2147352567, 'Exception occurred.', (0, None, None, None, 0, -2147024809), None)

A: It seems your variable itemSlicer is missing from the line throwing the error. It should look like:
workbook.SlicerCaches("Slicer_items").SlicerItems(itemSlicer ).Selected = True


text:
Q: Recursive Manager/Associate query in T/SQL looking at this example link
I want to be able to walk through an HR table that I populate with who the manager is that is looking up themself and their reports (which shows them what level they are also)
Data:
    AssociateID     AssociateName    ManagerID    AssociateTitle
    ===========     =============    =========    ==============
    1               Jack Frost                    Chief Executive Officer
    2               Cindy Smith      1            President of Sales
    3               William Howard   1            President of Technology
    4               Ben Samson       2            Director of Tradeshow
    5               Sarah Jones      2            Director of Documentation
    6               Laurie Ralph     4            Manager
    7               Tina Nelson      5            Manager
    8               Joe May          6            Coordinator
    9               Peter Gill       7            Coordinator
   10               Kelly Kraft      2            Director of Facilities
   11               Heidi Trump      8            Administrative Assistant

If CEO signs in he gets the following data:
Jack Frost
 Cindy Smith
  Ben Samson
   Laurie Ralph
    Joe May
     Heidi Trump
 William Howard

But if Cindy Smith signs in her list would be:
 Cindy Smith
  Ben Samson
   Laurie Ralph
    Joe May
     Heidi Trump

The indenting is for visual.  I was also wondering if there could be a column that indicates what level the people are below.  Level 1; Level 2; etc
And if a person who signs in (example: Heidi Trump) her list is only her name.
Is this possible with TSQL?

A: I have it and want to share:
DECLARE @Associate float
Set @Associate = 1

;
WITH DirectReports(ManagerID, EmployeeID, Associate, Title, EmployeeLevel) AS
(
    SELECT ManagerID, AssociateID, LegalLastName + ', ' + LegalFirstName, Title, 1 AS EmployeeLevel
    FROM AssociateMaster
    WHERE
        ManagerID = @Associate

    UNION ALL

    SELECT e.ManagerID, e.AssociateID, e.LegalLastName + ', ' + e.LegalFirstName, e.Title, EmployeeLevel + 1
    FROM dbo.AssociateMaster AS e
        INNER JOIN DirectReports AS d
        ON e.ManagerID = d.EmployeeID
)

SELECT
  DR.ManagerID, MGR.LegalLastName + ', ' + MGR.LegalFirstName AS AssociateName, DR.EmployeeID, DR.Associate, DR.Title, DR.EmployeeLevel
FROM DirectReports DR
  INNER JOIN AssociateMaster as Mgr ON DR.ManagerID = Mgr.AssociateID

UNION

SELECT ' ', ' ', AssociateID, LegalLastName + ', ' + LegalFirstName, Title, 0
FROM AssociateMaster
WHERE
    AssociateID = @Associate

ORDER BY
  DR.EmployeeLevel Asc,
  MGR.LegalLastName + ', ' + MGR.LegalFirstName ASC,
  DR.Associate Asc

OPTION (MAXRECURSION 0);


text:
Q: Write a list of lists into csv in Python I have a list of lists of pure data like this
a=[[1,2,3],
   [4,5,6],
   [7,8,9]]

How can I write a into a CSV file with each list in a column like this?
1 4 7
2 5 8
3 6 9

A: Use:
import csv
with open('output.csv', 'w', newline='') as csvfile:
    writer = csv.writer(csvfile)
    writer.writerows(list(zip(*l)))

A: Try this:
import csv
with open('output.csv', 'w', newline='') as f:
    writer = csv.writer(f, delimiter=' ')
    writer.writerows(a)


text:
Q: Select distinct if? I'm new to SQL and I'd like to implement a query with a behavior that is quite difficult for me to write.
My 'user' table looks like this and is running under PostGRE
    id     |           email           | guest |           token
-----------+---------------------------+-------+----------------------------------------------
 6XH898SJ  | email@gmail.com           | t     | test_token_1234
 L7DJ456MV | another@gmail.com         | f     | faQ2UJFRKZNtieFGub6D0XwhfA1QqLD6lwU5DmIzBaI=
 L2CN592JV | tyesttest@gmail.com       | f     | gspCpQSOtuxNpT8n+C1szL12/YKvBfygfpGLPLoBDws=
 5KX442FK  | email@gmail.com           | f     | test_token_1234

It's simple :
Multiple guest user can exist with the same email.
Only one registered user can exist with a given email, but you can have a guest and a registered user holding at the same time.
The token is nothing more than a hash of the email, that's why it's the same for the first and the fourth user.
My request has to SELECT all the tokens for guest and non guest. But if two tokens are the same (ie the same email is used for two users) I need to retrieve the line WHERE guest is false.
Can someone help me ?

A: In Postgres, you can do this with distinct on:
select distinct on (token) u.*
from user u
order by token, guest desc;


text:
Q: Case Sensitive Ordering within the CMS Server List I've got to believe there's a reason for this, but for the life of me I cannot figure it out.  It looks like ordering of Server Names within any Central Management Server is Case SENSITIVE, regardless the collation of the server acting as the CMS, itself.
Attached is an example of a CMS hosted on my local machine, which is configured with a server collation of SQL_Latin1_General_CP1_CI_AS.  CI meaning Case Insensitive.  When selecting from the system table holding the CMS objects, the proper order is returned, however as you can see in this screenshot, the way the servers are listed in the UI, the order is obviously being treated in a Case Sensitive manner.

Since it doesn't seem to be server-level related, I assume it's client tools related, but there is no where within the tools that I can identify a collation level (or even case sensitivity setting) that would affect this.
Obviously there is nothing critical about this question, but if someone does know how to force the UI to be case insensitive, I'd appreciate it as I like to Camel Case my server names which is throwing off the ordering.

A: I believe this is a bug and I could reproduce it.
I entered a connect item for it: https://connect.microsoft.com/SQLServer/feedback/details/3136521


text:
Q: Reverse proxy a remote IMAP/SMTP server with NGINX Is it possible to reverse proxy a remote (managed by another company, think Google Apps or Office 365) SMTP/IMAP server through NGINX? Example:
I host example.com, and use mailhost.com to host my mail. I tried adding 2 CNAME records on example.com to accomplish this, but it didn't work. [smtp.example.com -> smtp.mailhost.com, etc]
Preferably, I want one subdomain (mail.example.com), pointing to both smtp.mailhost.com and imap.mailhost.com, differentiating between the two using ports. [mail.example.com:993 -> imap.mailhost.com:993, smtp.example.com:587 -> smtp.mailhost.com:587]
Is this possible? The only reason I want to do it is to make setting up mail clients easier for my website's users, and to stop confusion when asking why I am asking them to connect to a seemingly random domain to get emails. I understand this may cause some problems with DKIM etc.
Is this task easy, more hassle than it is worth or impossible? I'm capable of setting up a mail server, but would rather use a ready solution.

A: This is pretty well covered in the Configuring NGINX as a Mail Proxy Server guide in the official docs.
You should note though that you might experience issues with mail deliverability unless you are able to make any SPF, SSL, and DKIM configuration match what's upstream.

A: In my opinion the NGINX mail proxy server guide lacks of one very important information that was necessary for me to get something similar working:
Using a PHP Script on an Apache Server as the IMAP Auth Backend
I spent some weeks to find a working solution as mocking the auth service was not working properly for me. After disabling all SSL features and adding the auth php script I was finally able to receive emails with IMAP via the NGINX proxy.
One Problem that still exists for SMTP is: NGINX doesn't forward the auth command to the server: https://forum.nginx.org/read.php?2,58181,58186#msg-58186.
Therefore disabling auth for SMTP is necessary to make use of NGINX mail proxy. If someone finds a workaround please post the solution here: https://stackoverflow.com/questions/56031592/nginx-forwarding-smtp-auth-credentials-to-next-server/56583571#56583571
Here are some related links to the topic I want to share:

*

*Nginx as reverse SMTP proxy

*reverse proxy for multiple SMTP / IMAP servers

*IMAP: Reverse Proxy?

*Configuring NGINX as a mail proxy server with load balancing based on user

*Nginx TCP forwarding based on hostname


text:
Q: Generate "hash" functions programmatically I have some extremely old legacy procedural code which takes 10 or so enumerated inputs [ i0, i1, i2, ... i9 ] and generates 170 odd enumerated outputs [ r0, r1, ... r168, r169 ]. By enumerated, I mean that each individual input & output has its own set of distinct value sets e.g. [ red, green, yellow ] or [ yes, no ] etc.
I'm putting together the entire state table using the existing code, and instead of puzzling through them by hand, I was wondering if there was an algorithmic way of determining an appropriate function to get to each result from the 10 inputs. Note, not all input columns may be required to determine an individual output column, i.e. r124 might only be dependent on i5, i6 and i9.
These are not continuous functions, and I expect I might end up with some sort of hashing function approach, but I wondered if anyone knew of a more repeatable process I should be using instead? (If only there was some Karnaugh map like approach for multiple value non-binary functions ;-) )

A: If you are willing to actually enumerate all possible input/output sequences, here is a theoretical approach to tackle this that should be fairly effective.
First, consider the entropy of the output.  Suppose that you have n possible input sequences, and x[i] is the number of ways to get i as an output.  Let p[i] = float(x[i])/float(n[i]) and then the entropy is - sum(p[i] * log(p[i]) for i in outputs).  (Note, since p[i] < 1 the log(p[i]) is a negative number, and therefore the entropy is positive.  Also note, if p[i] = 0 then we assume that p[i] * log(p[i])  is also zero.)
The amount of entropy can be thought of as the amount of information needed to predict the outcome.
Now here is the key question.  What variable gives us the most information about the output per information about the input?
If a particular variable v has in[v] possible values, the amount of information in specifying v is log(float(in[v])).  I already described how to calculate the entropy of the entire set of outputs.  For each possible value of v we can calculate the entropy of the entire set of outputs for that value of v.  The amount of information given by knowing v is the entropy of the total set minus the average of the entropies for the individual values of v.
Pick the variable v which gives you the best ratio of information_gained_from_v/information_to_specify_v.  Your algorithm will start with a switch on the set of values of that variable.
Then for each value, you repeat this process to get cascading nested if conditions.
This will generally lead to a fairly compact set of cascading nested if conditions that will focus on the input variables that tell you as much as possible, as quickly as possible, with as few branches as you can manage.

Now this assumed that you had a comprehensive enumeration.  But what if you don't?
The answer to that is that the analysis that I described can be done for a random sample of your possible set of inputs.  So if you run your code with, say, 10,000 random inputs, then you'll come up with fairly good entropies for your first level.  Repeat with 10,000 each of your branches on your second level, and the same will happen.  Continue as long as it is computationally feasible.
If there are good patterns to find, you will quickly find a lot of patterns of the form, "If you put in this that and the other, here is the output you always get."  If there is a reasonably short set of nested ifs that give the right output, you're probably going to find it.  After that, you have the question of deciding whether to actually verify by hand that each bucket is reliable, or to trust that if you couldn't find any exceptions with 10,000 random inputs, then there are none to be found.

Tricky approach for the validation.  If you can find fuzzing software written for your language, run the fuzzing software with the goal of trying to tease out every possible internal execution path for each bucket you find.  If the fuzzing software decides that you can't get different answers than the one you think is best from the above approach, then you can probably trust it.

A: Algorithm is pretty straightforward. Given possible values for each input we can generate all the input vectors possible. Then per each output we can just eliminate these inputs that do no matter for the output. As the result we for each output we can get a matrix showing output values for all the input combinations excluding the inputs that do not matter for given output.
Sample input format (for code snipped below):
var schema = new ConvertionSchema()
{
    InputPossibleValues = new object[][]
    {
        new object[] { 1, 2, 3, }, // input #0
        new object[] { 'a', 'b', 'c' }, // input #1
        new object[] { "foo", "bar" }, // input #2
    },
    Converters = new System.Func<object[], object>[]
    {
        input => input[0], // output #0
        input => (int)input[0] + (int)(char)input[1], // output #1
        input => (string)input[2] == "foo" ? 1 : 42, // output #2
        input => input[2].ToString() + input[1].ToString(), // output #3
        input => (int)input[0] % 2, // output #4
    }
};

Sample output:

Leaving the heart of the backward conversion below. Full code in a form of Linqpad snippet is there: http://share.linqpad.net/cknrte.linq.
public void Reverse(ConvertionSchema schema)
{
    // generate all possible input vectors and record the resul for each case
    // then for each output we could figure out which inputs matters

    object[][] inputs = schema.GenerateInputVectors();

    // reversal path
    for (int outputIdx = 0; outputIdx < schema.OutputsCount; outputIdx++)
    {
        List<int> inputsThatDoNotMatter = new List<int>();

        for (int inputIdx = 0; inputIdx < schema.InputsCount; inputIdx++)
        {
            // find all groups for input vectors where all other inputs (excluding current) are the same
            // if across these groups outputs are exactly the same, then it means that current input
            // does not matter for given output

            bool inputMatters = inputs.GroupBy(input => ExcudeByIndexes(input, new[] { inputIdx }), input => schema.Convert(input)[outputIdx], ObjectsByValuesComparer.Instance)
                .Where(x => x.Distinct().Count() > 1)
                .Any();

            if (!inputMatters)
            {
                inputsThatDoNotMatter.Add(inputIdx);
                Util.Metatext($"Input #{inputIdx} does not matter for output #{outputIdx}").Dump();
            }
        }

        // mapping table (only inputs that matters)
        var mapping = new List<dynamic>();

        foreach (var inputGroup in inputs.GroupBy(input => ExcudeByIndexes(input, inputsThatDoNotMatter), ObjectsByValuesComparer.Instance))
        {
            dynamic record = new ExpandoObject();

            object[] sampleInput = inputGroup.First();

            object output = schema.Convert(sampleInput)[outputIdx];

            for (int inputIdx = 0; inputIdx < schema.InputsCount; inputIdx++)
            {
                if (inputsThatDoNotMatter.Contains(inputIdx))
                    continue;

                AddProperty(record, $"Input #{inputIdx}", sampleInput[inputIdx]);

            }

            AddProperty(record, $"Output #{outputIdx}", output);

            mapping.Add(record);
        }

        // input x, ..., input y, output z form is needed
        mapping.Dump();
    }
}


text:
Q: Is Malekith the strongest of the Dark Elves? Malekith the Accursed is the ruler of the Realm of Svartalfheim. Is he the strongest and most physically powerful Dark Elf? This concerns the comic book universe.

A: No, the strongest Dark Elf of the realm of Svartalfheim was Algrim the Strong. Algrim was born over 5,000 years before the present day and served Malekith loyally through the war of the Nine Realms.
From the Marvel biography of Kurse:
Becoming stronger
Thor had fallen in love with Lorelei due to a love potion she had given him. Malekith the Accursed, to bait Thor, captured Lorelei and brought her to Svartalfheim with him. Thor being obsessed with rescuing her broke through the nexus between earth and the faerie world. When he entered Svartalfheim he saw Malekith menacing Lorelai and was distracted, and Algrim stood in ambush wearing magical ebony armor. Malekith ordered Algrim to destroy Thor and they began to battle. As the fight ensued, Malekith broke open the ground beneath them both sending them falling toward the molten lava beneath the crust of Svartalfheim. Thor summoned Mjolnir which allowed him to fly out of the pit, but Algrim sunk into the lava.
Beyonder had a fascination with Thor and wanted to test the thunder god, as a sort of science project. Sensing Algrim's hatred for Thor, Beyonder saved Algrim from death but not before the heat caused him amnesia and severe injuries. His armor had only barely kept him alive. The amnesia made him forget the true reason he fell into the lava, so Algrim seethed with rage against his last rival Thor. Beyonder restored Algrim's health and made him twice the strength of Thor as well as much better armor. At this point, Algrim the Strong became the being Kurse.
Second Augmentation
During Kurse's relentless rampage to kill Thor he found him in Manhattan. Thor donned his Power Belt which doubled his strength, making them now equal. Beyonder disapproved, so he augmented Kurse again to be vastly greater than Thor even wearing his power belt.
During battle Thor used Mjolnir to release so much intense heat and energy on Kurse that he was reminded of sinking into the lava, and his memory was restored. He now sought to kill Malekith who betrayed him.
Becoming Ruler of Hel
Unfortunately Malekith was dead, so Kurse could not kill him. Kurse rampaged past Heimdall and descended Yggdrasil the World Ash into Hel demanding Hela release Malekith so he could destroy him. Hela refused and the augmented Kurse easily bested her, becoming the Ruler of Hel himself.
Battling Thor in Full ForceMalekith was in Hel all along in the form of Lorelai (who was also dead), and in that form he decieved Kurse into believing Malekith had escaped to Midgard (Earth). He (she) also enchanted Kurse so he would see Thor as Malekith. Malekith (as Lorelai) showed Kurse the rift to Midgard, and she followed him with his army of dead in to New York, saying, "He should know he could never escape my rage merely by dying!"
The battle is partially shown below, explaining all of Kurse's augmentation.

(from The Mighty Thor #486)
This makes Kurse by far the strongest and most powerful Dark Elf; vastly stronger than Malekith the Accursed and even Thor.
Eventually Hela revealed that Malekith had been behind the whole conspiracy using Kurse to get Thor.


text:
Q: Simplify matrix algebra I'm trying to simplify some matrix linear algebra, for example, simplify
$$\big(a1\times(A1\cdot A2)\big)\cdot\Big(a2\times A3\cdot A4+(a3\times A5)\cdot(a4\times A6)\Big)^{T}$$
where lower case variables $(a1-a4)$ are numbers and upper case variables $(A1-A6)$ are matrixes. "$\times$" is the Times function and "$\cdot$" is the Dot function, $\text{T}$ is the transpose operation.
I have these math identities for my matrixes in my case:
$$
(A\cdot B)^{T}=B^{T}\cdot A^{T}\\
(A+B)^{T}=A^{T}+B^{T}\\
c\times(A+B)=c\times A+c\times B\\
c^{T}=c
$$
so the expresion will simplify into
$$
a1~a2~A1\cdot A2\cdot A4^{T}\cdot A3^{T}+a1~a3~a4(A1\cdot A2\cdot A6^{T} \cdot A5^{T})
$$
My major question is how can I use Simplify or FullSimplify to do this simplification in MMA in an elegant and extensible way? For extensible I mean that one can easily add more operation rules into the simplification identities, for example, we could add inverse operation and its identities such as $(A\cdot B)^{-1}=B^{-1}\cdot A^{-1}$ and $(A^{-1})^T=(A^T)^{-1}$ etc.

Here is my try (I'm a novice and apparently my code is not elegant in any sense so please don't hesitate to advice suggestions or to point out any mistakes I made, I'm very welling to learn from you guys. And please pardon my poor English :P):
1.First simplify $(A\cdot B)^{T}$ to $B^{T}\cdot A^{T}$ and  $(A+B)^{T}$ to $A^{T}+B^{T}$, I define a transformation function
g1[expr_] := expr /. Transpose[A_] :> If[Head[A] == Dot || Head[A] == Times || Head[A] == Plus,
 Head[A] @@ Reverse[Transpose /@ A], Transpose[A]]

which changes Transpose[Dot[A,B]] to Dot[Transpose[B],Transpose[A]], and Transpose[Plus[A,B]] to Plus[Transpose[B],Transpose[A]]. And then define a ComplexFunction that prefers the form that Transpose is in the inside, for example, prefer Dot[Transpose[B],Transpose[A]] to Transpose[Dot[A,B]] :
cpfunc[expr_] := Module[{funcls},
 If[Length[expr] > 1, 0,
  If[Depth[expr] <= 2, 0,
   funcls = Reverse[Part[#, 0] & /@ (Level[#, {0, Depth[#] - 2}])] &@expr;
   If[Max[Position[funcls, Transpose]] - Max[Position[funcls, Dot]] < 0 ||
      Max[Position[funcls, Transpose]] - Max[Position[funcls, Times]] < 0 ||
      Max[Position[funcls, Transpose]] - Max[Position[funcls, Plus]] < 0,
   10^3, 0] (*gives punishment when found Dot inside Transpose, etc.*)
]]]

This works for Transpose[A1.B1.C1]:
Simplify[Transpose[A1.B1.C1], TransformationFunctions -> {Automatic, g1},
  ComplexityFunction -> cpfunc]
(*Transpose[C1].Transpose[B1].Transpose[A1]*)

Simplify[Transpose[a*A1], TransformationFunctions -> {Automatic, g1},
  ComplexityFunction -> cpfunc]
(*Transpose[a] Transpose[A1]*)

2.Second simplify $(a\times A)^{T}$ to $a~A^{T}$ :
I define a transformation function:
g2[expr_] :=
 expr /. Transpose[x_] :> If[x ∈ Reals, x, Transpose[x]]

then
Simplify[g2@Simplify[Transpose[a*A1], TransformationFunctions -> {Automatic, g1},
   ComplexityFunction -> cpfunc],
   Assumptions -> a ∈ Reals && A1 ∉ Reals]
(*a Transpose[A1]*)

Initially I was trying to do something like this but it doesn't work(could you point out the mistakes?)
g2[expr_] := expr /. (Transpose[x_];/NumberQ[x]) :> x
Simplify[Transpose[a*A],TransformationFunctions->{Automatic,g1,g2},
   ComplexityFunction->cpfunc,Assumptions->a∈ Reals&&A1∉Reals]
(*Transpose[a] Transpose[A]*)

3.Simplify the whole expression:
Simplify[(a1*A1.A2).Transpose[a2*A3.A4 + (a3*A5).(a4*A6)],
 TransformationFunctions -> {Automatic, g1},
 ComplexityFunction -> cpfunc]
(*
 (a1 A1.A2).((Transpose[a4] Transpose[A6]).(Transpose[a3] Transpose[A5])
 + Transpose[A4].Transpose[A3] Transpose[a2])
*)

Simplify[g2@%, Assumptions -> {a1 ∈ Reals, a2 ∈ Reals,
 a3 ∈ Reals, a4 ∈ Reals, A1 ∉ Reals,
 A2 ∉ Reals, A3 ∉ Reals,
 A4 ∉ Reals, A5 ∉ Reals,
 A6 ∉ Reals}]
(*
 (a1 A1.A2).(a2 Transpose[A4].Transpose[A3]
 + (a4 Transpose[A6]).(a3 Transpose[A5]))
*)

the output is
$$
(\text{a1} \text{A1}\cdot\text{A2})\cdot(\text{a2} \text{A4}^{\mathsf{T}}\cdot\text{A3}^{\mathsf{T}}+(\text{a4} \text{A6}^{\mathsf{T}})\cdot(\text{a3} \text{A5}^{\mathsf{T}}))
$$
This final answer is close to the result I want to achieve. I tried to go further but without any luck. Here is my thinking(questions) about this:

*

*Is there some more elegant way to do this? For example, it is possible to set some kind of attributes to these different operations so that Dot, Times, Pulse etc have different priority in the calculation, and one can sort them directly by their attributes in order to simplify or expand an expression?

*I'm very curious how MMA Expand an algebra expression like (a + b)*(c + d*e).

*How to make a transformation function work on different assumptions? For example, when only x is a number, that the transformation Transpose[x_]:>x will apply.

A: I was really intrigued by this problem and I tried multiple solutions before posting one here.
The most elegant approach I found is to use ReplaceRepeated with a custom list of scalar variables.
In order for it to work we need the proper rule set
rules := {
  T[Dot[A_, B__]] :> T[Dot[B]].T[A],
  T[Plus[A_, B__]] :> T[A] + T[Plus[B]],
  T[a_ A_] /; MemberQ[scalars, a] :> a T[A],
  T[a_] /; MemberQ[scalars, a] :> a,

  x__.(y_ + z__).w___ :> (x.y.w) + (x.z.w),
  (x___).(a_ y_).(z___) /; MemberQ[scalars, a] :> a (x.y.z)
  }

Let's see what they are doing. The first two,
  T[Dot[A_, B__]] :> T[Dot[B]].T[A],
  T[Plus[A_, B__]] :> T[A] + T[Plus[B]],

correspond exactly to your first two math identities. Using a sequence (B__) instead of a single expression (B_) allows to apply this rules one argument at the time.
The third and the forth,
  T[a_ A_] /; MemberQ[scalars, a] :> a T[A],
  T[a_] /; MemberQ[scalars, a] :> a,

provide for some simplification whether a scalar is involved,
and the last two,
  x__.(y_ + z__).w___ :> (x.y.w) + (x.z.w),
  (x___).(a_ y_).(z___) /; MemberQ[scalars, a] :> a (x.y.z)

implement some properties of the dot product.
This is the expression which has to be simplified:
expr = (a1*A1.A2).T[a2*A3.A4 + (a3*A5).(a4*A6)]

This the result without any assumptions:
In[484]:= expr //. rules // Expand

Out[484]= (a1 A1.A2).T[a2 A3.A4] + (a1 A1.A2).T[a4 A6].T[a3 A5]

And this providing an explicit list of scalars:
In[485]:= Block[
 {scalars = {a1, a2, a3, a4}},
 expr //. rules // Expand
 ]

Out[485]= a1 a2 A1.A2.T[A4].T[A3] + a1 a3 a4 A1.A2.T[A6].T[A5]

where I use Expand only to avoid the automatic collection of a1.

All of that can also be packed into a function
MatrixSimplify[expr_, s : _List : {}] :=
 Module[{},
  If[OwnValues[$scalars] === {},
       $scalars = {}
   ];
  Block[
   {$scalars = Join[$scalars, Flatten[{s}]]},

   With[{rules = {
       T[Dot[A_, B__]] :> T[Dot[B]].T[A],
       T[Plus[A_, B__]] :> T[A] + T[Plus[B]],
       T[a_ A_] /; MemberQ[$scalars, a] :> a T[A],
           T[a_] /; MemberQ[$scalars, a] :> a,

       x__.(y_ + z__).w___ :> (x.y.w) + (x.z.w),
       (x___).(a_ y_).(z___) /; MemberQ[$scalars, a] :> a (x.y.z)
       }},

    expr //. rules // Expand
    ]
   ]
  ]

MatrixSimplify must be provided with an expression and an optional list of scalars.
In[562]:= expr // MatrixSimplify

Out[562]= (a1 A1.A2).T[a2 A3.A4] + (a1 A1.A2).T[a4 A6].T[a3 A5]

In[563]:= MatrixSimplify[expr, {a4, a1}]

Out[563]= a1 A1.A2.T[a2 A3.A4] + a1 a4 A1.A2.T[A6].T[a3 A5]

It also relies on the global variable $scalars (the bit of code within the If statement is to check whether $scalar is initialized and, if not, it does set it to an empty list), so you can do something like
In[564]:= $scalars = {a1, a2, a3, a4};

In[565]:= expr // MatrixSimplify

Out[565]= a1 a2 A1.A2.T[A4].T[A3] + a1 a3 a4 A1.A2.T[A6].T[A5]

P.S.
An alternative way to do this is by using MatchQ instead of MemberQ. This makes it possible to specify the scalar variables with patterns as in
$scalars = a[_] | b[_] | ...


text:
Q: How to calculate gas equation (not necessarily ideal) when the internal energy depends solely on the temperature? I know that for an ideal gas it can be shown through the equation of state and the Maxwell relationships, that the energy of the gas depends only on temperature.
But my question is how can I calculate a state equation when I know that the energy of specific real gas depends only on the temperature?

A: It is unnecessary to use Maxwell relations to show that if a gas obeys the equation of state of the perfect gas, the energy depends only on the temperature (and the number of moles).
Indeed, from $pV=nRT$, one gets
$$
\frac{p}{T}=\left.\frac{\partial{S}}{\partial{V}}  \right|_{U,n}= \frac{nR}{V}
$$
which can be integrated to give
$$
S=nR\log V + f(U,n)
$$
Therefore, the inverse temperature
$$
\frac{1}{T}=\left.\frac{\partial{S}}{\partial{U}}  \right|_{V,n}=
\left.\frac{\partial{f}}{\partial{U}}  \right|_{V,n}(U,n).
$$
From this last equation, by using the inverse function theorem, we get $U(n,T)$ using the inverse function theorem. Notice that unless additional information is provided, it is impossible to obtain the unknown function $f(U,n)$.
If we know that the internal energy is a function of $T$ (and n) but does not depend on $V$, this implies that
$$
S(U,V,n)=\phi(V,n)+f(U,n)
$$
(the dependence of the internal energy on $T$ and $n$ can be derived analogously to the previous case). However, we cannot go beyond the result that.
$$
\frac{p}{T}=\left.\frac{\partial{S}}{\partial{V}}  \right|_{U,n}= \left.\frac{\partial{\phi}}{\partial{V}}  \right|_{n}.
$$
There is no way to get the unknown function $\phi(V,n)$ without additional information.


text:
Q: How can client send a value to server using SignalR and the server update a model? If I want to update a model/DB using SignalR, how is this achieved? (The other way around, i.e. from Server to Client is explained in many tutorials, but this way?)
So say we have a simple Model
public class User
{
    public int UserID { get; set; }

    public string UserName { get; set; }

}

And the corresponding View has an input field for the name. The hub is something like
public class UserHub : Hub
{
    public void UpdateName(string value)
    {
        // now what?

        Clients.All.updateTheViewIfNecessary(string newValue);

    }
}

Edit
How do I update the model, i.e. how do I achieve the same result as in the regular CRUD edit controller
db.Entry(user).State = EntityState.Modified;
db.SaveChanges();

A: For the purpose of this example we will use a JS client to send a model to the Hub and references official documentation at
ASP.NET SignalR Hubs API Guide - JavaScript Client: How to call server methods from the client
Assuming a User Hub on the server
public interface IUserService {
    bool UpdateName(string userName);
    // Other methods not shown.
}

public class UserHub : Hub {
    private readonly IUserService service;

    public UserHob(IUserService service) {
        this.service = service;
    }

    public void UpdateName(string value) {
        if(value != null) {
            var newValue = value;
            if(service.UpdateName(newValue) == true) {
                Clients.All.updateTheViewIfNecessary(newValue);
            }
        }
    }
}

Reference documentation at Dependency Injection in SignalR to understand how to inject dependencies into the hub. In the above UserHub when the message is received, it uses the data in the model to update/persist data via the injected dependency and notifies clients based on the result of that operation. This could allow for long running processes that could later update clients as needed.
A JavaScript client code that invokes the server method (assuming with the generated proxy) would look something like this.
//This assumes View has an input field for the name
var message = "Test Name";
userHubProxy.server.updateName(message).done(function () {
    console.log ('Invocation of UpdateName succeeded');
}).fail(function (error) {
    console.log('Invocation of UpdateName failed. Error: ' + error);
});

The framework will handle whatever model binding needs to be done on the server.
The hub in effect acts as a service endpoint and sends the response of calling the service to all clients connected to it.

A: Call the server function to pass the values like shown in the javascript below.
I have also include the sample html table containing list of users to call server function against each button click

            <input type="button" value="User 1" />
            <button type="button" value="2" title="User 2">User 2</button>
            <input type="button" value="User 3" />
            <input type="button" value="User 4" />

var userId, userName, strOtherVal;
userId = 1; // sample values
userName = 'ali';
strOtherVal = 'admin';

         $(function () {
            $("#tblData tr td button,input").click(function (event) {

                 myHub.server.sendData(userId, userName, strOtherVal)
                    .fail(function (error) {
                        console.log('error sending data: ' + error)
                    });

            });
        });

On the server side your function will look like this
 public void sendData(int userId, string userName, string strOtherVal)
        {
            //create model
            var UserModel = new User() { UserID = userId, UserName = userName, OtherVal = strOtherVal };

            //here call your function to check or post this model to db

        }

 public class User
    {
        public int UserID { get; set; }

        public string UserName { get; set; }

        public string OtherVal { get; set; }
    }


text:
Q: Parse data from one format to another Typescript I need to parse some data got from BE from one format to another to can inject it into a table component. The format received is:
{
    "displayName": "Income",
    "baseVersionSum": null,
    "comparisonVersionSum": null,
    "variance": null,
    "variancePercent": null,
    "children": [
        {
            "displayName": "4000 Revenue",
            "baseVersionSum": null,
            "comparisonVersionSum": null,
            "variance": null,
            "variancePercent": null,
            "children": [
                {
                    "displayName": "4100 Product 1 Revenue",
                    "baseVersionSum": -1000000,
                    "comparisonVersionSum": 4300000,
                    "variance": -5300000,
                    "variancePercent": -123,
                    "children": []
                }
            ]
        }
    ]
}

and I need the following format:
{
    "key": "Income",
    "data": {
        "displayName": "Income",
        "baseVersionSum": null,
        "comparisonVersionSum": null,
        "variance": null,
        "variancePercent": null
    },
    "children": [
        {
            "key": "4000 Revenue",
            "data": {
                "displayName": "4000 Revenue",
                "baseVersionSum": null,
                "comparisonVersionSum": null,
                "variance": null,
                "variancePercent": null
            },
            "children": [
                {
                    "key": "4100 Product 1 Revenue",
                    "data": {
                        "displayName": "4100 Product 1 Revenue",
                        "baseVersionSum": -1000000,
                        "comparisonVersionSum": 4300000,
                        "variance": -5300000,
                        "variancePercent": -123
                    },
                    "children": []
                }
            ]
        }
    ]
}

Each parent can have more children or no children.
I tried to do something with reduce, but no result. This is what I've tried:
  const prepareTableValue = (data: any): any => {
    const res = data.reduce((result: any, node) => {
      if (node.children) {
        result.push({
          key: node.displayName,
          data: {
            displayName: node.displayName,
            baseBersionSum: node.baseVersionSum,
            comparisonVersionSum: node.comparisonVersionSum,
            variance: node.variance,
            variancePercent: node.variancePercent,
          },
          children: node.children,
        });
        prepareTableValue(node.children);
      }

      return result;
    }, []);

    return res;
  };

Thanks in advance!

A: Nice challenge ! Here is a solution with a recursive function that creates a new object and adds to it recursively by going through each child of the initial object and calling itself for that child and the child in that position in the new object:

const objToFormat = {
    "displayName": "Income",
    "baseVersionSum": null,
    "comparisonVersionSum": null,
    "variance": null,
    "variancePercent": null,
    "children": [
        {
            "displayName": "4000 Revenue",
            "baseVersionSum": null,
            "comparisonVersionSum": null,
            "variance": null,
            "variancePercent": null,
            "children": [
                {
                    "displayName": "4100 Product 1 Revenue",
                    "baseVersionSum": -1000000,
                    "comparisonVersionSum": 4300000,
                    "variance": -5300000,
                    "variancePercent": -123,
                    "children": []
                }
            ]
        }
    ]
};

const formatData = (objToFormat, formattedObj = {}) => {
    const { displayName, children, ...data } = objToFormat;

    formattedObj.key = displayName;
    formattedObj.data = { displayName, ...data };
    formattedObj.children = [];

    children.forEach((child, i) => {
        formattedObj.children[i] = {};
        formatData(child, formattedObj.children[i]);
    })

    return formattedObj;
}

console.log(formatData(objToFormat))

A: A recursive parse should work.
function parseData(items: any[]) {
    const parsed = items.map((item) => {
        const clone = Object.create(item);
        clone.key = clone.displayName;
        clone.data = {
            displayName: clone.displayName,
            baseBersionSum: clone.baseVersionSum,
            comparisonVersionSum: clone.comparisonVersionSum,
            variance: clone.variance,
            variancePercent: clone.variancePercent,
        };
        clone.children = parseData(clone.children);
        return clone;
    });
    return parsed;
}


text:
Q: Android YesNoDialogPreference You may think this is a duplicate question but i looked up almost every existing answer and i still did not get it right. Here is my question:

*

*I want to create a default YesNoDialogPreference by extending the DialogPreferenceclass

*Creating a preference using YesNoDialogPreference in prefs.xml

*In the MainActivity i want to set an onClickListener for Yes and No options

I have tried doing this using AlertDialog.Builder but it didn't work, i've also tried to use com.android.internal.preference.YesNoPreference and it did work cause of R.attr error
Can somebody please give me a full answer...PLEASE!!, i have been struggling with this for weeks now.
Here's my code:
YesNoDialogPreference.java
import android.content.Context;
import android.preference.DialogPreference;
import android.util.AttributeSet;

public class YesNoDialogPreference extends DialogPreference {

    public YesNoDialogPreference(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    protected void onDialogClosed(boolean positiveResult) {
        super.onDialogClosed(positiveResult);
        persistBoolean(positiveResult);
    }

}

The preference from prefs.xml
<com.me.myapp.YesNoDialogPreference
            android:key="KEY"
            android:dialogMessage="You sure ?"
            android:title="Do something"
            android:summary="will do something"
            />

I do not know how to link them in the MainActivity.

A: What you are trying to achieve does not make sense. The MainActivity is not active so can't be the target of the dialog.
You need an onClick handler in your YesNoDialogPreference which then does what you want. You typically safe the value in your settings and read that value in all other places - like your MainActivity.
Here is a code sample:
How to get the DialogPreference POSITIVE_BUTTON to work on OnClick?

A: Just use onClick method and implement listener to provide handle actions where you want
@Override
public void onClick(DialogInterface dialog, int which){

    if(which == DialogInterface.BUTTON_POSITIVE) {
        // do your stuff to handle positive button

    }else if(which == DialogInterface.BUTTON_NEGATIVE){
        // do your stuff to handle negative button
    }
 }


text:
Q: change text with Id by selecting an image with Id I have a query that makes changes on a list item's text while the mouse is over an image, I put an event target within the query  :
    $('img').on('mouseover', function(){
     // I would like an Id of a text instead of the 'li'
      $('li').css('text-decoration', 'underline');
    });

    $('img').on('mouseout', function(){
      $('li').css('text-decoration', 'none');
    });

but I want that change it to be applied to only the item which have the same Id as the image :
s[i++] = '
';
s[i++] =  ''+ vizList[j].name + '';
s[i++] =  '';
s[i++] = '
';

A: Is the below code what you expect?
$('img').on('mouseover', function(event){
  $(event.target).closest('li').css('text-decoration', 'underline');
});

$('img').on('mouseout', function(event){
  $(event.target).closest('li').css('text-decoration', 'none');
});

A: Firstly, ID is supposed to be unique, so either make them slightly different, or use classes.
Change your $('li') selector to $(this).find('li'). That should find the image within the hovered li
You can also use the .hover function to convert this into one call:
https://jsfiddle.net/juk41yLs/1/

$('img').hover(
  function() {
    $(this).parent('li').css('text-decoration', 'underline');
  },
  function() {
    $(this).parent('li').css('text-decoration', 'none');
  }
);

    Hover over this >

A: I assume you want to change the li contained img when mouse hovers over img. Then you should do it like this:
$('img').on('mouseover', function(event){

    $(this).parent().css('text-decoration', 'underline');
});

A:

   $('img').on('mouseover', function(event){
     // I would like an Id of a text instead of the 'li'
      var imgId = event.target.id;

      $('#' + imgId).css('text-decoration', 'underline');
    });


text: Q: MySQL master slave replication issue I have enabled filtered replication in MySQL. Only one table is being replicated from master to slave using replicate-do-table option and the replication is going smooth. Today morning I have noticed that a newly created procedure in master got replicated to the slave. Any ideas?


text:
Q: Why does the directory go before 2>&1 but after 2>/? I've been looking around for an answer yet I cannot find one. My question is the syntax of the above commands.
Why would I need to put the directory before one but after the other?
example:
>~/Desktop/log 2>&1

2>~/Desktop/log

Because when I try
2>&1~/Desktop/log

or
2>&1>~/Desktop/log

They do not work, which I am OK with. That's fine. I just want to know why the syntax seemingly contradicts itself.

A: Your issue is one of spacing and what the bits of the line mean.
>~/Desktop/log 2>&1 means redirect standard output > to ~/Desktop/log and then redirect standard error 2> to the standard output (file descriptor 1, &1).
Similarly with 2>~/Desktop/log which is redirect standard error 2> to ~/Desktop/log.
That being said 2>&1~/Desktop/log is confused (ambiguous) because it is unclear what you meant for that to be doing.
You also cannot redirect output to a directory as that isn't a valid target for writing output.
The order of redirections on a line matters in that they occur in a left-to-right manner. So >file 2>&1 redirects both standard output and standard error to the file but 2>&1 >file redirects standard error to where standard output is and then redirects standard output somewhere else (leaving standard error going to the old location).

A: When I try:
: 2>&1/dev/null

I get an 'ambiguous redirect' error (from Bash 4.3.28 - with some custom patches).
If I used:
: 2>&1 /dev/null

with a space, then the /dev/null is simply an argument to the : command (which is a no-op — it is convenient for testing, that's all).  The I/O redirection sends standard error to standard output for the duration of the : command.
With:
: 2>&1>/dev/null

the shell doesn't whinge.  It treats 2>&1 as one redirection, >/dev/null as another and gets on with life.
The notations:
: 2>/dev/null
: 2> /dev/null

both specify that standard error should go to /dev/null.
Main moral of the story: keep I/O redirections separate from each other.  Spaces are cheap and should be used to avoid ambiguity and to make it easier for other people (including yourself in six months time!) to read and understand.