text:
Q: Problema con Hibernate Me acaba de surgir un problema a la hora de insertar un producto (en este caso) en la base de datos. Estoy trabajando con el mapeo y siempre me devuelve "false". No encuentro donde puede estar el posible fallo.
Muestro las clases.
Clase mapeo Productos:
public class Productos  implements java.io.Serializable {

     private String codigoProducto;
     private Categoriasproductos categoriasproductos;
     private String nombreProducto;
     private String escala;
     private String vendedor;
     private String descripcion;
     private short unidadesStock;
     private BigDecimal precioCompra;
     private BigDecimal precioVenta;

    @Override
    public String toString() {
        return "Productos{" + "codigoProducto=" + codigoProducto + ", categoriasproductos=" + categoriasproductos + ", nombreProducto=" + nombreProducto + ", escala=" + escala + ", vendedor=" + vendedor + ", descripcion=" + descripcion + ", unidadesStock=" + unidadesStock + ", precioCompra=" + precioCompra + ", precioVenta=" + precioVenta + '}';
    }

    public Productos() {
    }

    public Productos(String codigoProducto, Categoriasproductos categoriasproductos, String nombreProducto, String escala, String vendedor, String descripcion, short unidadesStock, BigDecimal precioCompra, BigDecimal precioVenta) {
       this.codigoProducto = codigoProducto;
       this.categoriasproductos = categoriasproductos;
       this.nombreProducto = nombreProducto;
       this.escala = escala;
       this.vendedor = vendedor;
       this.descripcion = descripcion;
       this.unidadesStock = unidadesStock;
       this.precioCompra = precioCompra;
       this.precioVenta = precioVenta;
    }

    public String getCodigoProducto() {
        return this.codigoProducto;
    }

    public void setCodigoProducto(String codigoProducto) {
        this.codigoProducto = codigoProducto;
    }
    public Categoriasproductos getCategoriasproductos() {
        return this.categoriasproductos;
    }

    public void setCategoriasproductos(Categoriasproductos categoriasproductos) {
        this.categoriasproductos = categoriasproductos;
    }
    public String getNombreProducto() {
        return this.nombreProducto;
    }

    public void setNombreProducto(String nombreProducto) {
        this.nombreProducto = nombreProducto;
    }
    public String getEscala() {
        return this.escala;
    }

    public void setEscala(String escala) {
        this.escala = escala;
    }
    public String getVendedor() {
        return this.vendedor;
    }

    public void setVendedor(String vendedor) {
        this.vendedor = vendedor;
    }
    public String getDescripcion() {
        return this.descripcion;
    }

    public void setDescripcion(String descripcion) {
        this.descripcion = descripcion;
    }
    public short getUnidadesStock() {
        return this.unidadesStock;
    }

    public void setUnidadesStock(short unidadesStock) {
        this.unidadesStock = unidadesStock;
    }
    public BigDecimal getPrecioCompra() {
        return this.precioCompra;
    }

    public void setPrecioCompra(BigDecimal precioCompra) {
        this.precioCompra = precioCompra;
    }
    public BigDecimal getPrecioVenta() {
        return this.precioVenta;
    }

    public void setPrecioVenta(BigDecimal precioVenta) {
        this.precioVenta = precioVenta;
    }

}

Clase Operaciones con el método insertar:
public class Operaciones {

Session sesion = null;

    public Operaciones() {
        sesion = HibernateConnector.getInstance().getSession();
    }

 public ArrayList<Productos>getProductos() {

        ArrayList<Productos>array = new ArrayList<>();

        array = (ArrayList<Productos>) sesion.createQuery("from Productos").list();

        return array;

public boolean addProductos(Productos producto) {

Transaction transaccion = null;

 try {

transaccion = sesion.beginTransaction();

            sesion.save(producto);

            transaccion.commit();

            return true;
            } catch(HibernateException e) {
                transaccion.rollback();
                return false;
            }
         }
       }

    }

Por último el main:
public static void main(String[] args) {

        Operaciones op = new Operaciones();

        Productos p1 = new Productos("1111111",  null, "Producto47", "1:10", "Carlos Antonio", "la novedad de nuestra tienda", new Short("2"), null, null);

        System.out.println(op.addProductos(p1));

        ArrayList<Productos>array = op.getProductos();

        for (Productos productos : array) {

            System.out.println(productos.toString());

        }
}

}

Siempre retorna false:

Excepciones:

A: El capturar una excepción y no tratarla correctamente es un clásico fallo de novato por el que todos pasamos:
try {
      transaccion = sesion.beginTransaction();
      sesion.save(producto);
      transaccion.commit();
      return true;
} catch(HibernateException e) {
      // ¿Qué error ha ocurrido?
      e.printStackTrace();
      transaccion.rollback();
      return false;
}

La línea que he añadido hará que en la consola de tu IDE aparezca el mensaje de error. Puede ser algo tan tonto como que ya exista un producto con el mismo identificador (no sé cual es tu clave primaria para la tabla productos).
Por cierto, la tabla la puedes llamar tanto producto como productos (singular o plural), pero puesto que cada instancia de la clase representa un único producto, el nombre correcto debería ser Producto y no Productos. Un objeto Productos puede dar a entender que es una colección, no un único elemento


text:
Q: Vue.JS Image Cropper Всем привет. Пишу приложение на Vue.JS. Мне нужен компонент Image Cropper, в котором есть возможность экспортирования отредактированного изображения.
Я скачал JCrop. Но я не нашел этого.
У кого какие варианты?

A: Ищите компоненты тут: vuecomponents
А так есть варианты:

*

*vue-croppie

*vue-crop

redpajama_set_name: RedPajamaStackExchange


text:
Q: Using CustomBottomSheetBehavior in an Scrolling Activity causes an empty space behind tool-bar I am recently using CustomBottomSheetBehavior to make an googlemaps like bottom sheet behavior and it works great. I have only one problem.please look at this image

If I use it in a scrolling activity the content of tool-bar covers my list box. so I ahve to add margin-top to my list view. It works but when I draw bottomsheet up toolbar goes up and behind it, there is an empty space. This is because I have added some margin top to make my list's top visible. Is there any way to connect list's margin top to the amount of moving bottom-sheet and when It moves up decrease margin value to and when it moves down increase it?or is there any better way ?
It seems I have to develope my own TopMarginBehavior for this job but I have no idea how to do it.
thanks

A: *

*Create your own class related to the behavior you want (MarginTopBehavior)

*Extends it from CoordinatorLayout.Behavior

*Now you have to focus on 2 methods: layoutDependsOn and onDependentViewChanged. With the first one you are selecting the view that your MarginTopBehavior is following, in this case is a NestedScrollView. With the second one you are reacting (the magic!) when the scroll get moved.
At this point you get this:
public class MarginTopBehavior<V extends View> extends CoordinatorLayout.Behavior<V> {

    private FrameLayout.LayoutParams mLayoutParams;

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

    @Override
    public boolean layoutDependsOn(CoordinatorLayout parent, View child, View dependency) {
        return dependency instanceof NestedScrollView;
    }

    @Override
    public boolean onDependentViewChanged(CoordinatorLayout parent, View child, View dependency) {

    }
}

The logic to be applied in onDependentViewChanged is just this:
* Define the cap (min/max margin value) and controls when the margin value has reached one of those cap.
* Update margin value while the values are between the caps. In this point you have to implement an algorithm about what you want (parallax, linear, etc). That is what I'm calling THE_MAGIC_ECC in the next code:
public class MarginTopBehavior<V extends View> extends CoordinatorLayout.Behavior<V> {

    /**
     * Params of the component you want to modify the margin
     */
    private FrameLayout.LayoutParams mLayoutParams;
    /**
     * Used to access DIMENS in your project
     */
    private Context mContext;
    private int mMinYvalue;
    private int mMaxYValue;

    public MarginTopBehavior(Context context, AttributeSet attrs) {
        super(context, attrs);
        mContext = context;
    }

    @Override
    public boolean layoutDependsOn(CoordinatorLayout parent, View child, View dependency) {
        return dependency instanceof NestedScrollView;
    }

    @Override
    public boolean onDependentViewChanged(CoordinatorLayout parent, View child, View dependency) {

        if (mLayoutParams == null) {
            mLayoutParams = (FrameLayout.LayoutParams) child.getLayoutParams();
        }

        if (dependency.getY() <= mMinYvalue) {
            mLayoutParams.setMargins(0, 0, 0, 0);
            child.setLayoutParams(mLayoutParams);
            return true;
        }
        else if (dependency.getY() > mMinYvalue && dependency.getY() <= mMaxYValue) {
            int THE_MAGIC_ECC = 1 + 2 + 3;
            mLayoutParams.setMargins(0, 0, 0, THE_MAGIC_ECC );
            child.setLayoutParams(mLayoutParams);
            return true;
        }
        else {
            mLayoutParams.setMargins(0, 0, 0, 100);
            child.setLayoutParams(mLayoutParams);
            return true;
        }
    }
}


text:
Q: removing iterated string from string array I am writing a small script that lists the currently connected hard disks on my machine. I only need the disk identifier(disk0), not the partition ID(disk0s1, disk0s2, etc.)
How can I iterate through an array that contains diskID and partitionID and remove the partitionID entries? Here's what I'm trying so far:
    import os

    allDrives = os.listdir("/dev/")
    parsedDrives = []

    def parseAllDrives():
        parsedDrives = []
        matching = []
        for driveName in allDrives:
            if 'disk' in driveName:
                parsedDrives.append(driveName)
            else:
                continue
        for itemName in parsedDrives:
            if len(parsedDrives) != 0:
                if 'rdisk' in itemName:
                    parsedDrives.remove(itemName)
                else:
                    continue
            else:
                continue

#### this is where the problem starts: #####

        # iterate through possible partition identifiers
        for i in range(5):
            #create a string for the partitionID
            systemPostfix = 's' + str(i)
            matching.append(filter(lambda x: systemPostfix in x, parsedDrives))

        for match in matching:
            if match in parsedDrives:
                parsedDrives.remove(match)
                print("found a mactch and removed it")

        print("matched: %s" % matching)
        print(parsedDrives)

    parseAllDrives()

That last bit is just the most recent thing I've tried. Definitely open to going a different route.

A: try beginning with
allDrives = os.listdir("/dev/")
disks = [drive for drive in allDrives if ('disk' in drive)]

then, given disks id's are only 5-chars length
short_disks = [disk[:6] for disk in disks]
unique_short_disks = list(set(short_disks))


text:
Q: Interpreting statements in Lang's Undergraduate Algebra So, I've been reading this book and I've come across two sentences that I find a little confusing.

On pg. 109:
The polynomial ring $R[t]$ is generated by the variable $t$ over $R$, and $t$ is transcendental over $R$.
Context: $R[t]$ is the polynomial ring, and, for a fixed $x \in R$,  $R[x] = \{ f(x) : f \in R[t] \}$. $x$ is transcendental if $f \mapsto f(x)$ is an isomorphism from $R[t]$ to $R[x]$.
Problem: $t$ doesn't seem to be an element of $R$.

On pg. 117:
Let $F$ be a field and $\sigma : F[t] \rightarrow F[t]$ is an automorphism of the polynomial ring such that $\sigma$ restricts to the identity on $F$.
Problem: This seems to act as if $F \subset F[t]$?

Thanks the help.

