text:
Q: Java - Which is the best implementation structure for Graph? The graph is very large but undirected. Edges are unweighted.
In my implementation, I have to find the vertex with max degree and do deletion on both vertexes and edges.
Linked list? ArrayList? Map?
Which one is better for my implementation?

A: My suggestion would be to store the vertexes in a priority queue. That way you can have very fast access to the vertex with the highest degree. As for how to implement the vertexes, I would store each neighboring vertex in some kind of set data-structure such as a HashSet or a TreeSet to be able to remove stuff efficiently. I wouldn't represent the edges explicitly, it's not needed.
Code, something along the lines of:
class Graph {

  PriorityQueue<Vertex> vertexes;

  public Graph() {
    vertexes = new PriorityQueue<Vertex>(10,new Vertex());
  }

  public Vertex maxDegreeVertex() {
    return vertexes.peek();
  }

  ...

}

class Vertex implements Comparator<Vertex> {
  HashSet<Vertex> edges;

  public Vertex() {
    edges = new HashSet<Vertex>();
  }

  public compare(Vertex v1, Vertex v2) {
    v2.edges.size().compareTo(v1.edges.size());
  }

  ...

}

Hope this helps.

A: From the above suggested the answer would be
Map with LinkedList...
Your datastructure could be like this(varies according to your requirement)...
Map<?, List<?>>
<Node-name, List-of-nodes-connected-to-it>

Basically, Graphs are best implemented with the help of HASHING and the above datastructure helps a lot in that..

A: The two fundamental data structures for representing graphs are the

*

*adjacency list

*the adjacency matrix
see http://en.wikipedia.org/wiki/Adjacency_list and http://en.wikipedia.org/wiki/Adjacency_matrix.
The articles also discuss the pros and cons of those two structures.

A: If your algorithm requires looking up on max degree, then you want a data structure ordered by degree, something like a PriorityQueue would be good.
Then you need to store the graph itself. For deletion quickly I'd recommend something like a Sparse Array structure. If you have to use java.util data structures, then a HashMap from vertexes to the list of connected vertexes offers O(1) deletion.
If you could use 3rd party libraries, then there are a list of answers here of which JGraph and JUNG seem most popular.

A: Graph implementation depends on what you going to do with it. But for most cases Adjacency list based implementation helps.
In Java you can do it using a Map<>. Here is generic Adjacency List based Graph.Java implementation on my blog.

A: You could also have a look at specifically-designed libraries, like JUNG

A: Depends on what other requirements you have. A naive, simple approach could be
class Node
{
  List<Node> edges;
  int id;
}

where you'd have a List of all the nodes in the graph. The problem is this can become inconsistent; e.g. node A might be in node B's edges list, but node B might not be in node A's list.  To get around this, you could model it as such:
class Edge
{
  Node incidentA;
  Node incidentB;
}

class Node
{
  int id;
}

Again, you'd have List and List of all the edges and nodes in the system. Of course analyzing this data structure would be done in a very different way than in the other approach.

A:     public class Graph {
    private Set<Vertex>vertices;
    private Set<Edge>edges;
    private Map<Vertex,List<Edge>>adj;
    // Getter setter

    public Graph(Set<Vertex> vertices, Set<Edge> edges, Map<Vertex, List<Edge>> adj) {
        super();
        this.vertices = vertices;
        this.edges = edges;
        this.adj = adj;
    }
}

// Vertex class
public class Vertex {
    private String name;

    public Vertex(String name) {
        super();
        this.name = name;
    }

}

// Edge class

public class Edge {
    private Vertex from;
    private Vertex to;
    private int weight;

    public Edge(Vertex from, Vertex to,int weight) {
        super();
        this.from = from;
        this.to = to;
        this.weight = weight;
    }

}

// Driver class

import java.util.HashSet;
import java.util.Set;

public class Test {
    public static void  main(String[]args) {
        Graph gr = new Graph();
        Vertex a = new Vertex("a");
        Vertex b = new Vertex("b");
        Vertex c = new Vertex("c");
        Vertex d = new Vertex("d");
        Vertex e = new Vertex("e");
        Vertex f = new Vertex("f");
        Vertex g = new Vertex("g");

        Set<Vertex>vertices = gr.getVertices();
        if(vertices == null){
            vertices  = new HashSet<>();
            vertices.add(a);
            vertices.add(b);
            vertices.add(c);
            vertices.add(d);
            vertices.add(e);
            vertices.add(f);
            vertices.add(g);
        }

        Edge ae = new Edge(a, e, 3);
        Edge ac = new Edge(a, c, 1);
        Edge cf = new Edge(c, f, 9);
        Edge cd = new Edge(c, d, 4);
        Edge eb = new Edge(e, b, 2);
        Edge bd = new Edge(b, d, 5);
        Edge df = new Edge(d, f, 7);

    Set<Edge>edges = gr.getEdges();
    if(edges == null){
        edges = new HashSet<Edge>();
        edges.add(ae);
        edges.add(ac);
        edges.add(cf);
        edges.add(cd);
        edges.add(eb);
        edges.add(bd);
        edges.add(bd);
    }
        gr.setVertices(vertices);
        gr.setEdges(edges);

    }

}


text:
Q: Content Page Tool Bar Item Is Missing Upon Navigating using PopUpPage Prism I'm currently facing a problem that when I use
await _navigationService.PushPopupAsync()
The tool bar item on the next page where I am going to navigate is missing its like the PushPopupAsync() is destroying my next page.
Does somebody encounter this kind of problem?

A: What you're trying to do is no longer supported. That was a deprecated after version 1.
You'll need to be sure that you've registered the PopupNavigationService, and registered your PopupPage's the same as any other page. After that all you need to do is navigate to them the same as you would any other page NavigationService.NavigateAsync("SomePopupPage")
See Repo for more info and a full sample.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Count Number of invoices in oracle APPS i want a query to display how many invoices are created using a particular interface for the last one month in AR module. we are not using any other module except ar,ap ,gl.All our invoices are generated through interface only.Please tell me the table which i can find all the invoices created in AR module using a particular Interface.

A: This sounds simple to me but I don't have a lot of AR experience.
select count(*)
from
AP_INVOICES_ALL
where
CREATION_DATE > SYSDATE - 30
and SOURCE = '&source'
;


text:
Q: Pilha/Stack com prioridade em c#? Meu professor passou 2 exercícios, o primeiro era criar uma pilha (Stack) simples para executar testes unitários nesta classe:
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;

   namespace Collections
   {
public class Stack<T>
{
    private List<T> stack = new List<T>();
    private bool isEmpty = true;
    private int count = 0;
    private object top = null;

    public bool IsEmpty
    { get { return isEmpty; } }

    public int Count
    { get { return count; } }

    public void Push(T obj)
    {
        stack.Add(obj);
        count++;
        top = obj;
        if (isEmpty)
            isEmpty = false;
    }

    public T Pop()
    {
        if (!isEmpty)
        {
            T element = stack.Last();
            stack.RemoveAt(stack.Count -1);
            count--;
            if (count == 0)
                isEmpty = true;
            return element;
        }
        else
            throw new InvalidOperationException();
    }

    public object Peek()

    {
        if (top == null)
            throw new InvalidOperationException();
        else
            return top;

    }

    public void Clear()
    {
        stack.Clear();
        isEmpty = true;
        count = 0;
    }
}
  }

A classe foi criada, a classe de testes e uma classe cliente também.
A segunda questão é que o professor pediu para modificar a classe Stack que escrevemos com os seguintes propósitos:
Modificações a realizar:
Você deve modificar a pilha para que ela seja possível empilhar elementos prioritários. O méthodo PushPrioritaire() empilha um elemento com alta prioridade. No método pop, os elementos prioritários são desempilhados primeiramente.

Importante: Uma vez que essa classe já é usada em sua forma original, deve-se assegurar que o funcionamento habitual não seja modificado pelo add de funcionalidades.

Funcionalidades a acrescentar:

*

*PrioritaireIsEmpty(): Retorna um bool verdadeiro se a pilha não contiver elementos prioritários.

*PushPrioritaire(): Empilha um elemento prioritário.

E não tenho ideia de como escrever estas novas funções. A única coisa que consegui pensar era implementar um IComparable nos obj e retornar:
// obj 1 > obj 2 return > 0 (1)
// obj 1 < obj 2 return < 0 (-1)
// obj 1 == obj 2 return 0

Mas tudo que escrevi pensando nisso resultou em erro.

A: Começo por indicar que no seu código o Pop não está a atualizar o elemento de topo, logo um Peek apos Pop não devolve o elemento correto. Pode corrigir este problema da seguinte forma:
public T Pop()
{
    if (!isEmpty)
    {
        T element = stack.Last();
        stack.RemoveAt(stack.Count - 1);
        count--;

        if (count == 0)
        {
            isEmpty = true;
            top = null; //linha adicionada
        }
        else //linha adicionada
            top = stack[stack.Count - 1]; //linha adicionada, para atualizar para o ultimo

        return element;
    }
    else
        throw new InvalidOperationException();
}

Quanto aos elementos prioritarios vejo duas soluções:

*

*Construindo uma segunda lista interna só para os elementos prioritários.

*Ou criando uma classe auxiliar para cada elemento com o elemento e a prioridade, desta forma:
private class Elemento
{
    T elem;
    bool prioritario;
}

E trocar a lista para private List<Elemento> stack = new List<Elemento>(); e o resto da implementação nesse sentido.
Exemplificando a solução com duas listas ficaria assim:
public class Stack<T>
{

