Q:

SFINAE and std::enable_if in dummy template parameters to select struct based on two criteria

Lets say we want a templated struct part to be called by part<U,D>, where D is of type U:
template<typename U, U D>
struct part{};

We what two cases:

U is an unsigned type , and D%(sizeof(U)*8)==0
U is an unsigned type , and D%(sizeof(U)*8)!=0

Ok to distinguish cases lets have two members: value and divisible. Base case is no condition is met, and struct is instantiated with value and divisible both being false. If conditions 1) are met I should have value=true, divisible= false and if conditions 2) are met I should have value=true, divisible= true. Looking ahead lets also say that if 1) or 2) are met, I also have a type in the struct.
I set up an auxiliary struct choice to use in std::enable_if and select the appropriate case through a dummy template argument. The code follows:
// to be used in dummy template arguments
template<size_t D>
struct choice{};

// Base case
template<typename U, U D, typename E1 = choice<0>, typename E2 = choice<0> >
struct part{
  static constexpr bool value     = false;
  static constexpr bool divisible = false;
};

// Specialisation 1  <U, D, choice<1>, choice<0> >
template<typename U, U D>
struct part<U,D,std::enable_if_t<std::is_unsigned<U>::value, choice<1> >, std::enable_if_t<!(D%(sizeof(U)*8)), choice<0> > >{
  static constexpr bool value     = true;
  static constexpr bool divisible = false;
  typedef U type;
};

// Specialisation 2  <U, D, choice<1>, choice<1> >
template<typename U, U D>
struct part<U,D,std::enable_if_t<std::is_unsigned<U>::value, choice<1> >, std::enable_if_t<(D%(sizeof(U)*8)), choice<1> > >{
  static constexpr bool value     = true;
  static constexpr bool divisible = true;
  typedef U type;
};

This compiles. Great. Lets cheack what we did with a simple printing:
  std::cout << "Should get 0,0 "<< std::endl;
  std::cout << part<int,5>::value << std::endl;
  std::cout << part<int,5>::divisible << std::endl;

  std::cout << "Should get 1,0 "<< std::endl;
  std::cout << part<uint16_t,5>::value << std::endl;
  std::cout << part<uint16_t,5>::divisible << std::endl;

  std::cout << "Should get 1,1 "<< std::endl;
  std::cout << part<uint16_t,16>::value << std::endl;
  std::cout << part<uint16_t,16>::divisible << std::endl;

  std::cout << "Should get 1,0 "<< std::endl;
  std::cout << part<uint16_t,30>::value << std::endl;
  std::cout << part<uint16_t,30>::divisible << std::endl;

  std::cout << "Should get 1,1 "<< std::endl;
  std::cout << part<uint16_t,32>::value << std::endl;
  std::cout << part<uint16_t,32>::divisible << std::endl;

// RESULTS ON TERMINAL ARE:
//
// Should get 0,0
// 0
// 0
// Should get 1,0
// 0
// 0
// Should get 1,1
// 0
// 0
// Should get 1,0
// 0
// 0
// Should get 1,1
// 0
// 0

So not what I want at all. Ok lets try:
std::cout << std::is_same<part<uint16_t,5>::type, uint16_t> << std::endl;

// COMPILATION ERROR:
src/tests/test1.cpp(55): error: class "part<uint16_t={unsigned short}, (uint16_t={unsigned short})5U, choice<0UL>, choice<0UL>>" has no member "type"
    std::cout << std::is_same<part<uint16_t,5>::type, uint16_t> << std::endl;

Where am I going wrong? The code compiles so SFINAE is resolving the specialisations. But it seams it always select the base case. Why?

A:

This is not how the SFINAE trick works. You need to give std::enable_if_t the same type as second argument as you defined as default argument, so that if the std::enable_it_t does not cause substitution failure, the partial specialization matches with a template specialization that does not explicitly specify the defaulted parameter.
Therefore you want to use choice<0> everywhere instead of choice<1> and because you use it everywhere, you can really use void instead of choice<...> everywhere and with void you can also drop the second argument to std::enable_if_t because it is defaulted to that.
Then finally, you don't need two enabler parameters, just connect the conditions with logical operations:
// Base case
template<typename U, U D, typename = void>
struct part{
  static constexpr bool value     = false;
  static constexpr bool divisible = false;
};

// Specialisation 1  <U, D>
template<typename U, U D>
struct part<U,D,std::enable_if_t<std::is_unsigned_v<U> && !(D%(sizeof(U)*8))>{
  static constexpr bool value     = true;
  static constexpr bool divisible = false;
  typedef U type;
};

// Specialisation 2
template<typename U, U D>
struct part<U,D,std::enable_if_t<std::is_unsigned_v<U> && (D%(sizeof(U)*8))>{
  static constexpr bool value     = true;
  static constexpr bool divisible = true;
  typedef U type;
};

Also note that (based on what you showed) you don't need the last specialization:
// Base case
template<typename U, U D, typename = void>
struct part{
  static constexpr bool value     = false;
  static constexpr bool divisible = false;
};

// Specialisation 1  <U, D>
template<typename U, U D>
struct part<U,D,std::enable_if_t<std::is_unsigned_v<U>> {
  static constexpr bool value     = true;
  static constexpr bool divisible = (D%(sizeof(U)*8) == 0);
  typedef U type;
};

The SFINAE approach is only necessary for std::is_unsigned_v because the expression (D%(sizeof(U)*8) == 0) might be ill-formed if D has a type which is not an unsigned integer.
Also, since C++17 you can do:
template<typename U, U D>
struct part{
  static constexpr bool value     = std::is_unsigned_v<U>;
  static constexpr bool divisible = []{
      if constexpr(value)
          return D%(sizeof(U)*8) == 0;
      else
          return false;
  }();
};

to avoid partial specialization completely, even if U might be a type for which D%(sizeof(U)*8) is ill-formed.
If you do not intend to support types for which D%(sizeof(U)*8) is ill-formed, then just use:
template<typename U, U D>
struct part{
  static constexpr bool value     = std::is_unsigned_v<U>;
  static constexpr bool divisible = value && (D%(sizeof(U)*8) == 0);
};


Q:

Bytestring linking in ghc

Consider the following simple code:
import Crypto.Hash.SHA1 (hashlazy)
import qualified Data.ByteString as BS
main = return ()

I installed cabal install --global bytestring and then I obtain (on a newly installed Ubuntu 12.04 machine using ghc 7.4.1):
GHCi runtime linker: fatal error: I found a duplicate definition for symbol
   fps_minimum
whilst processing object file
   /usr/local/lib/bytestring-0.10.0.1/ghc-7.4.1/HSbytestring-0.10.0.1.o