A: From the comments above.

For the first question:
There is a problem with the definition you have of a transcendental element. You say that

[F]or a fixed $x\in R$, $R[x]=\{f(x):f\in R[t]\}$ [and] $x$ is transcendental if $f\mapsto f(x)$ is an isomorphism from $R[t]$ to $R[x]$.

I take it that $R[x]=\{f(x):f\in R[t]\}$ is meant to be a definition of $R[x]$, in which case it is quite restrictive. What should be said is that if $R$ and $S$ are rings with $R \subset S$, then for any fixed $x \in S$ we define $R[x] = \{ f(x) : f \in R[t] \}$. Now, $x \in S$ is said to be transcendental if $f \mapsto f(x)$ is an isomorphism from $R[t]$ to $R[x]$.
The earlier definition defined transcendence (over $R$) only on elements of $R$, which is inappropriate because no element of $R$ is transcendental over $R$.
For the second question:
There is a natural inclusion of $F$ inside $F[t]$, given by identifying $a \in F$ with the constant polynomial $at^0$. In this way we can view $F$ as a subset of $F[t]$.


text:
Q: Is there a significance to a matrix having an eigenvector equal to a column vector within a matrix? Consider matrix $A$:
$\begin{bmatrix}
2 & -2\\
3 & -3\\
\end{bmatrix}$
After little computing, we find the eigenvectors (and their corresponding eigenvalues) to be equal to
$E_{\lambda=0}=
\begin{bmatrix}
1\\
1\\
\end{bmatrix},\
E_{\lambda=-1}=
\begin{bmatrix}
2\\
3\\
\end{bmatrix}$
What, if any, is the significance of $\lambda$'s -1 eigenvector? I ask this because it is the same as the first column in the original matrix $A$ and I am curious to see if their is a specific set of parameters for this to occur and/or if this is significant in any way.

A: If you were to interpret the matrix as representing a "dynamical system" where the state after time $t$ had elapsed was given by $A^{t}x_0$ ($x_0$ the initial position), the eigenvector is where all states would eventually tend to. The reason your eigenvector is a column of the matrix is because all columns of the matrix are parallel - in general if we let $$A=\begin{bmatrix}c_0\textbf{x}&c_1\textbf{x}&\dots &c_n\textbf{x}\end{bmatrix}$$ ($\textbf{x}$ a vector) then for any input $y$ we will get $$A\textbf{y}=c\textbf{x}$$ for some constant $c$. Clearly then, $\textbf{x}$ will be an eigenvector of $A$ (and perhaps one of its columns!) because it will get sent to something parallel to itself.
Note however that there is nothing specifically significant per se about the eigenvector actually being a column. You could just as well have said that the eigenvector was $c\times\text{eigenvector}$ for any non-zero scalar and then it would not have been an actual column in the matrix.


text:
Q: MongoDB - Find and return all the items of an array in each document so I have this system where users can input tags, but i want to add suggestions/auto-complete with dynamic data from all the previous tags in the database.
Here's what the data looks like:
    collection = [
      {
        title: "Avengers",
        tags:["si-fi", "powers", "super-heroes", "iron-man"],
        ...
      },
      {
        title: "Lego Movie"
        tags:["spider-man", "bottle", "man of steel"],
        ...
      }
      ...
    ]

So I want to retreive an array of all the tags that match a search string.
For example, if I search with 'man', I want the data returned to be:
[
  "iron-man",
  "spider-man",
  "man of steel"
]

A: I think it cannot be done by direct querying. The following aggregation can do,
    db.collection.aggregate([{
        $unwind: '$tags'
    }, {
        $match: {
            'tags': { $regex: 'man' }
        }
    }, {
        $group: {
            _id: null,
            tags: { '$addToSet': '$tags' }
        }
    }]);

Hope this helps!


text:
Q: Uniqueness of the Interpolating Function Let's have the discrete periodic function $f(t)$ which has only 5 non-zero values $f(t_0) = -10, f(t_1) = -5, f(t_2) = -10, f(t_3) = -15$ and $f(t_4) = -10$, all other points within the period $[t_0,t_4]$ being zero. The obvious interpolating function which recovers these values is $f(t) = 5sin(t) - 10$. Is this a unique interpolating function or you can propose other interpolating functions, such as polynomial functions with constraints? Any concrete examples, please?

A: Your $f$ only interpolates these values if $t_i=\frac{i\pi}{2}$. Also, $f$ is clearly not zero at all the other points in $[t_0,t_4]$.
Moreover note that you can, for any finite number of value pairs $(t_i,v_i)_i$, find arbitrarily many smooth functions $F$ s.t. $F(t_i)=v_i$ for all $i$. Look for example at Lagrange polynomials/Newton polynomials etc. You can always change the function values in between the prescribed points so that your function is still continuous or even smooth.
When you drop the continuity/smoothness requirement (which you do if you say that it should have only 5 non-zero values) then finding an interpolation function is completely trivial (just take the function that is 0 everywhere except on the prescribed points where it takes the prescribed values). If you necessarily want to write it down as a formula you can always use a linear combination of Kronecker deltas:
$$f(t)=\sum_i y_i \delta^t_{t_i}.$$
where $(t_i,y_i)_i$ is your data and $\delta^t_s$ is 1 if $t=s$ and 0 if not.


text:
Q: DataGridView and BindingSource timer issue I have a DataGridview that displays the data and a TextBox that allows me to filter the BindingSource with an SQL query to display the data based on the input string. This is all working fine apart from once I have filtered the DataGridView the timer function I have is resetting it back so all the data is being displayed again. The timer is set on a 1000ms basis, so it will show the filtered result for a second, then revert back.
Heres my code:
Imports System.Data.OleDb

Public Class Form1

    Dim duraGadgetDB As String = "Provider=Microsoft.Jet.OLEDB.4.0; Data Source = C:\Users\Dave\Documents\duraGadget.mdb;"
    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Dim sql As String = "SELECT * FROM duragadget"
        Dim connection As New OleDbConnection(duraGadgetDB)
        Dim dataadapter As New OleDbDataAdapter(sql, connection)
        Dim ds As New DataSet()
        connection.Open()
        dataadapter.Fill(ds, "dura")
        connection.Close()
        DataGridView1.DataSource = ds
        DataGridView1.DataMember = "dura"
        DataGridView1.Columns(5).Width = 300
    End Sub

    Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
        insert.Show()
    End Sub

    Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
        Dim currentRowID As Integer
        Dim scrollPosition As Integer = DataGridView1.FirstDisplayedScrollingRowIndex
        Try
            If DataGridView1.CurrentRow IsNot Nothing Then

                currentRowID = DataGridView1.CurrentRow.Index

                Dim sql As String = "SELECT * FROM duragadget"
                Dim connection As New OleDbConnection(duraGadgetDB)
                Dim dataadapter As New OleDbDataAdapter(sql, connection)
                Dim ds As New DataSet()
                connection.Open()
                dataadapter.Fill(ds, "dura")
                connection.Close()
                DataGridView1.DataSource = ds
                DataGridView1.DataMember = "dura"
                DataGridView1.CurrentCell = DataGridView1.Item(1, currentRowID)
            End If
        Catch ex As Exception

        End Try
        DataGridView1.FirstDisplayedScrollingRowIndex = scrollPosition
    End Sub

    Private Sub txtSearchOnSku_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtSearchOnSku.TextChanged
        Dim currentRowID As Integer
        Dim scrollPosition As Integer = DataGridView1.FirstDisplayedScrollingRowIndex
        Try
            If DataGridView1.CurrentRow IsNot Nothing Then
                currentRowID = DataGridView1.CurrentRow.Index
                Dim sql As String = "SELECT * FROM duragadget"
                Dim connection As New OleDbConnection(duraGadgetDB)
                Dim dataadapter As New OleDbDataAdapter(sql, connection)
                Dim ds As New DataSet()
                Dim dsView As New DataView
                Dim bs As New BindingSource()
                connection.Open()
                dataadapter.Fill(ds, "dura")
                connection.Close()
                dsView = ds.Tables(0).DefaultView
                bs.DataSource = dsView
                bs.Filter = "skuNo LIKE'" & txtSearchOnSku.Text & "*'"
                DataGridView1.DataSource = bs
                DataGridView1.CurrentCell = DataGridView1.Item(1, currentRowID)
            End If
        Catch ex As Exception
        End Try
        DataGridView1.FirstDisplayedScrollingRowIndex = scrollPosition
    End Sub
End Class

Can anyone tell me how to stop this happening?

A: Assuming you mean that, if you have entered a value in your text box to filter your results, that you then don't want you timer to fire and unfilter them...
You can either, check the contents of the TextBox in the Timer1_Tick routine;
If txtSearchOnSku.Text <> "" Then Exit Sub

Or you can disable your timer in the txtSearchOnSku_TextChanged routine;
If txtSearchOnSku.Text <> "" Then
   Timer1.Stop
Else
   Timer1.Start
End If

Or, if you want to update your results once a second, based on you search, you can include the Filtering code in your Timer1_Tick routine.
As a quick point, you have alot of repeated code there. It may be worthwhile refactoring the repeated code out into another sub.


text:
Q: Microsoft Word formatting Strong format I want to replace Word formatting from Strong to simple text. It works with all formats except "Strong". Do you have any ideas?
Here is video.

A: In your example video you are searching for "Font: 29 pt" and replacing it with "Style: Normal".
Microsoft Word has two different types of style, "Paragraph style" and "Character style". If you right click a style and enter edit dialog you can see the type for each style:

The style "Normal" is a paragraph style. Setting a new paragraph style only replaces another paragraph style like "Heading 1".
"Strong" is a character style and can be applied on top of the current paragraph style. Setting a character style will not replace the paragraph style.
You can search like you do for "Font: 29 pt" and replace with "Font: Not Strong" (can be selected in the font dialog under style). This keeps font size and any other font attributes - except for font weight.


text:
Q: Which 3D object format is better with three.js If someone is working on a webgl-three.js context using many 3D objects (with textures,slight movement and mouse listeners) which format is more suitable to use to import them; JSON  or OBJMTL ?
I can make both work,I just want to know which is best before starting writting much code and then realize I should have done it that way.
NOTE: .obj and .mtl files seem to have much less information about the vertices etc than the .js files. is that a bad sign as far as the quality of rendering is concerned?

A: JSON is preferable.

*

*It is more concise and loading is faster

*Browser can load it directly into JavaScript data structures

*JSON format accommodates more than one material for a single mesh

*Three.js has a binary equivalent to its text-based JSON format


text:
Q: Using table 'as' across a join I am trying to find all of the skills a every user doesn't have for a position.
I know this is incorrect, but I can't think of a way to make this work.
This is what I'm trying to do:
select id, count(skillcode)
from person p, (
    select skillcode from requires_skill where poscode='1'
    minus
    select skillcode from hasskill where id=p.id)
group by p.id;

The part that isn't working is id=p.id.
I am using Oracle SQL.
Edit:
These are the sample tables
requires_skill
------------------
poscode | skillcode
-------------------
  1     |    2
  1     |    3
  1     |    4

hasskill
--------------------
id      | skillcode
--------------------
1       |    2
2       |    2
2       |    3

Expected output:
id    |    count(skillcode)
--------------------------
1     |     2
2     |     1