    private List<T> stack = new List<T>();
    private List<T> stackP = new List<T>(); //a lista prioritaria
    ...

Alguns dos métodos seriam iguais. Vejamos os que ficam diferentes, começando pelos pushes:
public void PushPrioritaire(T obj)
{
    PushAuxiliar(stackP, obj);
}

public void Push(T obj)
{
    PushAuxiliar(stack, obj);
}

private void PushAuxiliar(List<T> st, T obj) //agora recebe a lista a inserir
{
    st.Add(obj);
    count++;
    top = obj;
    if (isEmpty)
        isEmpty = false;
}

Separando aqui a lógica de inserção num método auxiliar que passa a receber a lista, para poder ser chamado com listas diferentes.
O PrioritaireIsEmpty ficaria super simples consultando apenas se a lista prioritária tem elementos:
public bool PrioritaireIsEmpty()
{
    return stackP.Count == 0;
}

No Clear seria apenas necessário limpar também a lista prioritária:
public void Clear()
{
    stack.Clear();
    stackP.Clear(); //limpa a prioritária também
    top = null;
    isEmpty = true;
    count = 0;
}

O que levaria mais alterações seria o Pop que fica agora com a responsabilidade de remover primeiro da lista prioritária, e se essa não tiver elementos remover da normal:
public T Pop()
{
    if (!isEmpty)
    {
        //escolhe a lista que vai remover com base no tamanho da prioritária
        List<T> st = stackP.Count == 0 ? stack : stackP;

        T element = st.Last();
        st.RemoveAt(st.Count - 1);
        count--;

        if (count == 0)
        {
            isEmpty = true;
            top = null;
        }
        else {
            //ajusta o top para a prioritária se tiver elementos ou normal caso contrario
            top = stackP.Count > 0 ? stackP[stackP.Count - 1] : stack[stack.Count - 1];
        }

        return element;
    }
    else
        throw new InvalidOperationException();
}

Veja a funcionar no .net Fiddle


text:
Q: align multiline equations with labels I have multiple equations with different labels (see below for MWE) that I would all like to align while being able to reference them separately. I have the following code:
\documentclass{article}
\usepackage{mathtools}

\begin{document}
    Equation \ref{eq:p1_m1} tests one model, equation \ref{eq:p1_m2} the extended model model and equation \ref{eq:p1_m3} a third one.
            \begin{align} \label{eq:p1_m1}
                ABC\textsubscript{n} &= \alpha\textsubscript{0} + \alpha\textsubscript{1} E\textsubscript{ij} + \alpha\textsubscript{2} E\textsubscript{ij} * F\textsubscript{i} + \varepsilon\textsubscript{i}
            \end{align}
            \vspace{-.25cm}
            \begin{align} \label{eq:p1_m2}
                ABC\textsubscript{n} &=  \alpha\textsubscript{0} + \alpha\textsubscript{1} E\textsubscript{ij} + \alpha\textsubscript{2} E\textsubscript{ij} * F\textsubscript{i} \nonumber \\
                & \quad + \alpha\textsubscript{3} \Delta\textsubscript{G\textsubscript{ij}} + \varepsilon\textsubscript{i}
            \end{align}
            \vspace{-.25cm}
            \begin{align} \label{eq:p1_m3}
            ABC\textsubscript{n} &=  \alpha\textsubscript{0} + \alpha\textsubscript{1} E\textsubscript{ij} + \alpha\textsubscript{2} E\textsubscript{ij} * F\textsubscript{i} \nonumber \\
            & \quad + \alpha\textsubscript{3} \Delta\textsubscript{G\textsubscript{ij}} + \alpha\textsubscript{4} E\textsubscript{ij} * G\textsubscript{nt} \nonumber \\
            & \quad + \alpha\textsubscript{5} E\textsubscript{ij} * F\textsubscript{i} * G\textsubscript{nt} + \alpha\textsubscript{6} \Delta\textsubscript{G\textsubscript{ij}} * G\textsubscript{nt} + \varepsilon\textsubscript{i}
            \end{align}
\end{document}

I would like (i) the equations to all align on the equal sign and (ii) be able to reference them as shown in the text. Additionally, I would like to be able to align all the \varepsilon signs in their respective columns.
Can someone help me out and point me in the right direction?

A: To achieve the first part of your formatting objective, don't employ three independent align environments. Instead, employ a single align environment. (I must confess to not understanding the part about aligning the \varepsilon symbols.)
A separate comment/suggestion: You should not use \textsubscript to create subscripts in math mode. Instead, please use _.
I must further confess to not being sure what the * (asterisk) symbols are suppose to denote. If they denote multiplication, you should either replace them with \cdot symbols or, better still, just omit them entirely.

\documentclass{article}
\usepackage{mathtools}
\usepackage[noabbrev]{cleveref} % optional

\begin{document}
\Cref{eq:p1_m1} tests one model, \cref{eq:p1_m2} the extended model, and \cref{eq:p1_m3} a third one.
\begin{align}
     ABC_{n}
     &= \alpha_{0} + \alpha_{1} E_{ij} + \alpha_{2} E_{ij} * F_{i} + \varepsilon_{i}
     \label{eq:p1_m1}\\
     ABC_{n}
     &=  \alpha_{0} + \alpha_{1} E_{ij} + \alpha_{2} E_{ij} * F_{i} \nonumber \\
     &\quad + \alpha_{3} \Delta_{G_{ij}} + \varepsilon_{i}
     \label{eq:p1_m2}\\
     ABC_{n}
     &=  \alpha_{0} + \alpha_{1} E_{ij} + \alpha_{2} E_{ij} * F_{i} \nonumber \\
     &\quad + \alpha_{3} \Delta_{G_{ij}} + \alpha_{4} E_{ij} * G_{nt} \nonumber \\
     &\quad + \alpha_{5} E_{ij} * F_{i} * G_{nt} + \alpha_{6} \Delta_{G_{ij}} * G_{nt} + \varepsilon_{i}
     \label{eq:p1_m3}
\end{align}
\end{document}

A: Here is a proposition with alignat and \mathllap. I also suggest using _the commands from cleveref to save quite some typing with cross-references:
\documentclass{article}
\usepackage{mathtools}
\usepackage{cleveref}
\crefname{equation}{equation}{equations}

\begin{document}

            \Cref{eq:p1_m1} tests one model, \cref{eq:p1_m2,eq:p1_m3} the extended model and a third one respectively.