This could be caused by:
   * Loading two different object files which export the same symbol
   * Specifying the same object file twice on the GHCi command line
   * An incorrect `package.conf' entry, causing some object to be
     loaded twice.
GHCi cannot safely continue in this situation.  Exiting now.  Sorry.

What can I do with that?

A:

This is a diamond dependency issue. You have a version of cryptohash built against one version of bytestring, but the rest of the GHC system built against another. Thus when the packages are linked together, two slightly different versions of bytestring are linked.
Normally this is ok, as long as the bytestring types are compatible.
However, bytestring includes a small C library for some utilities. C libraries have non-unique symbols, that prevent duplicate linking, hence your error.
You need to ensure cryptohash is built against the same version of bytestring.


Q:

How to make a multiply equation?

I need to make a equation like this

      1011   (this is 11 in decimal)
    x 1110   (this is 14 in decimal)
    ======
      0000   (this is 1011 x 0)
     1011    (this is 1011 x 1, shifted one position to the left)
    1011     (this is 1011 x 1, shifted two positions to the left)
 + 1011      (this is 1011 x 1, shifted three positions to the left)
 =========
  10011010   (this is 154 in decimal)

I tried to code like this
\begin{equation}
\frac{
    \frac{
        \begin{array}[b]{r}
                1011    \\
            \times 1110
        \end{array}
        }
        {
    \begin{array}[b]{r}
        0000    \\
        0000    \\
        0000    \\
        + 0000
    \end{array}
    }
}
{
10011010
}
\end{equation}

But the result is not aligned.
Any suggestions?

A:

The following is inspired by Robert Fuster's answer. (I have modified it slightly, because of some limitations which become important to make this solution interoperable with amsmath evnironments such as align and gather.)
Note. This environment requires the last row to end with an & or a \\, or else it will generate an error.
Simple example
The pre-amble is described below.
\begin{document}
\begin{equation}
\begin{arithmetic}
           1011 &   first factor    \\
    \times 1110 &   second factor   \\
           0000 & this row is redundant\\
          1011~ &   this row has been shifted once\\
         1011~~ \\
  +     1011~~~ \\
       10011010 & result
\end{arithmetic}
\end{equation}
\end{document}

Another example: now with subtraction and long division!
I have added code which allows the user to describe subtraction and long division as well. This is sample code showing the syntax. Again, the pre-amble for this document is described below.
\begin{document}
\begin{equation}
\begin{aligned}[t]
\begin{arithmetic}[t]
           1011 &   first factor    \\
    \times 1110 &   second factor   \\
           0000 & (this row is redundant)\\
          1011~ \\
         1011~~ \\
  +     1011~~~ \\
       10011010 & result
\end{arithmetic}
\quad
\begin{arithmetic}[t]
     3094 \\
  -  5029 \\
  {{-}}1935 \\
\end{arithmetic}
\quad\;\;
\begin{arithmetic}[t]
            1022~r1 \\
  13 \Into 13287~~~ \\
        \- 13~~~~~~ \\
            028~~~~ \\
         \-  26~~~~ \\
              27~~~ \\
           \- 26~~~ \\
               1~~~ \\
\end{arithmetic}
\end{aligned}
\end{equation}
\end{document}

Note the {{-}} in the sample code above, which is necessary to avoid seeing the negation symbol as another subtraction operation; and the \- symbols, which we use as an alternative symbol for subtraction in the midst of a long division to obtain a subtraction which behaves differently (ending the underline at the first space).
Preamble
This solution is based on making entries of a table automatically use underlines, whenever it detects an arithmetic operation is to be performed. It relies on ignoring leading whitespace in each table cell, and doing fancy things with the table-cell styles via the array package.
\documentclass{article}
\usepackage{array}

\makeatletter
    \providecommand\text\mbox
    \newenvironment{arithmetic}[1][]{\begin{tabular}[#1]{Al}}{\end{tabular}}
    \newcolumntype{A}{>{\bgroup\def~{\phantom{0}}$\@testOptor}r<{\@gobble\\$\egroup}}

The A column style is for arithmetic operations. It changes the meaning of ~ to make it act as a space character of the correct width, turns on math mode, and tries to detect an arithmetic operator from a hard-coded list. The column style ends with some odd commands involving end-rows for technical reasons.
\def\@testOptor\ignorespaces#1#2\\{%
    \ifx#1\times
        \@OperatorRow{#1}{#2}\@tempa%
    \else\ifx#1+
        \@OperatorRow+{#2}\@tempa%
    \else\ifx#1\discretionary% detects the soft hyphen, \-
        \@ShortSubtractRow{#2}\@tempa%
    \else\ifx#1-
        \@OperatorRow-{#2}\@tempa%
    \else
        \@NormalRow{#1#2}\@tempa%
    \fi\fi\fi\fi
    \@tempa}

The \@testOptor macro grabs everything between \ignorespaces in the column definition and \\ (which may be an end-of-row or merely part of an end-of-column). If it finds an arithmetic operation, it typesets it with underlines. Otherwise, it tries to typeset it normally.
There is one special case: the soft hyphen \- is used to bring up a subtraction-like syntax, where the underlines extend only as far as the first ~ space command.
\def\@OperatorRow#1#2#3{%
    \@IfEndRow#2\@gobble\\{%
        \def#3{\underline{{}#1 #2}\\}%
    }{%
        \def#3{\underline{{}#1 #2{}}}%
    }}

\def\@NormalRow#1#2{%
    \@IfEndRow#1\@gobble\\{%
        \def#2{#1\\}%
    }{%
        \def#2{#1{}}%
    }}

\def\@IfEndRow#1\@gobble#2\\#3#4{%
    \ifx#2\@gobble
        #4%
    \else
        #3%
    \fi}

\makeatother

We have to do some weird stuff because we don't know in any given cell whether we've only ended the cell, or ended the row. We test whether or not the final macro of the argument is \@gobble: if so, it's merely an end-of-row, and so we ought to add another \@gobble to make sure that the row doesn't actually end.
\def\@ShortSubtractRow#1#2{\@@ShortSubtractRow#1~\end{#2}}
\def\@@ShortSubtractRow#1#2~#3\end#4{%
    \@IfEndRow#3\@gobble\\{%
        \def#4{\underline{\text{--} #2}#3\\}%
    }{%
        \def#4{\underline{\text{--} #2{}}#3}%
    }}

For the short subtractions used in long division, we do similar testing for ends of rows, but also define the end of the argument to be underlined by the first ~ character. We use \text{--} in place of a proper minus sign to save space (it's not as long a stroke).
\def\Into#1\\{%
    \@IfEndRow#1\@gobble\\{%
        \def\@tempa{~\raisebox{0.17ex}{\parbox{0.15em}{\centering$\big|$}}\overline{~\big.#1}\\}%
    }{%
        \def\@tempa{~\raisebox{0.17ex}{\parbox{0.15em}{\centering$\big|$}}\overline{~\big.#1{}}}%
    }\@tempa}

The \Into command isn't an operator which the environment detects, but it similarly attempts to collect the remainder of the contents of the row, in order to draw an \overline over it.
Supplement this pre-amble with the one of the above sample documents, and voilà!

A:

\documentclass{article}
\begin{document}
\begin{equation}
\begin{array}{r}
                         1011\\
\underline{\mbox{}\times 1110}\\
                         0000\\
                        1011\phantom{0}\\
                       1011\phantom{00}\\
  \underline{\mbox{}+ 1011\phantom{000}}\\
                     10011010
\end{array}
\end{equation}
\end{document}

A:

If you don't need the annotations, I propose this solution:
\documentclass{article}
\usepackage{xparse}

\ExplSyntaxOn
\NewDocumentCommand{\multiplication}{ O{c} m m m o }
 {
  \IfNoValueTF { #5 }
   {
    \xiong_simple_table:nnnn { #1 } { #2 } { #3 } { #4 }
   }
   {
    \xiong_full_table:nnnnn { #1 } { #2 } { #3 } { #4 } { #5 }
   }
 }
\tl_new:N \l_xiong_table_body_tl

\cs_new_protected:Npn \xiong_simple_table:nnnn #1 #2 #3 #4
 {
  \begin{array}[#1]{r}
  #2 \\
  {\times}\; #3 \\
  \hline
  #4
  \end{array}
 }

\cs_new_protected:Npn \xiong_full_table:nnnnn #1 #2 #3 #4 #5
 {
  \tl_clear:N \l_xiong_table_body_tl
  \int_step_inline:nnnn { 0 } { 1 } { \clist_count:n { #5 } - 1 }
   {
    \tl_put_right:Nx \l_xiong_table_body_tl
     {
      \int_compare:nT { ##1 == \clist_count:n { #5 } - 1 }
       { {+}\exp_not:N \; }
      \clist_item:nn { #5 } { ##1 + 1 }
      \exp_not:n { \prg_replicate:nn { ##1 } { \hphantom{0} } \\ }
     }
   }
  \begin{array}[#1]{r}
  #2 \\
  {\times}\; #3 \\
  \hline
  \tl_use:N \l_xiong_table_body_tl
  \hline
  #4
  \end{array}
 }
\ExplSyntaxOff

\begin{document}
Short table: $\multiplication[t]{1011}{1110}{10011010}$

\bigskip

Long table: $\multiplication[t]{1011}{1110}{10011010}[0000,1011,1011,1011]$

\end{document}

The first optional argument is just the same as for the array environment: [t] or [b] for vertical alignment (default is center alignment). The three mandatory arguments are the factors and the result, the trailing optional argument contains the list of intermediate summands.

Here's an implementation for the automatic computation given the factors; limitations: multiplying by 0 is not allowed (it could be taken care of) and the product can have at most 31 digits.
\documentclass{article}
\usepackage{xparse}

\ExplSyntaxOn
\NewDocumentCommand{\fullmultiplication}{ O{c} m m }
 {
  \xiong_full_table:nnn { #1 } { #2 } { #3 }
 }

\tl_new:N \l__xiong_table_body_tl
\tl_new:N \l__xiong_padding_tl
\seq_new:N \l__xiong_multiplier_seq
\int_new:N \l__xiong_length_int

\cs_new_protected:Npn \xiong_full_table:nnn #1 #2 #3
 {
  \__xiong_compute:nn { #2 } { #3 }
  \begin{array}[#1]{r}
  #2 \\
  {\times}\; #3 \\
  \hline
  \tl_use:N \l__xiong_table_body_tl
  \hline
  \int_to_binary:n { \int_from_binary:n { #2 } * \int_from_binary:n { #3 } }
  \end{array}
 }

\cs_new_protected:Npn \__xiong_compute:nn #1 #2
 {
  % clear the variables
  \tl_clear:N \l__xiong_table_body_tl
  \tl_clear:N \l__xiong_padding_tl
  % split the multiplier into digits
  \seq_set_split:Nnn \l__xiong_multiplier_seq { } { #2 }
  % reverse the sequence, as we want to multiply from the right
  \seq_reverse:N \l__xiong_multiplier_seq
  % count the number of digits
  \int_set:Nn \l__xiong_length_int { \seq_count:N \l__xiong_multiplier_seq }
  % detach the most significant bit (we want to add a +)
  \seq_pop_right:NN \l__xiong_multiplier_seq \l__xiong_msb_tl
  % compute the partial summands (either zeroes or #1)
  \seq_map_inline:Nn \l__xiong_multiplier_seq
   {
    \tl_put_right:Nx \l__xiong_table_body_tl
     {
      \str_if_eq:nnTF { 1 } { ##1 }
       { #1 }
       { \prg_replicate:nn { \l__xiong_length_int } { 0 } }
     }
    \tl_put_right:NV \l__xiong_table_body_tl \l__xiong_padding_tl
    \tl_put_right:Nn \l__xiong_table_body_tl { \\ }
    \tl_put_right:Nn \l__xiong_padding_tl { \hphantom{0} }
   }
  % the last summand is #1
  \tl_put_right:Nn \l__xiong_table_body_tl { {+}\; #1 \tl_use:N \l__xiong_padding_tl \\ }
 }
\ExplSyntaxOff

\begin{document}
Here it is: $\fullmultiplication[t]{1011}{1110}$

\end{document}

With some options more, through a key-value syntax:
\documentclass{article}
\usepackage{xparse}

\ExplSyntaxOn
\NewDocumentCommand{\fullmultiplication}{ O{} m m }
 {
  \group_begin:
  \keys_set:nn { xiong/binmult } { #1 }
  \xiong_multiplication:nn { #2 } { #3 }
  \group_end:
 }

\keys_define:nn { xiong/binmult }
 {
  align .choice:,
  align/top    .code:n = \tl_set:Nn \l__xiong_align_tl { t },
  align/t      .code:n = \tl_set:Nn \l__xiong_align_tl { t },
  align/bottom .code:n = \tl_set:Nn \l__xiong_align_tl { b },
  align/b      .code:n = \tl_set:Nn \l__xiong_align_tl { b },
  align/c      .code:n = \tl_set:Nn \l__xiong_align_tl { c },
  align/center .code:n = \tl_set:Nn \l__xiong_align_tl { c },
  full         .bool_set:N = \l__xiong_full_bool,
  full         .initial:n  = true,
  showzero     .bool_set:N = \l__xiong_showzero_bool,
  showzero     .initial:n  = true,
 }

\tl_new:N \l__xiong_align_tl
\tl_set:Nn \l__xiong_align_tl { c } % default
\tl_new:N \l__xiong_table_body_tl
\tl_new:N \l__xiong_padding_tl
\seq_new:N \l__xiong_multiplier_seq
\int_new:N \l__xiong_length_int

\cs_new_protected:Npn \xiong_multiplication:nn #1 #2
 {
  \int_compare:nT { #2 == 0 } { \bool_set_false:N \l__xiong_full_bool }
  \bool_if:NT \l__xiong_full_bool
   { \__xiong_compute:nn { #1 } { #2 } }
  \begin{array}[\l__xiong_align_tl]{r}
  #1 \\
  {\times}\; #2 \\
  \hline
  \bool_if:NT \l__xiong_full_bool
  {
   \tl_use:N \l__xiong_table_body_tl
   \hline
  }
  \int_to_binary:n { \int_from_binary:n { #1 } * \int_from_binary:n { #2 } }
  \end{array}
 }

\cs_new_protected:Npn \__xiong_compute:nn #1 #2
 {
  % clear the variables
  \tl_clear:N \l__xiong_table_body_tl
  \tl_clear:N \l__xiong_padding_tl
  % split the multiplier into digits
  \seq_set_split:Nnn \l__xiong_multiplier_seq { } { #2 }
  % reverse the sequence, as we want to multiply from the right
  \seq_reverse:N \l__xiong_multiplier_seq
  % count the number of digits
  \int_set:Nn \l__xiong_length_int { \seq_count:N \l__xiong_multiplier_seq }
  % detach the most significant bit (we want to add a +)
  \seq_pop_right:NN \l__xiong_multiplier_seq \l__xiong_msb_tl
  % compute the partial summands (either zeroes or #1)
  \seq_map_inline:Nn \l__xiong_multiplier_seq
   {
    \tl_put_right:Nx \l__xiong_table_body_tl
     {
      \str_if_eq:nnTF { 1 } { ##1 }
       { #1 }
       {
        \bool_if:NT \l__xiong_showzero_bool
         { \prg_replicate:nn { \l__xiong_length_int } { 0 } }
       }
     }
    \tl_put_right:NV \l__xiong_table_body_tl \l__xiong_padding_tl
    \bool_if:nT { \l__xiong_showzero_bool || \str_if_eq_p:nn { 1 } { ##1 } }
     { \tl_put_right:Nn \l__xiong_table_body_tl { \\ } }
    \tl_put_right:Nn \l__xiong_padding_tl { \hphantom{0} }
   }
  % the last summand is #1
  \tl_put_right:Nn \l__xiong_table_body_tl { {+}\; #1 \tl_use:N \l__xiong_padding_tl \\ }
 }
\ExplSyntaxOff

\begin{document}
Here it is: $\fullmultiplication[align=t]{1011}{1110}$

Here it is: $\fullmultiplication[align=b,showzero=false]{1011}{1110}$

Here it is: $\fullmultiplication[align=b,full=false]{1011}{1110}$

Here it is: $\fullmultiplication{1011}{0}$
\end{document}


Q:

Generate table from Object data

I have an object like the one below:
var obj = {
   a : {
      x : 1,
      y : 2,
      z : 3
   },
   b : {
      x : 1,
      y : 2,
      z : 3
   }
}

With it, I will like to generate the following table. Format is showed bellow
http://jsfiddle.net/gD87t/
I am trying to get the elements from object and and trying to append but getting confused with the rowSpan value
var tr = document.createElement('tr');
for(var i in obj){
   var td = document.createElement('td');
   td.rowSpan = ? // Here I am getting confused.
}

Can a template engine solve my problem?
What is the best way to do this?

A:

Here's one way of doing it with a recursive function in pure js:
function addObjectToTable(table, obj, tr) {
  var rows = 0;
  for (key in obj) {
    if (tr == null) {
      tr = document.createElement('tr');
      table.appendChild(tr);
    }

    var td = document.createElement('td');
    td.textContent = key;
    tr.appendChild(td);

    var value = obj[key];
    if (typeof value != 'object') {
      var td = document.createElement('td');
      td.textContent = value;
      tr.appendChild(td);
      rows += 1;
    }
    else {
      var subrows = addObjectToTable(table, value, tr);
      td.setAttribute('rowspan',subrows);
      rows += subrows;
    }

    tr = null;
  }
  return rows;
}

Which would be called like this:
var table = document.createElement('table');
addObjectToTable(table,obj);
document.body.appendChild(table);

Note that when first called, the tr parameter is null, since we always have to create a new row at the top level. When the function is called recursively though, the tr parameter is passed in from the upper level since lower levels will intially be adding to the the row of their parent object.
The function returns the number of rows added, so when it is called recusively the caller will know what to set the rowspan value to.
Fiddle link

A:

I couldn't find an answer which handled circulars, and I also decided to do this without any unnecessary DOM writes. Also, I didn't follow the exact mark-up the OP requested because I felt nesting tables was more convenient for a recursive operation such as this- and serves close to the same visual purpose.
So, here's the function I've created:
function dataToTable (data) {
    var storage = [];
    return (function buildTable (data) {
        var table = '

';
        var name, value;
        // Add the object/array to storage for cirular detection.
        storage.push(data);
        for (name in data) {
            value = data[name];
            table += '
' + name + '	';
            // If the value is an object we've put in storage (circular)
            if (storage.indexOf(value) !== -1) {
                table += 'Circular';
            } else if (typeof value === 'object') {
                table += buildTable(value);
            } else {
                table += value;
            }
            table += '
';
        }
        return table + '

';
    }(data));
}

Here is the object I used to test:
var obj = {
   a : {
      x : 1,
      y : 2,
      z : 3
   },
   b : {
      x : 1,
      y : 2,
       z : {
           test1: 0,
           test2: {
               test3: 1,
               test4: ['a','b','c']
           }
       }
   }
};
obj.c = obj;
obj.b.z.test2.test4.push(obj.a);

The function will turn this object into an HTML table. What you do with the table is up to you. On my fiddle, I used the DOM to add the table to a DIV (document.getElementById).
http://jsfiddle.net/5RhXF/1/
I hope you'll find my implementation clear.
UPDATE::
I decided to test this on the jQuery library, and it worked! Except, the functions were printing as their toString value with no good format for text.. Which makes sense, but not very helpful. So, I'm thinking this is a nice and easy way to look through APIs for frameworks/libraries and what-not. Therefore, I added prettify for syntax-highlighting of functions, and also added a type-check for functions in the table generator, and a quick class to get rid of borders around the prettify box (as there's already a border on the table cell). If anyone is interested in the version designed for source-reading/debugging, here's the fiddle:
http://jsfiddle.net/5RhXF/7/


Q:

Is it possible to run three phase motor with single phase supply? How?

I have rubber mixer machine that motor need three phase supply. Unfortunately I only have single phase supply. I heard a rumor that three phase motor can be run with single phase supply. So, pls guy here help me out of this problem. Your answer is so greatful in advance.

A:

A variable-frequency drive (VFD) should be preferred over the Steinmetz connection. The Steinmetz connection only allows the motor to work at about 70% of its rated power and produce 20% to 30% of the rated starting torque. I suspect that a rubber mixer will not tolerate that limitation.
A VFD of a current design from a reputable manufacturer will allow most motors to work at full power and produce rated starting torque. Most manufacturers have both variable torque / standard duty models and constant torque / heavy duty models. For a rubber mixer, you should buy the heavy duty model. Most of the well-known international manufacturers of industrial electrical equipment make VFDs.
Single-phase input, three-phase output are only widely available for 230 volt motors rated up to about 3 Hp (2.2 kW). Larger sizes are available, but more difficult to find.


Q:

Automatic comments to redmine after teamcity build

I want to make automatic comment in redmine issue after build in teamcity. For example teamcity made build for branch , I want to make comment in redmine about build result in issue/xyz. What is the best way to do that?

A:

You will need to create a new build step at the end that will run some sort of script or program that you'll need to make.
What the script will do is make use of the TeamCity REST API to get the changes. (See this)
Then you can use the Redmine REST API to update the issue based off the changes found using the TeamCity REST API.


Q:

How to call method of controller in .module file with dependency injection

I have class named Book.
class Popups
{
  private $entityQuery;
  private $entityTypeManager;

  public function __construct(QueryFactory $entityQuery, EntityTypeManagerInterface $entity_type_manager) {
    $this->entityQuery = $entityQuery;
    $this->entityTypeManager = $entity_type_manager;
  }

public function read($cid)
  {
    $nodes = $this->entityTypeManager->getStorage('node')->loadByProperties(['type' => 'book', 'cid' => $cid ]);

    return $nodes;
  }

}

Now I have books.module file where I need to call read method;
how to call that method
$book = new Book();  // what param should i pass here
$book->read($cid)

A:

Add the class to mymodule.services.yml and inject the core services there:
mymodule.services.yml
services:
  mymodule.book:
    class: Drupal\mymodule\Book
    arguments: ['@entity.query', '@entity_type.manager']

Then use the service in procedural code:
\Drupal::service('mymodule.book')->read($cid)


Q:

Using #undef preprocessor directive

Here are the 2 programs with very minor change.

Practice.c

#include <stdio.h>
#define P (i+j)

main()
{
  int i,j,k=0;
  printf("\nI = ");
  scanf("%d",&i);
  printf("\nJ = ");
  scanf("%d",&j);
  k=P;
  printf("\nValue of Defined Macro P = %d\n",k);

  #undef P
    printf("\nValue of Undefined Macro P = %d\n",k);
}

Output of the above program is:
I = 5

J = 9

Value of Defined Macro P = 14

Value of Undefined Macro P = 14

New.c

#include <stdio.h>
#define P (i+j)

main()
{
  int i,j,k=0;
  printf("\nI = ");
  scanf("%d",&i);
  printf("\nJ = ");
  scanf("%d",&j);
  k=P;
  printf("\nValue of Defined Macro P = %d\n",P);

  #undef P
    printf("\nValue of Undefined Macro P = %d\n",P);
}

Output of the above program is :
Practice.c: In function 'main':
Practice.c:15:48: error: 'P' undeclared (first use in this function)
    printf("\nValue of Undefined Macro P = %d\n",P);
                                               ^
Practice.c:15:48: note: each undeclared identifier is reported only once for eac
h function it appears in

Now I want to know that why did Practice.c got successfully compiled and executed, where I used variable k to display the output, and why did New.c displayed error on using Macro Template P directly?

A:

Preprocessor directives are replaced where they occur. The variable k is set to 14 on the line where you write k=P which is exactly equivalent to writing k=14 so it still has its value after the #undef.


Q:

R code that applies a function to subsection of variables of a dataframe and saves it to original dataframe

I have a dataframe like mtcars
I want to program a function that searches for all variables of mtcars that start with "c", converts them to character and saves them back to mtcars.

A:

Here is one way:
f <- function(x, str = "^var") {
    want <- grep(str, names(x))
    x[, want] <- sapply(x[, want], as.character)
    x
}

[Edit: alternative version that implements the points raised by @hadley in comments.]
f <- function(x, str = "^var") {
    want <- grepl(str, names(x))
    x[, want] <- lapply(x[, want], as.character)
    x
}

The function allows you to pass through the string you want to match on, but defaults to "^var" as you requested. The "^" indicates we want to find names that start with "var", not any name that contains "var".
Example:
> bigdf <- data.frame(var1 = LETTERS[1:3], var2 = letters[1:3], var3 = 1:3,
+                     stuff = 4:6)
> bigdf
  var1 var2 var3 stuff
1    A    a    1     4
2    B    b    2     5
3    C    c    3     6
>
> bigdf2 <- f(bigdf)
> bigdf2
  var1 var2 var3 stuff
1    A    a    1     4
2    B    b    2     5
3    C    c    3     6
> str(bigdf2)
'data.frame':   3 obs. of  4 variables:
 $ var1 : chr  "A" "B" "C"
 $ var2 : chr  "a" "b" "c"
 $ var3 : chr  "1" "2" "3"
 $ stuff: int  4 5 6


Q:

page overflowing in table environment due to content outside tabulars

We made a command to print our software requirements but now that we hit things that use a lot of space we have an overflow issue.
We used a table environment to keep everything together and avoid weird things like a final bar ending up on a different page but this clearly is a hack.
I use two tabulars as writing text in a huge table cell was frustrating that a white line didn't results in a paragraph brake anymore.
How do I change this such that the overflows are gone and if a requirement gets spread over 2 pages each part has at least a few lines of content? Preferably without having to edit to much cases where this is already used?
\documentclass[12pt,a4paper]{report}

\usepackage{booktabs}

\newcommand{\requirement}[5]{
  \begin{table}[H]
  \begin{tabular*} {\textwidth} {  p{0.70\textwidth} r }
    \toprule
    \emph{#3} & \textbf{ID.#1.#2} \\
    \midrule
  \end{tabular*}
    #4

   \vspace{10pt}
    \textbf{Motivation:}\\
    #5

  \vspace{-5pt}
  \begin{tabular*}{\textwidth}{@{}p{\textwidth}}
      \bottomrule
  \end{tabular*}
  \end{table}
}

\begin{document}
long\\long\\long\\long\\long\\long\\long\\long\\long\\long\\long\\long\\long\\long
long\\long\\long\\long\\long\\long\\

\requirement{R}{6}{Name}
{Requirement way to long
long\\long\\long\\long\\long\\long\\long\\long\\long\\long\\long\\long\\long

long\\long\\long\\long\\long\\long\\long\\long\\long\\long\\long\\long\\long\\long

long\\long\\long\\long\\long\\long\\long\\long\\long\\long\\long\\long\\long\\long

long\\long\\long\\long\\long\\long\\long\\long\\long\\long\\long\\long\\long\\long
}
{motivation}

\end{document}

A:

Use a longtable.
MWE:
\documentclass[12pt,a4paper]{report}
\usepackage{booktabs,longtable,array}

\newcommand{\requirement}[5]{%
  \begin{longtable}[l]{@{}p{0.70\textwidth}>{\raggedleft\arraybackslash}p{\dimexpr0.30\textwidth-4\tabcolsep}}
    \toprule
    \emph{#3} & \textbf{ID.#1.#2} \\
    \midrule
    #4

  \end{longtable}
   \vspace{10pt}
    \noindent\textbf{Motivation:}\par
    \noindent#5

  \vspace{-5pt}
    \noindent\rule{\linewidth}{1pt}%
}

\begin{document}
\requirement{R}{6}{Name}
{Requirement way to long
long\\long\\long\\long\\long\\long\\long\\long\\long\\long\\long\\long\\long\\long\\
long\\long\\long\\long\\long\\long\\long\\long\\long\\long\\long\\long\\long\\long\\
long\\long\\long\\long\\long\\long\\long\\long\\long\\long\\long\\long\\long\\long\\
long\\long\\long\\long\\long\\long\\long\\long\\long\\long\\long\\long\\long\\long\\
}
{motivation}

\end{document}

Output

A:

\documentclass[12pt,a4paper]{report}

\newcommand{\requirement}[5]{\par
\smallskip
\hrule
\nopagebreak
\noindent{\large\strut}\textit{#3}\hfill\textbf{ID.#1.#2}
\par
\nopagebreak
\hrule
\par
\nopagebreak
\smallskip
\clubpenalty10000
#4 \par
\par
\nopagebreak
\hrule
\noindent{\large\strut}\textbf{Motivation:}\par
\smallskip
\clubpenalty10000
#5\par
\par
\nopagebreak
\hrule
\par
}

\begin{document}
\requirement{R}{6}{Name}
{Requirement way to long
long\\long\\long\\long\\long\\long\\long\\long\\long\\long\\long\\long\\long\\long\\
long\\long\\long\\long\\long\\long\\long\\long\\long\\long\\long\\long\\long\\long\\
long\\long\\long\\long\\long\\long\\long\\long\\long\\long\\long\\long\\long\\long\\
long\\long\\long\\long\\long\\long\\long\\long\\long\\long\\long\\long\\long\\long
}
{motivation}

\end{document}


Q:

How to add view in top of view hierarchy in Swift?

I have been using this:
UIApplication.sharedApplication().keyWindow?.rootViewController!.view.addSubview(self.customView)

To add a modal view over all the views in the view hierarchy in app.
But this is giving me problem. It adds subview as expected sometimes but sometimes it doesn't' work.
In what case this wont work and what's the best way to add modal view in view hierarchy like UIAlertView.

A:

Depending on what's happening, there can be more than one UIWindow at a time - for example, if a system alert shows up, you will have two separate windows (one for your view controller, one for the alert itself).
A similar example can be made for the system keyboard. If the keyboard has focus, that will be your keyWindow.
A way of making sure you are adding the subview on top of all windows, could be: UIApplication.sharedApplication().windows.last?.addSubview(yourSubView).
I've also seen people using the application delegate, with: UIApplication.sharedApplication().delegate?.window.


Q:

Laravel - can't access an object property

I have the following code:
$items = Item::where('type','egg')
        ->select('id','name','image','description')
        ->with('craft.reqItem')->get();

foreach($items as $item) {
            if (sizeof($item->craft)) {
                foreach ($item->craft as $craftItem)
                    return $craftItem;
            }
        }

The output is the following JSON:

When I'm trying to access the req_item from the code, laravel outputs nothing.
I'm trying to do it by changing:
return $craftItem to:
return $craftItem->req_item
If I'm trying to output any other property other than req_item (such as id,item_id,quantity) - laravel do return the right value.
Any idea why I can't access the req_item object?
dd req_item

A:

That's it, $craftItem->reqItem is an object and you can't simply "output" an object.
But you can do something like $craftItem->reqItem->req_item_id (that in the case you eager loaded reqItem, assuming its a relationship).
If that's not the case, then you simply call the query like $craftItem->reqItem()->req_item_id
Although I'd prefer eager loading, which probably you'll want to read about in the docs... But just to test your example is working, you can do something like $item->load('reqItem') before the conditional statement. And then you can access it as a property.
As devk mentioned, relationships have to be camelCase named. You may want to change it to reqItem() for simplicity.


Q:

Database Design Ideas/Feedback

I have made many relational database designs before, and think I am experienced in some of these design patterns...however, I cannot think of quite where to start for this problem.
I am creating a database of gyms, that will have basic gym information in a 'Gyms' Table.
Then I will have another table called 'Equipment' which is a list of possible equipment that any gym can have, such as "Bench", "Box", "Weight Plate", etc.
Then I have a table for GymsEquipment, which is a list of: GymId, EquipmentId, Available.
GYMS
-----------------
id   Name    Units
1    Gym A   Imperial
2    Gym B   Imperial
3    Gym C   Metric

EQUIPMENT
-----------------
id   Name
1    Bench
2    Box
3    Weight Plate
4    Dumbbells

GYM EQUIPMENT
-----------------
id   GymId    EquipmentId    Available
1    1        1              1
2    1        2              0
3    1        3              1
4    2        1              0
5    2        2              1
6    2        3              1

That's all quite basic...but now here is the difficult part that I am having trouble with. I want to ALSO record the available weight each gym has for each equipment.
For example, I want to record that Gym A has weight plates of 2.5lbs, 5lbs, 10lbs, 25lbs, 35lbs, 45lbs and 100lbs....while Gym B also has weight plates, but they have these ones: 5lbs, 25lbs, 45lbs.
To make things a little more complicated...gyms are also marked as either Imperial or Metric...so Gym C has weight plates, but theirs are 1.25kg, 2.5kg, 5kg, 10kg, etc.
I have considered an option where I simply just list out all of the possible options a user has (and will know what unit it is based on the gyms table) like this:
GYM EQUIPMENT WEIGHT
----------------------
id   GymId    EquipmentId    Weight
1    1        3              2.5
2    1        3              5
3    1        3              10
4    1        3              25
5    1        3              35
6    1        3              45
7    2        3              5
8    2        3              25
9    2        3              45
.......

I am really not sure how to start with this type of information. I would be open to a No-SQL solution as well if this would be more ideal...but I less familiar with this and regardless, have not been able to come up with a scalable idea.
Does anybody have any feedback, or better yet, better ideas? Thanks

A:

If I'm reading this correctly - then I don't think your initial 3 tables hold enough information to be able to handle the Weights issue?
I think that there are 2 easyish ways of handling this either

Add Weight column to the Equipment table (defaults to 0 for non weights)
Have an (optional) One to Many link from Equipment to a Weight Plates table.

Option A - your tables might look like this :
EQUIPMENT
-----------------
id   Name          Weight
1    Bench         0
2    Box           0
3    Weight Plate  2.5
4    Dumbbells     0
5    Weight Plate  5
6    Weight Plate  10
7    Weight Plate  20

GYM EQUIPMENT
-----------------
id   GymId    EquipmentId    Available
1    1        3              10
2    1        5              10
3    1        6              4
4    1        7              4

Then you would be able to work out that Gym 1 has 10 x 2.5, 10 * 5, 4 * 10 & 4*20 weight plates.
Option B - your tables might look like this :
EQUIPMENT
-----------------
id   Name
1    Bench
2    Box
3    Weight Plate
4    Dumbbells

WEIGHT PLATES
-----------------
id   Weight
1    2.5
2    5
3    10
4    20

EQUIPMENT TO PLATES
-----------------
id equipment_id   Weight_id  Available
1  3              1          10
2  3              2          10
3  3              3          4
4  3              4          4

And your Gym Equipment table like this :
GYM EQUIPMENT
-----------------
id   GymId    EquipmentId    WeightId   Available
1    1        3              1          4
2    1        3              2          4
3    1        3              3          4
4    1        3              4          4

Then you would be able to work out that Gym 1 has 4 x 2.5, 4 * 5, 4 * 10 & 4*20 weight plates. (Out of a total of 10 x 2.5, 10 * 5, 4 * 10 & 4*20)
For Imperial to Metric - I would treat this as either completely separate items (e.g. a 2.5KG plate is not a 5LB plate) - or as a display issue and convert the details with a formula after the fact.
e.g :
WEIGHT PLATES
-----------------
id   Weight  Metric?
1    2.5     true
2    5       true
3    10      true
4    20      true
5    5       false
6    10      false
7    20      false
8    40      false

PS - ((very) rough approximations of Imperial weights!)


Q:

How to search numbers inside brackets in GVIM

In Gvim, how do I search "numbers inside square brackets".
I tried the following search /[*] but it resulted in highlighting all pattern in between brackets including alphabetic characters.
I want to search only the numbers in between square brackets, is there any wild card ? Can someone help me out ?

A:

vim (and gvim) search via regular expressions.  In this case, you can do /\[[0-9]\+\] (or the shorthand /\[\d\+\] as Istvan mentioned).
See also:

:help search
Search and Replace
Vim tips: The basics of search and replace


Q:

svg elements reset on hide/show in chrome

I have 3 SVG <object> elements representing 3 differents floors of a building. In the bottom I have 3 buttons to navigate between them that do a simple hide() and show().

When I load the page a script setups some interactive elements in the svg, but when i switch between floors with the navigation buttons the interactive svg elements resets losing its functionality.
interactive elements

You can see the problem here
How can I prevent this? the script seems to be working on firefox.
Here's the code that hides/show the floors.
function showMap(mapId){
  var map = (typeof(mapId)=="string")? $('#'+mapId) : $(mapId);
  if(!map.is(':visible')){
    maps.hide(); // hides all svg objects
    map.show();  // display the selected one
  }
}

A:

Yes, this is a "feature" of Chrome. "display: none" (including css way) completely ruins all interactions with SVG.
Use size or position instead:
jQuery.fn.weirdHide = function() {
    $(this).css("width", 0)
        .css("height", 0)
        .css("position", "absolute")
        .css("left", "-9999px");
}

jQuery.fn.weirdShow = function() {
    $(this).css("width", "")
        .css("height", "")
        .css("position", "")
        .css("left", "");
}

$("#map").weirdHide();
$("#map").weirdShow();


Q:

Is it safe to delete or remerge a Gitlow feature branch after it was previously merged into the develop branch?

Let's take the Gitflow branching style. For every feature we have a "feature branch". We develop the feature and once it's done we can merge it into the "develop" branch.

Once the merge is done, can we simply delete the branch and nothing will ever be lost in the commit log history?
Assuming we haven't deleted the feature branch. After the merge into "develop", someone reviews the change and spots some minor issue (e.g. a misspelling or some other minor change). Is it safe to do the change in the "feature branch" and re-merge it into the "develo" branch? Or is it more appropriate to always create a new "feature branch" even for trivial things that mostly affect the work been done in some previous "feature"?

A:

Once the merge is done, can we simply delete the branch and nothing will ever be lost in the commit log history?

You would loose the intermediate commits done on the feature branch (if the merge wasn't a fast-forward one), but that is normally ok if the feature isn't too big (only the resulting merge commit matters).

Assuming we haven't deleted the feature branch. After the merge into "develop", someone reviews the change and spots some minor issue (e.g. a misspelling or some other minor change).
  Is it safe to do the change in the "feature branch" and re-merge it into the "develo" branch? Or is it more appropriate to always create a new "feature branch" even for trivial things that mostly affect the work been done in some previous "feature"?

Yes, you can re-use your feature branch since the next merge will only involve the new commit(s), not the older ones (which are marked as already merged).


Q:

Issue while inserting files in HDFS

I am facing a lot of issue while storing file in hdfs. File stored in HDFS is having binary values and timestamp. I am trying to remove it but not able to do it. Please help
Result :
000000: 46 48 50 7c b3 7e 5c 26 7c 4c 33 1d 43 7c MHS|1^&@|fff 000010:
Expected :
MHS|1^&@|fff 000010

Code :
 hadoop fs -put localpath hdfspath

A:

Under Apache Hue web interface, open the content of your file then you find the option to display the content in text format in the left menu bar


Q:

Do my kids need to file a tax return?

My kids (minors) each received a gift of some stock from my wife's parents last year.  The stock is in the kids' names, with my wife listed as the custodian.  They each made just slightly over $100 in dividends last year, and have no other income.  No income tax was withheld.  They each received a 1099-DIV form.
Are they required to file a tax return and pay tax on the dividends?

A:

No they do not. From form 1040 instructions, a single, non-blind dependent under age 65 must file if the following are true:

You must file a return if any of the following apply.

Your unearned income was over $1,000.
Your earned income was over $6,200.
Your gross income was more than the larger of—

$1,000, or
Your earned income (up to $5,850) plus $350.

There is no return required for receipt of a gift.

A:

If the gift was stock that they have owned for years there can be one hitch: The basis of the stock doesn't reset when it is gifted.
For example if grandparents have owned stock that is currently worth $10,000 today, but they bought it decades ago when it only cost them $1,000; then if the new owner sells it today they will have a gain of $9,000.
The clock to determine short term/long term also doesn't reset; which is good.
The basis needs to be determined now so that the gain  can be accurately calculated in the future. This information should be stored in a safe place.
Gains for dividends are investment income and the rules regarding the kiddie tax need to be followed.


Q:

Unable to scp from remote to local Mac

I have gone over SU and SO posts looking for a way to get this to work, but I'm about to put up my hands and stick with a GUI. I want to scp a ZIP file from a remote server to my local machine. I can SSH in just fine. I can create, delete, edit, etc... but am unable to download a ZIP. The "closest" so far.
# scp backup.zip Steven@111.111.111.11:/Users/Steven/Desktop/test.
For clarity, "backup.zip" is what I want to pull down from the server and is in my current directory. "Steven" is my username on my laptop. I've blanked out the IP address for my local machine with the ones, and the path is the path to the location I would like to copy to.
With that, however, I get:
ssh: connect to host 111.111.111.11 port 22: Connection timed out
lost connection
Funny thing is, I'm not booted out of the session. It just leaves me right where I was before entering in the command.
Am I missing some syntax?

A:

Do I understand correctly that you're using SSH to connect to the remote host, then you're running scp on the remote host to copy the file back to the local host?
Without knowing anything about these two hosts, it's perfectly possible that your local host can make SSH connections to the remote, but the remote can't make SSH connections to the local.
If you can make SSH connections from the local host to the remote host, you could run scp on the local host instead of the remote one:
scp remoteuser@remotehost:/path/to/backup.zip /Users/Steven/Desktop/test/


Q:

The lightning struck the hut and set it alight or set it on fire?

Let's say you were storytelling something about a hut that was struck by lightning, is there any difference between the two?

The lightning struck the hut and set it alight?

Vs.

The lightning struck the hut and set it on fire?

A:

Alight could simply mean "lit up". It does not specifically tells if the thing is on fire or not. (Especially in American English)
There's not much difference in British usage, but it's better to use set it on fire as this clearly describes the event without leaving a doubt in the reader's mind.

A:

That use of alight sounds awkward to me. Things can be alight, but you don't set them alight. I'm not saying it's technically incorrect, just that IMHO it would be distracting to me as a reader.
On fire is fine, but probably what you're looking for is ablaze.

A:

The difference is the second example uses an Idiom to explain what happens

alight
  adjective [ after verb ] UK   /əˈlaɪt/ US   /əˈlaɪt/
  alight adjective [ after verb ] (BURNING)
The rioters overturned several cars and set them alight.
--Cambridge English Dictionary

Reference Cambridge Thesaurus
Idioms
set sth/sb on fire
set fire to sth/sb


Q:

Can an iPhone/Android app have access to microphone during phone calls?

I'm wondering if it's possible to record phone calls via apps. (changing voice pitch and etc.)

A:

Android can access the microphone. There are apps in the Android Market that record phone calls. I am not sure if you can change the stream without root access.
iPhone - this is completely out - this is all private API and will cause your app to be rejected.


Q:

save result to variable

How can I save result from nc to the variable?
I want:

nc: connect to localhost port 1 (tcp) failed: Connection refused

on my variable. I tried:
a="$(nc -z -v localhost 1)"
echo $a

but output is empty.

A:

Just use $() to get the result of the command:
your_var=$(nc -z -v localhost 1)

If you also want the error to be stored, then redirect the 2 (error) to 1 (normal output):
your_var=$(nc -z -v localhost 1 2>&1)

A:

Just redirect stderr to stdout, expressed by 2>&1:
a="$(nc -z -v localhost 1 2>&1)"
echo $a
nc: connect to localhost port 1 (tcp) failed: Connection refused

File descriptor 2 is attached (unless redirected) to stderr, and fd 1 is attached to stdout. The  bash syntax $( ... ) only captures stdout.


Q:

Why does Linked questions allow anyone to see some details of a deleted post without checking their privileges?

Take for example the question (on Drupal.SE) about "How to process the results of a VBO enabled view via Rules?". It is deleted and in its Linked block (to the right, above its "Related" block) it shows 2 other questions. Users on that site with less than 10k reputation, or without a diamond, or not the author of the question (who happens to be me) only see a friendly "Page Not Found" message, which is all good.
However, by manually changing the URL to the Linked questions view of the question, any user can see it. Even with less than 10k reputation, even totally anonymous visitors. This is showing at least:

the title of the deleted question.
the title of the questions linked to the deleted question.

Why does Linked questions allow anyone to see some details of the deleted post without checking their privileges? That does not seem to be the case for  these variations for that same question:

The timeline page.
The revisions page.

Note: for deleted questions with 0 linked questions (such as this example), a similar Linked questions URL also reveals the title of the deleted question.

A:

I don't really see any issue with this. It doesn't really reveal any new information. If a < 10k user visits, e.g.:
https://drupal.stackexchange.com/questions/212520

You'll already see the title as the URL will be replaced with:
https://drupal.stackexchange.com/questions/212520/how-to-process-the-results-of-a-vbo-enabled-view-via-rules

Also, there's nothing you can really do with this information. There's no real consequences.
As for the linked questions, that doesn't seem to be an issue. They're just questions. If they themselves aren't deleted there's no reason to hide them.


Q:

How to make a thumbnail of a static image using sorl-thumbnail

I have a user model with an avatar field in my Django project:
class User(AbstractBaseUser):

    avatar = models.ImageField(
        null=True,
        blank=True,
        upload_to='user/avatar/',
    )

The avatar is not required, so I would like to use a default image if a user hasn't uploaded one. On the other hand I don't want to use a default parameter in order to be able to change the default avatar in the future for all users:
class User(AbstractBaseUser):

    avatar = models.ImageField(
        null=True,
        blank=True,
        default='defaults/no-avatar.png',
        upload_to='user/avatar/',
    )

So I ended up writing a get_avatar method that returns an image if the avatar exists or a path to a default static image:
@property
def get_avatar(self):
    if self.avatar:
        return self.avatar
    return '{0}defaults/no-avatar.png'.format(settings.STATIC_URL)

But in this case sorl-thumbnail doesn't generate a thumbnail for a default image
{% thumbnail user.get_avatar "46x46" crop="center" as im %}
    <img title="{{ user }}" src="{{ im.url }}" class="img-circle" />
{% endthumbnail %}

and returns the following error:
ERROR 2014-09-22 12:49:48,020 thumbnail :: Thumbnail tag failed:
Traceback (most recent call last):
  File "/Users/vera/.virtualenvs/my_app/lib/python2.7/site-packages/sorl/thumbnail/templatetags/thumbnail.py", line 45, in render
    return self._render(context)
  File "/Users/vera/.virtualenvs/my_app/lib/python2.7/site-packages/sorl/thumbnail/templatetags/thumbnail.py", line 97, in _render
    file_, geometry, **options
  File "/Users/vera/.virtualenvs/my_app/lib/python2.7/site-packages/sorl/thumbnail/base.py", line 56, in get_thumbnail
    source_image = default.engine.get_image(source)
  File "/Users/vera/.virtualenvs/my_app/lib/python2.7/site-packages/sorl/thumbnail/engines/pil_engine.py", line 12, in get_image
    buf = StringIO(source.read())
  File "/Users/vera/.virtualenvs/my_app/lib/python2.7/site-packages/sorl/thumbnail/images.py", line 121, in read
    return self.storage.open(self.name).read()
  File "/Users/vera/.virtualenvs/my_app/lib/python2.7/site-packages/django/core/files/storage.py", line 33, in open
    return self._open(name, mode)
  File "/Users/vera/.virtualenvs/my_app/lib/python2.7/site-packages/django/core/files/storage.py", line 159, in _open
    return File(open(self.path(name), mode))
  File "/Users/vera/.virtualenvs/my_app/lib/python2.7/site-packages/django/core/files/storage.py", line 260, in path
    raise SuspiciousFileOperation("Attempted access to '%s' denied." % name)

I tried to rewrite that method in order to return an image instead:
from django.core.files.images import ImageFile

@property
def get_avatar(self):
    if self.avatar:
        return self.avatar
    return ImageFile(open(os.path.join(settings.STATIC_ROOT, 'defaults/no-avatar.png'), 'r'))

but I got a similar error:
ERROR 2014-09-22 12:52:18,448 thumbnail :: Thumbnail tag failed:
Traceback (most recent call last):
  File "/Users/vera/.virtualenvs/my_app/lib/python2.7/site-packages/sorl/thumbnail/templatetags/thumbnail.py", line 45, in render
    return self._render(context)
  File "/Users/vera/.virtualenvs/my_app/lib/python2.7/site-packages/sorl/thumbnail/templatetags/thumbnail.py", line 97, in _render
    file_, geometry, **options
  File "/Users/vera/.virtualenvs/my_app/lib/python2.7/site-packages/sorl/thumbnail/base.py", line 56, in get_thumbnail
    source_image = default.engine.get_image(source)
  File "/Users/vera/.virtualenvs/my_app/lib/python2.7/site-packages/sorl/thumbnail/engines/pil_engine.py", line 12, in get_image
    buf = StringIO(source.read())
  File "/Users/vera/.virtualenvs/my_app/lib/python2.7/site-packages/sorl/thumbnail/images.py", line 121, in read
    return self.storage.open(self.name).read()
  File "/Users/vera/.virtualenvs/my_app/lib/python2.7/site-packages/django/core/files/storage.py", line 33, in open
    return self._open(name, mode)
  File "/Users/vera/.virtualenvs/my_app/lib/python2.7/site-packages/django/core/files/storage.py", line 159, in _open
    return File(open(self.path(name), mode))
  File "/Users/vera/.virtualenvs/my_app/lib/python2.7/site-packages/django/core/files/storage.py", line 260, in path
    raise SuspiciousFileOperation("Attempted access to '%s' denied." % name)
SuspiciousFileOperation: Attempted access to '/Users/vera/workspace/my-website/static/defaults/no-avatar.png' denied.

A:

sorl-thumbnail used storage functionality. Django delegates decisions about how and where to store files to a file storage system. This is the object that actually understands things like file systems, opening and reading files, etc. Django ships with a django.core.files.storage.FileSystemStorage class which implements basic local filesystem file storage. By default, Django stores files locally, using the MEDIA_ROOT and MEDIA_URL settings.
So in your case django try find image under MEDIA_ROOT, but you have saved the image under STATIC_ROOT.
How fix that
As hotfix you can try move image under MEDIA_ROOT and will change path in get_avatar method.
Or you can try write custom storage, which will work with both folders. Example custom storage.


Q:

Come si dice "meme" in italiano?

Buongiorno,
Come si traduce il termine "meme" in italiano (quelle sigle con un'immagine dietro che si vedono girare su Facebook e Internet). Inoltre vorrrei sapere dove posso trovare, se non vi dispiace, dei testi "mene" in italiano dai quali trarre ispirazione, modificare, e riusare. Scusate se questo è un po' off-topic, sono un po' imbranato.
Molte grazie per la vostra pazienza.

A:

Meme si dice in italiano “meme”, ovviamente pronunciato all'italiano e con come plurale “memi” (sul modello di “gene” e “geni”).
Nota che il concetto di meme è ben più ampio delle spiritosaggini su Internet e descrive qualsiasi elemento culturale, idea, anche una singola nuova parola che si diffonde e si modifica all'interno della società in un modo confrontabile con quello appunto dei geni. Cioè il meme starebbe alla cultura come il gene alla biologia.


Q:

React-native Determining whether the code is being debugged remotely or not

Is there a reliable way to determine if react-native code is running on the device, or in chrome (remote-debugging) from within the code?
I have some console logs, that are mostly useful in the chrome console, and want to disable them when on the device (they are already disabled for prod builds), as they have a major performance impact outside of remote debug mode.

A:

This seems to work for now:
const debuggingEnabled = !!window.navigator.userAgent;

As window.navigator.userAgent is undefined on android and ios


Q:

EXC_BAD_ACCESS in simple code in release

This simple code below works in debug, but fails in release on iPhone 6.
XCode 6.2 (6C131e)
Calling runTest causes the EXC_BAD_ACCESS on the latest 64bit iPhones. And it only happens when build Optimization Levels set 'Faster' and higher: -O2, -O3, -Os or -Ofast. So usually in Release configuration.
BTW, the code works well when Optimization Levels set 'None' or 'Fast': -O0 or -O1.
#import <objc/NSObject.h>

@interface Foo : NSObject
@end

@interface Test : NSObject {
    Foo *field;
}
@end

@implementation Foo

- (Foo *)bar {
    return self;
}

@end

@implementation Test

- (void)runTest {
    Foo *foo = [[Foo alloc] init];
    field = foo;
    field = nil;
    [foo bar];
}

@end

Please explain me why this happens.

A:

I posted problem to Apple Bug Reporter, but Apple once requested some more details and then never responded. Now the problem report has completely disappeared.
By the way this appears to work with clang, version 7.3.


Q:

Setting a cross-compiler file using the CMake GUI

I'm trying set-up my cross-compile build using CMake. So far I'm setting the cross compiler file calling CMake like this from the command line:
#Call cmake with the given options
cmake -D CMAKE_TOOLCHAIN_FILE=$cross_cmp_file \
      -D BUILD_TESTS:BOOLEAN=$build_test \
      ../src

This works just fine.
Now I'm trying to set the CMAKE_TOOLCHAIN_FILE variable from the GUI by adding:
#CMAKE cross compiler file
set(CMAKE_TOOLCHAIN_FILE "Toolchain file" CACHE FILEPATH "../arm-crosscompile.cmake")

To my CMakeLists.txt.
This actually shows the variable in the GUI but when I press the "Configure"  button, the c++ compiler that appear in the CMAKE_CXX_COMPILER variable is the one by default and not the one specified in the toolchain file.
How can I set the toolchain file from the Cmake-GUI?

A:

Finally got it. Simple enough.
The first time you press the "Configure" button you will get to specify the generator parameters, select any generator for your project. Then select the option "Specify toolchain file for cross-compiling" and click next:
:
Click Next. In the following dialog, input the path to the cross-compilation file and you're done.

A:

Do you set the variable before or after the call to project()?
The compiler detection happens inside that call so it has to be set before getting there.
Although I'm not sure you're able to change these settings after the first run.
Usually you'd set the toolchain the first time you run Cmake using the wizard style dialog.


Q:

Encrypted sql connection info in webconfig

Well, I have a website in asp.net 4.5, and I have now started to work with MSSQL, I have puted my connection string in the web-config so I can use it from more then 1 page without writing it down again and again, but then my website manger said I need to encrypt the connection string(so no one will be able to see it.. I guess).
How can I do that? I mean, I have no idea how to encrypt anything, not talking about things like that.
I have search the web for some information but found nothing. sorry if someone already asked it..

A:

Walkthrough: Encrypting Configuration Information Using Protected Configuration should help you.
Summary: use the aspnet_regiis.exe tool included with .NET on the destination server.


Q:

pass back data with protcols

i need to pass some data to previous view controller, what is problem with my codes?
in this code "contactViewController" is my first view controller and "groupViewController" is my second view controller
//ContactEditVC.h (firstViewController)

#import "GroupEditTVC.h"

@interface ContactEditVC : UIViewController <SecondViewControllerDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate> {
    UIImageView * imageView;
    UIButton * choosePhotoBtn;
    UIButton * takePhotoBtn;
    UIButton * btnGroup;
}

@property (nonatomic, strong) NSString *groupName;

---------------------------------------------------
//ContactEditVC.m (firstViewController)

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    if([[segue identifier] isEqualToString:@"selectGroup"]){
        //get selected contact

        //pass selected contact to MyContactAppViewController for editing
        GroupEditTVC *destViewcontroller=segue.destinationViewController;
        destViewcontroller.delegate=self;

    }
}

-(void)viewWillAppear:(BOOL)animated
{
    self.txtFname.text=groupName;

}

- (void)dataFromController:(NSString *)data
{
   groupName=data;
}

and in my second vie controller:
@protocol SecondViewControllerDelegate <NSObject>
- (void)dataFromController:(NSString *)data;
@end

@interface GroupEditTVC : UITableViewController <UIAlertViewDelegate>

@property (retain) id <SecondViewControllerDelegate> delegate;

@end
---------------------------------
//GroupEditTVC.m (secendViewController)

#import "ContactEditVC.h"

@interface GroupEditTVC ()
@end

@synthesize delegate;

- (IBAction)donePressed:(id)sender {
    [[self delegate]dataFromController:@"blabla"];
    [self dismissViewControllerAnimated:YES completion:nil];
}

A:

Set some breakpoints in - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender.  Im guessing that [segue identifier] is not equal to what you think it should be and thus it is never going into the block of code inside the if statement.


Q:

How can I remove duplicates from each item in jsrender template?

I am trying to remove duplicate file from each div in jsrender but not able to do it correctly as all the duplicates get removed.
$('.media-holder').each(function () {
  $('.media-item').each(function () {
    $('.media-item:contains("' + $(this).text() + `enter code here`'"):gt(0)').remove();
  });
});

Current output:
**Files part 1**
abc file
def file
abc file
**Files part 2**
abc file
def file
abc file
def file
ghi file

Desired Output:
**Files part 1**
abc file
def file
**Files part 2**
abc file
def file
ghi file

A:

Use media-holder as a selector context

$('.media-holder').each(function(i, holder) {
  $('.media-item').each(function() {
    $('.media-item:contains("' + $(this).text() + '"):gt(0)', holder).remove();
  });
});

abc file

def file

abc file

abc file

def file

abc file

def file

ghi file


Q:

Consolidating & Collecting into one Record

I'm trying to write a cypher query where all related nodes are collected and returned under a key in a map:
{
    name: 'chart',
    CONTAINTED: [
        {
            name: 'id'
        },
        {
            name: 'bloodpressure'
        },
        ...
    ],
    FOREIGNKEY: [
        {
            name: 'clientid'
        }
    ]
}

I've attempted to do this with the following cypher query but it isn't quite right. Using the method below two records are returned rather than just one.
MATCH path=(table:tabPHI {name: 'client'})-[r]-(c)
WITH table as tab, type(r) as rel, collect(c) as col
CALL apoc.map.setKey(tab, rel, col) YIELD value as foo
return foo

A:

MATCH (table:tabPHI {name: 'client'})-[r]-(c)
WITH table as tab, type(r) as rel, collect(c) as col
WITH tab, COLLECT(rel) AS keys, COLLECT(col) AS values
WITH keys(tab) as main_keys, [key IN keys(tab)|tab[key]] AS main_values, keys, values
CALL apoc.map.fromLists(main_keys + keys, main_values + values) YIELD value as foo
return foo

You're creating a single map for each relationship type in your query. You have to COLLECT(rel) at some point to get a single result for each tab.


Q:

RxJava Android sequence print data

I'm learning RxJava in Android.
I have:
Observable<Country> getCountries(){} // returns Countries
Observable<City> getCapital(int countryId){} // returns capital by country id

I want:
Print all country names returned by getCountries(). Then print capital name of each country from getCapital() method, except country with id=1. This all should be in one chain.
For example:
private Observable<Country> getCountries(){
    return Observable.just(
            new Country(0, "Luxemburg"),
            new Country(1, "Netherlands"),
            new Country(2, "Norway"),
            new Country(3, "India"),
            new Country(4, "Italy")
    );
}
private Observable<City> getCapital(int countryId){
    City city;
    switch (countryId){
        case 0: city = new City("Luxembrug");
            break;
        case 1: city = new City("Amsterdam");
            break;
        case 2: city = new City("Oslo");
            break;
        case 3: city = new City("Delhi");
            break;
        case 4: city = new City("Rome");
            break;
        default:
            city = new City("");
            break;
    }
    return Observable.just(city);
}

getCountries()
      .doOnNext(country -> Log.d("TAG", "Country: id="+country.getId()+" name="+country.getName()))
      .filter(country -> country.getId()!=1)
      .flatMap(country -> getCapital(country.getId()))
      .subscribe(city -> Log.d("TAG", "City: "+city.getName()));

What I want to get:
D: Country: id=0 name=Luxemburg
D: Country: id=1 name=Netherlands
D: Country: id=2 name=Norway
D: Country: id=3 name=India
D: Country: id=4 name=Italy
D: City: Amsterdam
D: City: Oslo
D: City: Delhi
D: City: Rome

What I get:
D: Country: id=0 name=Luxemburg
D: Country: id=1 name=Netherlands
D: City: Amsterdam
D: Country: id=2 name=Norway
D: City: Oslo
D: Country: id=3 name=India
D: City: Delhi
D: Country: id=4 name=Italy
D: City: Rome

How can I achieve this?
I should at first get all countries, print it and after then get capitals for this countries. But I don't understand how can I do this in one chain..
Thanks for any tips!

A:

Assuming you can't change the getCountries() and getCapital(int countryId) methods you can achieve it like this:
RxJava 1x:
    getCountries()
            .toList()
            .doOnNext(countries -> {
                for (Country country : countries) {
                    Log.d("TAG", "Country: id=" + country.getId() + " name=" + country.getName());
                }
            })
            .flatMap(Observable::from)
            .filter(country -> country.getId() != 1)
            .flatMap(new Func1<Country, Observable<City>>() {
                @Override public Observable<City> call(Country country) {
                    return getCapital(country.getId());
                }
            })
            .subscribe(city -> Log.d("TAG", "City: " + city.getName()));

RxJava 2x:
    getCountries()
            .toList()
            .doOnSuccess(countries -> {
                for (Country country : countries) {
                    Log.d("TAG", "Country: id=" + country.getId() + " name=" + country.getName());
                }
            })
            .toObservable()
            .flatMap(Observable::fromIterable)
            .filter(country -> country.getId() != 1)
            .flatMap(new Function<Country, ObservableSource<City>>() {
                @Override
                public ObservableSource<City> apply(@NonNull Country country) throws Exception {
                    return getCapital(country.getId());
                }
            })
            .subscribe(city -> Log.d("TAG", "City: " + city.getName()));


Q:

How do you get SharePoint "My Links" back after a profile has been deleted and restored?

We're running SharePoint 2007 SP1 and profiles are imported from Active Directory (a full import runs daily).  We had a problem where many of the users were disabled unintentionally in Active Directory and this caused their profiles to be removed from SharePoint.  We re-enabled their Active Directory accounts and ran a full import which restored their SharePoint profiles.  However, all of their My Links are missing.  Is there a method or best practice for restoring them?

A:

I posted this because I couldn't find an answer to my problem anywhere.  This post by Joel Oleson that describes a similar problem to mine gave me a hint as to where to go looking for the missing data.  And This post by Corey Roth showed me how to programatically add the links to a users My Links.
First things first - you need to restore a backup of the database that contains the My Links data.  You don't want to restore over your working database, you want to restore it to another location.  The links stored in the SSP Database.  (You can find out the name of the database by going into Central Admin --> Shared Services Admin then open the menu for the SSP and click on Edit Properties - the SSP Database is listed on the properties page.)
Once the database has been restored you want to retrieve the Link information:

the domain account name of the user who owns the link,
the url of the link
the name of the link

This query will get you that information:
SELECT UPF.NTName, UL.Url, UL.Title
FROM UserLinks UL INNER JOIN UserProfile_full UPF ON UL.recordID = UPF.recordID
INNER JOIN UserPrivacyPolicy UPP ON UL.PolicyId = UPP.id
ORDER BY NTName

(I should note that I did not take into account what group or what privacy level the links were set to, you could probably find that information by looking at the information in the UserPrivacyPolicy table)
I copied the results into Excel & saved it as a .csv file (comma separated list) - just because my production server did not have access to the location where I restored my database.  I ordered the columns with Title last because the Title could contain commas and that would mess up how I'm reading in the data.  (I checked and the other two fields do not contain commas - you should check yours before making this assumption.)
I then wrote a little console app to import the data.  It takes two arguments:

the path where the file containing all of the links is located (ie c:\temp\links.csv)
the url of the SSP from with the My Links have gone missing (ie https://portal.mydomain.com)

These are the references used:

Microsoft.Office.Server (C:\Program Files\Common Files\Microsoft    Shared\Web Server    Extensions\12\ISAPI\Microsoft.Office.Server.dll)
Microsoft.SharePoint (C:\Program Files\Common Files\Microsoft    Shared\Web Server    Extensions\12\ISAPI\Microsoft.SharePoint.dll)
System
System.Data
System.Web
System.Xml

And this is the code:
using System;
using System.IO;
using System.Collections.Generic;
using System.Text;
using Microsoft.Office.Server;
using Microsoft.Office.Server.UserProfiles;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;
using System.Web;

namespace UserLinks
{
    class Program
    {
        static void Main(string[] args)
        {
            string _accountName = "", _linkTitle = "", _url = "", _tmp = "", _path = "", _SPSsite = "";

            // Check arguments
            if (args.Length != 2)
            {
                ShowUsage();
                return;
            }

            _path = args[0];
            _SPSsite = args[1];

            using (SPSite _site = new SPSite(_SPSsite))
            {
                ServerContext _context = ServerContext.GetContext(_site);
                UserProfileManager _userProfileManger = new UserProfileManager(_context);

                /* Expecting a comma seperated list with 3 columns:
                 * AccountName in the format Domain\Account name - I am assuming there are no commas in this field
                 * URL - I am assuming there are no commas in this field
                 * Link Title - link title is last because there may be commas in the title
                */
                TextReader _reader = new StreamReader(_path, System.Text.Encoding.Default);
                while (_reader.Peek() != -1)
                {
                    _tmp = _reader.ReadLine();
                    _accountName = _tmp.Substring(0, _tmp.IndexOf(','));
                    _tmp = _tmp.Replace(_accountName + ",", "");
                    _url = _tmp.Substring(0, _tmp.IndexOf(','));
                    _linkTitle = _tmp.Replace(_url + ",", "");

                    try
                    {
                        UserProfile _currentUser = _userProfileManger.GetUserProfile(_accountName);
                        QuickLinkManager _quickLinkManager = _currentUser.QuickLinks;
                        _quickLinkManager.Create(_linkTitle, _url, QuickLinkGroupType.General, null, Privacy.Private);  //I am assuming that all links have no group assigned to them and they are all private links
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(_accountName);
                        Console.WriteLine(ex);
                    }

                }
                _reader.Close();

            }
        }

        private static void ShowUsage()
        {
            Console.WriteLine("Usage");
            Console.WriteLine("UserLinks [FilePath] [SharePoint URL]");
        }

    }
}

So problem solved & as a side benefit, this program can be used to force links to show up in a user's My Links list.


Q:

using xpath in java to go through this list?

i have an xml file that contains lots of different nodes. some in particularly are nested like this:
 <emailAddresses>
            <emailAddress>
                <value>sambj1981@gmail.com</value>
                <typeSource>WORK</typeSource>
                <typeUser></typeUser>
                <primary>false</primary>
            </emailAddress>
            <emailAddress>
                <value>sambj@hotmail.co.uk</value>
                <typeSource>HOME</typeSource>
                <typeUser></typeUser>
                <primary>true</primary>
            </emailAddress>
        </emailAddresses>

From the above node, what i want to do is go through each  and get the values inside it(value, typeSource, typeUser etc) and put them in a POJO.
i tried to see if i can use this xpath expression "//emailAddress" but it doesnt return me the tags inside inside it. maybe i am doing it wrong. i am pretty new to using xpath.
i could do something like this:
//emailAddress/value | //emailAddress/typeSource | ..  but doing that will list all elements values together if im not mistaken leaving me to work out when i have finished reading from a specific emailAddress tag and going to the next emailAddress tag.
well to sum up my needs i basically want this to be returned similar to how you would return results from a bog standard sql query that returns results in a row. i.e. if your sql query produces 10 emailAddress, it will return each emailAddress in a row and i can simply iterate over "each emailAddress" and get the appropriate value based on the colunm name or index.

A:

No,

//emailAddress

doesn't return the tags inside, that is correct. What it does return is a NodeList/NodeSet. To actually get the values you can do something like this:
String emailpath = "//emailAddress";
String emailvalue = ".//value";

XPathFactory xPathFactory = XPathFactory.newInstance();
XPath xpath = xPathFactory.newXPath();
Document document;
public XpathStuff(String file) throws ParserConfigurationException, IOException, SAXException {
    DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = docFactory.newDocumentBuilder();

    BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
    document = builder.parse(bis);

    NodeList nodeList = getNodeList(document, emailpath);
    for(int i = 0; i < nodeList.getLength(); i++){
        System.out.println(getValue(nodeList.item(i), emailvalue));
    }
    bis.close();
}

public NodeList getNodeList(Document doc, String expr) {
    try {
        XPathExpression pathExpr = xpath.compile(expr);
        return (NodeList) pathExpr.evaluate(doc, XPathConstants.NODESET);
    } catch (XPathExpressionException e) {
        e.printStackTrace();
    }
    return null;
}

//extracts the String value for the given expression
private String getValue(Node n, String expr) {
    try {
        XPathExpression pathExpr = xpath.compile(expr);
        return (String) pathExpr.evaluate(n,
                XPathConstants.STRING);
    } catch (XPathExpressionException e) {
        e.printStackTrace();
    }
    return null;
}

Maybe I should point out that when iterating over the Nodelist, in .//values the first dot means the current context. Without the dot you would get the first node all the time.


Q:

Simple Ajax Post to PHP echo

I have the following code on product.php .. can't seem to echo post variable from ajax post. Alert displays fine. Please help
JQUERY
    document.getElementById("LBTest").onchange = function(){
      var lbtest = $('#LBTest :selected').val();
      $.ajax({
      type: "POST",
      url: "product.php",
      data: {test: lbtest},
      success: function()
      {
          alert("Successful");
      }
      });
}

PHP
if(isset($_POST['test'])){
    $data = $_POST['test'];
    echo $data;
}

A:

You need to do something with the data you receive from the ajax call. For example, to put the result into a <div> called resultDiv:
success: function(data)
{
  $('#resultDiv').html(data);
  alert("Successful");
}


Q:

How to read files in folders?

I am trying to get my application to check for folders in the folderbrowserdialogs selectedpath and then get those files, but it doesn't work I have tried both listed ways below. The second way gives me an error: (Expression is of type char which is not a collection type)
    For Each folder In FileBrowserDialog.SelectedPath
        Dim counter As  _
System.Collections.ObjectModel.ReadOnlyCollection(Of String)
            counter = My.Computer.FileSystem.GetFiles(folder)
            Label1.Text = counter.Count.ToString
        Next

For Each folder In FileBrowserDialog.SelectedPath
        Dim counter As  _
System.Collections.ObjectModel.ReadOnlyCollection(Of String)
For Each foundfile In folder
            counter = My.Computer.FileSystem.GetFiles(foundfile)
            Label1.Text = counter.Count.ToString
        Next

Any help is appreciated.

A:

FolderBrowserDialog1.SelectedPath will return the path the user selected in the dialog.  You still need to write code to go get the files.  There may not be a need to get the folders and then files in them. Net has ways to do that for you:
FolderBrowserDialog1.ShowDialog()
Dim myPath As String = FolderBrowserDialog1.SelectedPath

' get all files for a folder
Dim files = Directory.GetFiles(myPath)

' get all files for all sub folders
Dim files = Directory.GetFiles(myPath, "*.*",
         System.IO.SearchOption.AllDirectories)

' get certain file types for folder and subs
Dim files = Directory.GetFiles(myPath, "*.jpg",
         System.IO.SearchOption.AllDirectories)

You also are not going to be able to simply assign the results to a ReadOnlyCollection like that, because they are ReadOnly.  The collection needs to be created/instanced with the complete list:
Dim counter As new ReadOnlyCollection(Of String)(files)


Q:

Conferir elementos de Listas dentro de outras listas Python

Boas,
Tenho duas listas
lista1 = [0,1,2,3]
lista2 = [0,1,2,3,4,5]

Como é que eu confirmo se todos os elementos da lista1 estão dentro da lista2 ?
Por exemplo :
lista1 = [0,1,2]
lista2 = [1,2,3,4]

lista3 = [0,1,2,3]
lista4 = [0,1,2,3,4]

Todos os elementos da lista1 não estão dentro da lista2 mas todos os elementos da lista3 estão dentro da lista4!
Já tentei fazer isto simplesmente fazendo :
if lista1 in lista2 :
    print('todos dentro')

Mas não funciona !
Alguém me ajuda?

A:

if lista1 in lista2 :
    print('todos dentro')

O que você comparou aqui não é se uma lista contém todos os elementos da outra, mas sim se uma lista contém a outra. São coisas distintas.

a = [1, 2], b = [1, 2, 3] (a in b => False)
a = [1, 2], b = [[1, 2], 3] (a in b => True)

Na situação (1) a lista b contém todos os elementos de a; na situação (2) a lista b contém a lista a. Você precisa verificar a situação (1), mas verificou a situação (2).
O que você pode fazer para verificar é fazer um laço percorrendo os elementos da primeira lista e verificar um a um se estão também na segunda lista. Em Python, a maneira mais simples de fazer isso seria:
if all(i in b for i in a):
    print('Todos dentro')

Isto é, verifica se i está em b para todo i que pertence a a.
Ou, como comentado, você pode utilizar teorias de conjuntos. No Python, você pode criar um conjunto a partir de uma lista a partir da estrutura set:
a = set([1, 2])
b = set([1, 2, 3])

E assim utilizar o método set.issubset para verificar se um conjunto é sub-conjunto de outro:
if a.issubset(b):
    print('Todos dentro')

Ou pelo operador <=, que faz a mesma coisa:
if a <= b:
    print('Todos dentro')


Q:

Ruby Dir.glob mystery: Where are the FNM_xxx flags described?

Note: This has already been posted on Ruby Forum some weeks ago. I'm crossposting it here, because I didn't get any response so far
Dir.glob provides an optional parameter, usually referred as 'flags'.
Where can I find a documentation about what flags are possible?
The Ruby 2.0 docs just say that the flags are "the same as used in
File.fnmatch".
Looking up the documentation of File.fnmatch, I only find the
explanation that these are the "FNM_xxx" flags, which can be or'ed
together. I could however find no documentation about what FNM_xxx flags
exist.
Where is this described?

A:

It's actually defined inside File::Constants, and thereby documented under the same.
Look it up with ri :
ri File::Constants

Or read the html doc : Module: File::Constants (Ruby 2.2.2).


Q:

Server side Push to clients when getting GET request from another client

I am trying to implement a scenario when I need to notify a specific client say A when another client B makes a GET request to the server.
I am looking at Atmosphere for server push.
I have successfully connected B to the server and able to Push him if sending messages through Atmosphere. But this particular scenario I am stuck. Can any one please present a viable solution?
Else some pointers in the direction?
import org.atmosphere.annotation.Broadcast;
import org.atmosphere.annotation.Suspend;
import org.atmosphere.config.service.AtmosphereService;
import org.atmosphere.cpr.AtmosphereResourceEvent;
import org.atmosphere.cpr.AtmosphereResourceEventListenerAdapter;
import org.atmosphere.jersey.JerseyBroadcaster;

import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;

/**
 * Simple chat resource demonstrating the power of Atmosphere. This resource supports transport like WebSocket, Streaming, JSONP and Long-Polling.
 *
 * @author Jeanfrancois Arcand
 */
@Path("/")
@AtmosphereService (broadcaster = JerseyBroadcaster.class)
public class ChatResource {

    /**
     * Suspend the response without writing anything back to the client.
     *
     * @return a white space
     */
    @Suspend(contentType = "application/json", listeners = {OnDisconnect.class})
    @GET
    public String suspend() {

        return "";
    }

    /**
     * Broadcast the received message object to all suspended response. Do not write back the message to the calling connection.
     *
     * @param message a {@link Message}
     * @return a {@link Response}
     */
    @Broadcast(writeEntity = false)
    @POST
    @Produces("application/json")
    public Response broadcast(Message message) {
        return new Response(message.author, message.message);
    }

    public static final class OnDisconnect extends AtmosphereResourceEventListenerAdapter {
        /**
         * {@inheritDoc}
         */
        @Override
        public void onDisconnect(AtmosphereResourceEvent event) {
            System.out.println(event);
        }
    }

}

A:

Instead of using @Broadcast, use Broadcaster directly using the BroadcasterFactory, and invoke broadcaster.broadcast(message, ClientB). Look at atmosphere-sample's, there is many example doing that.
-- Jeanfrancois


Q:

How get not containing flags

I have enum flags. How to get all combinations of flags that do not contain a specific one?
[Flags]
public enum TestEnum
{
    A = 1,
    B = 2,
    C = 4,
    D = 8
}

public static IEnumerable<Enum> AllNotContaining(this Enum value)
{....}

For example, TestEnum.A.AllNotContaining() should return {2, 4, 6, 8, 10, 12, 14}.

A:

Step 1, use the binary NOT:
var notUsedBits = ~ value;

But this will set all of the 32 bits that were not used.
So you will probably want a mask:
[Flags]
public enum TestEnum
{
    A = 1,
    B = 2,
    C = 4,
    D = 8,
    All = A|B|C|D,  // or compute this inside the method
}

and then the method becomes
// untested
public static TestEnum AllNotContaining(this TestEnum value)
{
    return ~ value & TestEnum.All;
}

this does not return an IEnumerable but that is weird (and inefficient) for a Flags enum anyway.


Q:

iTunes connect build submission issue

Build prolem
Hi i am uploading since a week but every time i am facing an issue.When i upload the build from Xcode it will sucessfully uploaded but in iTunes it will be displayed as screenshot.after 5 Min. it will be also disappered. So what is an issue in that? Anyone resolve this?

A:

Your screen shot shows that upload the build successfully to itunesconnect.You will an email alert from store for successfull upload. It will take approximate 10 to 15minutes times for processing. Once this processing completed. This build will show under the Builds. Select the build version and submit to App Store.
Reference screen shot.


Q:

loading tab separated text files with multipled data into arrays in python

I want to load tab separated input file as an array into python and I know that genfromtxt in numpy does that but the problem is that I have multiple sets of data that i would like to be loaded. Basically my sample file could be :
#FILE START
#intensities
11 1 1
0  1 2
#indexes
1 2 3 4 5 6
7 8 9 1 1 2
#FILE END
So i would like to use this file to load the intensities as an array and indexes as another array. I would not like to be aware of the number of rows of intensities before hand but i can put the commentary ("intensities" or [intensities] like in ConfigParser to mark where a section starts or end).
Does there exist something like this or I will have to write something of my own?
Thanks

A:

f = open(filepath, 'r')
tags = ["#intensities"]
answer = {}
for line in f:
    if line.strip() in tags: # we've encountered a new tag
        curr = line.strip()[1:]
        answer[curr] = []
    else:
        answer[curr].append(line.strip().split('\t'))

f.close()

Now, answer will look like this:
{'intensities':[['11', '1', '1'], ['0', '1', '2']]}

Hope this helps


Q:

Magento 2 : how to convert my Domain Http:// to Https://

Till now I was using http:// in my domain, how can I move my domain from Http:// to https://
Do i have to buy a SSL Certificate. my domain was registered through Godaddy.
if i change Following in Magento Admin.

Store-> Configuration-> General-> Web
- Base URl
- Base link Url

Please let me know how to Use SSL Certificate to assign to this Domain.
I have Changed the mu Domain url with http to https.

After changing it Google chrome is not allow me to that Site As it is Not Secure.
Now, I need to add the SSL certificate to my Domain url. As i said earlier.
please let me know the steps for assigning SSL to Domain

A:

Yes, you need to purchase SSL certificate. There are different vendors provide this SSL service, then you need to generate CSR for your domain and generate public and private key to install SSL successfully for the domain on your server.
Then you need to configure https://yourdomain.com on the secure base url.
Also you need to make configure redirection from http://yourdomain.com to https://www.yourdomain.com


Q:

How to delay the execution of the javascript function

here i am trying to execute the JavaScript function with 6 seconds of delay.
I am executing the javascript function at body onload. I am not able to get how to five the delay for function execution...
How can i do this?
Here is my javascript snippet
Code:
function hideDiv() {
    if (document.getElementById) {
        document.getElementById('div').style.visibility = 'hidden';
    }
}

the function hideDiv should execute after 6 seconds

A:

You use setTimeout to schedule a javascript function to run sometimes in the future.
setTimeout(hideDiv, 6000);

See MDN for documentation on setTimeout().  The first argument is a reference to the function you want it to execute.  The second argument is milliseconds of delay.

Keep in mind that this will not stop other javascript that comes after this statement from executing.  That will continue to execute immediately.  It will schedule that particular function to run on it's own at the allotted time in the future.  So, this is not like sleep() in other languages.  It does not stop execution for 6 seconds.  Instead, it schedules this particular function to run later, but continues executing the rest of your javascript.
So, if you had this code:
setTimeout(hideDiv, 6000);
document.getElementById("hello").style.color = "red";

The color would change immediately and hideDiv() would be called in 6 seconds.


Q:

Json.NET fails to serialize dictionary of sets

I'm trying to serialize (and later on deserialize) a Dictionary<string, ISet<string>>. Unfortunately, Json.NET (v6.0.3 via NuGet) fails to do this. What I do is
var value = new Dictionary<string, ISet<string>>
    {
        {"foo", new HashSet<string>{"bar"}}
    };
var settings = new JsonSerializerSettings
    {
        TypeNameHandling = TypeNameHandling.Objects,
        TypeNameAssemblyFormat = FormatterAssemblyStyle.Simple
    };
var json = JsonConvert.SerializeObject(value, settings);

The variable json then holds the string
{"$type":"System.Collections.Generic.Dictionary`2[[System.String, mscorlib],[System.Collections.Generic.ISet`1[[System.String, mscorlib]], System]], mscorlib","foo":["bar"]}

Now I want to deserialize the string with
JsonConvert.DeserializeObject<IDictionary<string, ISet<string>>>(json, settings);

which fails in resolving the Dictionary type, because it cannot find the System assembly that ISet belongs to. When I instead do the following
JsonConvert.DeserializeObject<IDictionary<string, ISet<string>>>(json);

everything works just fine. So it appears that the TypeNameHandling setting (changing/omitting the format does not change anything) actually breaks deserialization.
I found that, if I don't set the TypeNameHandling settings, the serialized $type properties are simply ignored. I.e., when deserializing, the type information is taken solely from the target type where they are resolved. This works.
When setting the TypeNameHandling, type resolution happens via reflection within the Json.NET assembly, which does not have a dependency on the System assembly and therefore fails to resolve the ISet interface. I can fix this by registering on AppDomain.CurrentDomain.AssemblyResolve and resolving the assembly like so
if (args.Name == "System")
{
     return typeof (ISet<>).Assembly;
}

but this seems very fragile to me, as it solves the problem for only this one specific assembly and I have to add another case for every assembly I need somewhere.
Does anyone have experience on how to solve this? Any help is greatly appreciated!

A:

Similar problem was addressed in the following thread: How can I deserialize with TypeNameHandling.Objects in Json.NET Silverlight?
The problem seems to be that Json is failing to load the assembly with partial name. You could overcome this issue by using TypeNameAssemblyFormat = FormatterAssemblyStyle.Full.


Q:

complex query in PHP

I have two tables like this:
table a:

    [id, name, roll, address, mark]

table b

    [id, name, fee, reg_date]

now I'm running a query like this:
select * from a, b where a.id = b.id;

and I'm using 'mysql_fetch_object' .
Now how can I print name of table a and name of table b??
I tried this:
class foo {
    public $name;
}

mysql_connect("localhost", "root", "");
mysql_select_db("dodex");

$result = mysql_query("select * from a, b where a.id = b.id");
$obj = mysql_fetch_object($result, 'foo');
var_dump($obj);

to find a way, but I can't.

A:

You can use mysql_fetch_assoc, instead of mysql_fetch_object:
$a = mysql_fetch_assoc($result);
echo $a['a.name'];
echo $a['b.name'];

Otherwise, with mysql_fetch_object, you can do this:
$obj = mysql_fetch_object($result,'foo');
echo $obj->{'a.name'};
echo $obj->{'b.name'};


Q:

Solution to "function 'floor' not support in this profile" in Ogre3D cg fragment shader

I am reading the book "Ogre3D 1.7 Beginngers guide".I writed a cg fragment shader but encountered the complier complain, "function 'floor' not support in this profile".
The fragment shader definition is here:
   fragment_program MyFragmentShader8 cg
{
    source Ogre3DBeginnersGuideShaders.cg
    entry_point MyFragmentShader8
    profiles ps_1_1 arbfp1
}

The implementation is here:
void MyFragmentShader8(float2 uv    :TEXCOORD0,
    out float4 color    :COLOR,
    uniform sampler2D texture)
{
    float num = 50;
    float stepsize = 1.0 / num;
    float2 fragment = float2(stepsize * floor(uv.x * num), stepsize * floor(uv.y * num));
    color = tex2D(texture, fragment);
}

A:

You can replace this line:
float2 fragment = float2(stepsize * floor(uv.x * num), stepsize * floor(uv.y * num));

with these 3 lines:
int tmp1 = uv.x * num;
int tmp2 = uv.y * num;
float2 fragment = float2(stepsize * tmp1, stepsize * tmp2);

The conversion to int is an implicit floor().


Q:

how to set different app icons respected to the iOS version

I am developing an universal app and using the following link for configuring the app icons
My doubt is, the names used for icons in info.plist are predefined ?
does it takes automatically respected icon ?

A:

From the naming convention it seems that the proper icon will be selected for the right context. Have a look at the Custom Icon and Image Creation Guidelines.