A: I think you need to JOIN the person and hasskill tables and use NOT EXISTS instead of MINUS.
Something like,
SELECT p.ID,
  COUNT(h.skillcode)
FROM person p
JOIN hasskill h
ON p.ID = h.ID
WHERE NOT EXISTS
  ( SELECT skillcode FROM requires_skill WHERE poscode='1'
  )
GROUP BY p.ID;

UPDATE
Regarding your question about the JOIN, you need to use an ALIAS for the sub-query.
For example,
WITH DATA AS
  ( SELECT skillcode FROM requires_skill WHERE poscode='1'
  MINUS
  SELECT skillcode FROM hasskill h, person p WHERE h.ID=p.ID
  )
SELECT p.ID,
  COUNT(a.skillcode)
FROM person p
JOIN data A
ON a.skillcode = p.skillcode
GROUP BY p.ID;

A: You can use scalar subquery like this
select id, (select count(1) from requires_skill) - cnt from (select id, count(1) cnt from hasskill group by id);

It works as long as there is foreign key relation ship between requires_skill and hasskill.


text:
Q: Initialize struct when declaring or in separate function I am working with a bunch of structs in C as I begin my GUI library. I am having a difficult time deciding how to initialize the structs. Here are the two cases:
#define GUI_CreateBox(PageName,x,y,z,w,h,color) \
  struct GUI_BOX BoxName = {x,y,z,w,h,color}

or
static void GUI_InitBox(struct GUI_BOX *box,uint32_t x, ... uint32_t color)
{
  init code
}

My question is, which one would use the least code space? I figured the function would be better. I wanted to use the define because it would be much faster than dereferencing the struct pointer a bunch of times. I just do not understand how the initialization of structs works and wanted a second opinion before I proceed.
What does everyone think?
Also some background info. I will be working on ARM Cortex M-4 devices. I want a nice library.

A: How many of these particular initializations will you be doing? How many variations on these initializations will you be doing?  That may affect what gives you the least code.  Which of these need to be applicable to variables at global (file) scope?  You can use the macro at file scope; you can't use the function at file scope — the function call must be made within the body of a function, which also leads to questions about "when is the variable initialized".
Note that the macro version means you write:
GUI_CreateBox(box1, 23, 45, 20, 30, 20, COLOUR_BLUE);

but the function version means you can write:
struct GUI_Box box2;
GUI_InitBox(&box2, 23, 45, 20, 30, 20, COLOUR_GREEN);
…some code using box2…
GUI_InitBox(&box2, 32, 54, 2, 3, 2, COLOUR_PURPLE);
…more code using box2…

That also leaves you an option of not initializing the structure; that may not be a good idea.
Your choice.  There isn't a lot to choose between them.
You might consider a compound literal too:
#define GUI_INITBOX(x, y, z, h, w, c) \
    (struct GUI_BOX){ .x = (x), .y = (y), .z = (z), .h = (h), .w = (w), .color = (c) }

Then you'd write:
struct GUI_BOX box1 = GUI_INITBOX(23, 45, 20, 30, 20, COLOUR_BLUE);

to declare and initialize, and you could write:
struct GUI_BOX box2;
…code…;
box2 = GUI_INITBOX(23, 45, 20, 30, 20, COLOUR_GREEN);

to assign (not initialize) box2 later.  Compound literals (and designated initializers) are part of C99 and hence also C11.

A: You have to consider the fact that you are not going to be initializing but once. As far as code size is concerned, since your initialization routine has ONLY assignments, the macro would be smaller. Also with the fact that you don't have to use a function call nor pass in a bunch or arguments, you save on your stack size and also your throughput.
But one main thing you would want to consider is how many people would be using your library. I've ran into this quite a few times when people use libraries which are comprised of a lot of macros. There is no protection (parameter type checking) for your arguments, which could obviously lead to bad object initialization.
For that point alone, I would always err on the side of safety and go with doing this inside a function, especially when you consider that
And while this doesn't apply to your example, if you plan on reusing a single parameter multiple times in a function like macro, you could get some unexpected side effects for people who prefer to do an operation in the argument.


text:
Q: Vim not showing numbering on side Hello and thanks in advance for looking over this.
I recently reset all of my settings for vim. I went back to edit the now empty .vimrc with numbering and it isn't working. Here's what I did:
vi ~/.vimrc
set number
set relativenumber

However no numbering appears in my vim editor. Any suggestions? Thank you for any help.
UPDATE
Solution found at this solution to solve the problem. Was using neovim for setup and it caused my init file to be empty


text:
Q: Using PyCrypto to calculate SHA256 hash of RSA public key I used OpenSSL to generate a 2048-bit RSA key:
openssl genrsa -out mykey.pem 2048
openssl rsa -pubout -in mykey.pem -out mypubkey.pub

I would like to use OpenSSL to calculate the SHA256 hash value of the public key (not the file, just the key)
I used the command: dgst -sha256 mypubkey.pub
The hash value generated by OpenSSL was:
876e4b63c2fa294c27e07c7449f5cb7ce2edae6deb74370440550700db67bbc3
Am I doing it right? As in getting the SHA256 hash value of the public key value and not the whole key file.
Also, how do I use PyCrypto to verify this?
The public key was:
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEApOa9doLz8vrN9aNfGf/m
iUT1czZz2PDWIVY5OtUXSB/Xm/26+QBKTR0si4vF2FW3rwn6ayBcYvGzsmtmwwA8
tfRWw78XrgeHevynKvZXVbsggI2gJqwPQr/xvmyfUrYj/EOgG72ryJo219dFJBCR
4gB6K/ZfIS8qLO4c4+z2WaXxZDDeur2X21UttTzIk878NT+VASmdt/avjsc7K5bD
Wu2Wmtg82LTPHCp56NgV08tMX9QUacidJzQ02eK1hWuDkpz1BRWXbE3Jas+sNBqN
mWMSRZ3sxMblQKNXVaXy/0IU9M5EHZEC135M2lHiumzJSZPs0pckjJFOTT2pTo2c
wQIDAQAB


text:
Q: Image embedded in Excel using POI but not showing I have created an excel file using POI and embedded image in it. its working fine. When i embed it in web application and deployed on apache tomcat server. Image is not showing up in excel file. Below is the code,
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet sheet = workbook.createSheet("Sheet1");
InputStream logo_image = new FileInputStream("C:\\Logo.jpg");
byte[] bytes = IOUtils.toByteArray(logo_image);
int picIndex = workbook.addPicture(bytes, Workbook.PICTURE_TYPE_JPEG);
logo_image.close();

HSSFPatriarch drawing = sheet.createDrawingPatriarch();

ClientAnchor my_anchor = new HSSFClientAnchor();
my_anchor.setCol1(0);
my_anchor.setRow1(1);
HSSFPicture my_picture = drawing.createPicture(my_anchor, picIndex);
my_picture.resize(.4);

FileOutputStream out = new FileOutputStream(new File( "C:\\image_example1.xls"));
workbook.write(out);
out.close();

Note: It is working on 1 tomcat instance but on another machine excel is being generated but image is not embedded.
I have tried adding my_anchor.setCol12(2);my_anchor.setRow2(0); as well, but no help.


text:
Q: Ограничение с помощью условных операторов Например, есть следующее:
echo 1;
echo 2;
echo 3;
echo 4;

Какими средствами, можно вывести только 2 первых echo, т.е 1 и 2?
A: <?php
$a = 1;
$b = 2;
if ($a+$a == $b) {
 echo 'fv allow';
} else {
if ($b-$a == $a-$a) {
 echo 'sv allow';
} else {
if ($a+$b*2 == 10) {
 echo 'tv allow';
}
}
}
?>

Например так, меняем значение переменных чтобы выполнялись разные условия.
A: удалить
echo 3;
echo 4;
Это же очевидно!
A: Если надо вывести 2 из 4-х, то два отсеиваются в любом случае по какому-то условию. А раз есть условие, то имеет место if


text:
Q: How to connect JMS queues from JBOSS 4 and 5? I have a server on which a Jboss 4.2.2 and a Jboss 5.1.0 runs. The problem is that a 3rd party is not able to upgrade its application to Jboss 5.1.0 in the near future, for us it is a simple matter. Unfortunately we need to send and receive some JMS messages from the third party app running on Jboss 4.2.2.
What is the easiest way to enable the transfer of JMS messages between JbossMQ and JbossMessaging?

A: I think I found the solution for my problem. The JBOSS documentation has a chapter to migrate messages between JBOSS Messaging and JBOSS MQ: http://www.redhat.com/docs/en-US/JBoss_Enterprise_Application_Platform/5.0.0.BETA/html/JBoss_Messaging_User_Guide/inst-mqmessagemigration.html
I have 2 topics myTopicSend and myTopicReceive on my JBOSS 4.2 and I have 2 topics myTopicSend5 and myTopicReceive5 on JBOSS 5.1.
I wanted to bridge all messages from myTopicSend to myTopicReceive5 and from myTopicSend5 to MyTopicReceive.
Somehow the configuration didn't work at all first, but after some time of experimenting I have now the following config:
<mbean code="org.jboss.jms.jndi.JMSProviderLoader"
       name="jboss.messaging:service=JMSProviderLoader,name=RemoteJBossMQProvider">
    <attribute name="ProviderName">RemoteXAConnectionFactory</attribute>
    <attribute name="ProviderAdapterClass">org.jboss.jms.jndi.JNDIProviderAdapter</attribute>
    <attribute name="FactoryRef">XAConnectionFactory</attribute>
    <attribute name="QueueFactoryRef">XAConnectionFactory</attribute>
    <attribute name="TopicFactoryRef">XAConnectionFactory</attribute>
    <attribute name="Properties">
        java.naming.factory.initial=org.jnp.interfaces.NamingContextFactory
        java.naming.factory.url.pkgs=org.jboss.naming:org.jnp.interfaces
        java.naming.provider.url=127.0.0.1:1099
    </attribute>
</mbean>

<mbean code="org.jboss.jms.server.bridge.BridgeService"
       name="jboss.messaging:service=Bridge,name=LegayBridgeSend" xmbean-dd="xmdesc/Bridge-xmbean.xml">
    <depends optional-attribute-name="SourceProviderLoader">jboss.messaging:service=JMSProviderLoader,name=RemoteJBossMQProvider</depends>
    <depends optional-attribute-name="TargetProviderLoader">jboss.messaging:service=JMSProviderLoader,name=JMSProvider</depends>
    <attribute name="SourceDestinationLookup">/topic/myTopicSend</attribute>
    <attribute name="TargetDestinationLookup">/topic/myTopicReceive5</attribute>
    <attribute name="QualityOfServiceMode">0</attribute>
    <attribute name="MaxBatchSize">1</attribute>
    <attribute name="MaxBatchTime">-1</attribute>
    <attribute name="FailureRetryInterval">5000</attribute>
    <attribute name="MaxRetries">-1</attribute>
    <attribute name="AddMessageIDInHeader">false</attribute>
</mbean>

