text:
Q: While configuring expect, found source tcl directories instead of its installation location I am building gcc from source. I meant to run the tests, which requires dejagnu, expect and tcl.
I first configured tcl (using dir1 instead of the actual dir for brevity), with
$ cd dir1/unix
$ ./configure --prefix="$HOME/usr/local"

and built.
Then I configured expect with
$ ./configure --prefix="$HOME/usr/local"

At that point, tcl was found in dir1, i.e.,
$ grep tcl config.log
configure:2650: result: found dir1/unix/tclConfig.sh
configure:2656: checking for existence of dir1/unix/tclConfig.sh
configure:5078: result: dir1/generic
...

My environment produces (using $HOME for brevity)
LIBRARY_PATH=$HOME/usr/local/lib:...
LD_LIBRARY_PATH=$HOME/usr/local/lib:...
CPATH=$HOME/usr/local/include:...
PATH=$HOME/usr/local/bin:...

How is it posible that the source directory of tcl was found?
I expected that tcl was found in $HOME/usr/local.
Perhaps expect is somehow reading the configuration of tcl, which looks very strange to me.

A: If --with-tcl is not specified it'll first try to see if there's also a Tcl's build dir in the same dir level (actually it'll also try 2 dir levels higher). For example, if you have
/src/dir/of/expect-5.xx

then it'll see if there's also
/src/dir/of/tcl-8.xx
# and
/src/dir/of/tcl-8.xx/unix/tclConfig.sh