    \begin{alignat}{2} \label{eq:p1_m1}
                    ABC_{\mathrm{n}} &= \alpha_{0} + \alpha_{1} E_{\mathrm{ij}} + \alpha_{2} E_{\mathrm{ij}} * F_{\mathrm{i}} & &{} + \varepsilon_{\mathrm{i}}\\[1ex]
  \label{eq:p1_m2}
 ABC_{\mathrm{n}} &= \alpha_{0} + \alpha_{1} E_{\mathrm{ij}} + \alpha_{2} E_{\mathrm{ij}} * F_{\mathrm{i}} \notag \\
 & &\mathllap{{}+ \alpha_{3} \Delta_{G_{\mathrm{ij}}}} & + \varepsilon_{\mathrm{i}}\\[1ex]
      \label{eq:p1_m3}
 ABC_{\mathrm{n}} &= \alpha_{0} + \alpha_{1} E_{\mathrm{ij}} + \alpha_{2} E_{\mathrm{ij}} * F_{\mathrm{i}} \notag \\
 &\phantom{{}=} + \alpha_{3} \Delta_{G_{ij}} + \alpha_{4} E_{\mathrm{ij}} * G_{\mathrm{nt}} \notag\\
 & & \mathllap{{}+ \alpha_{5} E_{\mathrm{ij}} * F_{\mathrm{i}} * G_{\mathrm{nt}} + \alpha_{6} \Delta_{\mathrm{G_{\mathrm{ij}}}} * G_{\mathrm{nt}}} & {}+ \varepsilon_{\mathrm{i}}
                \end{alignat}

\end{document}


text:
Q: ¿como reinstalar xampp en ubuntu? Perdón por la molestia otra vez ¿saben como puedo aplastar el xampp que actualmente tengo en ubuntu con uno nuevo? Digamos reinstalar pero machacando el que ya tengo ahora. Es que ha ocurrido un error que no puedo corregir por culpa de cambiar los permisos de una carpeta, y como no tengo mucho conocimiento de linux ubuntu prefiero reinstalar. Necesito por favor los comandos, ya perdi todo el dia intentando solucionar lo anterior y nada :(

A: Puedes asignarles los permisos con Chmod 777 * y chown root:root *, Elimina la carpeta de xampp por completo /opt/xampp, después puedes reinstalarlo`


text:
Q: Why does printing out an array sorted using JavaScript's `Array.sort` seem to sort the array before `Array.sort` is called? I'm confused about the difference between the output for the following two pieces of code:
var x = [{'size': 3}, {'size': 2}, {'size':1}];
console.log("Before I sort, x is", x);
x.sort(function(a, b) {
    console.log("Sorting x…");
    return a.size - b.size;
});
console.log("After I sort, x is", x);

yields

…which is surprising since the "Before I sort…" array seems sorted.  If I remove the sort, i.e. run
var x = [{'size': 3}, {'size': 2}, {'size':1}];
console.log("Before I sort, x is", x);
// x.sort(function(a, b) {  console.log("Sorting x…");
//  return a.size - b.size; });
// console.log("After I sort, x is", x);

Then I see what I expect in the first console.log,

Confused by this, I tried printing out x[0] as well, which is correct, even though the display of x is not, i.e.
var x = [{'size': 3}, {'size': 2}, {'size':1}];
console.log("Before I sort, x[0] is", x[0], "and x is", x);
x.sort(function(a, b) {  console.log("Sorting x…");
    return a.size - b.size; });
console.log("After I sort, x[0] is", x[0], "and x is", x);

yields

…which seems inexplicable, since the printed x's are the same, even though x[0] is not.
What gives?  How can I explain this behavior?
I hope it doesn't matter, but I'm running this on Google Chrome 69.0.3497.100 (Official Build) (64-bit)
Thanks!


text:
Q: Does Empirical Distribution Function Independent of Filtration? I encountered a problem when reading a paper:
We have i.i.d double exponential random variables $X_1,\dots,X_n$. Then consider the empirical distribution function $\hat{F_n}(x) = \frac{1}{n} \sum\limits_{i=1}^n \chi_{\{|X_i|\leq x\}}$ of $|X_1|,\dots,|X_n|$, where $\chi$ is the indicator function and $|X_i|$ follows exponential distribution with parameter $1$. Now the paper I am reading claims that $\hat{F_n}$ is independent of $\mathscr{A}_n$, where $\mathscr{A}_n$ is the sigma field generated by the signs and ranked absolute values of the first $n$ observations.
My question is, does the empirical distribution function $\hat{F_n}(x)$ independent of the nature sigma field $\sigma(X_1,\dots, X_n)$ generated by the first $n$ observations?
I feel like I don't understand how $\mathscr{A}_n$ is generated, so I don't know why the independence claimed in the paper holds. I understand the nature sigma field $\sigma(X_1,\dots, X_n)$ is the pre-image of all $n$-dim Borel sets, but what does $\mathscr{A}_n$ look like? And if I consider an extreme situation and take $n=1$, then it doesn't look like that $\chi_{\{|X_1|\leq x\}}$ is independent of $(sign(X_1),|X_1|)$. I guess I have some misunderstanding somewhere :(


text:
Q: Use GetLastError() to retrieve custom exception properties So I've created a custom exception class (let's call it CustomException) along with some custom properties not found in the Exception class.  In the global.asax.cs file there is the Application_Error method that is called whenever an exception happens.  I'm using Server.GetLastError() to grab the exception that triggered the Application_Error method.  The problem is that Server.GetLastError() only grabs an Exception object and not the CustomException object that is being thrown along with its custom properties.  Basically the CustomException is stripped down to an Exception object when retrieved by Server.GetLastError(), thus losing the custom properties associated with CustomException.
Is there a way for GetLastError() to actually retrieve the CustomException object and not the stripped down Exception version?  This is needed in order to store the errors in a database table with more information than would normally be supplied by an Exception.
Application_Error:
protected void Application_Error(object sender, EventArgs e)
{
    // This var is Exception, would like it to be CustomException
    var ex = Server.GetLastError();

    // Logging unhandled exceptions into the database
    SystemErrorController.Insert(ex);

    string message = ex.ToFormattedString(Request.Url.PathAndQuery);

    TraceUtil.WriteError(message);
}

CustomException:
public abstract class CustomException : System.Exception
{
    #region Lifecycle

    public CustomException ()
        : base("This is a custom Exception.")
    {
    }

    public CustomException (string message)
        : base(message)
    {
    }

    public CustomException (string message, Exception ex)
        : base(message, ex)
    {
    }

    #endregion

    #region Properties

    // Would like to use these properties in the Insert method
    public string ExceptionCode { get; set; }
    public string SourceType { get; set; }
    public string SourceDetail { get; set; }
    public string SystemErrorId { get; set; }

    #endregion
}

A: Just cast the Server.GetLastError's result to CustomException:
var ex = Server.GetLastError() as CustomException;

Remember that in some situations your CustomException could not be the top exception in the StackTrace, in this case you'll need to navigate through the InnerExceptions to find the right one.
Please, check the @scott-chamberlain links about how to design custom exceptions.


text:
Q: Arduino control peristaltic pump I'm working with a colleague to digitally control an old peristaltic pump using a digital potentiometer. The existing pump controller has a mechanical potentiometer and we are trying to replace it with an MCP4131-103.
Can anyone lend some insight on the types of questions we should be asking before doing a direct replacement? We have already burned a couple and I suspect we are wiring it incorrectly or using an under-rated IC. One measurement we already have is that the voltage across the A-B of the mechanical pot during operation is about 10V (from ground, I think I measured -40V on A and -50V on B, if that matters). Is that too much for this IC? Can anyone provide some pointers on how to proceed? Is there a better way to replace a mechanical pot than with a digital pot to allow for programmatic control?
Thanks in advance for the help provided. If I need to provide clearer details, please tell me some measurements/observations I can make about the current setup.

A: Whoa, no wonder you're burning these:

Absolute Maximum Ratings

Voltage on VDD with respect to VSS
-0.6V to +7.0V

Voltage on /CS, SCK, SDI, SDI/SDO, and /SHDN with respect to VSS
-0.6V to 12.5V

Voltage on all other pins (PxA, PxW, PxB, and SDO) with respect to VSS
-0.3V to VDD+0.3V

Essentially, you're feeding -40 and -50 volts to the pins PxA, PxW and PxB. Their absolute limit is rated at -0.3, up to VDD+0.3 volts. VDD can be up to 7 volts without damage, but the typical operating voltage is 5 volts.
There are a number digital potentiometers that can handle 10 volts, but you must make sure that you float them, if the pins you need to use really are at a potential of -40 or -50 volts. This is not necessarily easy to do.
Another alternative are motorized potentiometers.
You may get more solutions if you try to post the current schematic, maybe there's a way to bypass the potentiometer completely.


text:
Q: Spigot InventoryClickEvent only find item in inventory on second click I want to create a plugin where I have a table and in that I can craft regular crafting recipes and some custom ones.
I know that I can create custom Recipes by default but I want to make them only craftable in this "special" table.
So I've got this code for my InventoryClickEvent
https://hastebin.com/konehibohi.cs
And my problem is that this is throwing me a NullPointerException when I place an item in one of the specified crafting slots but when I put a second item in the same slot it outputs me the right recipe.
Console Output:
[02:21:51] [Server thread/INFO]: VanillaRL | Enabling VanillaRL...
[02:21:51] [Server thread/INFO]: VanillaRL | Enabled VanillaRL
[02:21:51] [Server thread/INFO]: Server permissions file permissions.yml is empty, ignoring it
[02:21:51] [Server thread/INFO]: F4LS3_: Reload complete.
[02:21:53] [Server thread/INFO]: [null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null]
[02:21:53] [Server thread/ERROR]: Could not pass event InventoryClickEvent to VanillaRL v1.0-SNAPSHOT
org.bukkit.event.EventException: null
        at org.bukkit.plugin.java.JavaPluginLoader$1.execute(JavaPluginLoader.java:319) ~[spigot-1.16.1.jar:git-Spigot-0287a20-7560f5f]
        at org.bukkit.plugin.RegisteredListener.callEvent(RegisteredListener.java:70) ~[spigot-1.16.1.jar:git-Spigot-0287a20-7560f5f]
        at org.bukkit.plugin.SimplePluginManager.fireEvent(SimplePluginManager.java:589) ~[spigot-1.16.1.jar:git-Spigot-0287a20-7560f5f]
        at org.bukkit.plugin.SimplePluginManager.callEvent(SimplePluginManager.java:576) ~[spigot-1.16.1.jar:git-Spigot-0287a20-7560f5f]
        at net.minecraft.server.v1_16_R1.PlayerConnection.a(PlayerConnection.java:2191) ~[spigot-1.16.1.jar:git-Spigot-0287a20-7560f5f]
        at net.minecraft.server.v1_16_R1.PacketPlayInWindowClick.a(SourceFile:32) ~[spigot-1.16.1.jar:git-Spigot-0287a20-7560f5f]
        at net.minecraft.server.v1_16_R1.PacketPlayInWindowClick.a(SourceFile:10) ~[spigot-1.16.1.jar:git-Spigot-0287a20-7560f5f]
        at net.minecraft.server.v1_16_R1.PlayerConnectionUtils.lambda$0(PlayerConnectionUtils.java:19) ~[spigot-1.16.1.jar:git-Spigot-0287a20-7560f5f]
        at net.minecraft.server.v1_16_R1.TickTask.run(SourceFile:18) ~[spigot-1.16.1.jar:git-Spigot-0287a20-7560f5f]
        at net.minecraft.server.v1_16_R1.IAsyncTaskHandler.executeTask(SourceFile:144) ~[spigot-1.16.1.jar:git-Spigot-0287a20-7560f5f]
        at net.minecraft.server.v1_16_R1.IAsyncTaskHandlerReentrant.executeTask(SourceFile:23) ~[spigot-1.16.1.jar:git-Spigot-0287a20-7560f5f]
        at net.minecraft.server.v1_16_R1.IAsyncTaskHandler.executeNext(SourceFile:118) ~[spigot-1.16.1.jar:git-Spigot-0287a20-7560f5f]
        at net.minecraft.server.v1_16_R1.MinecraftServer.aZ(MinecraftServer.java:943) ~[spigot-1.16.1.jar:git-Spigot-0287a20-7560f5f]
        at net.minecraft.server.v1_16_R1.MinecraftServer.executeNext(MinecraftServer.java:936) ~[spigot-1.16.1.jar:git-Spigot-0287a20-7560f5f]
        at net.minecraft.server.v1_16_R1.IAsyncTaskHandler.awaitTasks(SourceFile:127) ~[spigot-1.16.1.jar:git-Spigot-0287a20-7560f5f]
        at net.minecraft.server.v1_16_R1.MinecraftServer.sleepForTick(MinecraftServer.java:920) ~[spigot-1.16.1.jar:git-Spigot-0287a20-7560f5f]
        at net.minecraft.server.v1_16_R1.MinecraftServer.v(MinecraftServer.java:852) ~[spigot-1.16.1.jar:git-Spigot-0287a20-7560f5f]
        at net.minecraft.server.v1_16_R1.MinecraftServer.lambda$0(MinecraftServer.java:164) ~[spigot-1.16.1.jar:git-Spigot-0287a20-7560f5f]
        at java.lang.Thread.run(Thread.java:834) [?:?]
Caused by: java.lang.IllegalArgumentException: Result cannot be null
        at org.apache.commons.lang.Validate.notNull(Validate.java:192) ~[spigot-1.16.1.jar:git-Spigot-0287a20-7560f5f]
        at org.bukkit.craftbukkit.v1_16_R1.CraftServer.getRecipesFor(CraftServer.java:1214) ~[spigot-1.16.1.jar:git-Spigot-0287a20-7560f5f]
        at org.bukkit.Bukkit.getRecipesFor(Bukkit.java:717) ~[spigot-1.16.1.jar:git-Spigot-0287a20-7560f5f]
        at de.f4ls3.vanillarl.events.InventoryClickEvent.onInventoryClick(InventoryClickEvent.java:34) ~[?:?]
        at jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[?:?]
        at jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[?:?]
        at jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[?:?]
        at java.lang.reflect.Method.invoke(Method.java:566) ~[?:?]
        at org.bukkit.plugin.java.JavaPluginLoader$1.execute(JavaPluginLoader.java:315) ~[spigot-1.16.1.jar:git-Spigot-0287a20-7560f5f]
        ... 18 more
[02:21:54] [Server thread/INFO]: [null, null, null, null, null, null, null, null, null, null, ItemStack{OAK_PLANKS x 1}, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null]
[02:21:54] [Server thread/INFO]: [org.bukkit.craftbukkit.v1_16_R1.inventory.CraftShapelessRecipe@c41eafb]

For some more info about all the classes you can check my repo
https://github.com/F4LS3/VanillaRL
Thanks in advance!

A: I have found the source of the problem. It relies on the way the Spigot/Bukkit API handles events.

Why does this happen?
Here you have an explanation of why this may be happening.
Basic definition of an event
In Minecraft, an event wraps an action that the client has performed and it sends it to the server. In this way when you perform an action the server will know it and will be able to pass this event to other clients (other online players).
What happens when an event is not caught by an event handler?
If you don't implement an event handler, then an event will be processed in the following way:
Your client  ---------------->  The server --------------> All clients (including you)
Requests an action          Applies the action             Recieve the action

What happens when you catch an event in an event handler?
On the other hand, if you implement an event handler, you are intercepting an event on the server side so the event flow will be:
Your client  ----------\                     /---> The server -----> All clients
                        \-- Event handler --/

In the event handler, the server is waiting for you to handle the event before applying it to all clients.
On an InventoryClickEvent you may be modifying the inventory contents, but those changes aren't applied until your handler ends handling the event.
So if you look for the inventory contents during the event, you will be given the inventory contents before the user clicked. As the server hasn't processed the event yet.
If you then take the contents of a previously empty slot, the content will be null as the new Item hasn't been processed by the server yet. Then, when you take out the item, the content will return the item as the server doesn't know that the slot is empty yet.

My solution
Schedule an asynchronous delayed task so that your event handler will exit and the server will process the event before you checking the items the user placed:
Your client  ----------\                     /---> The server -----> All clients
                        \-- Event handler --/
                         \- Schedule async task -> Actual handling

The code I have implemented is the following:
public class InventoryClickEvent implements Listener
{

    private final VanillaRL plugin;

    public InventoryClickEvent(VanillaRL plugin) {
        this.plugin = plugin;
    }

    @EventHandler
    public void onInventoryClick(org.bukkit.event.inventory.InventoryClickEvent event)
    {
        new BukkitRunnable(){
            @Override
            public void run() {
                delayedHandler(event);
            }
        }.runTaskLaterAsynchronously(plugin, 2);
    }

    private void delayedHandler(org.bukkit.event.inventory.InventoryClickEvent event) {
        if(event.getWhoClicked() instanceof Player)
        {
            Player player = (Player) event.getWhoClicked();

            if (CraftingManager.hasInventory(event.getClickedInventory()))
            {
                CraftingInventory craftingInventory = CraftingManager.getCraftingInventories().stream().filter(craftingInventory1 -> craftingInventory1.getInventory().equals(event.getClickedInventory())).findFirst().get();
                System.out.println(Arrays.toString(craftingInventory.getInventory().getContents()));
                if (craftingInventory.getCraftingSlots().contains(event.getSlot()))
                {
                    if (event.getAction().equals(InventoryAction.PLACE_ALL) || event.getAction().equals(InventoryAction.PLACE_ONE) || event.getAction().equals(InventoryAction.PLACE_SOME))
                    {
                        System.out.println(Bukkit.getRecipesFor(craftingInventory.getItem(event.getSlot())));
                    }
                }
            }
        }
    }
}

Then on the main class when you register the event listener:
Bukkit.getPluginManager().registerEvents(new InventoryClickEvent(this), this);

Server output:
[12:48:34] [Craft Scheduler Thread - 0/INFO]: [null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, ItemStack{REDSTONE_BLOCK x 61}, null, null, null, null, null, null, null, null]
[12:48:34] [Craft Scheduler Thread - 0/INFO]: [org.bukkit.craftbukkit.v1_16_R1.inventory.CraftShapedRecipe@709b045a]

Let me know if this works for you!


text:
Q: SonarQube server [https://sonar.example.org] can not be reached In my situation, I have Jenkins with two nodes. One is acting as a master node, and the other nodes as a slave. Also, I have a separate instance for running on SonarQube.
I have an internal Certificate Authority. I used it to sign my certificates. also, I added this CA certificate to the Jenkins java instance trusted store using keytool.  I verified my works using SSLPoke.
But the things is when I run a job using SonarQube analysis it failed with the following error can anyone help me to troubleshoot this issue.
Started by user admin
Running as SYSTEM
Building remotely on centos7-slave in workspace /home/jenkins/workspace/BXGRN/UAT/UAT_SONAR
[WS-CLEANUP] Deleting project workspace...
[WS-CLEANUP] Deferred wipeout is used...
[WS-CLEANUP] Done
The recommended git tool is: NONE
No credentials specified
Cloning the remote Git repository
Cloning repository git@github.com:example-ict/warehouse.git
 > git init /home/jenkins/workspace/BXGRN/UAT/UAT_SONAR # timeout=10
Fetching upstream changes from git@github.com:example-ict/warehouse.git
 > git --version # timeout=10
 > git --version # 'git version 1.8.3.1'
 > git fetch --tags --progress git@github.com:example-ict/warehouse.git +refs/heads/*:refs/remotes/origin/* # timeout=10
 > git config remote.origin.url git@github.com:example-ict/warehouse.git # timeout=10
 > git config --add remote.origin.fetch +refs/heads/*:refs/remotes/origin/* # timeout=10
Avoid second fetch
 > git rev-parse refs/remotes/origin/master^{commit} # timeout=10
Checking out Revision 2b11909dea58f3e107ff0c78338b33e76d4beb47 (refs/remotes/origin/master)
 > git config core.sparsecheckout # timeout=10
 > git checkout -f 2b11909dea58f3e107ff0c78338b33e76d4beb47 # timeout=10
Commit message: "UI URL change"
 > git rev-list --no-walk 2b11909dea58f3e107ff0c78338b33e76d4beb47 # timeout=10
[UAT_SONAR] $ /home/jenkins/tools/hudson.plugins.sonar.SonarRunnerInstallation/Sonar_Runner/bin/sonar-scanner -Dsonar.host.url=https://sonar.example.org ******** -Dsonar.sourceEncoding=UTF-8 -Dsonar.typescript.lcov.reportPaths=coverage/lcov.info -Dsonar.sources=./ -Dsonar.language=js -Dsonar.exclusions=src/serviceWorker.js,src/Routes.js,src/index.js -Dsonar.projectVersion=36 -Dsonar.projectKey=bxgrn -Dsonar.verbose=true -Dsonar.log.level=DEBUG -Dsonar.test.inclusions=**/src/**/*.test.js,**/src/**/*.test.jsx -Dsonar.projectName=BXGRN -Dsonar.projectBaseDir=/home/jenkins/workspace/BXGRN/UAT/UAT_SONAR
INFO: Scanner configuration file: /home/jenkins/tools/hudson.plugins.sonar.SonarRunnerInstallation/Sonar_Runner/conf/sonar-scanner.properties
INFO: Project root configuration file: /home/jenkins/workspace/BXGRN/UAT/UAT_SONAR/sonar-project.properties
04:43:34.094 INFO: SonarScanner 4.6.0.2311
04:43:34.096 INFO: Java 9.0.4 Oracle Corporation (64-bit)
04:43:34.096 INFO: Linux 3.10.0-1127.19.1.el7.x86_64 amd64
04:43:34.238 DEBUG: keyStore is :
04:43:34.238 DEBUG: keyStore type is : pkcs12
04:43:34.238 DEBUG: keyStore provider is :
04:43:34.239 DEBUG: init keystore
04:43:34.239 DEBUG: init keymanager of type SunX509
04:43:34.372 DEBUG: Create: /home/jenkins/.sonar/cache
04:43:34.373 INFO: User cache: /home/jenkins/.sonar/cache
04:43:34.373 DEBUG: Create: /home/jenkins/.sonar/cache/_tmp
04:43:34.376 DEBUG: Extract sonar-scanner-api-batch in temp...
04:43:34.379 DEBUG: Get bootstrap index...
04:43:34.379 DEBUG: Download: https://sonar.example.org/batch/index
04:43:34.542 ERROR: SonarQube server [https://sonar.example.org] can not be reached
04:43:34.542 INFO: ------------------------------------------------------------------------
04:43:34.542 INFO: EXECUTION FAILURE
04:43:34.542 INFO: ------------------------------------------------------------------------
04:43:34.542 INFO: Total time: 0.489s
04:43:34.559 INFO: Final Memory: 3M/12M
04:43:34.559 INFO: ------------------------------------------------------------------------
04:43:34.559 ERROR: Error during SonarScanner execution
org.sonarsource.scanner.api.internal.ScannerException: Unable to execute SonarScanner analysis
    at org.sonarsource.scanner.api.internal.IsolatedLauncherFactory.lambda$createLauncher$0(IsolatedLauncherFactory.java:85)
    at java.base/java.security.AccessController.doPrivileged(Native Method)
    at org.sonarsource.scanner.api.internal.IsolatedLauncherFactory.createLauncher(IsolatedLauncherFactory.java:74)
    at org.sonarsource.scanner.api.internal.IsolatedLauncherFactory.createLauncher(IsolatedLauncherFactory.java:70)
    at org.sonarsource.scanner.api.EmbeddedScanner.doStart(EmbeddedScanner.java:185)
    at org.sonarsource.scanner.api.EmbeddedScanner.start(EmbeddedScanner.java:123)
    at org.sonarsource.scanner.cli.Main.execute(Main.java:73)
    at org.sonarsource.scanner.cli.Main.main(Main.java:61)
Caused by: java.lang.IllegalStateException: Fail to get bootstrap index from server
    at org.sonarsource.scanner.api.internal.BootstrapIndexDownloader.getIndex(BootstrapIndexDownloader.java:42)
    at org.sonarsource.scanner.api.internal.JarDownloader.getScannerEngineFiles(JarDownloader.java:58)
    at org.sonarsource.scanner.api.internal.JarDownloader.download(JarDownloader.java:53)
    at org.sonarsource.scanner.api.internal.IsolatedLauncherFactory.lambda$createLauncher$0(IsolatedLauncherFactory.java:76)
    ... 7 more
Caused by: javax.net.ssl.SSLPeerUnverifiedException: Hostname sonar.example.org not verified:
    certificate: sha256/efcGoaHuyZ3CK/sYVfBRQroEdq92kUq4ygagx2CcHz0=
    DN: CN=sonar.example.org, OU=Infrastructure, O=example (Private) Limited, L=Colombo, ST=Western Province, C=LK
    subjectAltNames: []
    at org.sonarsource.scanner.api.internal.shaded.okhttp.internal.connection.RealConnection.connectTls(RealConnection.java:350)
    at org.sonarsource.scanner.api.internal.shaded.okhttp.internal.connection.RealConnection.establishProtocol(RealConnection.java:300)
    at org.sonarsource.scanner.api.internal.shaded.okhttp.internal.connection.RealConnection.connect(RealConnection.java:185)
    at org.sonarsource.scanner.api.internal.shaded.okhttp.internal.connection.ExchangeFinder.findConnection(ExchangeFinder.java:224)
    at org.sonarsource.scanner.api.internal.shaded.okhttp.internal.connection.ExchangeFinder.findHealthyConnection(ExchangeFinder.java:108)
    at org.sonarsource.scanner.api.internal.shaded.okhttp.internal.connection.ExchangeFinder.find(ExchangeFinder.java:88)
    at org.sonarsource.scanner.api.internal.shaded.okhttp.internal.connection.Transmitter.newExchange(Transmitter.java:169)
    at org.sonarsource.scanner.api.internal.shaded.okhttp.internal.connection.ConnectInterceptor.intercept(ConnectInterceptor.java:41)
    at org.sonarsource.scanner.api.internal.shaded.okhttp.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:142)
    at org.sonarsource.scanner.api.internal.shaded.okhttp.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:117)
    at org.sonarsource.scanner.api.internal.shaded.okhttp.internal.cache.CacheInterceptor.intercept(CacheInterceptor.java:94)
    at org.sonarsource.scanner.api.internal.shaded.okhttp.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:142)
    at org.sonarsource.scanner.api.internal.shaded.okhttp.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:117)
    at org.sonarsource.scanner.api.internal.shaded.okhttp.internal.http.BridgeInterceptor.intercept(BridgeInterceptor.java:93)
    at org.sonarsource.scanner.api.internal.shaded.okhttp.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:142)
    at org.sonarsource.scanner.api.internal.shaded.okhttp.internal.http.RetryAndFollowUpInterceptor.intercept(RetryAndFollowUpInterceptor.java:88)
    at org.sonarsource.scanner.api.internal.shaded.okhttp.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:142)
    at org.sonarsource.scanner.api.internal.shaded.okhttp.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:117)
    at org.sonarsource.scanner.api.internal.shaded.okhttp.RealCall.getResponseWithInterceptorChain(RealCall.java:221)
    at org.sonarsource.scanner.api.internal.shaded.okhttp.RealCall.execute(RealCall.java:81)
    at org.sonarsource.scanner.api.internal.ServerConnection.callUrl(ServerConnection.java:115)
    at org.sonarsource.scanner.api.internal.ServerConnection.downloadString(ServerConnection.java:99)
    at org.sonarsource.scanner.api.internal.BootstrapIndexDownloader.getIndex(BootstrapIndexDownloader.java:39)
    ... 10 more
04:43:34.561 ERROR:
04:43:34.561 ERROR: Re-run SonarScanner using the -X switch to enable full debug logging.
WARN: Unable to locate 'report-task.txt' in the workspace. Did the SonarScanner succeed?
ERROR: SonarQube scanner exited with non-zero code: 1
Finished: FAILURE

A: The issue was in my certificate; I need to add SAN to the particular domain name (sonar.example.org). After creating a new certificate with SAN, everything goes as expected.


text:
Q: Dynamic content depending on css class I use middleman for developing a website and want to separate markup from content by using the .yml-file. So here is the question:
Is there a way to change the ruby data path depending on a certain css class?
For example I want to put out certain content only if there a css class in the parent tag:
Something like that
If I use just class "page" the ouput must came from sliderA-Section, from the slider.yml

            <%= data.slider.sliderA.content %>

But if I add class "B" to the "page" container, the output must came from the same yml-file but from the SliderB-section in it.
I wish to make this (DYN) part in the data path dynamic by using a variable or so.. which depends on a css-class
<%= data.slider.DYN.content %>

Is something like that possible?

A: You should be able to access your data dynamically as follows:
<% DYN = sliderA %>
<%= data.slider[DYN].content %>

PS: Are you aware of the page_classes helper (http://middlemanapp.com/helpers/#toc_8)? Maybe it could help you, too.

A: you can try the following:
</%= eval "data.slider.#{dyn}.content" %>


text:
Q: Sending data to remote Bluetooth device Hi anyone knows how to send data from the Android phone to the remote Bluetooth device (through OutputStream) without needing to wait for a desired number of bytes to be read by InputStream?
I tried to implement the code as shown below to send data to the remote Bluetooth device but nothing was being sent across.
EDIT: Added in the connectedThread codes:
ConnectedThread.java:
public class ConnectedThread extends Thread{
        public final BluetoothSocket mmSocket;
        public final InputStream mmInStream;
        public final OutputStream mmOutStream;

        public ConnectedThread(BluetoothSocket socket){
            mmSocket = socket;
            InputStream tmpIn = null;
            OutputStream tmpOut = null;

            try{
                tmpIn = socket.getInputStream();
                tmpOut=socket.getOutputStream();
            }catch(IOException e){
            }
            mmInStream = tmpIn;
            mmOutStream = tmpOut;
        }

    public void run() {
            byte[] buffer = new byte[1024];  // buffer store for the stream
            int bytes; // bytes returned from read()

            // Keep listening to the InputStream until an exception occurs
            while (true) {
                try {
                    // Read from the InputStream
                    bytes = mmInStream.read(buffer);
                } catch (IOException e) {
                    break;
                }
            }
        }

        /* Call this from the main activity to send data to the remote device */
        public void write(byte[] bytes) {
            try {
                mmOutStream.write(bytes);
            } catch (IOException e) { }
        }

public void sendData() throws IOException{
            write("1");
        }

ConnectThread.java:
public class ConnectThread extends Thread{
        public final BluetoothSocket mmSocket;
        public final BluetoothDevice mmDevice;
        public final BluetoothAdapter mmAdapter;

        BluetoothConnection mConnectedThread = new BluetoothConnection();

        public ConnectThread(BluetoothDevice device, BluetoothAdapter mAdapter) throws SecurityException, NoSuchMethodException,  IllegalArgumentException, IllegalAccessException, InvocationTargetException {
            mmAdapter = mAdapter;
            mmDevice = device = mmAdapter.getRemoteDevice("00:06:66:4F:90:F8");
            BluetoothSocket tmp = null;

        try{
            tmp = mmDevice.createRfcommSocketToServiceRecord(UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"));
            }catch(IOException e){
                System.out.println("Failed to create Rfcomm and connect to remote device");
            }
            mmSocket = tmp;
        }

        public void run(){
            mmAdapter.cancelDiscovery();

            //sleep to allow time for bluetooth device to get ready
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e5) {
                e5.printStackTrace();
            }

            //handler get message from arduino: that bluetooth device is ready

            //Get BluetoothDevice object
            try{
                //Connect to device
                mmSocket.connect();
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

        }catch(IOException e){
            try{
                //Connect to device
                mmSocket.connect();
            }catch(IOException e1){
                }
                return;
        }
            return;
        }

            mConnectedThread.ConnectedThread(mmSocket);
        }

    }

BluetoothConnection.java:
public class BluetoothConnection extends Service {

public final BluetoothAdapter mAdapter = null;
public ConnectThread mConnectThread;
    public ConnectedThread mConnectedThread;

private final IBinder mBinder = new BluetoothService();

public class BluetoothService extends Binder{
    BluetoothConnection getService(){
            return BluetoothConnection.this;
    }
}

@Override
public IBinder onBind (Intent intent){
    Log.d("Blueooth Connection", "Intent Binder");
    return mBinder;
}

public synchronized void connect(BluetoothDevice device, BluetoothAdapter mAdapter)     throws NoSuchMethodException, IllegalAccessException, InvocationTargetException{

    try{
        mConnectThread = new ConnectThread(device, mAdapter);
        mConnectThread.start();

    }catch(SecurityException e){
        System.out.println("SecurityException at connect()");
    } catch(IllegalArgumentException e){
        System.out.println("IllegalArgumentException at connect()");
    }catch(NullPointerException e)
 {System.out.println("Null Pointer Exception at connect()");
    }
}

public synchronized void ConnectedThread(BluetoothSocket socket){
    mConnectedThread = new ConnectedThread(socket);
    mConnectedThread.start();
}

public void write(String out){
    //create temporary object
    ConnectedThread r;
    synchronized(this){
        r = mConnectedThread;
    }
    r.write(out);
}

@Override
public void onDestroy() {
}
}

In another Activity:
I called sendData(); to write "1" to Arduino.

A: Edit:
Maybe it's not what is causing your problem, but you should not do something like this:
    //Get BluetoothDevice object
    try{
        //Connect to device
        mmSocket.connect();
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

    }catch(IOException e){
        try{
            //Connect to device
            mmSocket.connect();
        }catch(IOException e1){
        }
        return;
    }

You may end with an unconnected mmSocket because you are just ignoring IOException and trying again. Try to e.printStackTrace() in the first try/catch block to see if you have connection issues.
In general, you should never just ignore an exception, as they represent abnormalities in program flow. At worst, print an error message to help you while debugging.
Edit 2:
Please change
public void write(byte[] bytes) {
    try {
        mmOutStream.write(bytes);
    } catch (IOException e) { }
}

to
public void write(byte[] bytes) {
    try {
        mmOutStream.write(bytes);
    } catch (IOException e) {
        e.printStackTrace();
    }
}

and take a look at the logcat output to see if it shows something wrong.


text:
Q: OpenSSL::SSL::SSLError: hostname "smtp.gmail.com" does not match the server certificate This is what i have setup in setup_email.rb file,
if Rails.env.production?
  ActionMailer::Base.smtp_settings = {
      :address              => "smtp.gmail.com",
      :port                 => "587",
      :domain               => "gmail.com",
      :user_name            => "username",
      :password             => "mypass",
      :authentication       => "login",
      :enable_starttls_auto => true
  }
end

This code works in development and staging envoirnment.
This code was working fine on production, suddenly after several days it stopped working and i  am getting error message.
I have tried setting up openssl_verify_mode: none still does'nt work.

Then i changed gmail account but getting same error. Seems like some
  server side error

Error:

OpenSSL::SSL::SSLError: hostname "smtp.gmail.com" does not match the
  server certificate

I have tried different methods out there on internet but its not working. Any help would be appreciated.

A: use
openssl_verify_mode: OpenSSL::SSL::VERIFY_NONE

or
openssl_verify_mode: 'none'

A: In case this answer shows up for others, I had the same problem with a new Rails 7, Ruby 3.1 app.
In my instance, I send emails from the Rails app to a local Postfix instance which relays email to a commercial provider. Always worked fine for me for earlier apps.
My typical settings are:
 config.action_mailer.smtp_settings = {
    address: "localhost",
    port: 25,
    domain: "WHATEVERYOURDOMAINIS",
    enable_starttls_auto: false,
    openssl_verify_mode: OpenSSL::SSL::VERIFY_NONE
  }

This usually works fine, but with the current app, I kept getting errors like this:
SSL_connect returned=1 errno=0 peeraddr=127.0.0.1:25 state=error: certificate verify failed (Hostname mismatch) (OpenSSL::SSL::SSLError)

Using the method to test mailers from this helpful post: https://makandracards.com/makandra/52335-actionmailer-how-to-send-a-test-mail-directly-from-the-console I find that using 0 or 'none' instead of OpenSSL::SSL:VERIFY_NONE does nothing, but it pointed me in the direction of the net-protocol gem, which also supports the disable_start_tls option.
I then adjusted my config to:
  config.action_mailer.smtp_settings = {
    address: "localhost",
    port: 25,
    domain: "WHATEVERYOURDOMAINIS",
    openssl_verify_mode: 'none',
    disable_start_tls: true,
  }

This gets rid of the problem in my case, though clearly it's disabling TLS completely so only useful if you're relaying mail like me through a local mailer.


text:
Q: Android - Search XML (String array) file for items I want to make something that searches through an XML file, to see if a string, entered by the user, exists. My XML file looks like this:
<?xml version="1.0" encoding="utf-8"?>
<resources><string-array name="dict_nl_array" ><item>ADHD</item><item>ADSL</item><item>AMvB</item><item>AOV</item><item>AOW</item><item>uniteit</item></string-array></resources>

The only difference is that my XML is about 500 times as long as this.
I tried loading the arraylist (xml) directly, but then I get this error:

Failed adding to JNI local ref table (has 512 entries)

Which seems logical, because its a gigantic list of items.
So, I was thinking, can I search through that XML file, without having to load it completely?
Ofcourse, other suggestions to do this are welcome! (If possible, with an example, I'd greatly appreciate that!)

A: Late answer, but it might help anyone else with this problem!
Based on this question, you can avoid this error by encoding the resource as a string, rather than a string-array.
<string name="array">ADHD#ADSL#AOV#AOW</string>

The # character separates the entries. To speed up the reformatting, just Find/Replace </item><item> with #. Then you can parse the string into an array like so:
myStringArray = getResources().getString(R.id.array).split("#");

Hope this helps!


text:
Q: NavigationDrawer propagates MotionEvent I am experiencing the following issue:
In an Android application, I use NavigationDrawer for, well ..., navigation.
My issue is that even if the user is opening the drawer (by swiping on left screen border) the ACTION_DOWN MotionEvent is not consumed by the drawer, it is propagated to the underlying view (a GLSurfaceView). In such case, my view receives the MotionEvent with the ACTION_DOWN action, but never receives the ACTION_UP MotionEvent. This corrupts my event management logic.
What I would expect is that whenever you receive the ACTION_DOWN event (and handle it) you should receive the ACTION_UP event when the user stop interacting.
What am I missing ?

A: your GLSurfaceView will most likely receive ACTION_CANCEL event


text:
Q: Help with updating loop condition Okay. So I'm trying to write an applicaton that solves problems in the correct order of operations (i.e. PEMDAS, but without the PE lol). I'm probably doing this wrong, but whatever. What I need help on is that as a iterate through each element in the array, if it is an operator, I remove two elements(the numbers surrounding the operator because I replace the operator the correct computation, so an array with three elements, 5+5, will become an array with one element, 10) which would be fine, but the for-statement condition doesn't update, so, in other words, when i update the array, the array.length gets shorter, but the for-statement doesn't recognize that and continues on pass the bounds of the array, this causes outofbounds errors. Best way to explain is by my code, so here it is:
for (i = 0; i < splitEquation.length; i++){
        if (splitEquation[i].equals("*")){
            splitEquation[i] = Double.toString(Double.parseDouble(splitEquation[i - 1]) * Double.parseDouble(splitEquation[i + 1]));
            splitEquation = removeIndex(splitEquation, i - 1);
            splitEquation = removeIndex(splitEquation, i + 1);
            solution += Double.parseDouble(splitEquation[i - 1]);

        }
}

And removeIndex():
private String[] removeIndex(String [] s, int index){
    String [] n = new String[s.length - 1];

    System.arraycopy(s, 0, n, 0, index - 1);
    System.arraycopy(s, index, n, index - 1, s.length - index);
    return n;
}

Thanks in advance,
-Eric
P.S. Let me know if you need any clarification of what my code does :)

A: Using an ArrayList Would make your life a whole lot easier:
ArrayList<String> splitEquation =
    new ArrayList<String>(Arrays.toList("5","*","5"));

for (i = 0; i < splitEquation.size(); i++){
    if (splitEquation.get(i).equals("*")) {
        splitEquation.set(i,
            (Double.toString(Double.parseDouble(splitEquation.get(i - 1)) *
                Double.parseDouble(splitEquation.get(i + 1))));
        splitEquation.remove(i - 1); // shortens array by 1
        splitEquation.remove(i); // this used to be (i + 1)
        i--; // move back one (your computed value)
        solution += Double.parseDouble(splitEquation.get(i));

    }
}

That being said ... do you really need to modify your array in place?
EDIT: The question is now more clear, the array was being modified because it needs to be evaluated as a series of expressions. He also wants to add addition and subtraction:
Recursive functions are your friend :)
public static double result(ArrayList<String> mySequence, double total, int index)
{
    if (index == 0)
        total = Double.parseDouble(mySequence.get(index));

    if (index == (mySequence.size() - 1))
        return total;
    else if (mySequence.get(index).equals("*"))
        total *= Double.parseDouble(mySequence.get(index + 1));
    else if (mySequence.get(index).equals("/"))
        total /= Double.parseDouble(mySequence.get(index + 1));
    else if (mySequence.get(index).equals("+"))
    {
        index++;
        double start = Double.parseDouble(mySequence.get(index));
        total += result(mySequence, start, index);
        return total;
    }
    else if (mySequence.get(index).equals("-"))
    {
        index++;
        double start = Double.parseDouble(mySequence.get(index));
        total -= result(mySequence, start, index);
        return total;
    }

    index++;
    return result(mySequence, total, index);

}

public static void main(String args[])
{
    ArrayList<String> splitEquation =
        new ArrayList<String>(
            Arrays.asList("5","*","5","/","5","*","4","-","3","*","8"));

    double myResult = result(splitEquation, 0, 0);
    System.out.println("Answer is: " + myResult);
}

Output:

Answer is: -4.0

A: Why modify the input array when you could use the input array as read-only and create output ArrayLists (or better stacks)?

A: I think that if you use a dynamic structure, such as an ArrayList, you should be able to fix that problem.
According to this:

The capacity is the size of the array
  used to store the elements in the
  list. It is always at least as large
  as the list size. As elements are
  added to an ArrayList, its capacity
  grows automatically.

and this previous SO post, using a dynamic data structure should solve your problem, I think that the same mechanism applies for when you remove, as well as add, elements from the list. You might however, need to implement some mechanism to keep track of where the items are after each and every replacement you make.


text:
Q: git merge the current branch as second parent When a merge has conflicts I back out and redo the merge with a temporary branch such that I'm merging my feature branch into the upstream branch.
This makes it simplier to see the merge diff when there are conflicts. During the merge a git status or git diff contain my feature branch changes vs. the many changes that have happened upstream.
Can I simplify these commands, hopefully to a single git command then a commit?:
# prepare a place to do the merge:
git checkout -b my-feature-merged-into-master origin/master
git merge my-feature
# If there are conflicts, git status should show results similar to
# git diff origin/master...my-feature
git commit
git branch -D my-feature
git branch --move my-feature-merged-into-master my-feature

A: You start with my-feature branch and you end with my-feature branch but augmented with the upstream changes.  So clearly the easiest way, in terms of minimal Git commands, is:
git merge origin/master

If there are no conflicts, you are done.  If there are conflicts, then you will want to examine them all, one by one, and the effort involved in the examination will be much more than generating the diff.  Overall, thus, a win for the above command.


text:
Q: Proper way to retrieve return value of wait  command I have the following code in a bash script:
 for job in `jobs -p`; do
     echo "PID => ${job}"
     if ! wait ${job} ; then
     echo "At least one test failed with exit code => $?" ;
     EXIT_CODE=1;
     fi
 done

wait <pid>, in this case, wait ${job}, should return the exit code, but I don't know how to get/see the value. What I need to do is change the above script to something like this:
for job in `jobs -p`; do
     echo "PID => ${job}"
     CODE=0;
     wait ${job} || CODE=$?
     if ! ${CODE} ; then
     echo "At least one test failed with exit code => ${CODE}" ;
     EXIT_CODE=1;
     fi
 done

is there a cleaner less verbose way to do this? I am confused about how to retrieve the "return value" from wait <pid>, besides using the technique I just used. Is there another way to do it?

A: How about this:
declare -A failures
for job in `jobs -p`; do
  wait "$job" || ((failures[$job] = $?))
done

if (( "${#failures[@]}" > 0 )); then
  # traverse the hash and print which processes failed, along with exit code
fi

A: If you really want to be more concise, you could do like:
wait $job || {
   echo "$job failed with code $?"
   EXIT_CODE=1
}

Side Note: for job in $(jobs -p); do might not be the best idea.  The jobs list is expanded when the loop starts, but jobs might complete while the loop is running (e.g. while you are waiting for the first job in the list, the second job finishes).
Instead, you could do something like:
while :; do
   wait -n && continue            # wait for any job to finish
   code=$?
   ((code==127)) && break         # no jobs found to wait for
   echo "A test failed with code $code"
done

A: Cleaner? What could be cleaner than the most obvious and straightforward way:
wait $job
status=$?
if (( $status != 0 )); then
    ...
fi

Sure it's a tiny bit verbose, but it's also easy to understand. What you don't want is code that will make you scratch your head and be confused.


text:
Q: $\sum \frac{n^2+1}{n+2}$ using root test If I'm only using root test, then is $\sum \frac{n^2+1}{n+2}$ useful to root test? I make it $(\frac{n^2+1}{n+2})^{\frac{1}{n}}$ simply, and it's turning to 1. Then there is impossible to see if the test works. ¿Yes? or no.

A: You are right about the value of the limit in this particular case, the root test is inconclusive. However, note that $\frac{n^2 + 1}{n + 2} \geq 1$ for all $n \geq 2,$ so that your series does not converge. Another way to see this is to note that $\lim_{n \to \infty} \frac{n^2 + 1}{n + 2} = \infty.$ I hope this helps. :)


text:
Q: Node alignment on flowcharts So, I'm building a flowchart based operation manual for the SEM at the lab that I work, and I'm having a trouble aligning a node with respect to two others.
I've seen already a few pages[1][2][3][4] here that present the same problem and tried their solutions, but with no success what soever, so if someone can help me I would appreciate very much.
This is my MWE:
%%%  DOCUMENT SETTINGS  %%%
\documentclass[12pt, a3paper]{article} %page type
\usepackage[margin=2cm]{geometry} %margins
\usepackage{setspace}
\usepackage{indentfirst} %indenting package
\setstretch{1.5} %between lines spacement
\setlength{\parindent}{1.5cm} %first line indentation

%page settings
\usepackage{fancyhdr}
\pagestyle{fancy} % seting to use the customizable head and footers
\fancyhf{} % cleaning standard head and footers to use the new one
\rfoot{Autores: Eduardo de Almeida Isoppo;\\Luiz Felipe Pompermaier.} % page number on the footer's right side
\renewcommand{\headrulewidth}{0pt} %remove the line on the headers
\usepackage{float} % tables and figures in multicols.

%font and language configs
\usepackage[brazil]{babel} %letter type
\usepackage[utf8]{inputenc} %normal acentuation
%\usepackage{arial}
    % using pseudoarial font Helvetica.
    \usepackage{helvet}
    \renewcommand{\familydefault}{\sfdefault}
    \usepackage[T1]{fontenc}

%Reference configs
\usepackage{hyperref}
\hypersetup{
    colorlinks=true,
    linkcolor=red,
    citecolor=black,
    filecolor=magenta,
    urlcolor=blue,
    breaklinks=false,
    pdfauthor={Luiz Felipe Pompermaier}
    }

%image config
\usepackage{graphicx} % Image using package
%\graphicspath{{Imagens/}} % Image path
\usepackage{caption} % Image, tables, and others captions.
\usepackage{subcaption} % SubImage package. More then one per line.

%math config
\usepackage{amssymb}
\usepackage{amsmath}

% text packages
\usepackage{blindtext} % lorem ipsum
%\usepackage{lipsum}
%\usepackage{titling} % used to make title higger in page
\usepackage{sectsty} % section title
\sectionfont{\fontsize{12}{15}\selectfont} %changing section fontsize
\usepackage{multicol} % multiple columns
\usepackage{xcolor} % coloring text
\usepackage[none]{hyphenat} % no hyphenation
\usepackage{microtype} % better justification
\usepackage{tcolorbox} % text in coloured boxes

% tikz package for flowchart drawings
\usepackage{tikz}
\usepackage{tikz-layers}
\usetikzlibrary{shapes.geometric, arrows}
\usetikzlibrary{positioning}
\usetikzlibrary{fit}
\usetikzlibrary{calc}
\usetikzlibrary{intersections}

% Flowchart configs
\tikzstyle{startstop} = [ellipse, minimum width=3cm, minimum height=2cm,text centered, text width=3cm, draw=black, fill=red!30]
\tikzstyle{io} = [trapezium, trapezium left angle=70, trapezium right angle=110, minimum width=3cm, minimum height=1cm, text centered, draw=black, fill=blue!30]
\tikzstyle{process} = [rectangle, minimum width=3cm, minimum height=1cm, text centered, text width=3cm, draw=black, fill=orange!30]
\tikzstyle{decision} = [diamond, aspect=2, minimum width=3cm, minimum height=1cm, text centered, text width=3cm, draw=black, fill=green!30]
\tikzstyle{arrow} = [thick,->,>=stealth, line width=2pt]

\newlength{\AL}
\setlength{\AL}{2cm}

\begin{document}

\begin{center}
    \Huge \textbf{Fluxograma de Operação do MEV}
\end{center}

\begin{figure}[!htb]
    \centering
    \begin{tikzpicture}
        % Nodes and texts
        \node (SftWrk) [decision, below=\AL of ScrnON] {Software está funcionando?};
        \node (SftErr) [process, left=\AL of SftWrk] {Chame um Técnico};
        \node (VentCb) [process, below=\AL of SftWrk] {Ventilar câmara segurando \textbf{VENT}.};
        \node (SmplHd) [process, left=\AL of VentCb, dashed] {Montar Porta-amostras desejado.};
        \begin{scope}[on behind layer]
            \node (Sample) [io][fit=(SmplHd)]{};
        \end{scope}

        % Arrows
        \begin{scope}[on background layer]
            \draw[arrow] (SftWrk) -- node[anchor=south] {\textbf{NÃO}} (SftErr);
            \draw[arrow] (SftWrk) -- node[anchor=east] {\textbf{SIM}} (VentCb);
            \draw[arrow] (Sample) |- ($(EvacCb)!.5!(VentCb)$);
            \draw[arrow] (VentCb) -- +(0,-\AL);
    \end{tikzpicture}
\end{figure}

\end{document}

This is the result it produces (focusing on the area of interest):

And what I want is to align the (SmplHd) box below of (SftErr) and left of (VentCb), if this makes sense to everyone reading this.
And to be more explicit about it, no the at (SftErr|-VentCb) command does not work.
For the complete compilation please check https://www.overleaf.com/read/nfyvphkggdny

A: Edit:
Extend of image fragment with two more nodes an slightly modified nodes shapes styles.
Like this?

This image fragment is produced by the following MWE (Minimal Working Example)
\documentclass[12pt, margin=3mm]{standalone}    % page type
\usepackage{helvet}
    \renewcommand{\familydefault}{\sfdefault}
\usepackage[brazil]{babel}

\usepackage{tikz}
\usetikzlibrary{arrows.meta,
                backgrounds,
                calc, chains,
                fit,
                intersections,
                positioning,
                quotes,
                shapes.geometric,
            babel
                }
% Flowchart config
\makeatletter
\tikzset{
         base/.style = {draw=black, semithick, font=\small,
                        minimum height=9mm, text width=33mm, align=flush center,
                        outer sep=0pt},
    startstop/.style = {base,
                        ellipse, fill=red!30},
           io/.style = {base,
                        trapezium, trapezium left angle=70, trapezium right angle=110,
                        fill=blue!30},
      process/.style = {base, fill=orange!30},
     decision/.style = {base, inner sep=1pt,
                        diamond, aspect=2, fill=green!30},
          arr/.style = {-Stealth, thick},
every edge quotes/.append style = {auto, pos=0.4, font=\footnotesize\bfseries},
  suspend join/.code = {\def\tikz@after@path{}} % for use in not showed image part
        }
\makeatother
\newlength{\AL}
\setlength{\AL}{12mm}

\begin{document}
    \begin{tikzpicture}[
node distance = \AL and \AL,
  start chain = going below
                        ]
% first branch (unfinished)
    \begin{scope}[nodes = {on chain, join=by arr}]
\node (ScrnON)  [process]   {Ligar Monitores};
\node (SftWrk)  [decision]  {Software está funcionando?};
\node (VentCb)  [process]   {Ventilar câmara segurando \textbf{VENT}.};
\node (EvacCb)  [process]   {Evacuar câmara segurando \textbf{EVAC}.};
   \end{scope}
% left from first branch
\node (SftErr)  [process,
                 left=of SftWrk]    {Chame um Technico};
\node (SmplHd)  [process, dashed,
                 at={(SftErr |- VentCb)}]   {Montar Porta-amostras desejado.};
\scoped[on background layer]
    \node (Sample) [io, fit=(SmplHd)]   {};
% second branch (unfinished)
    \begin{scope}[nodes = {on chain, join=by arr}]
\node (HeatON) [process, suspend join,
                right=2*\AL of ScrnON] {Subir corrente \textbf{devagar} até ponto de saturação.};
\node (SmpLct) [process]    {Localizar Amostra a ser analisada.};
\end{scope}
% third branch

% Arrows
\path
    (SftWrk) edge ["\textbf{NÃO}" '] (SftErr)
    (SftWrk) edge ["\textbf{SIM}"]   (VentCb);
\draw[arr]
    (SftWrk) -- (SftErr);
\draw[arr]
    (Sample) |- ($(VentCb.south)!0.5!(EvacCb.north)$);
    \end{tikzpicture}
\end{document}

*

*In MWE are omitted all what is not relevant at drawing of the image.

*Used is recent syntax for determining of nodes shapes styles (with \tikzset instead of obsolete tikzstyle)

*Position of the node with dashed border is on intersection of vertical lines through above node and horizontal line through right node, i.e. by at={(SftErr |- VentCb)}.

*positions of nodes in other branches is planed to be determined by chains (indicated are only with two top nodes in the second chain)

*MWE code is significantly simplified. By used of join=by ... macro are drawn all connection lines between nodes of in branch, so they need to be draw only for nodes out of branches and between branches.


text:
Q: Is there a way to theme the notifications in XFCE? I'm kinda bored of how they look and the fact that there's only 3 themes to choose from is even worse, so I was wondering if there is a way to theme the notification bubbles of XFCE?.

A: Theming the xfce notifications
The themes of the notification bubble defined by a specially formatted file called gtkrc found within the folder structure /usr/share/themes/[theme name]/xfce-notify-4.0
All system-wide themes must follow the above naming convention.
For user-specific notification bubbles, the same [theme name]/xfce-notify-4.0/gtkrc file & folder structure can be created in your home folder ~/.themes
Lets create a copy of an existing notification bubble theme to work with - our new theme is going to be called playtime:
mkdir -p ~/.themes/playtime/xfce-notify-4.0
cp /usr/share/themes/Greybird/xfce-notify-4.0/gtkrc ~/.themes/playtime/xfce-notify-4.0/

Now launch the notification manager in system settings:

You'll see our new playtime theme.
customisation
Now lets have some fun with customizing this theme.
Open the gtkrc file for playtime
leafpad ~/.themes/playtime/xfce-notify-4.0/gtkrc

When customising the theme - change to another notification theme and back to playtime for the change to take effect.
changing the font
The bit in this file we are interested in to customise the text is this section:
style "greybird-notify-text"
{
    fg[NORMAL] = "#ffffff"
    GtkWidget::link-color = "#a7a7a7"
}

We can customise the font by adding font_name = "Serif 18" to this (between the { ... }:

So where to we get the font name - easiest place is actually the Font Window in the Appearance window:

Just add the text descriptions together as shown - for example Serif Italic 10
changing the font colour
We can change the font colour by modifying the RBG format number i.e. ff0000 is Red, 00ff00 is Blue and 0000ff Green - other colours are mixtures of these.
Thus - fg[NORMAL] = "#ff0000" gives us this:

changing the background colour
The bit in this file we are interested in to customise the background colour is this section:
style "greybird-notify-window"
{
    XfceNotifyWindow::summary-bold = 1
    bg[NORMAL] = "#111"
    XfceNotifyWindow::border-color = "#ffffff"
    XfceNotifyWindow::border-radius = 10.0
    XfceNotifyWindow::border-width = 3.0
}

The bg[NORMAL] value is again in RBG format - e.g. #00ff00 is green:


text:
Q: how to serialize HashSet i'm building an android app and i want to add a history function. I heard that i can serialize a list to be able to save and retrieve data instead of using a Database, i have no idea how it works so i come here and ask for advice, is there somewhere i could get started with this. Some good links could be useful.
Thanks

A: HashSet implements Serializable. So as long as all the objects you put inside your hash set also implements Serializable (and all objects inside them again etc.), you can serialize it as any other normal serializable java object.

A: You should not use serializable, android implements parcelables in a much much more effective way. The catch is you have to define how parcel the object yourself, but it really isnt that hard.
Simple example:
public class MyParcelable implements Parcelable {
     private int mData;

     public int describeContents() {
         return 0;
     }

     public void writeToParcel(Parcel out, int flags) {
         out.writeInt(mData);
     }

     public static final Parcelable.Creator<MyParcelable> CREATOR
             = new Parcelable.Creator<MyParcelable>() {
         public MyParcelable createFromParcel(Parcel in) {
             return new MyParcelable(in);
         }

         public MyParcelable[] newArray(int size) {
             return new MyParcelable[size];
         }
     };

     private MyParcelable(Parcel in) {
         mData = in.readInt();
     }
 }

If you want to save a Hashset, you just need to make sure that the objects inside the Hash are also parcelable.
If you feel this is too much trouble, the answer previously posted by Nailuj is right.


text:
Q: How to get a tables TD-offset()'s with jQuery 1.5.2 (Drupal7)? I need to find the correct .offset()-position of a tabled TD-elements within a Drupal7-generated HTML-site (jQuery_update installed). I use
        $('#contenttable td').each(function(){
            console.log($(this).offsetParent());
            console.log($(this).offset().left);
        });

within my
jQuery(function($) {
    //$(document).ready(function(){

of my script.js to get the offset().left-position but the console allways traces me '0' for all TDs.
When I use the Safari Developer Console the output of
jQuery('#contenttable td:nth-child(2)').offset().left

is '1728', so it seems to work at all. But why doesn't it work from within my DOCUMENT.READY?
The .offsetParent() is BODY by the way... And changing some of the parents DIV's position to absolute or relative didn't give any change, too.
THNX!
edit: seems not to work for any element at all.

A: Unfortunately, jQuery.offset does not work on hidden elements, because the browser doesn't bother rendering them at all. So if possible, you need to make the element visible in order to get its offset. According to jquery: get the offset of hidden element , you should be able to call .show() on the table/content, get the desired offset, then call .hide() on it. This show/hide should not be apparent to the user, as it won't repaint the page since it's in the same execution event.


text:
Q: Como converter os caracteres dentro do formulário e imprimo em tela? Como faço com que os caracteres de - sejam convertidos em : número dentro do formulário.

Ao colar um número dentro do formulário, como no exemplo acima; quero que os - sejam convertidos em :, ficando 00:00:00:00.

function substituiPonto(){
  valor = document.calcform.visor.value;
  document.getElementById("visor").value = valor.replace("-", ":");
}
function tela(){
  window.alert(valor);
}
<form name="calcform" method="post" action="">
  <input type="text" name="visor" id="visor" value="" onKeyPress="substituiPonto()"/>
</form>

Por esse código eu só consigo que converta enquanto digito, e não converte quando dou CTRL+V dentro do formulário.

A: Colocando o onfocusout="substituiPonto(), aproveitando sua função substituiPonto(), apenas substituindo replace() para replaceAll(). Quando colar (CTRL+V) o formato 00-00-00 por exemplo, e ao sair do seu input, ou seja, no evento onfocusout, será chamado substituiPonto(), substituindo todo - encontrado por :. Aí já poderia exibir no formato que você quer, utilizando :.

function substituiPonto(){
  valor = document.calcform.visor.value;
  document.getElementById("visor").value = valor.replaceAll("-", ":");
}
function tela(){
  window.alert(valor);
}
<form name="calcform" method="post" action="">
  <input type="text" name="visor" id="visor" value="" onKeyPress="substituiPonto()" onfocusout="substituiPonto()"/>
</form>


text:
Q: Global Positioning System in j2me Can I use GPS in J2me enabled phones?
I am curious to know whether one can use GPS in J2ME enabled phone or can create an application based on GPS?

A: JSR 179 Location API for J2ME is intended to support creation of applications based on GPS, see JSR 179 specification page, section 2.5:

...this API shall work with most positioning methods, such as GPS...

If you are interested in more details, below tutorials make for a good start:

*

*Develop a location-based service application using JSR 179

*Developing Location Based Services: Introducing the Location API for J2ME


text:
Q: Target for a Poker game Neural Network I've created a python simulation of a texas holdem poker game with 3 random actions, check/fold, check/call and bet. I have then looped this round several times to produce a training data set for each decision. With the outcome of the hand in terms of final hand strength, profit and also action taken.
I've then created a variety of models with the favored being a one hot softmax category for each of the 3 actions. However, when I re-run the simulation comparing random against the trained model, I barely do better than random.
I'm currently only training on actions where the profit of the hand is => 0. However I've read that excluding negative data can adversely effect the model.
I've also tried changing the action to check/fold where there is a loss, as this would have been the correct action to take. However the model is then massively skewed towards folding and predicts fold 99.9% of the time.
What is the best target variable to use? Can I use a categorical target, applying the magnitude or significance of that scenario using the profit?


text:
Q: Google Maps - not displaying? I want to display a map and then 3 text links in a sidebar that onclick will change the location on the map.
The map won't display as a result of trying to port over code from V2 to V3.
I'm sure just a small error..  my code is as follows:

A: Ok, try this code:
<!DOCTYPE html>


text:
Q: C# : "Logon failure: unknown user name or bad password " error while using PROCESS.START() METHOD I tried to login to gmail with the code:
private void button1_Click(object sender, EventArgs e)
{
    var user = new SecureString();
    foreach (char c in textBox3.Text)
    {
        user.AppendChar(c);
    }

    Process.Start("C:/Users/Indish/Desktop/chrome",
        "www.gmail.com", user, textBox4.Text);
}

The program says logon failure as mentioned in the question.So, if any one can help .........Thanks in advance

A: First of all, you are using the wrong parameters for the overload of the method that you are using. The parameters are:
Process.Start(fileName, userName, password, domain)

So, you are sending www.gmail.com as user name, and the user name as password, that's why you get the error message that the login fails.
You need to use the overload that takes five parameters to send arguments and login to the method:
Process.Start(fileName, arguments, userName, password, domain)

However, that is used to provide a login for the user account that is used to run the program, not sending the login information to the program.
If the web page supports it, you can send login information in the URL:
Process.Start("C:/Users/Indish/Desktop/chrome", user + ":" + textBox4.Text + "@www.gmail.com");

Otherwise you would need to embed a browser control in your program to access the form after it has loaded.

A: I can help you, however, where is the code you are using for the HTML interaction? Maybe I am misunderstanding. Are you posting these variables to the web server and checking the response, or are you using a no return method to just log in?
--EDIT--
I apologize, I am a little new to Stack Overflow's operations yet. What you will want to do for something like that is use a webBrowser1.Document.GetElementById("IDNAME").SetAttribute("value", "data to put in"); on web browser inside of the application. In the case of FaceBook, the HTML of the website already has an  tag embedded on the box you are trying to set.
So, with this in mind, you can use the HTML ID of the tag by replacing "IDNAME" with "email" as is the ID for that box on FaceBook. You can do this for the entire login process (including using webBrowser1.Document.GetElementByID("ID OF THE BUTTON HERE").InvokeMember("click");
You can usually access the developer console as seen in my Chrome below via F12, or CTRL+SHIRT+C in Chrome, F12 with FireBug in FireFox, and F12 in IE. You are looking for a tool called "Inspect Element" to find the ID.


text:
Q: Dropdown reset issues with IE7 works fine on FireFox and Chrome Hello Stackoverflow I have a simple form validation logic that doesn't seem to work on IE7 for some reason.
Basically I have two dropdown boxes and an input box. When the first dropdown box state changes the other dropdown and inputbox clears.
Current this logic seem to work on FF, Chrome but not IE7. Also the clearing of the input box works as expected on IE as well.
$('#names').change(function(){
    $('#rate').val("0");
    $('#amount').val("");
});

Any helps would be greatly appreciated.

A: It seems IE requires you to add the null value in order to change it to the first element.
<option>--</option>

To
<option value="0">--</option>

Fixed the issue :)


text:
Q: Get Unique List of Combinations of Strings, regardless of Order I have a dataframe with two columns that repeat themselves in reverse order (i.e. the pairing of the two columns will always be the same)
Example:
col1 <- c('a', 'c', 'g', 'd', 'e', 'b', 'f', 'h')
col2 <- c('b', 'd', 'h', 'c', 'f', 'a', 'e', 'g')

df <- data.frame(col1, col2, stringsAsFactors = FALSE)

I want to add a column as an identifier of these combinations regardless of the order (e.g. row 1 and row 6 are equivalent). The final solution would look like:
  col1 col2 ID
1    a    b  1
2    c    d  2
3    g    h  3
4    d    c  2
5    e    f  4
6    b    a  1
7    f    e  4
8    h    g  3

A: df$grp <- interaction(do.call(pmin, df[1:2]), do.call(pmax, df[1:2]))

df
#   col1 col2 grp
# 1    a    b a.b
# 2    c    d c.d
# 3    g    h g.h
# 4    d    c c.d
# 5    e    f e.f
# 6    b    a a.b
# 7    f    e e.f
# 8    h    g g.h

If you want numbers, you can then do
df$grp <- as.integer(df$grp)

df
#   col1 col2 grp
# 1    a    b   1
# 2    c    d   6
# 3    g    h  16
# 4    d    c   6
# 5    e    f  11
# 6    b    a   1
# 7    f    e  11
# 8    h    g  16

A: data.table oneliner
You create the by using apply
apply (df, 1, function(x) paste0( sort( x ), collapse='' ) )
which results in
[1] "ab" "cd" "gh" "cd" "ef" "ab" "ef" "gh",
the sorted combination of col1 and col2.
Based in this vector, data.table can create group-numbers for each unique element, which you pass to the new ID-variable using .GRP.
library(data.table)

setDT(df)[, ID := .GRP, by = apply (df, 1, function(x) paste0( sort( x ), collapse='' ) ) ][]

#    col1 col2 ID
# 1:    a    b  1
# 2:    c    d  2
# 3:    g    h  3
# 4:    d    c  2
# 5:    e    f  4
# 6:    b    a  1
# 7:    f    e  4
# 8:    h    g  3

A: A solution using dplyr and purrr:
ordered_paste <- function(x, y) {
  paste0(c(x, y)[order(c(x, y))], collapse = "")
}

df %>%
  mutate(ID = map2(col1, col2, ~ ordered_paste(.x, .y)))
#   col1 col2 ID
# 1    a    b ab
# 2    c    d cd
# 3    g    h gh
# 4    d    c cd
# 5    e    f ef
# 6    b    a ab
# 7    f    e ef
# 8    h    g gh


text:
Q: Prove existence positive integers $\epsilon <|h\sqrt{m}-k\sqrt{n}|<2\epsilon$ Given positive integers $h,k$ and $\epsilon>0$ show that there exist positive integers $m,n$ so that the inequality $\epsilon<|h\sqrt{m}-k\sqrt{n}|<2\epsilon$

A: You can even achieve $\epsilon< h\sqrt{m}-k\sqrt{n}<2\epsilon$, without absolute value.
Begin by considering the curves $h\sqrt{y}-k\sqrt{x}=\epsilon$ and $h\sqrt{y}-k\sqrt{x}=2\epsilon$  in the positive quadrant of the $xy$-plane. It helps to present them as graphs of functions: $y=f_1(x)=((\epsilon+k\sqrt{x})/h)^2$, and similarly for the other, $y=f_2(x)=((2\epsilon+k\sqrt{x})/h)^2$. Then consider the difference $f_2(x)-f_1(x)$ and show that it grows indefinitely  as $x\to\infty$. Therefore, $f_2(x)-f_1(x)>1$ for all sufficiently large $x$. Conclude that there is a point with integer coordinates between these two curves.

A: This is problem B1 from the 2011 Putnam competition. One solution is on the MAA Putnam website.


text:
Q: ¿Cómo puedo ingresar varios valores a una misma columna? Quisiera poder realizar una base de datos de una escuela
Tengo una base de datos hecha en la cual, al realizar el login de los usuarios de la escuela, debo ingresar a cada alumno y eso está bien porque en ese caso es agregar el curso del alumno y ya está pero, en caso de los preceptores debo poner más de un curso y en caso del directivo debe tener acceso a todos los cursos y en mi caso de administrador también, por lo que quería saber cómo podría hacer para agregar varios valores a un usuario y en una misma columna.

A: Eso lo puedes hacer con relaciones de tablas, que para el ejemplo actual seria una relacion de mucho a mucho.
Por Ejemplo, tener las siguientes tablas:
Usuarios{
 id, nombre, etc
}

Cursos{
 id, nombrecurso, etc
}

En esta tabla se expone la relacion mucho a mucho entre ambas tablas
Lo puedes hacer en base a roles en vez de usuarios, y que los usuario tengan relacion con los roles.
RelUsuarioCurso {
 id, usuarioId, cursoId
}


text:
Q: jQuery - toggleClass() needs to start closed on refresh Is there a way to make a menu that is closed by toggleClass() be closed automatically after refreshing the page?
The button that calls toggleClass() works perfectly. The session also remembers if the menu is hidden, so it performs the closing animation upon refresh. Is there an easy way to have the menu hidden when refreshed instead of performing the animation?
For further clarification, here is a quick video I took of the issue:
initialize: function()
    {
        if(sessionStorage.getItem('sidebar.open') == 'false')
        {
            this.toggle();
        }
    },

    toggle: function()
    {
        var self = this;

        $(this.sidebarEl).toggleClass('active');

        _.each(this.contentEl, function(el)
        {
            $(el).toggleClass('active');
        });

        sessionStorage.setItem('sidebar.open',
                                $(this.sidebarEl).hasClass('active'));
    },

A: I'm assuming the transition is a CSS transition, right? That's why you're only changing the class...
Think about maybe canceling the transition, and then re-appending it.
CSS
.notransition { /*class to cancel transition*/
  -webkit-transition: none !important;
  -moz-transition: none !important;
  -o-transition: none !important;
  -ms-transition: none !important;
  transition: none !important;
}

HTML

...

JS
initialize: function()
{
    if(sessionStorage.getItem('sidebar.open') == 'false')
    {
        this.toggle();
    }
    $(this.sidebarEl).removeClass("nontransition") // Then, delete nontransition, and allow the transition to work
},


text:
Q: Finding undefined variable name string in ReferenceError My question is simple, but Javascript VM dependent.
When catching a ReferenceError (in my case when doing eval(...)), how do I get back the actual identifier token from the error object?
Matching for "known" error messages and parsing them seems way too hackish for me, but is the only available option to me right now.
edit: For the moment I'm only "matching" V8 and Firefox by doing this:
catch(e){
    if (e.name === "ReferenceError"){
       var varname = e.toString().replace("ReferenceError: ","")
                      .replace(" is not defined","").trim();
       foobar(varname);
    }
 }

A: You should be able to do this using e.message and matching the text up until the first space.
The following code works in IE7/IE8/IE9/IE10/Chrome and Firefox.
try {
    alert(tesssst);
} catch(e){
    if (e.name === "ReferenceError" || e.name === "TypeError") { //IE7 uses TypeError instead
        var variableName = e.message.substr(0, e.message.indexOf(" "));

        //IE7 and IE8 fix (it adds ' around the variable name)
        if (variableName.substr(0, 1) == "'" && variableName.substr(variableName.length - 1) == "'") {
            variableName = variableName.substr(1, variableName.length - 2);
        }

        console.log(variableName); //tesssst
    }
}

Edit:
Added IE7/IE8 fixes
Edit 2:
With a little regex magic you can change this to the following:
try {
    alert(tesssst);
} catch(e){
    if (e.name === "ReferenceError" || e.name === "TypeError") { //IE7 uses TypeError instead
        var variableName = e.message.match(/^'?(.*?)'? /)[1];
        console.log(variableName);
    }
}


text:
Q: delete rows matrix R containing NaN I import a table into R using:
mydata = read.csv("mydata.csv")

Some of the cells of the table are undefined, I convert them to NaN.
mydata[mydata == "<undefined>"] <- NA

I would like to find the indeces of the rows containing NaN for the column 4 and delete the corresponding rows (across all the table).
Could you please help me?
In matlab I would do:
idx_rows_nan = find(isnan(mydata(:,4)));
mydata(idx_rows_nan,:)=[];

A: Try is.na() (with a dot)
mydata[!is.na(mydata[,4]),]

In two steps, one could first identify the rows containing NA in column 4 by defining a logical vector na_rows:
na_rows <- is.na(mydata[,4])

The row numbers with NA in column 4 can be displayed with which(na_rows)
Then one could remove these rows with
mydata <- mydata[!na_rows,]

If you want to identify NaN entries instead of NA, the function is.nan() can be used.


text:
Q: I need a SQL query for top 5 upcoming birthdays and recent previous birthdays I have a SQL query to the today birthdays user.
SELECT * FROM Table_EmployeeInfo WHERE MONTH(DOB) = MONTH(getdate()) and day(DOB)=day(getdate())

But I need top 5 users SQL query for upcoming birthdays, not today users birthday, it should be tomorrow, if no body will tomorrow means take from next days.
Also, I need recent top 5 user birthdays gone, not today users birthday.

A: You can use ROW_NUMBER() function like this:
SELECT * FROM(
    SELECT t.*,
    row_number() OVER(order by datepart(mm,t.DOB),datepart(dd,t.DOB)) as rnk
    FROM Table_EmployeeInfo t
    where t.DOB > getdate())
WHERE rnk <= 5

A: Messy, but it works:
select * from (
SELECT datediff(dd,DATEADD(yyyy, DATEDIFF(yyyy, DOB, GETDATE()), DOB),getdate()) as daysSinceBD
,  DENSE_RANK() OVER( ORDER BY datediff(dd,DATEADD(yyyy, DATEDIFF(yyyy, DOB, GETDATE()), DOB),getdate()) desc ) as Ranking
,  * FROM Table_EmployeeInfo
 where datediff(dd,DATEADD(yyyy, DATEDIFF(yyyy, DOB, GETDATE()), DOB),getdate()) < 0

 )x   where ranking <=5 order by 1 desc

A: Try this below for select upcoming 5 birthdays
SELECT top 5 * FROM Table_EmployeeInfo WHERE CONVERT(DATETIME,
            CONVERT(VARCHAR(10), DOB, 111)) > CONVERT(DATETIME,
            CONVERT(VARCHAR(10), GETDATE(), 111)) order by dob

This one for past 5 birthdays
SELECT top 5 * FROM Table_EmployeeInfo WHERE CONVERT(DATETIME,
            CONVERT(VARCHAR(10), DOB, 111)) < CONVERT(DATETIME,
            CONVERT(VARCHAR(10), GETDATE(), 111)) order by dob

A: I have tested the codes against an old database with Date of Birth data, and they worked.
Since I do not have Date of Birth exact time (hour and etc), I did not handle the situation where I have 10 or more people with birthday on same day.
I have used the "OFFSET - FETCH" approach, that can help you if you need some kind of pagination in the future.
I do not know your scenario and/or data model, but if this query is to be run frequently and database tends to be big, I'd suggest you to consider a computed column "Anniversary", or anything compliant with your database names convention. This is because you have to use a lot of functions to achieve what you need, and this is not good for performance. With a computed column, you have less complexity on queries and a better indexing strategy.
Please find below the code I have written, and let me know if it helps.
-- LAST 5 BIRTHDAYS GONE, NOT FROM TODAY
SELECT
*
FROM
    Table_EmployeeInfo AS T
WHERE
    DATEPART(DD, T.DOB) < DATEPART(DD, GETDATE())
AND
    DATEPART(MM, T.DOB) <= DATEPART(MM, GETDATE())
ORDER BY
     DATEPART(MM, T.DOB) DESC
    ,DATEPART(DD, T.DOB) DESC
OFFSET 0 ROWS FETCH NEXT 5 ROWS ONLY

-- NEXT 5 BIRTHDAYS TO COME, NOT FROM TODAY
SELECT
*
FROM
    Table_EmployeeInfo AS T
WHERE
    DATEPART(DD, T.DOB) > DATEPART(DD, GETDATE())
    AND
    DATEPART(MM, T.DOB) >= DATEPART(MM, GETDATE())
ORDER BY
     DATEPART(MM, T.DOB) ASC
    ,DATEPART(DD, T.DOB) ASC
OFFSET 0 ROWS FETCH NEXT 5 ROWS ONLY

P.S.: OFFSET-FETCH will work only on SQL Server 2012 or above. If you are using and older version, try using TOP(5) instead.


text:
Q: Possible ways to get to a point (on a prism)
I could find the answer by trying every possible way. But now i want to know if there is any sort of equation or formula i can use to solve this.

A: Use variables such as $x$ (down), $y$ (right), $z$ (forward) for one step in each direction.  Here the sequence would be $$x,y,y,z,z$$
Now find no of ways $N$ to rearrange this sequence. Here that would be
$$N = \dfrac{5!}{2!\cdot 2!} = 30$$
Now subtract the no. of cases $n$ when $x$ comes third in sequence and z and y come left to it, as Christian Blatter pointed out! That would be
$$n=2$$


text:
Q: Will 'Desktop' RAM work in a Rack Server? I am very new to Rack servers and am exploring options for RAM.
I am looking at the Dell PowerEdge R710 I have found this PDF which explains memory requirements. It however does not mention ECC, NonECC etc.
This page on the official Dell site does not explain what type of DDR3 ram is compatible with this system.
Therefore my question is - will any DDR3 ram work here? Desktop? ECC? Is desktop ram and ecc ram different pin configurations? Which should I use?
--------update---------
I see in the system hardware manual that it says:

Your system supports DDR3 registered DIMMs (RDIMMs) or ECC
unbuffered DIMMs (UDIMMs). Single and dual-rank DIMMs can be 1067-
or 1333-MHz, and quad-rank DIMMs can be 1067-MHz.

Which to me suggests it supports both Registered DIMMs and normal desktop Ram (UDIMM). And combinations of both?
Can you confirm my understanding

I purchased a system(it's being delivered soon) which comes with 8GB of RAM...and I want to buy more, but I don't know what that RAM is, so have compatibility concerns and don't know how accommodating these servers are.
Many thanks

A: Yes, it will. ASSUMING IT FITS - and given that pretty much any rack server is using a different standard than desktop machines, the answer is.... most likely not.
And the detailed answer is: Read the manuals.
As in: You state "I have found this PDF which explains memory requirements. It however does not mention ECC, NonECC etc."
Did you search? Because ONE google search ("Dell R710 manual" - hardly arcane) pointed me to https://downloads.dell.com/manuals/all-products/esuprt_ser_stor_net/esuprt_poweredge/poweredge-r710_owner%27s%20manual_en-us.pdf, which is the complete owners manual.
Page 129 talks quite clear what is needed:

Your system supports DDR3 registered DIMMs (RDIMMs) or ECC
unbuffered DIMMs (UDIMMs). Single and dual-rank DIMMs can be 1067-
or 1333-MHz, and quad-rank DIMMs can be 1067-MHz.

Not using the manual makes me want to close this - seriously, whether you have worked with rack servers or not, you should ALWAYS try to read the manual. Btw., the page goes on with specifying what sizes and hoe many modules fit etc. - read it.
Anyhow, you can fit any RAM that matches the description. Have fun finding a desktop system using RDIMM. And as i says, you need alternatively ECC UDIMM.