<mbean code="org.jboss.jms.server.bridge.BridgeService"
       name="jboss.messaging:service=Bridge,name=LegayBridgeReceive" xmbean-dd="xmdesc/Bridge-xmbean.xml">
    <depends optional-attribute-name="SourceProviderLoader">jboss.messaging:service=JMSProviderLoader,name=JMSProvider</depends>
    <depends optional-attribute-name="TargetProviderLoader">jboss.messaging:service=JMSProviderLoader,name=RemoteJBossMQProvider</depends>
    <attribute name="SourceDestinationLookup">/topic/myTopicSend5</attribute>
    <attribute name="TargetDestinationLookup">/topic/myTopicReceive</attribute>
    <attribute name="QualityOfServiceMode">0</attribute>
    <attribute name="MaxBatchSize">1</attribute>
    <attribute name="MaxBatchTime">-1</attribute>
    <attribute name="FailureRetryInterval">5000</attribute>
    <attribute name="MaxRetries">-1</attribute>
    <attribute name="AddMessageIDInHeader">false</attribute>
</mbean>

A important thing I realized was, to tweak the MaxBatchSize and MaxBatchTime parameters, because I want to deliver the messages immediately to the target queue.
A description of these parameters may be found at http://www.redhat.com/docs/en-US/JBoss_Enterprise_Application_Platform/5.0.0/html/JBoss_Messaging_1.4.6/index.html


text:
Q: Error when trying to access index.php in a mediawiki server I'm running an apache server and a mysql db with docker composer. I do have connection with the server but i keep getting this error when i try to access index.php (so i can configure my MediaWiki page):

Fatal error: Uncaught Error: Call to a member function getCode() on null in /var/www/html/includes/user/User.php on line 1578

I've checked User.php but everything seems fine.
error i get in the browser
    $defOpt = $wgDefaultUserOptions;
    // Default language setting
    $defOptLang = $wgContLang->getCode();
    $defOpt['language'] = $defOptLang;
    foreach ( LanguageConverter::$languagesWithVariants as $langCode ) {
        $defOpt[$langCode == $wgContLang->getCode() ? 'variant' : "variant-$langCode"] = $langCode;
    }

Someone can give me a hand here? Thanks

A: I solved the issue installing an clean version of apache and mediawiki (same version as the old) and later exporting the old apache2_conf/ directory to the new /etc/apache2/ directory, after this, I migrated the MySQL DB.


text:
Q: Get more details from exception Trying to run Google spreadsheets sample application.
Got exception while uploading credentials:
try:
    creds = store.get()
except Exception as e:
    print(e)
    print("exception end")

Strange is fact that only line _module was printed while executing Exception code block.
How to understand what exactly was wrong?
What does _module means?
Whole code:
from __future__ import print_function
from googleapiclient.discovery import build
from httplib2 import Http
from oauth2client import file, client, tools

# If modifying these scopes, delete the file token.json.
SCOPES = 'https://www.googleapis.com/auth/spreadsheets.readonly'

# The ID and range of a sample spreadsheet.
SAMPLE_SPREADSHEET_ID = '1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms'
SAMPLE_RANGE_NAME = 'Class Data!A2:E'

def main():

    print("starting")
    """Shows basic usage of the Sheets API.
    Prints values from a sample spreadsheet.
    """
    #store = file.Storage('token.json')
    store = file.Storage('D:\pyth_nonsens\workspace_python\PyhonTutorial\google\credentials.json')

    #store = file.Storage('My Project aaa-8102e33b9fef.json')
    try:
        creds = store.get()
    except Exception as e:
        print(e)
        print("exception end")

    if not creds or creds.invalid:
        flow = client.flow_from_clientsecrets('credentials.json', SCOPES)
        creds = tools.run_flow(flow, store)
    service = build('sheets', 'v4', http=creds.authorize(Http()))

    # Call the Sheets API
    SPREADSHEET_ID = '1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms'
    RANGE_NAME = 'Class Data!A2:E'
    result = service.spreadsheets().values().get(spreadsheetId=SPREADSHEET_ID,
                                                range=RANGE_NAME).execute()
    values = result.get('values', [])

    if not values:
        print('No data found.')
    else:
        print('Name, Major:')
        for row in values:
            # Print columns A and E, which correspond to indices 0 and 4.
            print('%s, %s' % (row[0], row[4]))

print(__name__)
if __name__ == 'test_spread':
    print("true")
    main()