The Expect author may think people may first compile Tcl and then Expect at the same time. :)
See the file tclconfig/tcl.m4 in Expect's source code, lines 80~105:
 63
 64  # First check to see if --with-tcl was specified.
 65  if test x"${with_tclconfig}" != x ; then
 66      case "${with_tclconfig}" in
 67          */tclConfig.sh )
 68              if test -f "${with_tclconfig}"; then
 69                  AC_MSG_WARN([--with-tcl argument should refer to directory containing tclConfig.sh, not to tclConfig.sh itself])
 70                  with_tclconfig="`echo "${with_tclconfig}" | sed 's!/tclConfig\.sh$!!'`"
 71              fi ;;
 72      esac
 73      if test -f "${with_tclconfig}/tclConfig.sh" ; then
 74          ac_cv_c_tclconfig="`(cd "${with_tclconfig}"; pwd)`"
 75      else
 76          AC_MSG_ERROR([${with_tclconfig} directory doesn't contain tclConfig.sh])
 77      fi
 78  fi
 79
 80  # then check for a private Tcl installation
 81  if test x"${ac_cv_c_tclconfig}" = x ; then
 82      for i in \
 83              ../tcl \
 84              `ls -dr ../tcl[[8-9]].[[0-9]].[[0-9]]* 2>/dev/null` \
 85              `ls -dr ../tcl[[8-9]].[[0-9]] 2>/dev/null` \
 86              `ls -dr ../tcl[[8-9]].[[0-9]]* 2>/dev/null` \
 87              ../../tcl \
 88              `ls -dr ../../tcl[[8-9]].[[0-9]].[[0-9]]* 2>/dev/null` \
 89              `ls -dr ../../tcl[[8-9]].[[0-9]] 2>/dev/null` \
 90              `ls -dr ../../tcl[[8-9]].[[0-9]]* 2>/dev/null` \
 91              ../../../tcl \
 92              `ls -dr ../../../tcl[[8-9]].[[0-9]].[[0-9]]* 2>/dev/null` \
 93              `ls -dr ../../../tcl[[8-9]].[[0-9]] 2>/dev/null` \
 94              `ls -dr ../../../tcl[[8-9]].[[0-9]]* 2>/dev/null` ; do
 95          if test "${TEA_PLATFORM}" = "windows" \
 96                  -a -f "$i/win/tclConfig.sh" ; then
 97              ac_cv_c_tclconfig="`(cd $i/win; pwd)`"
 98              break
 99          fi
100          if test -f "$i/unix/tclConfig.sh" ; then
101              ac_cv_c_tclconfig="`(cd $i/unix; pwd)`"
102              break
103          fi
104      done
105  fi
106


text:
Q: How to get selected value from Dropdown list in JavaScript How can you get the selected value from drop down list using JavaScript? I have tried the following but it does not work.
var sel = document.getElementById('select1');
var sv = sel.options[sel.selectedIndex].value;
alert(sv);

A: It is working fine with me.
I have the following HTML:

    <select id="select1">
        <option value="1">test1</option>
        <option value="2" selected="selected">test2</option>
        <option value="3">test3</option>
    </select>

    <button onClick="GetSelectedItem('select1');">Get Selected Item</button>

And the following JavaScript:
function GetSelectedItem(el)
{
    var e = document.getElementById(el);
    var strSel = "The Value is: " + e.options[e.selectedIndex].value + " and text is: " + e.options[e.selectedIndex].text;
    alert(strSel);
}

See that you are using the right id. In case you are using it with ASP.NET, the id changes when rendered.

A: Direct value should work just fine:
var sv = sel.value;
alert(sv);

The only reason your code might fail is when there is no item selected, then the selectedIndex returns -1 and the code breaks.

A: Hope it's working for you
 function GetSelectedItem()
 {
     var index = document.getElementById(select1).selectedIndex;

     alert("value =" + document.getElementById(select1).value); // show selected value
     alert("text =" + document.getElementById(select1).options[index].text); // show selected text
 }

A: Here is a simple example to get the selected value of dropdown in javascript
First we design the UI for dropdown

<select class="form-control" id="language">
    <option>---SELECT---</option>
    <option>JAVA</option>
    <option>C</option>
    <option>C++</option>
    <option>PERL</option>
</select>

Next we need to write script to get the selected item

Tried and tested.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Loopback & Angular : How to set default value in form So I hit an error today when I tried to set value in my form.
this is my form:
<div class="list">
     <label class="item item-input">
        <input type="text" ng-model="user.isActive" value="false">
     </label>
</div>

The value didn't appear when I put ng-model="user.isActive" in <input>.
Please looking for my code.
Thanks

A: use ng-init

    <input type="text" ng-model="user.isActive" ng-init="user.isActive='yourvalue'">


text:
Q: Wedge Product Algebra If $A′,B′,C′$ are the midpoints of $BC, CA, AB$ respectively, then show that
$$4A′ ∧ B′ ∧ C′ = A ∧ B ∧ C.$$
So to begin with I have $4A' = 2BC, B' = 1/2(CA), C' = 1/2(AB)$ and therefore
$4A′ ∧ B′ ∧ C′ = 2(B-C) ∧ 1/2(A-C) ∧ 1/2(B-A)$, then I try to manipulate this by expanding and other various ways but can't get it right, is there something obvious that I am missing?

A: Do you really believe the midpoint of $BC$ is $\frac{B-C}{2}$? That would mean the midpoint of $(1,0)$ and $(2,0)$ is $(-0.5, 0)$ and that the midpoint of the points in the other order is $(0.5,0)$.
So the first big problem must be that you need to use the right expression for the midpoint: $\frac{B+C}{2}$. (Notice how the order of the endpoints doesn't matter.)
After that, it's a simple matter to compute that
$$
(B+C)\wedge(C+A)\wedge (A+B)=2(A\wedge B\wedge C)
$$
and then juggling the scalar factors that are missing:
$$
4\left(\frac{B+C}{2}\wedge\frac{C+A}{2}\wedge \frac{A+B}{2}\right)=A\wedge B\wedge C
$$


text: Q: Gulp Local and CLI version mismatch globally and within project folder I am trying to run Gulp 3.9.0 in my project folder and have downgraded my Gulp via npm install gulp@3.9.0. However, it seem like only my local version of gulp is 3.9.0. How do I get my CLI to the same version?


text:
Q: array offset calculations in multi dimensional array (column vs row major) A textbook I recently read discussed row major & column major arrays.  The book primarily focused on 1 and 2 dimensional arrays but didn't really discuss 3 dimensional arrays.  I'm looking for some good examples to help solidify my understanding of addressing an element within a multi-dimensional array using row major & column major arrays.

           +--+--+--+  |
          /  /  /  /|  |
         +--+--+--+ +  |        +---+---+---+---+
        /  /  /  /|/|  |       /   /   /   /   /|
       +--+--+--+ + +  |      +---+---+---+---+ +
      /  /  /  /|/|/|  |     /   /   /   /   /|/|
     +--+--+--+ + + +  |    +---+---+---+---+ + +
    /  /  /  /|/|/|/|  |   /   /   /   /   /|/|/|
   +--+--+--+ + + + +  |  +---+---+---+---+ + + +
  /  /  /  /|/|/|/|/   |  |000|001|002|003|/|/|/|
 +--+--+--+ + + + +    |  +---+---+---+---+ + + +
 |00|01|02|/|/|/|/     |  |004|005|006|007|/|/|/|
 +--+--+--+ + + +      |  +---+---+---+---+ + + +
 |03|04|05|/|/|/       |  |008|009|00A|00B|/|/|/
 +--+--+--+ + +        |  +---+---+---+---+ + +
 |06|07|08|/|/         |  |00C|00D|00E|00F|/|/
 +--+--+--+ +          |  +---+---+---+---+ +
 |09|0A|0B|/           |  |010|011|012|013|/
 +--+--+--+            |  +---+---+---+---+
 arr[5][3][4]          |    arr[3][4][5]

NOTE: Original question incorrectly represented arr[3][4][5].  I have learned that the original subscript represents depth. The data has been corrected to reflect intended array representation.

Example hex data
 +---+---+---+---+  +---+---+---+---+  +---+---+---+---+
 |000|001|002|003|  |100|101|102|103|  |200|201|202|203|
 +---+---+---+---+  +---+---+---+---+  +---+---+---+---+
 |004|005|006|007|  |104|105|106|107|  |204|205|206|207|
 +---+---+---+---+  +---+---+---+---+  +---+---+---+---+
 |008|009|00A|00B|  |108|109|10A|10B|  |208|209|20A|20B|
 +---+---+---+---+  +---+---+---+---+  +---+---+---+---+
 |00C|00D|00E|00F|  |10C|10D|10E|10F|  |20C|20D|20E|20F|
 +---+---+---+---+  +---+---+---+---+  +---+---+---+---+
 |010|011|012|013|  |110|111|112|113|  |210|211|212|213|
 +---+---+---+---+  +---+---+---+---+  +---+---+---+---+
      slice 0            slice 1            slice 2

 short Arr[3][4][5]; // assume array is filled with hex test data

 arr[1][2][3] = 0x10B use slice 1, row 2, col 3
 arr[2][3][4] = 0x210 use slice 2, row 3, col 4
                       resolves to row 4, col 0

row major
 {000,001,002,003,004,005,006,007,008,009,00A,00B,00C,00D,00E,00F,010,011,012,013,
  100,101,102,103,104,105,106,107,108,109,10A,10B,10C,10D,10E,10F,110,111,112,113,
  200,201,202,203,204,205,206,207,208,209,20A,20B,20C,20D,20E,20F,210,211,212,213}
column major
 {000,004,008,00C,010,001,005,009,00D,011,002,006,00A,00E,012,003,007,00B,00F,013,
  100,104,108,10C,110,101,105,109,10D,111,102,106,10A,10E,112,103,107,10B,10F,113,
  200,204,208,20C,210,201,205,209,20D,211,202,206,20A,20E,212,203,207,20B,20F,213}

  Calculation offset for arr[1][2][3] using row major offset?
  Calculation offset for arr[1][2][3] using column major offset?

A: I would see the Row-major order Wikipedia article. There is a section that described dimensions higher than 2. There is also a good article here. That article gives the following formula for a three-dimensional array using a row-major layout:
Address = Base + ((depthindex*col_size+colindex) * row_size + rowindex) * Element_Size

For a 3D array: type A[depth][col][row]. The base is the starting offset of the array. In addition, the size variables are the different sizes of each dimension. The Element_Size variable denotes the size of whatever type the array is composed of.
Suppose you had row-major array a[4][6][5] composed of standard C++ integers. To compute the offset of a[1][3][2], you would plug the following numbers into the formula:
Address = Base + ((1 * 6 + 3) * 5 + 2) * 4

For a 3 dimensional array that has a column-major layout, the equation would rather be this:
Address = Base + ((rowindex*col_size+colindex) * depth_size + depthindex) * Element_Size

The numbers you would plug in for the example above using a column-major layout would now be this:
Address = Base + ((2 * 6 + 3) * 4 + 1) * 4

A: The terms 'row major' and 'column major' don't translate well to a third dimention.  The notion that the next element stored is from the current row or current column break down.  It sounds a little comical but this becomes 'depth major' vs. 'width major' ordering.   Each subsequent element is no longer a single entry but one full two dimentional matrix.

          / X
         /
        +---+---+---+
       /   /   /   /|
      +---+---+---+-+-------
      | 1 | 5 | 9 |/|  Y
      +---+---+---+ +
      | 2 | 6 | A |/|
      +---+---+---+ +
      | 3 | 7 | B |/|
      +---+---+---+ +
      | 4 | 8 | C |/
      +---+---+---+

So the memory would literally have 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13 in memory sequentially.  This is classical column major ordering.  By placing the D entry at the position marked X you have not changed the fact that your matrix has colum major ordering.  If you place the D entry where the Y is you still have not changed the fact that you are using column major ordering.  Where you decide to place the next block will affect if you are using depth major (X) or width major (Y) ordering. As you well know these are equivalents but calling it something may assist you writing equations:
[ 0 Based arrays assumed ]
You access the memory location of a two dimentional colum major element through the equation:
MatrixOffset = base + (sizeof(entry) * ((4 * ( column - 1 ))   +  (row - 1)))

This address would be adjusted using depth or width its all a matter of terminology.
TotalOffset = MatrixOffset + (sizeof(entry) * ((4 * 3) * (depth - 1)))

OR
TotalOffset = MatrixOffset + (sizeof(entry) * ((4 * 3) * (width - 1)))

The constants 4 and 3 would likely be variables COLUMNS and ROWS.
Don't ask me about the 4th dimention!

A: Don't artificially constrain yourself by focusing on 3-dimensional and 2-dimensional. Instead focus on learning the expression for addressing n-dimensional arrays.
Expressing n-dimensional addressing would solidfy your grasp on this subject and will be easier to remember one formula rather than separate formulas for 2d and 3d addressing.

Here's my attempt at n-dimensional addressing:
#define LEN 10

int getValue_nDimensions( int * baseAddress, int * indexes, int nDimensions ) {
    int i;
    int offset = 0;
    for( i = 0; i < nDimensions; i++ ) {
        offset += pow(LEN,i) * indexes[nDimensions - (i + 1)];
    }

    return *(baseAddress + offset);
}

int main() {
    int i;
    int * baseAddress;
    int val1;
    int val2;

    // 1 dimensions
    int array1d[LEN];
    int array1d_indexes[] = {2};
    int array1d_nDimensions = 1;
    baseAddress = &array1d[0];
    for(i = 0; i < LEN; i++) { baseAddress[i] = i; }
    val1 = array1d[2];
    val2 = getValue_nDimensions( // Equivalent to: val1 = array1d[2];
        baseAddress,
        &array1d_indexes[0],
        array1d_nDimensions
    );
    printf("SANITY CHECK: %d %d\n",val1,val2);

    // 3 dimensions
    int array3d[LEN][LEN][LEN];
    int array3d_indexes[] = {2,3,4};
    int array3d_nDimensions = 3;
    baseAddress = &array3d[0][0][0];
    for(i = 0; i < LEN*LEN*LEN; i++) { baseAddress[i] = i; }
    val1 = array3d[2][3][4];
    val2 = getValue_nDimensions( // Equivalent to: val1 = array3d[2][3][4];
        baseAddress,
        &array3d_indexes[0],
        array3d_nDimensions
    );
    printf("SANITY CHECK: %d %d\n",val1,val2);

    // 5 dimensions
    int array5d[LEN][LEN][LEN][LEN][LEN];
    int array5d_indexes[] = {2,3,4,5,6};
    int array5d_nDimensions = 5;
    baseAddress = &array5d[0][0][0][0][0];
    for(i = 0; i < LEN*LEN*LEN*LEN*LEN; i++) { baseAddress[i] = i; }
    val1 = array5d[2][3][4][5][6];
    val2 = getValue_nDimensions( // Equivalent to: val1 = array5d[2][3][4][5][6];
        baseAddress,
        &array5d_indexes[0],
        array5d_nDimensions
    );
    printf("SANITY CHECK: %d %d\n",val1,val2);

    return 0;
}

Output:
SANITY CHECK:     2     2
SANITY CHECK:   234   234
SANITY CHECK: 23456 23456

A: When I asked this question I was hoping to find some good 3 dimensional array examples. Especially code examples.  Since I didn't find anything that was understandable, I decided to create a little C program to help display the concept.  It uses the same test data in a 3x4x5 array.    It also includes test data for a 5x5x5 array.  It creates a column major array from the row major array so the offset calculations can be verified.

The array offset methods are:

*
char *calc_RowMajor(char *Base, int elemSz, int depth_idx, int row_idx, int col_idx)

*char *calc_ColMajor(char *Base, int elemSz, int depth_idx, int col_idx, int row_idx)

I added comments in the code where applicable to help clarify what the code is doing.

//
// Arrays.cpp :
//     Purpose: Display rowMajor & colMajor data and calculations.
//
#include "stdafx.h"

#define _show_Arrays 1  // 1=display rowMajor & colMajor arrays
#define _square_array 0 // 1=use arr[5][5][5], 0=use arr[3][4][5]

#if (_square_array == 1)
    const int depthSz = 5;
    const int rowSz = 5;
    const int colSz = 5;
    /*
    +---+---+---+---+---+
    |x00|x01|x02|x03|x04|
    +---+---+---+---+---+
    |x05|x06|x07|x08|x09|
    +---+---+---+---+---+
    |x0A|x0B|x0C|x0D|x0E|
    +---+---+---+---+---+
    |x0F|x10|x11|x12|x13|
    +---+---+---+---+---+
    |x14|x15|x16|x17|x18|
    +---+---+---+---+---+
          slice x
    */
    short row_arr[depthSz][colSz][rowSz] = {
    { /* slice 0 */
      {0x000,0x001,0x002,0x003,0x004},
      {0x005,0x006,0x007,0x008,0x009},
      {0x00A,0x00B,0x00C,0x00D,0x00E},
      {0x00F,0x010,0x011,0x012,0x013},
      {0x014,0x015,0x016,0x017,0x018}},
    { /* slice 1 */
      {0x100,0x101,0x102,0x103,0x104},
      {0x105,0x106,0x107,0x108,0x109},
      {0x10A,0x10B,0x10C,0x10D,0x10E},
      {0x10F,0x110,0x111,0x112,0x113},
      {0x114,0x115,0x116,0x117,0x118}},
    { /* slice 2 */
      {0x200,0x201,0x202,0x203,0x204},
      {0x205,0x206,0x207,0x208,0x209},
      {0x20A,0x20B,0x20C,0x20D,0x20E},
      {0x20F,0x210,0x211,0x212,0x213},
      {0x214,0x215,0x216,0x217,0x218}},
    { /* slice 3 */
      {0x300,0x301,0x302,0x303,0x304},
      {0x305,0x306,0x307,0x308,0x309},
      {0x30A,0x30B,0x30C,0x30D,0x30E},
      {0x30F,0x310,0x311,0x312,0x313},
      {0x314,0x315,0x316,0x317,0x318}},
    { /* slice 4 */
      {0x400,0x401,0x402,0x403,0x404},
      {0x405,0x406,0x407,0x408,0x409},
      {0x40A,0x40B,0x40C,0x40D,0x40E},
      {0x40F,0x410,0x411,0x412,0x413},
      {0x414,0x415,0x416,0x417,0x418}}
    };

#else
  const int depthSz = 3;
    const int rowSz = 4;
    const int colSz = 5;
    /*
    +---+---+---+---+
    |000|001|002|003|
    +---+---+---+---+
    |004|005|006|007|
    +---+---+---+---+
    |008|009|00A|00B|
    +---+---+---+---+
    |00C|00D|00E|00F|
    +---+---+---+---+
    |010|011|012|013|
    +---+---+---+---+
         slice x
    */
    short row_arr[depthSz][colSz][rowSz] = {
    {  /* slice 0 */
      {0x000,0x001,0x002,0x003},
      {0x004,0x005,0x006,0x007},
      {0x008,0x009,0x00A,0x00B},
      {0x00C,0x00D,0x00E,0x00F},
      {0x010,0x011,0x012,0x013}},
    { /* slice 1 */
      {0x100,0x101,0x102,0x103},
      {0x104,0x105,0x106,0x107},
      {0x108,0x109,0x10A,0x10B},
      {0x10C,0x10D,0x10E,0x10F},
      {0x110,0x111,0x112,0x113}},
    {  /* slice 2 */
      {0x200,0x201,0x202,0x203},
      {0x204,0x205,0x206,0x207},
      {0x208,0x209,0x20A,0x20B},
      {0x20C,0x20D,0x20E,0x20F},
      {0x210,0x211,0x212,0x213}}
    };
#endif
    short col_arr[depthSz*colSz*rowSz]; //

char *calc_RowMajor(char *Base, int elemSz, int depth_idx, int row_idx, int col_idx)
{  // row major slice is navigated by rows
  char *address;
  int   lbound = 0; // lower bound (0 for zero-based arrays)
  address = Base        /* use base passed */
     + ((depth_idx-lbound)*(colSz*rowSz*elemSz))    /* select slice */
     + ((row_idx-lbound)*rowSz*elemSz)      /* select row */
     + ((col_idx-lbound)*elemSz);       /* select col */
    return address;
}
char *calc_ColMajor(char *Base, int elemSz, int depth_idx, int col_idx, int row_idx)
{  // col major slice is navigated by columns
  char *address;
  int   lbound = 0; // lower bound (0 for zero-based arrays)
  int   pageSz = colSz*rowSz*elemSz;
  int   offset;

  offset = (col_idx-lbound)*(colSz*elemSz)  /* select column */
         + (row_idx-lbound)*(elemSz);   /* select row */
    if (offset >= pageSz)
    {   // page overflow, rollover
        offset -= (pageSz-elemSz);                          /* ajdust offset back onto page */
    }
    address = Base            /* use base passed */
            + ((depth_idx-lbound)*pageSz)  /* select slice */
            + offset;
    return address;
}

void disp_slice(char *pStr, short *pArr,int slice,int cols, int rows)
{
  printf("== %s slice %d == %p\r\n",pStr, slice,pArr+(slice*rows*cols));
  for(int x=0;x<rows;x++)
  {
    for(int y=0;y<cols;y++)
      printf("%03X ",*(pArr+(slice*rows*cols)+(x*cols)+y));
      printf("\r\n");
  }
}

int _tmain(int argc, _TCHAR* argv[])
{
  // initialize col based array using row based array data
  { // convert row_arr into col_arr
    short *pSrc = &row_arr[0][0][0];
    short *pDst = &col_arr[0];
    for(int d=0;d<depthSz;d++)
      for(int r=0;r<rowSz;r++)
        for(int c=0;c<colSz;c++)
        {
    *pDst++ = *(pSrc+((d*rowSz*colSz)+(c*rowSz)+r));
        }
  }

  printf("Using Array[%d][%d][%d]\r\n",depthSz,rowSz,colSz);

#if (_show_Arrays == 1)
  { for(int x=0;x<depthSz;x++) {disp_slice("rowMajor",&row_arr[0][0][0],x,rowSz,colSz);}}
  { for(int x=0;x<depthSz;x++) {disp_slice("colMajor",&col_arr[0],x,rowSz,colSz);}}
#endif

  int d = 2;    // depth
  int r = 3;    // row
  int c = 4;    // column

  for(d=0;d<depthSz;d++)
  {
    c = r = d;  // simple access test pattern arr[0][0][0],arr[1][1][1],arr[2][2][2],...
    { // retrieve Array element
      printf("    row_arr[%d][%d][%d] = %x\t",d,r,c,row_arr[d][r][c]);
      printf("&row_arr[%d][%d][%d] = %p\r\n",d,r,c,&row_arr[d][r][c]);
    }
    { // retrieve RowMajor element
      short *pRowMajor = (short*)calc_RowMajor((char*)&row_arr[0][0][0],sizeof(short),d,r,c);
      printf("calc_RowMajor(%d,%d,%d) = %x\t\t",d,r,c,*pRowMajor);
      printf("pRowMajor = %p\r\n",pRowMajor);
    }
    {   // retrieve ColMajor element
      short *pColMajor = (short*)calc_ColMajor((char*)&col_arr[0],sizeof(short),d,c,r);
      printf("calc_ColMajor(%d,%d,%d) = %x\t\t",d,r,c,*pColMajor);
      printf("pColMajor = %p\r\n",pColMajor);
    }
 } // for

 getchar(); // just to hold the console while looking at the information
  return 0;
}

A: Basically in a 3D arrray with row major E.g Arr[3][4][5]
when u want Arr[0],it looks for the front slice of the image like above
Arr[1] second slice and so on.
so Arr[0] means 2D array of size [4][5] ,so every Arr[x] corresponds to x*(4*5)
Now about Arr[x][y] can be thought of a 1D array of size [5] whose position is [x][y] from top view in the image above
so when when we want Arr[x][y] = x*(4*5)+y*(5)
now Arr[x][y][z] is the specific element of Arr[x][y] at depth z
Arr[x][y][z]=x*(4*5)+y*5+z
now on the basis of size of the data type u want to store in the array,the offset can be multiplied to the size get the address with respect to start

A: The formula for k-dimensional arrays is
    k-1       n
i  + ∑  i  *  ∏  c
 0  n=1  n   m=0  m

where i subscript n is the index of dimension n for n = { 0, 1, 2, ... k-1 }
and c subscript m is the cardinality of dimension m for m = { 0, 1, 2, ... k-2 }.
A nicer rendering of the formula in PNG format can be found here:
http://modula-2.info/m2r10/pmwiki.php/Spec/LanguageReport#MultiDimensionalArrays


text:
Q: Whether to incorporate zero inflation into model of binary variable on count variable? I have a dataset comprising two groups with 1 continuous covariate (ratio scale). The dependent variable is a count variable. The distribution of the dependent variable looks like this:

I was wondering what the right model to analyze this dataset would be. I tried poisson, binomial, and negative binomial. For negative binomial, the Log Likelihood was closest to zero (or largest if you will). Therefore, I assume the negative binomial model is the best for my data (please correct me if I my reasoning is wrong).
Should I try a model that incorporates zero inflation?

A: Zero-inflation (or any similar arbitrary additional degree of freedom) will probably increase the likelihood.  That's why if you're going to compare models, you should be using cross-validation to check how the validation error changes rather than just maximizing the likelihood on all of your data.
I once read that it's more convincing to reason about why a model theoretically fits data rather than just looking for low validation error.  It is easy to fool yourself into thinking that you have a good model.


text:
Q: SELECT FOUND_ROWS() not working with PDO PHP? I changed my code to finally using PDO instead of mysql_..
I changed the code of one of my query which is like
SELECT SQL_CALC_FOUND_ROWS * ....etc

but now my code
SELECT FOUND_ROWS()

and the array
echo $array[0]['FOUND_ROWS()']

return value = 0;
there is anything I should know about PDO and this type of queries?


text:
Q: What is the maximum possible IPC can be achieved by Intel Nehalem Microarchitecture? Is there an estimation for the maximum Instructions Per Cycle achievable by the Intel Nehalem Architecture? Also, what is the bottleneck that effects the maximum Instructions Per Cycle?

A: TL:DR:
Intel Core, Nehalem, and Sandybridge / IvyBridge: a maximum of 5 IPC, including 1 macro-fused cmp+branch to get 5 instructions into 4 fused-domain uops, and the rest being single-uop instruction.  (up to 2 of these can be micro-fused store or load+ALU.)
Haswell up to 9th Gens: a maximum of 6 instructions per cycle can be achieved using two pairs of macro-fusable ALU+branch instructions and two instructions that are decoded into two potentially micro-fused uops.  The max unfused-domain uop throughput is 7 uops per clock, according to my testing on Skylake..
Early P6-family: Pentium Pro/PII/PIII, and Pentium M.  Also Pentium 4: a maximum of 3 instructions per cycle can be achieved using 3 instructions that are decoded into 3 uops. (No macro-fusion, and 3-wide decode and issue).
The max IPC on Sunny Cove may be 7, thanks to increased front-end bandwidth of 5 uops per clock.

Source: Agner Fog's microarch pdf and instruction tables.  Also see the x86 tag wiki.
The out-of-order pipeline in Intel Core2 and later can issue/rename 4 fused-domain uops per clock.  This is the bottleneck.  Macro-fusion will combine a cmp / jcc into a single uop, but this can only happen once per decode block.  (Until Haswell).
Also decode is another important bottleneck before the uop-cache in SnB-family. (Up to 4 instructions into up-to-7 uops with a 4-1-1-1 pattern in Core2 and Nehalem; SnB-family is up-to 4 total, or up to 5 in Skylake, e.g. a 2-1-1-1 pattern from still only 4 decoders, not 5 as some sources incorrectly report).  Multi-uop instructions have to decode in the first "slot".  See Agner Fog's microarch guide for much more about the potential bottlenecks in Nehalem.
Nehalem InstLatx64 shows that nop surprisingly only has 0.33c throughput, not 0.25, but it turns out according to https://www.uops.info/table.html that's because nop needs an ALU execution unit in CPUs before Sandybridge.  Agner Fog says he didn't detect a retirement bottleneck on Nehalem.
Even if you could arrange things so more than one macro-fused pair per 4 uops was in a loop, Nehalem has a throughput of only one fused test-and-branch uop per clock (port 5).  So it couldn't sustain more than one macro-fused compare-and-branch per clock even if some of them are not-taken.  (Haswell can run not-taken branches on port 0 or port 6, so 6 IPC throughput can be sustained as long as at least one of the macro-fused branches is not-taken.)
;; Should run at one iteration per clock
.l:
    mov   edx, [rsi]    ; doesn't need an ALU uop.  A store would work here, too, but a NOP need an ALU port on Nehalem.
    add   eax, edx
    inc   rsi
    cmp   rsi, rdi          ; macro-fuses
    jb   .l                 ; with this, into 1 cmp+branch uop

For ease of testing, and remove cache/memory bottlenecks, you could change it to load from the same location every time, instead of using the loop counter in the addressing mode.  (As long as you avoid register-read stalls from too many cold registers.)
Note that pre-Haswell uarches only have three ALU ports.  But mov loads or stores take pipeline bandwidth so there's a benefit to having 4-wide issue/rename.  It's also useful for the front-end to be able to issue faster than the out-of-order core can execute, so there is always a buffer of work to do queued up in the scheduler, so it can find the instruction-level parallelism and get started on future loads early, and stuff like that.
I think other than load/store (including push/pop thanks to the stack engine), fxchg might be the only fused-domain uop that doesn't need an ALU port in Nehalem.  Or maybe it actually does, like nop.  On SnB-family uarches, xor same,same is handled in the rename/issue stage, and sometimes also reg-reg movs (IvB and later).  nop is also never executed, unlike on Nehalem, so SnB/IvB have 0.25c throughput for nop even though they only have 3 ALU ports.
An eliminated mov reg,reg on Ivy Bridge can also be part of a loop that runs 4 front-end uops per clock with only 3 back-end ALU port.
For maxing out back-end uop throughput, you need micro-fusion to get 2 back-end uops (load + ALU) through the front-end as a single fused-domain uop in decode, issue/rename, and in the ROB.  https://www.agner.org/optimize/blog/read.php?i=415#852


text:
Q: Update of table1 with table2 values using SQL Server I want to update table1 with table2 mobile number, the common column in table1 and table2 is name, but table1 name is mixed with initial, table2 only has the name.
Can anyone tell how to update table1?
I've tried this:
update table1
set table1.mobile = table2.mobile
from table1
join table2 on table1.name = table2.name

Table1
Name    Mobile
abc 123
def 456

Table2
Name    Mobile
abc  x  null
def  Y  Null

I want to update table1 mobile in table2  mobile
I tried
update table1 set table1.mobile=table2.mobile from table1
       join table2 on table1.name=table2.name

A: You can do this using sub-query.
update table1 set table1.mobile = (select TOP 1 table2.mobile from table2 where table2.name = substring(table1.name, 0, charindex(' ', table1.name)))

Edit:
I did a substring on the first word of the column value. The "anil y" will now be "anil".

A: You can try something like below:
Create table #table1
(
name varchar(10),
mobile int
)
insert into #table1 values ('Anil', 123)
insert into #table1 values ('abc', 888)
insert into #table1 values (NULL, 321)

Create table #table2
(
name varchar(10),
mobile int
)
insert into #table2 values ('Anil y', NULL)
insert into #table2 values ('z abc', NULL)
insert into #table2 values (NULL, NULL)

Update #table2
Set #table2.mobile = #table1.mobile
from #table2, #table1
Where charindex(#table1.name, #table2.name) > 0

Select * from #table2

Output:
Anil y  123
z abc   888
NULL    NULL


text:
Q: Latency occuring between typing the character and printing on screen on a Dell Inspiron m101z? i am facing a bit problem with my laptop dell inspiron m101z and the problem is there is slight latency occurring in typing the text on keyboard and getting up same on the screen.
also sometimes i feel that my system is performing slow.
my configuration is :-

*

*4gb RAM ddr3

*320 hardisk

*amd athlon II k125

A: Take a look at top, lsof, other performance tools to see what's running. It could be that your resources are just maxed out. It could also be an issue with your desktop manager of choice. More information will be needed before this can be definitively answered.


text:
Q: How can I get src of video from HTML on example.com is <video> like:
<video controls="" preload="false" src="http://example.com/video.mp4"></video>

and I would like to get content of src="" which is inside of that <video> tag
(example.com is not my website, I need to use PHP to get to the HTML code and get the src from the video tag)
thank you!

A: If you want to get any value in php you have to do an Ajax call and send the data:
   $('#element').click(function({
             var src = $(this).attr('src');
             $.ajax({
                url:'/someFile.php/ajax/',
                type:'post',
                dataType:'json',
                data:{
                    src:src;
                },
                success:function(data){
                   console.log('src sended');
                }
             });
         });

You can also do it entirely in PHP with https://simplehtmldom.sourceforge.io/

A: Quick and dirty way
<?php
preg_match_all('#<video .*?src="(.*?)"#', file_get_contents('https://example.com'), $results);

print_r($results[1]);

A better way is to use web scraping/crawling tools like FriendsOfPHP/Goutte


text:
Q: Create pgp file with gpg from command line I want to encrypt an xml file and I am using gpg4win (kleopatra).
Using the kleopatra interface I set an option to produce files with extension pgp instead of gpg which is the default extension.
I am trying to create a pgp file from command line using the command
gpg -r test@test.gr -se C:\temp\myfile.xml

because I need to submit it in a web app that accepts pgp only.
I have tried to put some other options in the command but I always get a gpg file. How can I produce a pgp file from command line?

A: This may not be the same process as others, but this worked for me:
gpg --batch --yes --recipient "user" --output "fulldirectory\filename.txt.pgp" --encrypt "fulldirectory\filename.txt"

A: GnuPG syntax for encryption is stated here. You can simply use the --output [filename].[suffix] parameter.
So go with gpg --encrypt C:\temp\myfile.xml --recipient test@test.gr --output C:\temp\myfile.pgp.
Please note that .pgp is actually the suffix for a key not an encrypted file. See here.


text:
Q: How do I make an Excel VBA macro to delete columns with many different strings as headers? So I'm importing a large spreadsheet with anywhere from 20 to 40 headers at the top and I'd like to automatically (and quickly) delete all the columns with specific headers.  I have a current code that works, but it loops through all the columns multiple times, each time looking for a different string.  I would like it to loop through once and delete any column that has any of the strings to delete.
Here's a fraction of my code to explain a little better:
Sub SetUpICTRP()

'MsgBox "Excel will refresh when macro is complete"
Application.ScreenUpdating = False

Dim c As Range
Dim SrchRng As Range
Dim lastColumn As Long

lastColumn = ActiveSheet.Cells(1, Columns.Count).End(xlToLeft).Column
Set SrchRng = ActiveSheet.Range("A1", Cells(1, lastColumn))

Do
    Set c = SrchRng.Find("column", LookIn:=xlValues)
    If Not c Is Nothing Then c.EntireColumn.Delete
Loop While Not c Is Nothing
Do
    Set c = SrchRng.Find("Erroneous", LookIn:=xlValues)
    If Not c Is Nothing Then c.EntireColumn.Delete
Loop While Not c Is Nothing
Do
    Set c = SrchRng.Find("Unnecessary", LookIn:=xlValues)
    If Not c Is Nothing Then c.EntireColumn.Delete
Loop While Not c Is Nothing
Do
    Set c = SrchRng.Find("Not_", LookIn:=xlValues)
    If Not c Is Nothing Then c.EntireColumn.Delete
Loop While Not c Is Nothing
Application.ScreenUpdating = True
End Sub

So currently it will delete all the columns with headers that contain the phrase "column," "Erroneous," "Unnecessary", and "Not_". What I really need is for it to be able to find and delete columns like "column218", "columnadfe", "column099", "Not_needed", without running through a separate loop multiple times.  I think the solution lies somehow in creating an array of strings and then looping through each string for each column, but I'm rather new to VBA and can't seem to make that work. Any help would be great!

A: You could loop through and find the words and use the Union() method to collate your headers into a single Range object, then use the .EntireColumn method to delete columns related to the non-contiguous cells.

Sub SO()

Dim findValue As Variant, findRange As Excel.Range, deleteRange As Excel.Range
Dim findAddress As String

For Each findValue In Array("column", "Erroneous", "Unnecessary", "Not_", _
    "Other1", "Other2", "Other3", "etc...")

    Set findRange = Rows(1).EntireRow.Find(what:=findValue, LookIn:=xlValues, lookat:=xlPart)

    If Not findRange Is Nothing Then
        findAddress = findRange.Address
        Do
            If Not deleteRange Is Nothing Then
                Set deleteRange = Union(deleteRange, findRange)
            Else
                Set deleteRange = findRange
            End If

            Set findRange = Rows(1).EntireRow.FindNext(findRange)
        Loop Until findRange Is Nothing Or findRange.Address = findAddress

    Set findRange = Nothing
    End If

Next findValue

If deleteRange Is Nothing Then
    MsgBox "No columns were found for deletion!"
Else
    deleteRange.EntireColumn.Delete
End If

End Sub

or following your original setup you could use something like:
Sub SO()

Dim c As Range, findValue As Variant

For Each findValue In Array("column", "Erroneous", "Unnecessary", "Not_", _
    "Other1", "Other2", "Other3", "etc...")
    Do
        Set c = Rows(1).EntireRow.Find(findValue, LookIn:=xlValues)
        If Not c Is Nothing Then c.EntireColumn.Delete
    Loop While Not c Is Nothing

Next findValue

End Sub


text:
Q: Deleting drop down boxes from an Excel file using Interop.Excel I need to delete a drop down box from an excel sheet. I've tried searching for the formula value, deleting the cell value, deleting it from the macro and nothing works. Any suggestions would be appreciated. The client would like this update today. Thanks!

A: I tried this one. It works for me.
   var cell = (Microsoft.Office.Interop.Excel.Range)oSheet.Cells[row, column];
   cell.Validation.Delete();
   cell.Validation.Add(
      XlDVType.xlValidateInputOnly,
      Type.Missing,
      Type.Missing,
      Type.Missing,
      Type.Missing);
   cell.Value = "";
   cell.Validation.IgnoreBlank = false;
   cell.Validation.InCellDropdown = false;

A: You might take a look at the Delete method of the Validation object -- e.g.,
        Excel.Range range = wksht.get_Range("A1", "A1");
        range.Validation.Delete();


text:
Q: Integer overflow issues vector<int> getRow(int rowIndex) {
vector<int> result;
if(rowIndex < 0)   return result;
if(rowIndex == 0){
    result.push_back(1);
    return result;
}
for(int i = 0; i < rowIndex+1; i++){
    if(i == 0)  result.push_back(1);
    else{
        result.push_back(result[i-1] * (rowIndex+1-i)/i);
    }
}
return result;
}
int main()
{
    vector<int> tmp = getRow(30);
    for(int i = 0; i < tmp.size(); i++){
        cout << tmp[i] << " ";
    }
    cout << endl;
    return 0;
}

This is the Pascal's triangle - coding problem from LeetCode, which asks to output the nth row of the Pascal triangle. With rowIndex=30, the output looks like:
1 30 435 4060 27405 142506 593775 2035800 5852925 14307150 30045015 54627300 86493225 119759850 145422675 -131213633 -123012780 -101304642 -73164463 -46209134 -25415023 -12102391 -4950978 -1722079 -502273 -120545 -23181 -3434 -367 -25 0

Obviously, there is an overflow problem. Now to fix this, I modified the line result.push_back(result[i-1] * (rowIndex+1-i)/i); to result.push_back((double)result[i-1] * (double)(rowIndex+1-i)/i);. And it produces the correct output:
1 30 435 4060 27405 142506 593775 2035800 5852925 14307150 30045015 54627300 86493225 119759850 145422675 155117520 145422675 119759850 86493225 54627300 30045015 14307150 5852925 2035800 593775 142506 27405 4060 435 30 1

Can someone explain what exactly is the problem here?
We know that the range of signed integer value is -2147483648 to 2147483647. Without casting, why at value 155117520 is printed as overflow -131213633?

A: I the expression
result[i-1] * (rowIndex+1-i)/i

multiplication takes place first, and results in overflow:
result[i-1] * (rowIndex + 1-i)

and then the result gets divided by i, producing the negative output.

BTW, if you decide to cast, avoid casting to double due to possible rounding issues. You could try long instead, but it is perhaps better to use at the first place
vector<long>

or even
vector<unsigned long>

or, thanks to @WorldSEnder,
vector<unsigned long long>

Still, be aware that the standard does not guarantee that long or long long is longer than int. Neither it guarantees that int is in the range [-2147483648, 2147483647].


text:
Q: Get entry point script file location in setuputils package? So I have an entry point defined in my setup.py [console_scripts] section. The command is properly installed and works fine, but I need a way to programatically find out the path to the script (e.g. on windows it'll be something like C:/my/virtual/env/scripts/my_console_script.exe). I need this so I can pass that script path as an argument to other commands, regardless of where the package is installed. Setuputils provides the pkg_resources, but that doesn't seem to expose any way of actually getting at the raw installed paths, only loadable objects.
Edit: To make the use case plain here's the setup.
I have a plugin-driven application that communicates with various local services. One of these plug-ins ties into the alerting interface of an NMS package. The only way this alerting package can get alerts out to an arbitrary handler is to call a script - the path to execute (the console_scripts entry point in this case) is register as a complete path - that's the path I need to get.

A: Have you tried `os.path.abspath(__file__)' in your entry point script? It'll return yours entry point absolute path.
Or call find_executable from distutils.spawn:

import distutils.spawn
distutils.spawn.find_executable('executable')

A: You could get the path for site_packages directory as follows:
from distutils.sysconfig import get_python_lib
get_python_lib()

If your script is somewhere relative to that path, either in site-packages or up a directory you could then join the relative path with the site-packages path as follows:
import os
scriptPath = os.path.realpath(os.path.join(get_python_lib(), '../my/relative/path/script.exe'))

Another trick you could try is to import the associated module and then look at its file parameter. You could then look for your script the same way as the example above if you know what the relative path is to that file. Try it on the command line interface..
import django
django.__file__

/usr/lib/python2.6/site-packages/django/init.pyc
modulePath = os.path.split(django.__file__)[0]
scriptPath = os.path.realpath(os.path.join(modulePath, '../my/relative/path/script.exe'))

Is the above advice on the right track?

A: Well, you could pass an option of the form --install-option="--install-scripts=/usr/local/bin" to pip and just set the path yourself. But I understand why you might not want to hardcode that in a cross-platform project.
So, we just need to find out what directory setuptools is actually using. Unfortunately, the path is determined in the middle of a whole bunch of actual setup code, rather than in a separate function we can just call.
So the next step is to write a custom install command that observes and saves the path. (For that matter, you could also set self.install_scripts to a directory of your choice in this custom installer class, thereby keeping that piece of config in one place (the package) rather than in the package and in a command line arg to setup...)
Example:
from setuptools import setup
from setuptools.command.install import install
from distutils.command.build_py import build_py
import os

class InstallReadsScriptDir(install):
    def run(self):
        self.distribution._x_script_dir = self.install_scripts
        install.run(self)

class BuildConfiguresScriptDir(build_py):
    def run(self):
        build_py.run(self)
        if self.dry_run:
            return
        script_dir = self.distribution._x_script_dir  # todo: check exists
        target = os.path.join(self.build_lib, 'mypackage', 'scriptdir.py')
        with open(target, 'w') as outfile:
            outfile.write('path = """{}"""'.format(script_dir))

setup(
    name="MyPackage",
    version='0.0.1',
    packages = ['mypackage'],
    entry_points = {
        'console_scripts': [
            'footest = mypackage:main',
        ],
    },
    cmdclass= {
        'install': InstallReadsScriptDir,
        'build_py': BuildConfiguresScriptDir,
    },
)

Possible objections:

*

*Some people don't like any form of code generation. In this case it's more like configuration, though putting it in a .py in the package makes it easy to get at from Python code anywhere.

*On the surface it looks like a bit of a hack. However, setuptools is specifically designed to allow custom command classes. Nothing here is really accessing anything private, except maybe the value passing using the distribution object which is just to avoid a global.

*Only gets the directory, not the executable names. You should know the names though, based on your entry point configuration. Getting the names would require calling the parsing methods for your entry point spec and generating more code.

*It's going to need some bugfixing if you e.g. build without installing. sdist is safe though.

*develop is possible but needs another command class. install isn't called and build_py is only called if you set use_2to3. A custom develop command can get the path as in the install example, but as self.script_dir. From there you have to decide if you're comfortable writing a file to your source directory, which is in self.egg_path -- as it will get picked up by install later, though it should be the same file (and the build command will overwrite the file anyway)
Addendum
This little flash of insight may be more elegant as it does not require saving the path anywhere, but still gets the actual path setuptools uses, though of it assumes no configuration has changed since the install.
from setuptools import Distribution
from setuptools.command.install import install

class OnlyGetScriptPath(install):
    def run(self):
        # does not call install.run() by design
        self.distribution.install_scripts = self.install_scripts

def get_setuptools_script_dir():
    dist = Distribution({'cmdclass': {'install': OnlyGetScriptPath}})
    dist.dry_run = True  # not sure if necessary, but to be safe
    dist.parse_config_files()
    command = dist.get_command_obj('install')
    command.ensure_finalized()
    command.run()
    return dist.install_scripts

Addendum 2
Just realized/remembered that pip creates an installed-files.txt in the egg-info, which is a list of paths relative to the package root of all the files including the scripts. pkg_resources.get_distribution('mypackage').get_metadata('installed-files.txt') will get this. It's only a pip thing though, not created by setup.py install. You'd need to go through the lines looking for your script name and then get the absolute path based on your package's directory.


text:
Q: Extending threading.Timer for returning value from function gives TypeError I tried to extend threading.Timer so I can get return values from the function. I used the solution from this thread and applied the modifications (as Timer() already takes *args and **kwargs I don't think I need to pass it through __init__ again). Code goes exactly like this:
from threading import Timer

class CustomTimer(Timer):
    def __init__(self):
        super(CustomTimer, self).__init__()
        self._return = None

    def run(self):
        super(CustomTimer, self).run()
        self._return = self._Thread__target(*self._Thread__args, **self._Thread__kwargs)

    def join(self):
        super(CustomTimer, self).join()
        return self._return

Then I get the following error running the main module:
Traceback (most recent call last):
  File "main.py", line 43, in <module>
    from storage import *
  File "/home/mei/tmwAthena/manamarket/storage.py", line 13, in <module>
    from utils import ItemDB
  File "/home/mei/tmwAthena/manamarket/utils.py", line 142, in <module>
    class CustomTimer(Timer):
TypeError: Error when calling the metaclass bases
    function() argument 1 must be code, not str

I don't understand this error since function() is quite simple, it receives *self.args and **self.kwargs and I can't see where it could be looking for a string since the initializator is pretty much the same from superclass. Note that this is occurring while importing the class, it's not even getting to be used by the code.

A: The error you're getting is because Timer is not a class, it is a function/method in Python 2 threading.py:
>>> from threading import Timer
>>> type(Timer)
<type 'function'>

The concrete class is _Timer. Furthermore your code does have some problems; your init is missing arguments and the target , args, kwargs and interval are not set.
You might have luck with this CustomTimer:
from threading import _Timer

class CustomTimer(_Timer):
    def __init__(self, interval, function, args=[], kwargs={}):
        self._original_function = function
        super(CustomTimer, self).__init__(
            interval, self._do_execute, args, kwargs)

    def _do_execute(self, *a, **kw):
        self.result = self._original_function(*a, **kw)

    def join(self):
        super(CustomTimer, self).join()
        return self.result

Demo:
def add_together(a, b):
    return a + b

c = CustomTimer(1, add_together, (2, 4))
c.start()
print c.join()

prints 6 after 1 second.


text:
Q: dhclient - Applying configuration changes with no reboot After editing some configurations on the dhclient configuration file (/etc/dhcp/dhclient.conf) the changes doesn't seem to have any effect until I reboot the machine. Since dhclient is running on the background, I believe the process needs to restart to actually read the configuration file again and apply said changes.
What would be the best way to accomplish it?
On the dhclient man page I found the following option:
-r            Release the current lease and stop the running  DHCP  client  as
              previously  recorded  in  the  PID file.  When shutdown via this
              method dhclient-script will be executed with the specific reason
              for calling the script set.  The client normally doesn't release
              the current lease as this is not required by the  DHCP  protocol
              but  some  cable ISPs require their clients to notify the server
              if they wish to release an assigned IP address.

If I understood it right, this option would kill the dhclient and thus make it release the lease and read the configuration file again when it started (which I'm not sure if would be as simply as calling dhclient &).
Checking the processes tree, I also noticed dhclient is a child process of network-manager. Would run sudo service network-manager restart be a cleaner way to make dhclient start again with the new configurations?

A: Re-activate the connection.
For example via nmcli connection up $NAME or any other client of NetworkManager.
You usually wouldn't restart NetworkManager.


text:
Q: How to include a html file which contains mathjax equation in AngularJs? <!DOCTYPE html>

<title>MathJax POC</title>

But When i run this, got an error i.e
Error: [$parse:lexerr] : http://errors.angularjs.org/1.5.6/$parse/lexerr?p0=Unexpected%20next%20character%20&p1=s%202-2%20%5B%5E%5D&p2=m%7D%5E%7B2
I think it is happening because Notes.html file contains MathJax equation. Following are the equation :
[{{m}^{2}}]
Also searched a solution for that but i didn't get any solution, so please someone help me out.
-----Notes.html-----

        The floor of a building consists of 3000 tiles which are rhombus shaped and each of its diagonals are 45 cm and 30 cm in length. Find the total cost of polishing the floor, if the cost per \[{{m}^{2}}\] is Rs 4.

A: Try to put your math equation in controller.

Notes.html
The floor of a building consists of 3000 tiles which are rhombus shaped and each of its diagonals are 45 cm and 30 cm in length. Find the total cost of polishing the floor, if the cost per {{mathEq}} is Rs 4.
If Notes.html is from remote server, you can escape the characters itself. Refer http://www.theukwebdesigncompany.com/articles/entity-escape-characters.php


text:
Q: Show that $(L^\infty,\|\cdot\|_\infty)$ is a normed vector space. I want to show that $(L^\infty,\|\cdot\|_\infty)$ is a normed vector space. I understand that there are two things to show; firstly, that $L^\infty(X,\mu)$ is a linear space and secondly that $\|\cdot\|_\infty$ defines a norm on this space.
I don't have solutions to check whether what I have done here is correct or not - could somebody verify for me and point out anything I have done wrong, or that could be done better? In particular:

*

*In part (iii) of (b), how is it that taking out the factor of $|c|$ out of the $\inf$ doesn't affect the value of $M\in\mathbb R^+$ which bounds $|cf(x)|$?

*Similarly, in part (iv) of (b), should there be a $\le$" sign on the jump from line two to three when taking the $\inf$ of the sum?
(a) $L^\infty(X,\mu)$ is a linear space:
Take $f+g\in L^\infty(X,\mu)$ then $\exists\,M,N\ge 0:|f(x)|\le M\,,\forall x\in X\setminus A$ and $|g(x)|\le N\,,\forall x\in X\setminus B$, where $A,B$ are measurable sets of measure zero.
Consider then $|(f+g)(x)|\le|f(x)|+|g(x)|\le M+N,\,\forall x\in X\setminus(A\cup B)$. So, defining $P:=M+N\ge0$ we have shown that $|(f+g)(x)|\le P$. Thus, $f+g\in L^\infty(X,\mu)$.
Take then $f\in L^\infty(X,\mu)$ and some $c\in\mathbb R$. Then consider $|cf(x)|=|c||f(x)|\le|c|M=:Q$ where, clearly, $Q\ge0$. And so, it follows that $cf\in L^\infty(X,\mu)$.
Hence, $L^\infty(X,\mu)$ is closed under the addition and scalar multiplication of it's elements, and so is a linear space.
(b) $(L^\infty,\|\cdot\|_\infty)$ is a normed vector space:
We recall that $\|f\|_\infty=\inf\{M:|f(x)|\le M,\,\forall x\in X\setminus A\}$, where $f\in L^\infty(X,\mu)$.
(i) Suppose $f\in L^\infty(X,\mu)$ and consider $\|f\|_\infty=\inf\{M:|f(x)|\le M,\,\forall x\in X\setminus A\}$. By definition, such an $M$ is greater than or equal to zero, hence $\|f\|_\infty\ge0$, showing that our norm is nonnegative.
(ii) Consider: $\|f\|_\infty=0\iff\inf\{M:|f(x)|\le M,\,\forall x\in X\setminus A\}=0$
$\iff\forall x\in X\setminus A,\,|f(x)|\le0\iff\forall x\in X\setminus A,\,0\le f(x)\le0$ which means that $f\equiv0$ on $X\setminus A$. This establishes nondegeneracy of the norm.
(iii) For $c\in\mathbb R$ consider $\|cf\|_\infty=\inf\{M:|cf(x)|\le M,\,\forall x\in X\setminus A\}=\inf\{M:|c||f(x)|\le M,\,\forall x\in X\setminus A\}$
$=|c|\inf\{M:|f(x)|\le M,\,\forall x\in X\setminus A\}=|c|\|f\|_\infty$, showing multiplicativity of our norm.
(iv)Lastly, for $f,g\in L^\infty(X,\mu)$ consider,
$$\|f+g\|_\infty=\inf\{P:|f(x)+g(x)|\le P,\,\forall x\in X\setminus (A\cup B)\}$$
$$\le\inf\{M+N:|f(x)|+|g(x)|\le M+N,\,\forall x\in X\setminus (A\cup B)\}$$
$$=\inf\{M:|f(x)|\le M,\,\forall x\in X\setminus A\}+\inf\{N:|g(x)|\le N,\,\forall x\in X\setminus B\}$$
$$=\|f\|_\infty +\|g\|_\infty$$
So showing the triangle inequality.

A: I think you could be more careful with how you are treating the statements involving things that only hold on the complement of a measurable set.
E.g. I'd like better:
$\|f\|_\infty=\inf\{M:\exists A, \mu(A)=0 \colon \forall x\in X\setminus A\ |f(x)|\le M,\}$
Otherwise I might ask myself what the set $A$ is supposed to be.
But this is just notation...
To (b) iii:
$\inf\{M\colon |c||f(x)|\leq M, ... \}=\inf\{M\colon |f(x)|\leq \frac{M}{|c|}, ... \}=\inf\{|c|\tilde{M}\colon |f(x)|\leq \tilde{M}, ... \}=|c|\cdot\inf\{\tilde{M}\colon |f(x)|\leq \tilde{M}, ... \}=\|f\|_\infty$
(at least for $c\neq 0$)
To (b) iv: yes I think you should use an $\leq$ sign
Otherwise I don't have concerns about your solutions, seems okay to me.


text:
Q: WxPython wxMenu InsertRadioItem issue wxMenuItem = wxMenuSource.InsertRadioItem(order, wx.ID_ANY, test, "")

App.Bind(wx.EVT_MENU, OnPerspective_Click, wxMenuItem)

order += 1

I insert radio items procedurally and when I click menu item my program crashs, I don't know what is happening...

A: I have encountered this, and there's not really a great "fix".  The problem is that the radio buttons don't get grouped properly when you attempt to add or insert them dynamically.  The best work around I could come up with as this method that I added to my MenuBar class to recreate a Servers menu for me.
def setServers(self):
  menu = Menus['Servers']
  while menu.GetMenuItemCount() > 2:
    menu.RemoveItem(menu.FindItemByPosition(2))
  menu.AppendSeparator()
  servers = Config.getValueList('rpcservers', ['hostname', 'port', 'state'])
  for s in servers:
    id = wx.NewId() #@ReservedAssignment
    evtname = 'S%s:%s' % (s['hostname'], s['port'])
    connection = '%s:%s' % (s['hostname'], s['port'])
    menu.Append(id, connection, s['description'], kind = wx.ITEM_RADIO)
    if s['state'] == 'inuse':
      menu.Check(id, True)

Some of the code there isn't directly relevant (sorry, quick copy and paste) but the idea here is that the elements that are radio buttons are all at the bottom of this menu.  I remove all of the elements, and a separator, before adding a separator and all of the new radio buttons.  By recreating them in this way I am able to circumvent the bug I was encountering where a newly added radio button wasn't related to its siblings.  Hopefully that helps.  Let me know if you need clarification.


text:
Q: Split char* to char * Array I'm trying to split a char* to an array of char* in C.
I'm used to program in Java / PHP OO. I know several easy way to do that in these languages but in C... I'm totally lost. I often have segfault for hours x)
I'm using TinyXML and getting info from XML File.
Here's the struct where we find the array.
const int MAX_GATES = 64;

typedef struct {
    char *name;
    char *firstname;
    char *date;
    char *id;
    char *gates[MAX_GATES];
} UserInfos;

And here's where I fill this struct :
    UserInfos * infos = (UserInfos*)malloc(1024);

    infos->firstname = (char*)malloc(256);
    infos->name = (char*)malloc(128);
    infos->id = (char*)malloc(128);
    infos->date = (char*)malloc(128);

    sprintf(infos->firstname, "%s", card->FirstChild("firstname")->FirstChild()->Value());
    sprintf(infos->name, "%s", card->FirstChild("name")->FirstChild()->Value());
    sprintf(infos->date, "%s", card->FirstChild("date")->FirstChild()->Value());
    sprintf(infos->id, "%s", card->FirstChild("filename")->FirstChild()->Value());

    ////////////////////////
    // Gates
    char * gates = (char*) card->FirstChild("gates")->FirstChild()->Value();

    //////////////////////////

The only problem is on 'gates'.
The input form XML looks like "gate1/gate2/gate3" or just blank sometimes.
I want gate1 to be in infos->gates[0] ; etc.
I want to be able to list the gates array afterwards..
I always have a segfault when I try.
Btw, I don't really now how to initialize this array of pointers. I always initialize all gates[i] to NULL but It seems that I've a segfault when I do
    for(int i=0;i

Thanks for all.
It's OK when I've only pointers but when String(char*) / Arrays / Pointers are mixed.. I can't manage =P
I saw too that we can use something like
    int *myArray = calloc(NbOfRows, NbOfRows*sizeof(int));
Why should we declare an array like that.. ? x)
Thanks!

A: The problem that people frequently have with XML is that they assume all the elements are available.  That's not always safe.  Thus this statement:
sprintf(infos->firstname, "%s", card->FirstChild("firstname")->FirstChild()->Value());

Isn't safe to do because you don't actually know if all of those
functions actually return valid objects.  You really need something
like the following (which is not optimized for speed, as I don't
know the tinyXML structure name being returned at each point and thus
am not storing the results once and am rather calling each function
multiple times:
if (card->FirstChild("firstname") &&
   card->FirstChild("firstname")->FirstChild()) {
   sprintf(infos->firstname, "%s", card->FirstChild("firstname")->FirstChild()->Value());
}

And then, to protect against buffer overflows from the data you should
really be doing:
if (card->FirstChild("firstname") &&
   card->FirstChild("firstname")->FirstChild()) {
   infos->firstname[sizeof(infos->firstname)-1] = '\0';
   snprintf(infos->firstname, sizeof(infos->firstname)-1, "%s", card->FirstChild("firstname")->FirstChild()->Value());
}

Don't you just love error handling?
As to your other question:
I saw too that we can use something like int *myArray =
calloc(NbOfRows, NbOfRows*sizeof(int)); Why should we declare an array
like that.. ? x)
calloc first initializes the resulting memory to 0, unlike malloc.
If you see above where I set the end of the buffer to '\0' (which is
actually 0), that's because malloc returns a buffer with potentially
random (non-zero) data in it.  calloc will first set the entire buffer
to all 0s first, which can be generally safer.


text:
Q: In C++, how would one unit test a method that must throw an exception when a private array no longer has "space"? I am implementing an ECS system with a data-oriented design, and with a TDD methodology using Catch 2. I have the following class declaration snippet for an EntityManager:
using Entity = std::uint16_t;
using Signature = std::bitset<MAX_NUM_COMPONENTS>;

const std::uint16_t MAX_NUM_ENTITIES = 10000;

class EntityManager
{
public:
  ...
  Entity createEntity();
  ...
private:
  Signature entities[MAX_NUM_ENTITIES];
  ...
}

The purpose of EntityManager::createEntity() is to simply return an Entity (which we will refer to as e), and set entities[e] to some value. However, the method must throw an exception when the number of entities that exists are more than MAX_NUM_ENTITIES.
I would like to unit test the aforementioned method. But, I am unsure how to do so. An idea I have is to fill up the entire entities array by calling createEntity() MAX_NUM_ENTITIES + 1 times in my test to trigger an exception. However, I have a feeling that it is not the best way to do it, and may even result in a slow test run. Another idea, but similar to the previous one, is to somehow mock entities so that it would have a small size. We will then call createEntity() multiple times until an exception is raised just like the previous idea.
What approach would you recommend?

A:
how would one unit test a method that must throw an exception when a private array no longer has "space"?

Reverse the question: how would you design a method that would support testing it?
You'd probably arrange things so that your test could control the size of the buffer, so that you can set it to something simple to test, like 1 or 2.  You might also have methods that allow your test to inspect what is going on.
Replacing "designs that are hard to test" with "designs that are easy to test" is an important motivator for tdd.


text:
Q: Swift Casting Any Object to Double How to cast an Any object to a Double. I was able to cast it to a string but I can't find anywhere to cast to a Double. Either read in zip code as a Double or cast zip code after to a Double.
let zipCode = ((o as AnyObject).fieldValue("Zip__c"))!

//String cast that works
lender.First_Name__c = String(describing: zipCode)

A: The short answer is that you can use as to cast, though you can do this in a few ways.  The safe, Swift way of doing it is with optional binding, like this:
if let doubleValue = o as? Double {
     print(doubleValue)
}

If you can guarantee it's a Double you can force unwrap it like so:
let doubleValue = o as! Double


text:
Q: How to select nth element from more than one variable Is it possible to select the nth element from more than one variable within one command?
For example: I have 2 variables Romania_Pollen$V23 and Romania_Pollen$V24.
> Romania_Pollen$V23
 [1] S174883             230       1                   174883    --/596/--
 [8] --/597/-- 2                             90                  1
[15] 4         1                   43
[22]           13                            1
[29]                     7         1
[36]                               55        1
[43]
[50] 1                   1
[57]                                                   1         1
[64]                     1                   18
[71]           1         20        1                             7
[78]           1         2                   1         1         2
[85]                                         1
[92] 2                                       1
[99]
Levels:  --/596/-- --/597/-- 1 13 174883 18 2 20 230 4 43 55 7 90 S174883

and then
> Romania_Pollen$V24
 [1] S174884             240       1                   174884    --/621/--
 [8] --/613/-- 4                             110                 1
[15] 2         1                   100
[22]           18
[29]                     12        2
[36]                               58                  1
[43]                                                   1
[50]                               1
[57]                                                   8         1
[64]                     3         1         13
[71]           1         33        1
[78]           1         3                   1                   1
[85]                               1         1
[92] 1         1
[99]
18 Levels:  --/613/-- --/621/-- 1 100 110 12 13 174884 18 2 240 3 33 4 58 ... S174884

Now, is it possible to select the 3rd variable of each variable (V$23, V$24)?
The thing is, I have 99 variables and would like to make  a vector out of the nth element out of these 99 variables.
How could I do that? And another question is: How will R handle the empty spaces? When I look at the variables with dput(variable), each empty space is labelled as " ". (Could I replace them 0 in the final vector?)
I hope this is clear!
Thank you for your help! Regards


text:
Q: PowerBI DAX for Finding Last Record Question
What is an efficient way to create a calculated column finding the last value of my DATE column, using the ModifiedOn column, per ID? I don't want the MAX date, just the last record (even if the last record is the minimum). Also, my table is a calculated column.
Example Table
ID
DATE
ModifiedOn
A
2/4/2020
1/16/2019
A
2/5/2020
1/17/2019
B
3/2/2020
2/7/2020
B
3/3/2020
2/8/2020
B
3/1/2020
2/9/2020
Current Formula
LastRecord =
VAR Max_Date =
CALCULATE (
    MAX ( 'Table1'[ModifiedOn] ),
    ALLEXCEPT ( 'Table1', 'Table1'[ID] )
 )

RETURN
IF (
    Table1[ModifiedOn] = Max_Date,
    Table1[DATE]
    )

Current Results
But using the formula I get a calculated column that looks like this:
I keep getting blanks where they should be filled with the LAST recorded date of that ID.

A: Use the following dax formula to create the expected column:
Column =
VAR __id = 'Table'[ID]
VAR __lastMod =
    CALCULATE(
        MAX( 'Table'[ModifiedOn] ),
        FILTER( 'Table', 'Table'[ID] = __id )
    )

VAR __lastDate =
    CALCULATE(
        MAX( 'Table'[Date] ),
        FILTER( 'Table', 'Table'[ID] = __id && 'Table'[ModifiedOn] = __lastMod )
    )

Return __lastDate


text:
Q: where is text highlighted stored? I need to make an application which copies the highlighted text .
I tried this program
String myString = "This text will be copied into clipboard when running this code!";
StringSelection stringSelection = new StringSelection (myString);
Clipboard clpbrd = Toolkit.getDefaultToolkit ().getSystemClipboard ();
clpbrd.setContents (stringSelection, null);

but this copies the text already existing in clipboard
it prints the text from clipboard after we highlight the text and hit copy option
I want to know after we simply select a text by highlighting, where is this stored, how can I access this highlighted text directly without physically copying it by OS's copy option

A: You can listen to selection changes using the CaretListener. Then you can retrieve the selected Text using the #getSelectedText().
Here is a simple example with a TextArea:
    final JTextArea textArea = new JTextArea();
    textArea.addCaretListener(new CaretListener() {
        @Override
        public void caretUpdate(CaretEvent e) {
            String selectedText = textArea.getSelectedText();
            // do something with it...
        }
    });


text:
Q: HTTP request that throws a null exception I have an activity that create a new instance of connection. like this:
public class myActivity extends Activity {

TextView tv;
ProgressDialog dialog = null;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.daily_news);

    gestureDetector = new GestureDetector(new SwipeGestureDetector());
    tv = (TextView) findViewById(R.id.tx);
    dialog = ProgressDialog.show(myActivity.this, "","Validating user...", true);
    connection con = new connection(dialog);
    final String str =con.connect_to_db("http://10.0.2.2:8000/daily/my.php");

    runOnUiThread(new Runnable() {
        public void run() {
            tv.setText(str);
            dialog.dismiss();
        }
    });
}

}
in connection class i have an HttpResponse that returns null. like this:
public class connection {

private HttpPost httppost;
private HttpClient httpclient;
private HttpResponse response;
private ProgressDialog dialog = null;
private String result;

 public connection(ProgressDialog di){
     dialog = di;
 }
public String connect_to_db(String url){

    try{
        httpclient=new DefaultHttpClient();
        httppost= new HttpPost(url);
        response=httpclient.execute(httppost);
        ResponseHandler<String> responseHandler = new BasicResponseHandler();
        result = httpclient.execute(httppost, responseHandler);
    }catch(Exception e){
        dialog.dismiss();
        System.out.println("Exception : " + e.getMessage());
    }
    return result;
}

}
why the value of "result" in connection class is null?

A: This line:
 final String str =con.connect_to_db("http://10.0.2.2:8000/daily/my.php");

Should not be written in the onCreate, but rather in a separate thread => NetworkOnMainThreadException
For your NullPointer, please tell us if you have the Internet permission in Manifest and if response is null or not.

A: May be because you are doing network operation in onCreate Method. It will not create any problem if you are using android2.2, but if it is  HoneyComb then chances are that it is causing some exception and finally you are getting null value. Move the code to onResume() method.
For Simplicity use
HttpResponse response =  httpclient.execute(httppost);
and
String valueString = EntityUtils.toString(response.getEntity());
int  statusCode = response.getStatusLine().getStatusCode();

print these values and see the out put.


text:
Q: The ten's digit and unit's digit of numbers I have this code
int[,] array = new int[,]{ {34, 21, 32, 41, 25},
                           {14 ,42, 43, 14, 31},
                           {54, 45, 52, 42, 23},
                           {33, 15, 51, 31, 35},
                           {21, 52, 33, 13, 23} };

            for (int i = 0; i < array.GetLength(1); i++)
            {
                for (int j = 0; j < array.GetLength(0); j++)
                {
                    Console.Write(array[i, j] + " ");
                }
                Console.WriteLine();
            }

and i need to find a specific number ( the treasure ).
For each value the ten's digit represents the row number and the unit's digit represents the column number of the cell containing the next clue.
Starting in the upper left corner (at 1,1), i have to use the clues to guide me search of the array. (The first three clues are 11, 34, 42).
The treasure is a cell whose value is the same as its coordinates.
The program should output the cells it visits during its search.
I did the simply way:
Console.WriteLine("The next clue is: {0}", array[0, 0]);
Console.WriteLine("The next clue is: {0}", array[2, 3]);
Console.WriteLine("The next clue is: {0}", array[3, 2]);
Console.WriteLine("The next clue is: {0}", array[0, 4]);

and so on, but the problem is, that if I change the array to set another route the program will output the wrong way. So the solution needs to be dynamic and find the treasure regardless of the array content.
My problem is that i don't know how to do to find the ten's digit of the numbers and the unit's digit.
Can anyone please help me with this?

A: To illustrate my comment: code below and Fiddle
(I've added a HashSet<int> to track which cells have already been visited and avoid ending up with an infinite loop)
int[,] array = new int[,]
{
    {34, 21, 32, 41, 25},
    {14 ,42, 43, 14, 31},
    {54, 45, 52, 42, 23},
    {33, 15, 51, 31, 35},
    {21, 52, 33, 13, 23}
};

int currentCoordinates = 11;
bool treasureFound = false;
var visitedCells = new HashSet<int>();

while (!treasureFound && !visitedCells.Contains(currentCoordinates))
{
    int currentRowIndex = currentCoordinates / 10;
    int currentColumnIndex = currentCoordinates % 10;

    int nextCoordinates = array[currentRowIndex - 1, currentColumnIndex - 1];
    if (nextCoordinates == currentCoordinates)
    {
        treasureFound = true;
    }
    else
    {
        visitedCells.Add(currentCoordinates);
        currentCoordinates = nextCoordinates;
    }
}

if (treasureFound)
{
    Console.WriteLine($"Treasure found in cell {currentCoordinates}");
}
else
{
    Console.WriteLine("No treasure");
}


text:
Q: How to implement ReST services with Sails.js? I am quite new to Node. I came across Sails.js. I think it is based on WebSocket, which seems to be really good for building real-time applications. I would like to know that whether Sails can be used to implement REST architecture as it uses WebSocket? And if yes, how?

A: Yes it can. Sails JS allows you to easily build a RESTful API, essentially with no effort to get started. Also, websockets (through socket.io) are integrated by default into the view and api.
To create a fully RESTful app from the ground up, it actually requires no JS. Try:
sails new testapp
cd testapp
sails generate model user
sails generate controller user
cd <main root>
sails lift

The CRUD (Create, Read, Update, Delete) actions are already created for you. No code!
You can create a user in your browser by doing the following:
HTTP POST (using a tool like PostMan) to http://:1337/user/create
{
        "firstName": "Bob",
        "lastName": "Jones"
}
Next, do a GET to see the new user:
HTTP GET http://:1337/user/
FYI - Sails JS uses a default disk based database to get you going
Done.

A: sails new testapp

cd testapp

sails generate api apiName

controller
create: function (req, res) {
        var payload = {
          name:req.body.name,
          price:req.body.price,
          category:req.body.category,
          author:req.body.author,
          description:req.body.description
        };
       Book.create(payload).exec(function(err){
          if(err){
            res.status(500).json({'error':'something is not right'})
          }else{
            res.status(200).json({'success':true, 'result':payload, 'message':'Book Created success'})
          }
       });
   },

   readone: async function (req, res) {
        var id = req.params.id;
        var fff = await Book.find(id);
           if(fff.length == 0){
             res.status(500).json({'error':'No record found from this ID'})
           }else{
             res.status(200).json({'success':true, 'result':fff, 'message':'Record found'})
           }
    },

model
 attributes: {
    id: { type: 'number', autoIncrement: true },
    name: { type: 'string', required: true, },
    price: { type: 'number', required: true, },
    category: { type: 'string', required: true, },
    author: { type: 'string' },
    description: { type: 'string' },
  },

routes
'post /newbook': 'BookController.create',
  'get /book/:id': 'BookController.readone',


text:
Q: C# Error Displaying The Xml Element in DataGridView The purpose of the code is reading the xml elements and display every element under related column name in datagridview.
So, here I have my code:
            IEnumerable<XElement> tables = xelement.Elements(df + "Table");
            foreach (XElement table in tables)
            {
                //Get name from TableName node
                XElement tableNameNode = table.Element(df + "TableName");
                tbTableName.Text = tableNameNode.Value.ToString();
                XElement numberRows = table.Element(df + "NumberOfRows");
                tbNumRows.Text = numberRows.Value.ToString();
                string tableName = tableNameNode.Value;

                TableData td = new TableData(CurrentProject.CurrentSchema.FindTable(tableName));
                td.PopulateFieldData();
               // tableDataList.TryGetValue(tableName, out td);
                tableDataList.Add(tableName, td);
                //If you open the project after you save it or open it, exception throws: Already Added Key!

                IEnumerable<XElement> fields = table.Elements(df + "Field");
                foreach (XElement field in fields)
                {
                    XElement fieldNameNode = field.Element(df + "Name");
                    string fieldName = fieldNameNode.Value;
                    FieldData fd = td.FieldList[fieldName];

                    IEnumerable<XElement> fieldProps = field.Descendants();
                    foreach (XElement fieldProp in fieldProps)
                    {
                        string fieldPropertyName = fieldProp.Name.ToString();
                        if (fieldPropertyName == "Name")
                        {
                            fd.Name = fieldProp.Value;
                        }

                        if (fieldPropertyName == "Type")
                        {
                            fd.DataType = fieldProp.Value;
                        }

                        if (fieldPropertyName == "Size")
                        {
                            int i = 0;
                            int.TryParse(fieldProp.Value.ToString(), out i);
                            fd.Size = i;
                        }

                        if (fieldPropertyName == "Nullable")
                        {
                            if (fieldProp.Value.ToString() == "True")
                                fd.Nullable = true;
                            else
                                fd.Nullable = false;
                        }

                        if (fieldPropertyName == "ContentSource")
                        {
                            fd.contentSource = fieldProp.Value;
                        }

                        if (fieldPropertyName == "ConstantValue")
                        {
                            fd.constantValue = fieldProp.Value;
                        }

                        if (fieldPropertyName == "RandomValue")
                        {
                            fd.averageSize = fieldProp.Value;
                        }

                        if (fieldPropertyName == "List")
                        {
                            fd.pickList = fieldProp.Value;
                        }
                     }
                    dataGridView1.Rows.Add(fd.Name, fd.DataType, fd.Size, fd.Nullable);

                    string ColumnName = dataGridView1.CurrentRow.Cells[0].Value.ToString();

                    this.tableDataList.TryGetValue(tbTableName.Text, out td);
                    if (td != null)
                    {
                        td.FieldList.TryGetValue(ColumnName, out fd);
                    }
                    foreach (var fdl in td.FieldList)
                    {

                         if (td != null && fd != null)
                    {
                        if (fd.contentSource == "Constant")
                        {
                            dataGridView1.CurrentRow.Cells[4].Value = fd.contentSource + "(" + "Value= " + fd.constantValue + ")";

                        }
                        if (fd.contentSource == "List")
                        {
                            dataGridView1.CurrentRow.Cells[4].Value = fd.contentSource + "(" + fd.pickList + ")";

                        }
                        if (fd.contentSource == "Random")
                        {
                            dataGridView1.CurrentRow.Cells[4].Value = fd.contentSource + "(" + fd.averageSize + ")";
                            }
                        }
                    }

                }
            }

Here is the Xml file I am reading:

<?xml version="1.0"?>

<GeneratorXml>

<SchemaPath>C:\Projects\CoreSchema.xml</SchemaPath>

<GroupName>Documents</GroupName>

-<Table>

<TableName>directory</TableName>

<NumberOfRows>33</NumberOfRows>

-<Field>

<Name>dir_id</Name>

<Type>number</Type>

<Size>10</Size>

<Nullable>False</Nullable>

<ContentSource>Random</ContentSource>

<ConstantValue> </ConstantValue>

<RandomValue>4</RandomValue>

<List> </List>

</Field>

-<Field>

<Name>directory_number</Name>

<Type>number</Type>

<Size>5</Size>

<Nullable>False</Nullable>

<ContentSource>List</ContentSource>

<ConstantValue> </ConstantValue>

<RandomValue> </RandomValue>

<List>Coffee</List>

</Field>

-<Field>

<Name>file_count</Name>

<Type>number</Type>

<Size>5</Size>

<Nullable>False</Nullable>

<ContentSource>Constant</ContentSource>

<ConstantValue>2</ConstantValue>

<RandomValue> </RandomValue>

<List> </List>

</Field>

+<Field>

</Table>

</GeneratorXml>

When I run the code, I only get this GridView:

I think my for loops got a problem, but I can't find it. Thanks in advance for every thoughts.


text:
Q: Nsmutable Array getting corrupt on accessing it I have a NSMutable array that gets populated from an api call and has 31 valid values in it.

As we can see It has a collection of class object which has 4 attributes in it. Each of them have valid values assigned to them. Eg: dat,ancillary etc. This is in dispatch_aync.
In the main queue, i am traversing the chart_data but i EXC_BAD_ACCESS code=1, when i tried to debug deeper into the matter. I found that my NSmutable array was getting corrupt.
Here is a screenshot of when i access the array.

Random address or values are assigned to it which then breaks my code, because i expect double and date values.
There are no operations on the chart_data in between these 2 transactions. Any idea why this could be happening. and this started to happen out of a sudden where the code was working perfectly fine till today.
The code that popluates the Nsmutable array
+(NSMutableArray*)GetData:(NSDictionary*)dataArray
{
    daily_unit_Array = [[NSMutableArray alloc]init];

    for (int i=0; i < 31; i++)
    {
        UnitCost *unit_cost = [[UnitCost alloc]init];

        unit_cost.date = [keys objectAtIndex:i];

        NSArray *unit_cost_value = [dataArray objectForKey:[keys objectAtIndex:i]];

        unit_cost.val1 = [unit_cost_value valueForKey:@"val1"];
        unit_cost.val2 = [unit_cost_value valueForKey:@"val2"];
        unit_cost.val3 = [unit_cost_value valueForKey:@"val3"];
        unit_cost.val4 = [unit_cost_value valueForKey:@"val4"];

        [daily_unit_Array addObject:unit_cost];
    }
    return daily_unit_Array;
}

and this is returned to the function that calls it and assigns it to chart_data
P.S : This is a sporadic issue that occurs 8 in 10 times. Sometimes when i run the app, it perfectly runs and shows me what i want.
Note: Just a note. I updated my Xcode to 5.1 beta 4 version yesterday. but i dont seem that this could cause an issue, because i tried running my same code in older version of Xcode and i could reproduce the error.

A: I finally found the solution.
As @trojafoe pointed, the issue was not in the NSmutable Array but in the objects within them.
I figured out that the properties of UnitCost object were of type (assign,nonatomic). As soon as i changed them to (retain,nonatomic) the issue got resolved...
I guess the values were not been retained.

A: use NSArray * and copy.
NSArray *chart_data = [[HttpMethods GetChartDataPost:1] copy];


text:
Q: Can I find out when a cell is queued? I have a couple of things in my custom UITableViewCell's that I'd like to clean up before the cell gets queued. In a normal view, I'd put these kinds of calls in -(void)dealloc, but as they're being re-used rather than having an instance each, they won't dealloc. For now, I'd just like to print out a text in the log, NSLog(@"Cell out"); when the cell is queued, or "done".
I'm really just looking for something like -(void)didQueue in the cell-class, but my searches haven't shown anything.
I just found -(void)prepareForReuse, but I need more like prepareForQueue. I have to know when it's on its way out, not back in.
Random thought..: Searching for when the cell leaves the screen (or a bit after) might do exactly the same as what I'm looking for, but I'm thinking that costs a lot of processing..

A: For iOS 6+ the table view delegate will receive tableView:didEndDisplayingCell:forRowAtIndexPath: which tells you when the cell is not being used any more (irrelevant of queueing).
That said, prepareForReuse would generally be considered the correct place for the code you describe. If it isn't then you are probably assigning the cell responsibility it shouldn't have.


text:
Q: How to get the XML from mxGrpah diagram?
*

*Pointed index.html from mxGraph diagram sample

*Able to draw the diagrams using editor

*Enabled local storage

*Able to get the XML from local storage

Editor.useLocalStorage = true;
var temp = localStorage['testing.xml'];
console.log(temp);

But, I want to get the XML dynamically without using local storage, So I used the code from mxGraph -Save functionality not working locally but it's throwing graph is not defined
let encoder = new mxCodec();
let result = encoder.encode(graph.getModel());
let xml = mxUtils.getXml(result);

Code:

<!DOCTYPE html>

    <title>Grapheditor</title>
 <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
 <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <link rel="stylesheet" type="text/css" href="styles/grapheditor.css">

  <input type="button" value="Save" onclick="getxml()" />

A: Well in the www/index.html where it seems your example to be taken from it is not very clear to me where the Graph exists so you can retrieve it but I propose you the following workaround to solve your problem:
1) Add an extra variable holding the "xml" state of the graph which you can retrieve any time
In the /examples/grapheditor/www/js/Graph.js add the following variable
Graph.xml = "";

2) On the this.graph.click event of Graph.js add code to retrieve to update the Graph.xml variable holding the xml state of the graph each time there is a change so instead of
this.graph.click = mxUtils.bind(this, function(me)
{
    graphClick.apply(this.graph, arguments);

    if (this.currentState != null && !this.graph.isCellSelected(this.currentState.cell) &&
        mxEvent.isTouchEvent(me.getEvent()) && !this.graph.model.isVertex(me.getCell()))
    {
        this.reset();
    }
});

add the following:
this.graph.click = mxUtils.bind(this, function(me)
{
    let encoder = new mxCodec();
    let result = encoder.encode(this.graph.getModel()); //where graph is the object you are using
    Graph.xml  = mxUtils.getXml(result);

    graphClick.apply(this.graph, arguments);

    if (this.currentState != null && !this.graph.isCellSelected(this.currentState.cell) &&
        mxEvent.isTouchEvent(me.getEvent()) && !this.graph.model.isVertex(me.getCell()))
    {
        this.reset();
    }
});

So when you want the xml state of the canvas you should call the Graph.xml, this worked for me in a local environment

A: Did you try this?
  var enc = new mxCodec(mxUtils.createXmlDocument());
  var node = enc.encode(graph.getModel());
  var xmlString = mxUtils.getXml(node);

A: <?php
                // Includes the mxGraph library
                include_once("_js/mxgraph/php/src/mxServer.php");

                $xml =  $_POST['xml'];
                $xml = output_html($xml);
                $xml = str_replace("%3C", "<", $xml);
                $xml = str_replace("%3E", ">", $xml);
                $xml = str_replace("%22", '"', $xml);
                $xml = str_replace("%20", " ", $xml);
                $xml = str_replace("%3D", "=", $xml);
                $xml = str_replace("%2F", "/", $xml);
                $xml = str_replace("%3B", ";", $xml);
                $xml = str_replace("%23", "#", $xml);

                // XML
                $fh = fopen("xml.xml", "w+");
                fputs($fh, stripslashes($xml));
                fclose($fh);

?>

output_html:
<?php
/**
*
* File: _admin/_functions/output_html.php
* Version 2 - Updated 19:31 06.03.2015
* Copyright (c) 2008-2015 S. Ditlefsen
* License: http://opensource.org/licenses/gpl-license.php GNU Public License
*
*
*
* -----> Please also see: encode_national_letters.php <-----
* encode_national_letters.php are used when this class cannot be used, because
* this class also removes html entities. Example SQL with links, bold text etc
*
*
*/
function output_html($value){
    // Stripslashes
    $value = htmlentities($value);
    $value = str_replace('"',""","$value");
    $value = str_replace("'","'","$value");
    $value = str_replace("<",">","$value"); // less than
    $value = str_replace(">","<","$value"); // greater than
    $value = str_replace("\n","
","$value");

    // Trim and line space
    $value = trim($value);

    // Math
    $value = str_replace("&#699;","'","$value");
    $value = str_replace("&#3647;","฿","$value");
    $value = str_replace("&#960;","π","$value"); // pi
    $value = str_replace("&#966;","φ","$value"); // phi
    $value = str_replace('÷', '÷', $value);  // Yeah, I know.  But otherwise the gap is confusing.  --Kris

    // Check last, if it is backslash, then replace it...
    $check  = substr($value, -1);
    $check  =  "^" . $check . "^";
    if($check == "^\^"){
        $new_value = substr($value, 0, -1);
        $value   = $new_value . "&#92";
    }

    // A
    $value = str_replace('æ', 'æ', $value);
    $value = str_replace("æ", "æ", $value);
    $value = str_replace("&aelig;", "æ", $value);
    $value = str_replace('ø', 'ø', $value);
    $value = str_replace('ø', 'ø', $value);
    $value = str_replace('&oslash;', 'ø', $value);
    $value = str_replace("å", "å", $value);
    $value = str_replace("Ã¥", "å", $value);
    $value = str_replace("&aring;", "å", $value);
    $value = str_replace('Æ', 'Æ', $value);
    $value = str_replace('Æ', 'Æ', $value);
    $value = str_replace('&AElig;', 'Æ', $value);
    $value = str_replace('Å', 'Å', $value);
    $value = str_replace('Ã…', 'Å', $value);
    $value = str_replace('&Aring;', 'Å', $value);

    $value = str_replace('á', 'á', $value);
    $value = str_replace('à', 'à', $value);
    $value = str_replace('À', 'À', $value);
    $value = str_replace('â', 'â', $value);
    $value = str_replace('Â', 'Â', $value);
    $value = str_replace('Á', 'Á', $value);

    $value = str_replace('Ä', 'Ä', $value);
    $value = str_replace('ä', 'ä', $value);

    $value = str_replace('À', 'À', $value);
    $value = str_replace('Á', 'Á', $value);
    // $value = str_replace('Â', 'Â', $value);
    // $value = str_replace('Ã', 'Ã', $value);
    $value = str_replace('Ä', 'Ä', $value);
    $value = str_replace('à', 'à', $value);
    $value = str_replace('á', 'á', $value);
    $value = str_replace('â', 'â', $value);
    $value = str_replace('ã', 'ã', $value);
    $value = str_replace('ä', 'ä', $value);

    // C
    $value = str_replace('Ç', 'Ç', $value);
    $value = str_replace('ç', 'ç', $value);

    // E
    $value = str_replace('è', 'è', $value);
    $value = str_replace('È', 'È', $value);
    $value = str_replace('é', 'é', $value);
    $value = str_replace('É', 'É', $value);
    $value = str_replace('ê', 'ê', $value);
    $value = str_replace('Ê', 'Ê', $value);
    $value = str_replace('ë', 'ë', $value);
    $value = str_replace('Ë', 'Ë', $value);
    $value = str_replace('È', 'È', $value);
    $value = str_replace('É', 'É', $value);
    $value = str_replace('Ê', 'Ê', $value);
    $value = str_replace('Ë', 'Ë', $value);
    $value = str_replace('è', 'è', $value);
    $value = str_replace('é', 'é', $value);
    $value = str_replace('ê', 'ê', $value);
    $value = str_replace('ë', 'ë', $value);

    // I
    $value = str_replace('î', 'î', $value);
    $value = str_replace('Î', 'Î', $value);
    $value = str_replace('ï', 'ï', $value);
    $value = str_replace('Ï', 'Ï', $value);
    $value = str_replace('Í', 'Í', $value);
    $value = str_replace('í', 'í', $value);
    $value = str_replace('¿', '¿', $value);
    $value = str_replace('¡', '¡', $value);
    $value = str_replace('Ì', 'Ì', $value);
    $value = str_replace('Í', 'Í', $value);
    $value = str_replace('Î', 'Î', $value);
    $value = str_replace('Ï', 'Ï', $value);
    $value = str_replace('ì', 'ì', $value);
    $value = str_replace('í', 'í', $value);
    $value = str_replace('î', 'î', $value);
    $value = str_replace('ï', 'ï', $value);

    // D
    $value = str_replace('Ð', 'Ð', $value);

    // N
    $value = str_replace('Ñ', 'Ñ', $value);
    $value = str_replace('ñ', 'ñ', $value);
    $value = str_replace('Ñ', 'Ñ', $value);

    // O
    $value = str_replace('Ø', 'Ø', $value);
    $value = str_replace('Ø', 'Ø', $value);
    $value = str_replace('&Oslash;', 'Ø', $value);
    $value = str_replace('ô', 'ô', $value);
    $value = str_replace('Ô', 'Ô', $value);
    $value = str_replace('Ó', 'Ó', $value);
    $value = str_replace('ó', 'ó', $value);
    $value = str_replace('º', 'º', $value);
    $value = str_replace('ª', 'ª', $value);
    $value = str_replace('Ö', 'Ö', $value);
    $value = str_replace('ö', 'ö', $value);
    $value = str_replace('Ò', 'Ò', $value);
    $value = str_replace('Ó', 'Ó', $value);
    $value = str_replace('Ô', 'Ô', $value);
    $value = str_replace('Õ', 'Õ', $value);
    $value = str_replace('Ö', 'Ö', $value);
    $value = str_replace('ð', 'ð', $value);
    $value = str_replace('ñ', 'ñ', $value);
    $value = str_replace('ò', 'ò', $value);
    $value = str_replace('ó', 'ó', $value);
    $value = str_replace('ô', 'ô', $value);
    $value = str_replace('õ', 'õ', $value);
    $value = str_replace('ö', 'ö', $value);

    // P
    $value = str_replace('Þ', 'Þ', $value);
    $value = str_replace('þ', 'þ', $value);

    // S
    $value = str_replace('ß', 'ß', $value);

    // U
    $value = str_replace('ù', 'ù', $value);
    $value = str_replace('Ù', 'Ù', $value);
    $value = str_replace('û', 'û', $value);
    $value = str_replace('Û', 'Û', $value);
    $value = str_replace('ü', 'ü', $value);
    $value = str_replace('Ü', 'Ü', $value);
    $value = str_replace('Ú', 'Ú', $value);
    $value = str_replace('ú', 'ú', $value);
    $value = str_replace('ü', 'ü', $value);
    $value = str_replace('Ù', 'Ù', $value);
    $value = str_replace('Ú', 'Ú', $value);
    $value = str_replace('Û', 'Û', $value);
    $value = str_replace('Ü', 'Ü', $value);
    $value = str_replace('ù', 'ù', $value);
    $value = str_replace('ú', 'ú', $value);
    $value = str_replace('û', 'û', $value);
    $value = str_replace('ü', 'ü', $value);

    // Y
    $value = str_replace('ÿ', 'ÿ', $value);
    $value = str_replace('Ÿ', 'Ÿ', $value);
    $value = str_replace('Ý', 'Ý', $value);
    $value = str_replace('ý', 'ý', $value);
    $value = str_replace('ÿ', 'ÿ', $value);

    // X
    $value = str_replace('×', '×', $value);  // Yeah, I know.  But otherwise the gap is confusing.  --Kris

    // Other
    $value = str_replace('ç', 'ç', $value);
    $value = str_replace('Ç', 'Ç', $value);
    $value = str_replace('œ', 'œ', $value);
    $value = str_replace('Œ', 'Œ', $value);

    //Punctuation
    $value = str_replace('«', '«', $value);
    $value = str_replace('»', '»', $value);
    $value = str_replace('‹', '‹', $value);
    $value = str_replace('›', '›', $value);
    $value = str_replace('"', '“', $value);
    $value = str_replace('"', '”', $value);
    $value = str_replace(''', '‘', $value);
    $value = str_replace(''', '’', $value);
    $value = str_replace('—', '—', $value);
    $value = str_replace('–', '–', $value);

    // Money
    $value = str_replace('€', '€', $value);

    // Degree
    $value = str_replace('°', '°', $value);
    $value = str_replace('&deg;', '°', $value);

    // &
    $value = str_replace('&amp;', '&', $value);

    // Return
    return $value;
}
?>


text:
Q: onLoad not been called in lightning:recordEditForm I am having input fields inside my recordEditForm. When i try to run the component it's not calling the onload event handler. I don't want to put any lightning:inputField into it. Because I don't need standard UI. Also receiving error on submit.Here is my sample code.
newContact.cmp
<aura:component >
    <aura:attribute name="simpleNewContact" type="Object"/>
    <lightning:recordEditForm
            onload="{!c.handleLoad}"
            onsubmit="{!c.handleSubmit}"
            onerror="{!c.handleError}"
            onsuccess="{!c.handleSuccess}"
            objectApiName="Contact" aura:id="myRecordForm">

            <lightning:card iconName="action:new_contact" title="Create Contact">

                    <lightning:input aura:id="contactField" label="First Name" value="{!v.simpleNewContact.FirstName}"/>
                    <lightning:input aura:id="contactField" label="Last Name" value="{!v.simpleNewContact.LastName}"/>
                    <lightning:input aura:id="contactField" label="Title" value="{!v.simpleNewContact.Title}"/>

                    <lightning:button label="Save Contact" type="submit" variant="brand"/>

            </lightning:card>

    </lightning:recordEditForm>

    <aura:if isTrue="{!not(empty(v.newContactError))}">

            {!v.newContactError}

    </aura:if>
</aura:component>

newContactController.js
({
    handleLoad : function(component, evnet, helper){
        console.log('loaded');
    },
    handleSuccess : function(component, evnet, helper){
        var payload = event.getParams().response;
        alert(payload.id);
    },
    handleError:function(component, evnet, helper){
        var error = event.getParam('error');
        alert(JSON.stringify(error));
    },
    handleSubmit : function(component, evnet, helper){
        event.preventDefault();
        var fields = event.getParam('fields');
        console.log(fields);
        component.find("myRecordForm").submit(component.get("v.simpleNewContact"));
    }
})

Any suggestions ?

A: If you don't need the "standard UI", use force:recordData instead. You can load and save records using this component without requiring a UI.