text:
Q: Преобразовать строку в число? C++/CLI Всем привет, есть textBox я с него получаю данные таким методом:
String^S1 = textBox1->Text;
Дальше чтобы перевести в число я использую x = Convert::ToInt32(S2);
Но у меня получается int`овское значение, и при вводе float я получаю ошибку, как конвертировать в тип float?

A: Для парсинга чисел с плавающей точкой в .NET есть Double::Parse и TryParse. Аналогично для Single (который синоним float)


text:
Q: Planning to get started code coverage tool Looking for books or other references that discuss actually to write a code coverage tool in Java; some of the various techniques or tricks - source vs. byte code instrumentation. This is for a scripting language that generates java byte code under the hood.
Any Help would appreciated in advance.
Thanks

A: See the paper "Branch Coverage for Arbitrary Languages Made Easy" at http://www.semanticdesigns.com/Company/Publications/TestCoverage.pdf


text:
Q: How to avoid Java system properties on command line? I have a Java program and it uses user.home system property to get user home directory.
This program should not allow user.home property on command line. If user pass wrong directory from command line for user.home (java -Duser.home) then my program will have security hole.
So how can I restrict user.home from command line and it should uses only through program?

A: It is not possible to guarantee that user.home is set correctly.
user.home is initialized from the $HOME environment variable if it isn't passed directly to the JVM.
It isn't possible to prevent a user from modifying their own environment.


text:
Q: How to deal with "Too many load/unload tasks running: try again later I have tried the fastload and it worked all right the first time .   When I ran it the second time i got Too many load/unload tasks running: try again later . Then   I closed the connection and tried again and it worked .
Then i tried to replicate everything again to check whether closing connection deals with Too many load/unload tasks running: try again later and was not able to fastload .
Does closing connection guarantee no problem with Too many load/unload tasks running: try again later  ?  If no , then what does ?  Is there any command that deletes ALL miltithread loads associated with the Connection so that one can proceed with fastload without this error ?

A: Depending on the database version Teradata constrains the number of concurrent load utilities that are permitted to run. In releases prior to Teradata 13 or 13.10 this limit was managed in the DBS Controls. Starting with Teradata 13 or 13.10 utilities limits were managed by Workload Management ruleset via Viewpoint.
It is not uncommon for load utilities to be further constrained during the time period which is reserved for end users or the business.Something else that may come into play is whether you are running on an Appliance or an Enterprise class system which you haven't indicated.
If you are not the DBA of the environment I would suggest consulting with the DBA responsible for the environment.


text:
Q: External Table on DELTA format files in ADLS Gen 1 We have number of databricks DELTA tables created on ADLS Gen1. and also, there are external tables built on top each of those tables  in one of the databricks workspace.
similarly, I am trying to create same sort of external tables on the same DELTA format files,but in different workspace.
I do have read only access via Service principle on ADLS Gen1. So I can read DELTA files through spark data-frames, as in given below:
read_data_df = spark.read.format("delta").load('dbfs:/mnt/data/<foldername>')

I can even able to create hive external tables, but I do see following warning while reading data from the same table:

Error in SQL statement: AnalysisException: Incompatible format detected.

A transaction log for Databricks Delta was found at `dbfs:/mnt/data/<foldername>/_delta_log`,
but you are trying to read from `dbfs:/mnt/data/<foldername>` using format("hive"). You must use
'format("delta")' when reading and writing to a delta table.

To disable this check, SET spark.databricks.delta.formatCheck.enabled=false
To learn more about Delta, see https://learn.microsoft.com/azure/databricks/delta/index
;

If I create external table 'using DELTA', then I see a different access error as in:
Caused by: org.apache.hadoop.security.AccessControlException:
OPEN failed with error 0x83090aa2 (Forbidden. ACL verification failed.
Either the resource does not exist or the user is not authorized to perform the requested operation.).
failed with error 0x83090aa2 (Forbidden. ACL verification failed.
Either the resource does not exist or the user is not authorized to perform the requested operation.).

Does it mean that I would need full access, rather just READ ONLY?, on those underneath file system?
Thanks

A: Resolved after upgrading to Databricks Runtime environment to  runtime version DBR-7.3.


text:
Q: String or binary data would be truncated - large strings We have an extremely large nvarchar(max) field that contains html. Within this html is an img tag.
Example:
<img style="float:right" src="data:image/png;base64,/9j/4AAQSkZJRgABAQEBLAEsAAD/7gAOQW....

The length of this column is 1645151, although what is being replace is a bit less than this, but not a lot.
What we are trying to do, is a replace in SQL on the column:
declare @url varchar(50) = 'myimageurl';
UPDATE table SET field =
CAST(REPLACE(CAST(field as NVARCHAR(MAX)),@source,'@url') AS NVARCHAR(MAX))

Where @source, is the above image bytes as string, which are assigned to an nvarchar(max) variable before running the replace. and dest is the url of an image, rather than the images bytes as string.
Although I still get the message string or binary data would be truncated.
Does anyone know if this is possible in SQL to replace strings as large as this.

A: I had the same error, but on a different function.
The fault was that my pattern has longer than my expression, which means that your search pattern will be truncated.
I hope this helps someone.
Also, make sure you put pattern and expression in the right location of your function.

A: Instead of doing the replace, can you rebuilt the entire field by parsing out the rest of the img tag?
Something like:
declare @Field nvarchar(max) = ''
declare @Source nvarchar(max) = 'data:image/png;base64,/9j/4AAQSkZJRgA....BAQEBLAEsAAD/7gAOQW'
declare @URL nvarchar(max) = 'www.img.img/img.png'
declare @Chars int = 20

select left(@Field,patindex('%' + left(@Source,@Chars) + '%', @Field) - 1) as HTMLStart
        ,@URL as ImgURL
        ,right(@Field,len(@Field) - patindex('%' + right(@Source,@Chars) + '%', @Field) - @Chars + 1) as HTMLEnd

If you were wanting to run this on a whole dataset at once, you would simply need to look for the src="data:image/png;base64, element and work backwards from there using a similar methodology to the above.  Depends on how you are identifying which binary data to replace and what to replace it with.


text:
Q: "Use Theme.AppCompat theme with this activity" Exception I used recently Android Asset Studio to generate a custom Action bar theme for an app and when I placed everything in my project the app crashes with this exception:

java.lang.IllegalStateException: You need to use a Theme.AppCompat theme (or descendant) with this activity.

This is the code in my style.xml:
<resources>

    <style name="Theme.Blinkmessage" parent="@android:style/Theme.Holo.Light">
        <item name="android:actionBarItemBackground">@drawable/selectable_background_blinkmessage</item>
        <item name="android:popupMenuStyle">@style/PopupMenu.Blinkmessage</item>
        <item name="android:dropDownListViewStyle">@style/DropDownListView.Blinkmessage</item>
        <item name="android:actionBarTabStyle">@style/ActionBarTabStyle.Blinkmessage</item>
        <item name="android:actionDropDownStyle">@style/DropDownNav.Blinkmessage</item>
        <item name="android:actionBarStyle">@style/ActionBar.Solid.Blinkmessage</item>
        <item name="android:actionModeBackground">@drawable/cab_background_top_blinkmessage</item>
        <item name="android:actionModeSplitBackground">@drawable/cab_background_bottom_blinkmessage</item>
        <item name="android:actionModeCloseButtonStyle">@style/ActionButton.CloseMode.Blinkmessage</item>

    </style>

    <style name="ActionBar.Solid.Blinkmessage" parent="@android:style/Widget.Holo.Light.ActionBar.Solid">
        <item name="android:background">@drawable/ab_solid_blinkmessage</item>
        <item name="android:backgroundStacked">@drawable/ab_stacked_solid_blinkmessage</item>
        <item name="android:backgroundSplit">@drawable/ab_bottom_solid_blinkmessage</item>
        <item name="android:progressBarStyle">@style/ProgressBar.Blinkmessage</item>
    </style>

    <style name="ActionBar.Transparent.Blinkmessage" parent="@android:style/Widget.Holo.Light.ActionBar">
        <item name="android:background">@drawable/ab_transparent_blinkmessage</item>
        <item name="android:progressBarStyle">@style/ProgressBar.Blinkmessage</item>
    </style>

    <style name="PopupMenu.Blinkmessage" parent="@android:style/Widget.Holo.Light.ListPopupWindow">
        <item name="android:popupBackground">@drawable/menu_dropdown_panel_blinkmessage</item>
    </style>

    <style name="DropDownListView.Blinkmessage" parent="@android:style/Widget.Holo.Light.ListView.DropDown">
        <item name="android:listSelector">@drawable/selectable_background_blinkmessage</item>
    </style>

    <style name="ActionBarTabStyle.Blinkmessage" parent="@android:style/Widget.Holo.Light.ActionBar.TabView">
        <item name="android:background">@drawable/tab_indicator_ab_blinkmessage</item>
    </style>

    <style name="DropDownNav.Blinkmessage" parent="@android:style/Widget.Holo.Light.Spinner">
        <item name="android:background">@drawable/spinner_background_ab_blinkmessage</item>
        <item name="android:popupBackground">@drawable/menu_dropdown_panel_blinkmessage</item>
        <item name="android:dropDownSelector">@drawable/selectable_background_blinkmessage</item>
    </style>

    <style name="ProgressBar.Blinkmessage" parent="@android:style/Widget.Holo.Light.ProgressBar.Horizontal">
        <item name="android:progressDrawable">@drawable/progress_horizontal_blinkmessage</item>
    </style>

    <style name="ActionButton.CloseMode.Blinkmessage" parent="@android:style/Widget.Holo.Light.ActionButton.CloseMode">
        <item name="android:background">@drawable/btn_cab_done_blinkmessage</item>
    </style>

    <!-- this style is only referenced in a Light.DarkActionBar based theme -->
    <style name="Theme.Blinkmessage.Widget" parent="@android:style/Theme.Holo">
        <item name="android:popupMenuStyle">@style/PopupMenu.Blinkmessage</item>
        <item name="android:dropDownListViewStyle">@style/DropDownListView.Blinkmessage</item>
    </style>

    <style name="AuthBackground">
        <item name="android:background">@mipmap/background_fill</item>
    </style>

    <style name="AuthBackgroundImage">
        <item name="android:layout_width">match_parent</item>
        <item name="android:layout_height">match_parent</item>
        <item name="android:layout_alignParentTop">true</item>
        <item name="android:layout_alignParentLeft">true</item>
        <item name="android:background">@mipmap/background</item>
        <item name="android:scaleType">fitStart</item>
        <item name="android:contentDescription">@string/content_desc_background</item>
    </style>

    <style name="AuthTitle">
        <item name="android:layout_width">wrap_content</item>
        <item name="android:layout_height">wrap_content</item>
        <item name="android:textAppearance">?android:attr/textAppearanceLarge</item>
        <item name="android:layout_alignParentTop">true</item>
        <item name="android:layout_centerHorizontal">true</item>
        <item name="android:textSize">50sp</item>
        <item name="android:textStyle">bold</item>
        <item name="android:textColor">@android:color/white</item>
        <item name="android:layout_marginTop">32dp</item>
    </style>

    <style name="AuthSubtitle" parent="AuthTitle">
        <item name="android:textStyle">bold</item>
        <item name="android:textSize">13sp</item>
        <item name="android:layout_alignParentTop">false</item>
        <item name="android:layout_below">@+id/title</item>
        <item name="android:layout_marginTop">0dp</item>
    </style>

    <style name="AuthFiledContainer">
        <item name="android:layout_width">match_parent</item>
        <item name="android:layout_height">wrap_content</item>
        <item name="android:layout_below">@id/subTitle</item>
        <item name="android:layout_marginTop">@dimen/login_vertical_margin</item>
        <item name="android:layout_marginLeft">@dimen/activity_horizontal_margin</item>
        <item name="android:layout_marginRight">@dimen/activity_horizontal_margin</item>
        <item name="android:background">@android:color/white</item>
        <item name="android:paddingLeft">@dimen/login_horizontal_padding</item>
        <item name="android:paddingRight">@dimen/login_horizontal_padding</item>
        <item name="android:paddingTop">@dimen/activity_horizontal_margin</item>
        <item name="android:paddingBottom">@dimen/activity_horizontal_margin</item>
        <item name="android:orientation">vertical</item>
    </style>

    <style name="AuthEditText">
        <item name="android:layout_width">match_parent</item>
        <item name="android:layout_height">wrap_content</item>
        <item name="android:textColorHint">@color/light_gray</item>
        <item name="android:textSize">17sp</item>
    </style>

    <style name="AuthButton">
        <item name="android:layout_width">match_parent</item>
        <item name="android:layout_height">wrap_content</item>
        <item name="android:background">@drawable/button_custom</item>
        <item name="android:layout_marginLeft">@dimen/activity_horizontal_margin</item>
        <item name="android:layout_marginRight">@dimen/activity_horizontal_margin</item>
        <item name="android:textSize">13sp</item>
        <item name="android:textColor">@color/text_color</item>
        <item name="android:layout_centerHorizontal">true</item>
    </style>
</resources>

and this is the code in my manifest file:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="koemdzhiev.com.blinkmessage" >

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

    <uses-feature
        android:name="android.hardware.camera"
        android:required="true" />

    <application
        android:name=".RibbitApplication"
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/Theme.Blinkmessage" >
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name"
            android:screenOrientation="portrait"
            android:theme="@style/Theme.Blinkmessage">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name=".LoginActivity"
            android:label="@string/title_activity_login"
            android:screenOrientation="portrait" >
        </activity>
        <activity
            android:name=".SignUpActivity"
            android:label="@string/title_activity_sign_up"
            android:parentActivityName=".LoginActivity"
            android:screenOrientation="portrait" >
        </activity>

        <meta-data
            android:name="com.google.android.gms.version"
            android:value="@integer/google_play_services_version" />

        <activity
            android:name=".EditFriendsActivity"
            android:label="@string/title_activity_edit_friends"
            android:parentActivityName=".MainActivity"
            android:screenOrientation="portrait" >
            <meta-data
                android:name="android.support.PARENT_ACTIVITY"
                android:value="koemdzhiev.com.blinkmessage.MainActivity" />
        </activity>
        <activity
            android:name=".RecipientsActivity"
            android:label="@string/title_activity_recipients"
            android:parentActivityName=".MainActivity"
            android:screenOrientation="portrait"
            android:theme="@android:style/Theme.Holo.Light.DarkActionBar" >
            <meta-data
                android:name="android.support.PARENT_ACTIVITY"
                android:value="koemdzhiev.com.blinkmessage.MainActivity" />
        </activity>
        <activity
            android:name=".ViewImageActivity"
            android:label="@string/title_activity_view_image"
            android:screenOrientation="portrait"
            android:parentActivityName=".MainActivity" >
            <meta-data
                android:name="android.support.PARENT_ACTIVITY"
                android:value="koemdzhiev.com.blinkmessage.MainActivity" />
        </activity>
    </application>

</manifest>

main activity:
public class MainActivity extends ActionBarActivity implements ActionBar.TabListener {
public static final int TAKE_PHOTO_REQUEST = 0;
public static final int TAKE_VIDEO_REQUEST = 1;
public static final int PICK_PHOTO_REQUEST = 2;
public static final int PICK_VIDEO_REQUEST = 3;
public static final int FILE_SIZE_LIMIT = 1024 * 1024 * 10;

public static final int MEDIA_TYPE_IMAGE = 4;
public static final int MEDIA_TYPE_VIDEO = 5;

// media path as Uri (Uniform resource unifier) unify system resorses
protected Uri mMediaUri;

protected DialogInterface.OnClickListener mDialogListener = new DialogInterface.OnClickListener() {
    @Override
    public void onClick(DialogInterface dialog, int which) {
        switch (which){
            case 0:  //Take picture
                Intent takePhotoIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                mMediaUri = getOutputMediaFileUrl(MEDIA_TYPE_IMAGE);
                if(mMediaUri == null){
                    // display an error
                    Toast.makeText(MainActivity.this,getString(R.string.error_external_storage),Toast.LENGTH_LONG).show();
                }
                takePhotoIntent.putExtra(MediaStore.EXTRA_OUTPUT,mMediaUri);
                startActivityForResult(takePhotoIntent, TAKE_PHOTO_REQUEST);
                break;
            case 1: //Take video
                    Intent videoIntent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
                    mMediaUri = getOutputMediaFileUrl(MEDIA_TYPE_VIDEO);
                if(mMediaUri == null){
                    // display an error
                    Toast.makeText(MainActivity.this,getString(R.string.error_external_storage),Toast.LENGTH_LONG).show();
                }
                videoIntent.putExtra(MediaStore.EXTRA_OUTPUT,mMediaUri);
                videoIntent.putExtra(MediaStore.EXTRA_DURATION_LIMIT,10);
                videoIntent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY,0);
                startActivityForResult(videoIntent,TAKE_VIDEO_REQUEST);
                break;
            case 2://Choose picture
                Intent choosePhotoIntent = new Intent(Intent.ACTION_GET_CONTENT);
                choosePhotoIntent.setType("image/*");
                startActivityForResult(choosePhotoIntent,PICK_PHOTO_REQUEST);

                break;
            case 3:   //Choose video
                Intent chooseVideoIntent = new Intent(Intent.ACTION_GET_CONTENT);
                chooseVideoIntent.setType("video/*");
                Toast.makeText(MainActivity.this,getString(R.string.video_size_warning),Toast.LENGTH_LONG).show();
                startActivityForResult(chooseVideoIntent, PICK_VIDEO_REQUEST);
                break;
        }
    }

    private Uri getOutputMediaFileUrl(int mediaType) {
        if(isExternalStoreageAvailable()){
            //get URI

            // 1. Get the external storage directory
            String appName = MainActivity.this.getString(R.string.app_name);
            File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
                                        appName);
            Log.d(TAG,mediaStorageDir + "");
            // 2. Create our subdirectory
            if(! mediaStorageDir.exists()){
                //creates directory. IF it fails returns false otherwise it creates the directory and returns true
                if(! mediaStorageDir.mkdirs()){
                    Log.e(TAG,"Failer to create directory");
                    return null;
                };
            }
            // 3. Create a file name
            // 4. Create the file
            File mediaFile;
            Date now = new Date();
            String timestamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.UK).format(now);
            String path = mediaStorageDir.getPath() + File.separator;
            if(mediaType == MEDIA_TYPE_IMAGE){
                mediaFile = new File(path + "IMG_" + timestamp + ".jpg");
            }else if (mediaType == MEDIA_TYPE_VIDEO){
                mediaFile = new File(path + "VID_" + timestamp + ".mp4");
            }else{
                return null;
            }

            // 5. Return the file's uri
            Log.d(TAG,"File: " + Uri.fromFile(mediaFile));
            return Uri.fromFile(mediaFile);
        }else{
            return null;
        }

    }

    private boolean isExternalStoreageAvailable(){
        String state = Environment.getExternalStorageState();
        if(state.equals(Environment.MEDIA_MOUNTED)){
            return true;
        }else{
            return false;
        }
    }
};

private static final String TAG = AppCompatActivity.class.getSimpleName();
/**
 * The {@link android.support.v4.view.PagerAdapter} that will provide
 * fragments for each of the sections. We use a
 * {@link FragmentPagerAdapter} derivative, which will keep every
 * loaded fragment in memory. If this becomes too memory intensive, it
 * may be best to switch to a
 * {@link android.support.v4.app.FragmentStatePagerAdapter}.
 */
SectionsPagerAdapter mSectionsPagerAdapter;

/**
 * The {@link ViewPager} that will host the section contents.
 */
ViewPager mViewPager;

@Override
protected void onCreate(Bundle savedInstanceState) {
    //start it here to be available in the Fragment's activity too
    supportRequestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_main);
    ParseUser currentUser = ParseUser.getCurrentUser();
    if(currentUser == null) {
        navigateToLogin();

    }else{
        Log.i(TAG,currentUser.getUsername());
    }
    // Set up the action bar.
    final ActionBar actionBar = getSupportActionBar();
    actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
    actionBar.setTitle("        Blink Message");
    actionBar.setLogo(R.mipmap.ic_launcher);
    actionBar.setDisplayUseLogoEnabled(true);
    actionBar.setDisplayShowHomeEnabled(true);

    // Create the adapter that will return a fragment for each of the three
    // primary sections of the activity.
    mSectionsPagerAdapter = new SectionsPagerAdapter(this,getSupportFragmentManager());

    // Set up the ViewPager with the sections adapter.
    mViewPager = (ViewPager) findViewById(R.id.pager);
    mViewPager.setAdapter(mSectionsPagerAdapter);

    // When swiping between different sections, select the corresponding
    // tab. We can also use ActionBar.Tab#select() to do this if we have
    // a reference to the Tab.
    mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
        @Override
        public void onPageSelected(int position) {
            actionBar.setSelectedNavigationItem(position);
        }
    });

    // For each of the sections in the app, add a tab to the action bar.
    for (int i = 0; i < mSectionsPagerAdapter.getCount(); i++) {
        // Create a tab with text corresponding to the page title defined by
        // the adapter. Also specify this Activity object, which implements
        // the TabListener interface, as the callback (listener) for when
        // this tab is selected.
        actionBar.addTab(
                actionBar.newTab()
                        .setText(mSectionsPagerAdapter.getPageTitle(i))
                        .setTabListener(this));
    }
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if(resultCode == RESULT_OK){
        // if we pick a photo or video store the uri
        if(requestCode == PICK_PHOTO_REQUEST || requestCode == PICK_VIDEO_REQUEST){
            if(data == null){
                Toast.makeText(this,R.string.general_error,Toast.LENGTH_LONG).show();
            }else{
                mMediaUri = data.getData();
            }
             Log.i(TAG,"Media path: "+mMediaUri);
            if(requestCode == PICK_VIDEO_REQUEST){
                //ckech the size of the video - less than 10 MB

                int fileSize = 0;
                InputStream inputStream = null;
                try {
                    inputStream = getContentResolver().openInputStream(mMediaUri);
                    fileSize = inputStream.available();
                }catch (FileNotFoundException e){
                    Toast.makeText(this,getString(R.string.error_open_file),Toast.LENGTH_LONG).show();
                    return;
                }catch (IOException e){
                    Toast.makeText(this,getString(R.string.error_open_file),Toast.LENGTH_LONG).show();
                    return;
                }finally {
                    try {
                        inputStream.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    if(fileSize >= FILE_SIZE_LIMIT){
                        Toast.makeText(this,getString(R.string.file_too_large),Toast.LENGTH_LONG).show();
                        //return to the activity
                        return;
                    }
                }

            }
        }
        //else add it to the gallery
        else {
            //successful add it to the gallery
            Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
            mediaScanIntent.setData(mMediaUri);
            sendBroadcast(mediaScanIntent);
        }

        Intent recipientsIntent = new Intent(this,RecipientsActivity.class);
        recipientsIntent.setData(mMediaUri);
        String fileType;
        if(requestCode == PICK_PHOTO_REQUEST || requestCode == TAKE_PHOTO_REQUEST){
            fileType = ParseConstants.TYPE_IMAGE;
        }else{
            fileType = ParseConstants.TYPE_VIDEO;
        }
        recipientsIntent.putExtra(ParseConstants.KEY_FILE_TYPE,fileType);
        startActivity(recipientsIntent);

    }else if(resultCode != RESULT_CANCELED){
        Toast.makeText(this,getString(R.string.general_error),Toast.LENGTH_LONG).show();
    }
}

private void navigateToLogin() {
    Intent intent = new Intent(this,LoginActivity.class);
    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
    startActivity(intent);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();
    switch (id){
        case R.id.action_logout:
            ParseUser.logOut();
            navigateToLogin();
            break;
        case R.id.action_edit_friends:
            Intent intent = new Intent(this,EditFriendsActivity.class);
            startActivity(intent);
            break;
        case R.id.action_camera:
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setItems(R.array.camera_choices,mDialogListener);
            AlertDialog dialog = builder.create();
            dialog.show();
            break;
    }
    //noinspection SimplifiableIfStatement

    return super.onOptionsItemSelected(item);
}
//-----------ActionBar.TabListener methods-------------------//
@Override
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
    // When the given tab is selected, switch to the corresponding page in
    // the ViewPager.
    mViewPager.setCurrentItem(tab.getPosition());
}

@Override
public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}

@Override
public void onTabReselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}

A: You should use Theme.AppCompat theme (or descendant) as parent for your theme.
<style name="Theme.Blinkmessage" parent="Theme.AppCompat">

A: change the parent of your Theme.BlinkMessage to Theme.AppCompat.Light. This should fix your :
<style name="Theme.Blinkmessage" parent="Theme.AppCompat.Light">


text:
Q: How to create an elasticsearch k/v json field I have the following json object:
{
    "AVAILED_NOT_LIVE": {
        "ExceptionType": "Avail'd - Not Live",
        "ExceptionReason": "Clear For Rent",
        "ExpectedValue": "Cleared for VOD (Yes)",
        "FoundValue": "Cleared for VOD (No)"
    },
    "LIVE_NOT_AVAILED": {
        "ExceptionType": "Live - Not Avail'd",
        "ExceptionReason": "--",
        "ExpectedValue": "No",
        "FoundValue": "Yes"
    }
}

How would I create an index for this field? So far I have:
"properties": {
    "ExceptionType": { "type": "text" },
    "ExceptionReason": { "type": "text" },
    "ExpectedValue": { "type": "text" },
    "FoundValue": { "type": "text" },

 },

But this is missing the key (AVAILED_NOT_LIVE, LIVE_NOT_AVAILED), that may have various values. How would I dot hat mapping?

A: Generally I'd just insert a document and then customize the generated dynamic mapping:
Your 2 initial requests:
PUT /foo/_doc/1
{
  "AVAILED_NOT_LIVE": {
    "ExceptionType": "Avail'd - Not Live",
    "ExceptionReason": "Clear For Rent",
    "ExpectedValue": "Cleared for VOD (Yes)",
    "FoundValue": "Cleared for VOD (No)"
  },
  "LIVE_NOT_AVAILED": {
    "ExceptionType": "Live - Not Avail'd",
    "ExceptionReason": "--",
    "ExpectedValue": "No",
    "FoundValue": "Yes"
  }
}

GET /foo/_mapping

Response for the mapping, which you could then customize:
{
  "foo" : {
    "mappings" : {
      "_doc" : {
        "properties" : {
          "AVAILED_NOT_LIVE" : {
            "properties" : {
              "ExceptionReason" : {
                "type" : "text",
                "fields" : {
                  "keyword" : {
                    "type" : "keyword",
                    "ignore_above" : 256
                  }
                }
              },
              "ExceptionType" : {
                "type" : "text",
                "fields" : {
                  "keyword" : {
                    "type" : "keyword",
                    "ignore_above" : 256
                  }
                }
              },
              "ExpectedValue" : {
                "type" : "text",
                "fields" : {
                  "keyword" : {
                    "type" : "keyword",
                    "ignore_above" : 256
                  }
                }
              },
              "FoundValue" : {
                "type" : "text",
                "fields" : {
                  "keyword" : {
                    "type" : "keyword",
                    "ignore_above" : 256
                  }
                }
              }
            }
          },
          "LIVE_NOT_AVAILED" : {
            "properties" : {
              "ExceptionReason" : {
                "type" : "text",
                "fields" : {
                  "keyword" : {
                    "type" : "keyword",
                    "ignore_above" : 256
                  }
                }
              },
              "ExceptionType" : {
                "type" : "text",
                "fields" : {
                  "keyword" : {
                    "type" : "keyword",
                    "ignore_above" : 256
                  }
                }
              },
              "ExpectedValue" : {
                "type" : "text",
                "fields" : {
                  "keyword" : {
                    "type" : "keyword",
                    "ignore_above" : 256
                  }
                }
              },
              "FoundValue" : {
                "type" : "text",
                "fields" : {
                  "keyword" : {
                    "type" : "keyword",
                    "ignore_above" : 256
                  }
                }
              }
            }
          }
        }
      }
    }
  }
}

PS: From the mapping it's also getting clear how nested objects are being mapped — by having properties in a property.


text:
Q: Как можно добавить цветной бордер к бейджу в табБаре? Каким образом можно добавить вот такой цветной ободок

к бейджику для UITabBar (тени и "отблески" не нужны)

A: У стандартных значков сейчас нет таких свойств/методов меняющих borderWidth и borderColor https://developer.apple.com/documentation/uikit/uitabbaritem/1648567-badgecolor .
Конечно, можно пробежаться по subviews у ваших view и попробовать найти нужный вам значок, и у них уже поменять нужные вам свойства. Пример есть здесь https://stackoverflow.com/questions/13341603/is-it-possible-to-change-uitabbaritem-badge-color . Правда тут меняют цвет, но вы таким же способом можете заменить у layer borderWidth и borderColor.
Либо можете воспользоваться готовыми решения из https://github.com/Minitour/EasyNotificationBadge или https://github.com/evgenyneu/swift-badge.


text:
Q: Output not displaying correctly on HDMI connection to display My Asus AT3N7A-I-based computer is connected to my TV via a HDMI cable. However the screen is cut off by 1cm in each direction. I have so far been unable to find settings to change or resize the display. It has an onbuilt nVidia grapics adaptor and is a 32" Bush TV.

A: There is a setting in NVidia and ATI settings for overscanning, over cropping, or something similar to that. If you change this, it will utilize the entire screen.


text:
Q: WMM and IGRF model? I am studying about World Magnetic Model (WMM) and International Geomagnetic Reference Field (IGRF) model provides the seven parameters about the earth magnetic field. These models have to be deployed on the nano satellite now i am confused how these models works.
I got one formula for the potential of the field and after taking partial derivative of that formula getting the field strength in the respective direction.
But is there any way to get the satellite attitude by that model and having magnetometer reading. Please give any idea if have.


text:
Q: Why am I getting org.codehaus.jackson.map.JsonMappingException: No suitable constructor found for type Can someone please tell me Why am I getting org.codehaus.jackson.map.JsonMappingException: No suitable constructor found for type error?
Here is my call:
try
        {
            String jsonreturn = restTemplate.getForObject("http://" + mRESTServer.getHost() + ":8080/springmvc-rest-secured-test/json/{name}", String.class, vars);
            LOGGER.debug("return object:  " + jsonreturn.toString());
        } catch (HttpClientErrorException e)
        {
            /**
             *
             * If we get a HTTP Exception display the error message
             */

            LOGGER.error("error:  " + e.getResponseBodyAsString());

            ObjectMapper mapper = new ObjectMapper();
            ErrorHolder eh = mapper.readValue(e.getResponseBodyAsString(), ErrorHolder.class);

            LOGGER.error("error:  " + eh.errorMessage);

        }

which I am trying to test the error so I should be creating a ErrorHolder Object but I am getting the error;
Here is my ErrorHolder class:
public class ErrorHolder
{

    public String errorMessage;

    public ErrorHolder(String errorMessage)
    {
        this.errorMessage = errorMessage;
    }

    public String getErrorMessage()
    {
        return errorMessage;
    }

    public void setErrorMessage(String errorMessage)
    {
        this.errorMessage = errorMessage;
    }

    @Override
    public String toString()
    {
        return "ErrorHolder{" +
                "errorMessage='" + errorMessage + '\'' +
                '}';
    }
}

I dont know why I am getting the following error:
2013-06-12 14:36:32,138 [main] ERROR Main - error:  {"errorMessage":"Uh oh"}
Exception in thread "main" org.codehaus.jackson.map.JsonMappingException: No suitable constructor found for type [simple type, class ErrorHolder]: can not instantiate from JSON object (need to add/enable type information?)
 at [Source: java.io.StringReader@628016f7; line: 1, column: 2]

A: I believe that you need to add a no parameter constructor to your ErrorHolder class like this:
public ErrorHolder(){
   this(null);
}

A: Two options, either you provide a default no-argument constructor which does the job. However, for your use-case a nicer solution IMHO is provided by @JsonCreator and @JsonProperty:
public class ErrorHolder
{
    public String errorMessage;

    @JsonCreator
    public ErrorHolder(@JsonProperty("errorMessage") String errorMessage)
    {
        this.errorMessage = errorMessage;
    }

    // getters and setters
 }

A: The process of deserialization (Conversion of stream to java object) will access default constructor that is called for the first class in the inheritance hierarchy that does not implement interface Serializable.
Hence all that you need to resolve is a default constructor (no args/parameterless). THis article will help you understand better : https://docs.oracle.com/javase/6/docs/platform/serialization/spec/serial-arch.html#4539

A: I needed to add a dummy constructor
public ErrorHolder(){
}


text:
Q: Infinitesimal description of homogeneous supermanifolds Lie's third theorem says that if $\mathfrak{g}$ is a real, finite-dimensional Lie algebra, then there is a unique (up to isomorphism) simply-connected Lie group $G$ whose tangent Lie algebra is isomorphic to $\mathfrak{g}$.  Let me abuse notation and rephrase this theorem simply as saying that every real, finite-dimensional Lie algebra is the Lie algebra of a unique simply-connected Lie group.
In the context of homogeneous spaces, one might hope for a similar theorem: namely, that to every pair $(\mathfrak{g},\mathfrak{h})$ where $\mathfrak{h}$ is a Lie subalgebra of $\mathfrak{g}$, there exists a unique simply-connected homogeneous space $G/H$, where $G$ is a simply-connected Lie group with Lie algebra $\mathfrak{g}$ and $H$ the connected subgroup generated by $\mathfrak{h}$.
It is not difficult to convince oneself that this is cannot be true: if the subgroup $H$ generated by $\mathfrak{h}$ is not closed, then $G/H$ is not smooth.  So we require the pair $(\mathfrak{g},\mathfrak{h})$ to be geometrically realisable.  We also need to ensure that the action of $G$ is at least locally effective, so that there is no ideal of $\mathfrak{g}$ contained in $\mathfrak{h}$.  Such a pair $(\mathfrak{g},\mathfrak{h})$ is said to be effective.
The theorem is then that every geometrically realisable, effective pair $(\mathfrak{g},\mathfrak{h})$ is the Klein pair associated to a unique simply-connected homogeneous space $G/H$.
So far so good.
My question really is about homogeneous supermanifolds.  For the purposes of this question, let us take supermanifolds in the sense of Kostant: so a ringed space $(M,\mathcal{A})$ where $M$ is a finite-dimensional smooth manifold and $\mathcal{A}$ the sheaf of superfunctions.  I will also take Lie supergroups to be synonymous with super Harish-Chandra pairs $(G_0, \mathfrak{g})$, where now $\mathfrak{g} = \mathfrak{g}_{\bar 0} \oplus \mathfrak{g}_{\bar 1}$ is a Lie superalgebra and $G_0$ is a Lie group with Lie algebra $\mathfrak{g}_{\bar 0}$.
I would expect a similar theorem to the one above: namely, that to every pair $(\mathfrak{g},\mathfrak{h})$ where $\mathfrak{g}$ is a finite-dimensional real Lie superalgebra and $\mathfrak{h}$ a Lie sub-superalgebra (subject to some mild conditions, such as being geometrically realisable and effective) there corresponds a unique simply-connected homogeneous supermanifold $G/H$.
Question
Is this true?  And can someone point out a reference containing a similar result?
I would be happy already in the special case where $\mathfrak{h} \subset \mathfrak{g}_{\bar 0}$.


text:
Q: IPv6 not working from terminal I was able to scp files from my VPS using IPv6 but after some mess-ups (like using shadowsocks and Foxyproxy to circumvent GFW) with my Ubuntu 16.04 I have a strange problem. I can access IPv6 websites (like ipv6.google.com) from my firefox browser, but ping6 ipv6.google.com returns nothing (sometimes Network is unreachable sometimes 100% packet loss). And I can't ssh or scp from my VPS using IPv6 anymore.
I have read questions like this but the solution is not working for me. As in that question, running [ -f /proc/net/if_inet6 ] && echo 'IPv6 OK' || echo 'No IPv6' gives IPv6 OK. So this means my system is able to make an IPv6 connection.
I think it has something to do with proxies but I'm not sure what to look at. Could anyone suggest some solutions?
ifconfig gives:
eth0      Link encap:Ethernet  HWaddr 70:4d:7b:b8:4f:7d
      inet addr:166.111.66.250  Bcast:166.111.67.255  Mask:255.255.252.0
      inet6 addr: fe80::10d8:ad64:c0dc:f66a/64 Scope:Link
      UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
      RX packets:7817729 errors:0 dropped:0 overruns:0 frame:0
      TX packets:99607 errors:0 dropped:0 overruns:0 carrier:0
      collisions:0 txqueuelen:1000
      RX bytes:656752046 (656.7 MB)  TX bytes:51522303 (51.5 MB)
      Interrupt:16 Memory:df200000-df220000

is0       Link encap:IPv6-in-IPv4
      inet6 addr: fe80::200:5efe:a66f:42fa/64 Scope:Link
      UP RUNNING NOARP  MTU:1280  Metric:1
      RX packets:106 errors:0 dropped:0 overruns:0 frame:0
      TX packets:69 errors:35 dropped:0 overruns:0 carrier:0
      collisions:0 txqueuelen:1
      RX bytes:9904 (9.9 KB)  TX bytes:3408 (3.4 KB)

lo        Link encap:Local Loopback
      inet addr:127.0.0.1  Mask:255.0.0.0
      inet6 addr: ::1/128 Scope:Host
      UP LOOPBACK RUNNING  MTU:65536  Metric:1
      RX packets:89984 errors:0 dropped:0 overruns:0 frame:0
      TX packets:89984 errors:0 dropped:0 overruns:0 carrier:0
      collisions:0 txqueuelen:1
      RX bytes:57274557 (57.2 MB)  TX bytes:57274557 (57.2 MB)

wlx30b49e2f621f Link encap:Ethernet  HWaddr 30:b4:9e:2f:62:1f
      UP BROADCAST MULTICAST  MTU:1500  Metric:1
      RX packets:0 errors:0 dropped:0 overruns:0 frame:0
      TX packets:0 errors:0 dropped:0 overruns:0 carrier:0
      collisions:0 txqueuelen:1000
      RX bytes:0 (0.0 B)  TX bytes:0 (0.0 B)


text:
Q: Pidgin not working with Gtalk I have downloaded latest Pidgin(version 2.10.6) for Windows and tried to gtalk account to it. It shows "not authorized" error.
I have tried many options given in the net and its not working for me, Below are the values I have given,
Basic Tab:
Protocal: XMPP
Username: <my username>
Domain: gmail.com
Password: <My Password>

and enabled Remember password check box
Advanced Tab:
Connection security: Require Encryption (Default)
Unhecked "Allow plaintext auth over unencrypted streams" (Default)
Connection Port: 5222 (Default)
Connect server: talk.google.com
File Transfer proxies: proxy.eu.jabber.org (default)
BOSH URL: <Empty> (default)

I enabled two step verification process for my gmail account, So I created application specific password and given here. But Its not working.
Please help me what could be the problem and how to resolve it?

A: Since you are using a 2-step authentication, you'll need the application specific password that you can get from:

Google > Account > Security > Authorising applications

A: Just spent a few hours struggling to get Pidgin work with 2-step verification. It looks like Google Accounts website structure has been changed, making all the instructions and links on the web outdated. It's especially misleading that Manage Apps and App Passwords are two different sections.
Updated Guide for Adding App Specific Passwords to Google Account
Here's how to navigate to App Passwords section:
Google Accounts > Signing in to Google > App Passwords

Or use the direct link below:
https://security.google.com/settings/security/apppasswords


text:
Q: Importing and playing multiple animations with THREE.GLTFLoader in three.js From Blender I have exported an animated model(spaceship) and an animated camera as a .glb using the gltfExporter, when I drop the .glb file into the glTF viewer (gltf-viewer.donmccurdy.com) everything works, so I know the issue is not with the model/Blender.
The problem is when I try and play the animation in my script. I can either have the model animate perfectly OR I can have the camera animate perfectly, but when I try and do both camera and model go crazy. I think it might be my lack of understanding with Animation Mixers? Perhaps I only need to utilize one Mixer for the one file? Anyway this is what I'm doing in brief:
I create two separate animation mixers, one for the spaceship and one for camera:
gltfStore.mixer = new THREE.AnimationMixer(gltf.cameras[0]);
gltfStore.mixerShip = new THREE.AnimationMixer(gltf.scene.children[2]);

I play the animations using clipAction:
gltfStore.mixer.clipAction(gltfStore.animations[0]).play();
gltfStore.mixerShip.clipAction(gltfStore.animations[0]).play();

In my loop, I render the animations:
gltfStore.mixer.update(clock.getDelta());
gltfStore.mixerShip.update(clock.getDelta());

Separately they work, but together they do not. Something that I noticed is that the animation data imported in the glTF animation object includes the animation for both camera and model under gltf.animations[0]. What I mean is gltf.animations[0] has a tracks array with 6 items, the position, quaternion and scale for each item. is that right?
For your convenience, here is the main js file:
var scene = new THREE.Scene();
var mixer, animationClip;
var clock = new THREE.Clock();

var renderer = new THREE.WebGLRenderer();
renderer.setSize( window.innerWidth, window.innerHeight );
document.body.appendChild( renderer.domElement );

//LIGHTS
var light = new THREE.PointLight( 0xffffff, 1, 200 );
light.position.set( 10, -10, 0 );
scene.add( light )

//OBJECT TO STORE THE GLTF ASSETS WHEN LOADED
var gltfStore = {};

var loader = new THREE.GLTFLoader();

// LOAD GLTF ASSETS
var gltfCamera = loader.load(
    'spaceship.glb',
    function ( gltf ) {

        scene.add( gltf.scene );
        gltfStore.animations =  gltf.animations;
        gltfStore.ship = gltf.scene.children[2];
        gltfStore.cam =  gltf.cameras[0];

        gltfStore.mixer = new THREE.AnimationMixer(gltf.cameras[0]);
        gltfStore.mixerShip = new THREE.AnimationMixer(gltf.scene.children[2]);

        gltfStore.mixer.clipAction(gltfStore.animations[0]).play();
        gltfStore.mixerShip.clipAction(gltfStore.animations[0]).play();
        }
);

function animate() {
    requestAnimationFrame( animate );
    if(gltfStore.mixer && gltfStore.cam){
        //gltfStore.mixer.update(clock.getDelta());
        gltfStore.mixerShip.update(clock.getDelta());
          renderer.render(scene, gltfStore.cam);
    }
};

animate();

Thank you for any help/ideas!

A: So after further examining examples I found my answer.
Simply put, there was no need to extract and attempt to animate the model and camera individually, all what was required was to create an AnimatioMixer from the scene itself:
gltfStore.mixer = new THREE.AnimationMixer(gltf.scene);
gltfStore.mixer.clipAction(gltfStore.animations[0]).play();

The above animated all elements perfectly.


text:
Q: How to test props in React-typescript? I'm working on a react-typescript project and I want to test props passed to a react component using react-testing library.
here is my SharedDashboardUiLatestValueWidget.tsx component
export interface SharedDashboardUiLatestValueWidgetProps {
  title?: string,
  value: number,
  type: 'temperature' | 'humidity',
  varient: 'small' | 'big',
  backgroundColor?:string,
  titleColor?:string,
  valueColor:string
}

export function SharedDashboardUiLatestValueWidget(
  props: SharedDashboardUiLatestValueWidgetProps
) {

  if (props.varient === 'small') {
    return <Card  elevation={4} sx={{ height: '100%', width: '100%', boxSizing: 'border-box',backgroundColor:props.backgroundColor}} >
      <CardContent sx={{ display: 'flex', flexFlow: 'column' }} >
        <Typography  variant='h5' sx={{m:1, fontSize:30,color:props.titleColor}}>
          {props.title || ""}
        </Typography>
        <Typography data-testid="type" variant='h4' sx={{m:1, color:props.valueColor}}>
          { props.value }
          { props.type === 'temperature' ? " °C" : props.type === 'humidity' ? " %" : "" }
        </Typography>
      </CardContent>
    </Card>
...

This is my testing code
describe('SharedDashboardUiLatestValueWidget', () => {

  it('should render SharedDashboardUiLatestValueWidget Props correctly', ()=>{
     render(<SharedDashboardUiLatestValueWidget value={0} type={'temperature'} varient={'big'} valueColor={''} />);
     expect(screen.queryByTestId("type")).toBe('temperature');

  })

});

Even though I passed the values for props I received null value. Can someone help me to test the props in this code ?

A: Well first things first your variant prop has the value big and your if statement in your component is only true if variant is small so your test not working is to be expected. Also screen.queryByTestId returns a node, if the data-testid is found, which is not comparable to a string, if you want to test for the contents of the element I believe you can use .innerHTML for that. Now that that's out of the way I can tell you how I like to write tests like these. Now keep in mind that I'm not claiming my methods to be the best just what I find to work well. If you want to test if the props work as intended you need to test if the elements in the component are affected as expected depending on the values if your props. For example if you pass props to your component where varient is small, value is 0, and type is temperature you would expect screen.queryByTestId("test").innerHTML to be 0°C. And then make a test where you change one of the props, and check that the component now behaves in a different way as expected.


text:
Q: How to match each array field to other field in Mongodb I have an array as below:
const test = [{
    "_id": 1,
    "name": "apple",
    "car": "ford"
},{
    "_id": 2,
    "name": "melon",
    "car": "ferrari"
},{
    "_id": 3,
    "name": "perl",
    "car": "Renaut"
}]

And there is are documents of Mongodb as below:
[{
  "name": "perl", "company": "A"
},{
  "name": "melon", "company": "B"
},{
  "name": "apple", "company": "C"
},{
  "name": "apple", "company": "D"
},{
  "name": "perl", "company": "E"
},{
  "name": "apple", "company": "F"
}]

And I want to get this result using mongodb aggregate:
[{
  "name": "perl", "company": "A", testInform: { "_id": 3, "name": "perl", "car": "Renaut"}
},{
  "name": "melon", "company": "B", testInform: { "_id": 2, "name": "melon", "car": "ferrari"}
},{
  "name": "apple", "company": "C", testInform: { "_id": 1, "name": "apple", "car": "ford"}
},{
  "name": "apple", "company": "D", testInform: { "_id": 1, "name": "apple", "car": "ford"}
},{
  "name": "perl", "company": "E", testInform: { "_id": 3, "name": "perl", "car": "Renaut"}
},{
  "name": "apple", "company": "F", testInform: { "_id": 1, "name": "apple", "car": "ford"}
}]

I think to use aggregate with $match and $facet, etc., but I don't know exactly how to do this. Could you recommend a solution for this?
Thank you so much for reading this.

A: $lookup with pipeline keyword
db.demo2.aggregate(
    {
      $lookup:
         {
           from: "demo1",
           let: { recordName: "$name"},
           pipeline: [
              { $match:
                 { $expr:
                    { $and:
                       [
                         { $eq: [ "$$recordName",  "$name" ] },
                       ]
                    }
                 }
              },
           ],
           as: "testInform"
         }

    }
    )

A: If the test array data is stored in a collection then acheiving O/P is pretty straightforward $lookup with $project aggregation
$arrayElemAt Why? because the lookup would fetch the joined documents in an array as testInform
db.maindocs.aggregate([
  {
    $lookup: {
      from: "testdocs",
      localField: "name",
      foreignField: "name",
      as: "testInform"
    }
  },
  {
    $project: {
      _id: 0,
      name: 1,
      company: 1,
      testInform: { $arrayElemAt: ["$testInform", 0] }
    }
  }
]);

Update based on comments:
The idea is to iterate the cursor from the documents stored in mongodb  Array.prototype.find() the object from test which matches the name field, add it to result.
const test = [
  {
    _id: 1,
    name: "apple",
    car: "ford"
  },
  {
    _id: 2,
    name: "melon",
    car: "ferrari"
  },
  {
    _id: 3,
    name: "perl",
    car: "Renaut"
  }
];

const cursor = db.collection("maindocs").find();
const result = [];

while (await cursor.hasNext()) {
  const doc = await cursor.next();
  const found = test.find(e => e.name === doc.name);
  if (found) {
    doc["testInform"] = found;
  }
  result.push(doc);
}

console.info("RESULT::", result);

A: The aggregation has one stage: Iterate over the test array and get the array element as an object which matches the name field in both the document and the array (using the $reduce operator).
const test = [ { ... }, ... ]

db.test_coll.aggregate( [
  {
      $addFields: {
          testInform: {
              $reduce: {
                  input: test,
                  initialValue: { },
                  in: {
                      $cond: [ { $eq: [ "$$this.name", "$name" ] },
                               { $mergeObjects: [ "$$this", "$$value" ] },
                               "$$value"
                             ]
                      }
               }
          }
      }
  }
] )


text:
Q: Set maximum requests per IP in IIS7 I have a web site deployed to IIS 7. One page it is has 15+ .js files linked to it.
Last two files referenced in <head> tag (loaded last) get 403 forbidden response from server.
I have enabled FailedRequestTracing and have been able to see a detailed error code which is 403.502.
I suppose over a very short period of time I am just pulling to much and the IIS blocks me.
Is there a way I can configure the limit to enable larger number of requests and get rid of 403.502 error?

A: Solved it. It turns out I had IIS Dynamic IP Restrictions plugin installed on the web server, with default configuration set to 20 max requests per 200 milliseconds. After increasing the limit the problem was gone.


text:
Q: Epiphany gives insecure message on valid, secure site When I visit this site, https://stream1.fxxy.net/, in Google Chrome or Firefox I am connected and see that it's recognized as a secure site with a valid security certificate verified by COMODO RSA Domain Validation Secure Server CA. However, visiting the same URL with Epiphany 3.24.1, the connection is blocked with an error message: "This Connection is Not Secure" and "This website's identification was not issued by a trusted organization." I can then click on an "Accept Risk and Proceed" button to continue.
Firstly, I don't understand why the cert is accepted by Chrome and Firefox but not Epiphany. Any explanation would be appreciated. But more importantly, is there anything I can set/change in Epiphany to have it accept the site as secure and continue on smoothly like the other two browsers?
I'm running the latest Ubuntu Gnome, 17.04 Zesty Zapus.

A: Answering my own question so others don't waste their time with it, and maybe help someone else in the process.
The problem was not with Epiphany but with the certificate. I learned from Michael Catanzaro, a leading Gnome developer, that Firefox and Chrome are fairly permissive in their validation of certificates while Epiphany is intentionally not. The certificate in question was a single certificate without a chain to a recognized signing authority. Firefox and Chrome likely cached the chain from earlier encounters with similar certificates and deemed it acceptable. Epiphany does not cache intermediate chain certificates and rejected the single certificate as insecure.
Hope this helps someone...


text:
Q: Filebeat Script Processor Event.Get All Fields In Log I am looking to get all of the fields in a record in filebeat using the Script processor and perform an action on them. Using the event.Get() from the script processor, it says, "Get a value from the event (either a scalar or an object). If the key does not exist null is returned. If no key is provided then an object containing all fields is returned."
https://www.elastic.co/guide/en/beats/filebeat/current/processor-script.html
Therefore, my question is, what would I do to ensure that no key is provided to get an object that contains all of the fields are returned?

A: The event.Get() field will provide the top level fields. To look through these top level fields, use a for loop like:
  - script:
      lang: javascript
      id: get_fields
      source: >
        function process(event) {
            var a = event.Get();
            for (var key in a) {
              if(event.Get(key) == ""){
                   event.Delete(key);
              }
            }
         }

I am unsure how to do this for nested fields in this way nor have I tried to extend it to nested fields, but this is how it works for now.


text:
Q: How to scope materialize css? I am having an plug and play tool which can be plugged with any website, i had used materialize as my css framework, the problem is when i am hooking my plug and play tool to another portal which uses bootstrap or any other css framework, both portal and my tool css is getting tampered because of conflict
how can i resolve the above issue ??
one way i can find is to scope it, but it would be a framework level change , but does materialize provide any stuff by which i can scope it