问:
STM32 DMA transfer error both FIFO and transfer error flags set
I have an STM32F769I-EVAL configured to receive 8 bit parallel data based on code from ST's AN4666. What I expect to happen is: the clock from my input device triggers the input capture DMA and writes data to SDRAM until my OC timer interrupt disables the transfer. At that point I can manipulate the data in SDRAM and transfer it elsewhere. However, after the hardware is configured and the input capture enabled I get a DMA transfer error. The value for errorcode (6) in the HAL_DMA_IRQHandler function shows that both FIFO and transfer error flags are set. According to my understanding of the datasheet (see pg 261) this should not be possible, I assume I have mis-configured a setting somewhere but I am at a loss as far as how to proceed. What steps can I take to solve this?

DMA configuration:

```<code>void HAL_TIM_Base_MspInit(TIM_HandleTypeDef *htim)
{
    GPIO_InitTypeDef   GPIO_InitStruct;
    static DMA_HandleTypeDef  hdma_tim;

    /* TIMx clock enable */
    TIMx_CLK_ENABLE();

    /* Enable DMA clock */
    DMAx_CLK_ENABLE();

    /* Enable TIM input GPIO clock */
    TIMx_CHy_GPIOCLK_ENABLE();

    /* Configure input of TIMx_CHy on AF */
    GPIO_InitStruct.Pin = TIMx_CHy_PIN;
    GPIO_InitStruct.Mode = GPIO_MODE_AF_PP;
    GPIO_InitStruct.Pull = GPIO_NOPULL;
    GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_VERY_HIGH;
    GPIO_InitStruct.Alternate = GPIO_AF_TIMx;
    HAL_GPIO_Init(TIMx_CHy_PORT, &GPIO_InitStruct);

    /* Set the parameters to be configured */
    hdma_tim.Init.Channel  = DMA_CHANNEL;
    hdma_tim.Init.Direction = DMA_PERIPH_TO_MEMORY;
    hdma_tim.Init.PeriphInc = DMA_PINC_DISABLE;
    hdma_tim.Init.MemInc = DMA_MINC_ENABLE;
    hdma_tim.Init.PeriphDataAlignment = DMA_PDATAALIGN_BYTE ; /* Reading in GPIO PC[7:0]*/
    hdma_tim.Init.MemDataAlignment = DMA_MDATAALIGN_WORD ;
    hdma_tim.Init.Mode = DMA_NORMAL;  /* double memory buffer used */
    hdma_tim.Init.Priority = DMA_PRIORITY_HIGH;
    hdma_tim.Init.FIFOMode = DMA_FIFOMODE_ENABLE; /* using FIFO mode since memory datasize=32bit and GPIO=8bits in our case */
    hdma_tim.Init.FIFOThreshold = DMA_FIFO_THRESHOLD_1QUARTERFULL; /* flushing FIFO at each 32bit reception (4 data) */
    hdma_tim.Init.MemBurst = DMA_MBURST_SINGLE;
    hdma_tim.Init.PeriphBurst = DMA_PBURST_SINGLE;

    /* Set hdma_tim instance */
    hdma_tim.Instance = DMA_STREAM;

    /* Link hdma_tim to hdma[CC1] */
    __HAL_LINKDMA(htim, hdma[TIMx_DMA_ID], hdma_tim);

    /* Initialize TIMx DMA handle */
    HAL_DMA_Init(htim->hdma[TIMx_DMA_ID]);

    /* NVIC configuration for TIMx output compare interrupt */
    HAL_NVIC_SetPriority(TIMx_IRQn, 0, 2);
    HAL_NVIC_EnableIRQ(TIMx_IRQn);

    /* Configure the NVIC for DMA                             */
    /* NVIC configuration for DMA transfer complete interrupt */
    HAL_NVIC_SetPriority(TIMx_DMA_IRQn, 0, 0);
    HAL_NVIC_EnableIRQ(TIMx_DMA_IRQn);

}
</code>```

Code from main:

```<code>/* Initialize SDRAM */
BSP_SDRAM_Init();

/* Configure the Data GPIO in input mode  */
Data_GPIO_Config();

/* Set Timers instance */
TimHandle.Instance = TIMx;

/* Initialize global Timer parameters */
TimHandle.Init.Period            = MAX_COUNTER;
TimHandle.Init.Prescaler         = TIMx_PRESCALER - 1;
TimHandle.Init.ClockDivision     = TIM_CLOCKDIVISION_DIV1;
TimHandle.Init.CounterMode       = TIM_COUNTERMODE_UP;
TimHandle.Init.RepetitionCounter = 0;
if (HAL_TIM_Base_Init(&TimHandle) != HAL_OK)
{
    /* Initialization Error */
    Error_Handler();
}

//Initialize Timer "OC" channel for OC mode
sOConfig.OCMode       = TIM_OCMODE_TIMING/*TIM_OCMODE_TOGGLE*/;
sOConfig.OCPolarity   = TIM_OCPOLARITY_HIGH;
sOConfig.Pulse        = NB_COUNTER_CYCLE;
sOConfig.OCNPolarity  = TIM_OCPOLARITY_HIGH;
sOConfig.OCFastMode   = TIM_OCFAST_DISABLE;
sOConfig.OCNIdleState = TIM_OCNIDLESTATE_RESET;
sOConfig.OCIdleState  = TIM_OCIDLESTATE_RESET;
if (HAL_TIM_OC_ConfigChannel(&TimHandle, &sOConfig, TIMx_CHANNEL_OC) != HAL_OK)
{
    //Configuration Error
Error_Handler();
}

/* Initialize Timer "IC" channel for IC mode     */
sICConfig.ICPolarity  = CLK_LATCHING_DATA_EDGE;
sICConfig.ICSelection = TIM_ICSELECTION_DIRECTTI;
sICConfig.ICPrescaler = TIM_ICPSC_DIV1;
sICConfig.ICFilter    = TIM_IC_FILTER;  /* filter the clock signal over/undershoot */
if (HAL_TIM_IC_ConfigChannel(&TimHandle, &sICConfig, TIMx_CHANNEL_IC) != HAL_OK)
{
    /* Configuration Error */
    Error_Handler();
}

/* Set the DMA memory0 conversion complete callback */
TimHandle.hdma[TIMx_DMA_ID]->XferCpltCallback = TransferComplete;
/* Set the DMA memory1 conversion complete callback */
TimHandle.hdma[TIMx_DMA_ID]->XferM1CpltCallback = TransferComplete;
/* Set the DMA error callback */
TimHandle.hdma[TIMx_DMA_ID]->XferErrorCallback = TransferError ;

/* Update second memory address */
second_mem_address = (uint32_t)((SDRAM_BANK_ADDR + WRITE_READ_ADDR) + (DMA_MEM_BUFF_SIZE));

/* Start DMA multi buffer transfer */
if (HAL_DMAEx_MultiBufferStart_IT(TimHandle.hdma[TIMx_DMA_ID], GPIOx_IDR, (SDRAM_BANK_ADDR + WRITE_READ_ADDR), second_mem_address, DMA_MEM_BUFF_SIZE) != HAL_OK)
{
    /* Transfer Error */
    Error_Handler();
}

__HAL_TIM_ENABLE_DMA(&TimHandle, TIMx_DMA_CC);

/* Enable the TIMx OC channel interrupt */
__HAL_TIM_ENABLE_IT(&TimHandle, TIMx_IT_OC);
/* Enable the TIMX OC channel */
TIM_CCxChannelCmd(TimHandle.Instance, TIMx_CHANNEL_OC, TIM_CCx_ENABLE);

/* Enable the TIMx IC channel */
TIM_CCxChannelCmd(TimHandle.Instance, TIMx_CHANNEL_IC, TIM_CCx_ENABLE);

HAL_TIM_OC_Start(&TimHandle, TIMx_CHANNEL_OC); // enable counter

/* processing while Timeout not reached */
while (timeout_flag == 0);
</code>```

答:
The error was caused by a FIFO overrun condition while receiving data. Increasing the FIFO threshold value from 1/4 to full stops the transfer errors from occurring.

The cortex-M7 introduces a data and instruction cache which may cause issues with DMA transfers but I could confirm that this was not the case, further information here.

Body:
I have an STM32F769I-EVAL configured to receive 8 bit parallel data based on code from ST's AN4666. What I expect to happen is: the clock from my input device triggers the input capture DMA and writes data to SDRAM until my OC timer interrupt disables the transfer. At that point I can manipulate the data in SDRAM and transfer it elsewhere. However, after the hardware is configured and the input capture enabled I get a DMA transfer error. The value for errorcode (6) in the HAL_DMA_IRQHandler function shows that both FIFO and transfer error flags are set. According to my understanding of the datasheet (see pg 261) this should not be possible, I assume I have mis-configured a setting somewhere but I am at a loss as far as how to proceed. What steps can I take to solve this?

DMA configuration:

void HAL_TIM_Base_MspInit(TIM_HandleTypeDef *htim)
{
    GPIO_InitTypeDef   GPIO_InitStruct;
    static DMA_HandleTypeDef  hdma_tim;

    /* TIMx clock enable */
    TIMx_CLK_ENABLE();

    /* Enable DMA clock */
    DMAx_CLK_ENABLE();

    /* Enable TIM input GPIO clock */
    TIMx_CHy_GPIOCLK_ENABLE();

    /* Configure input of TIMx_CHy on AF */
    GPIO_InitStruct.Pin = TIMx_CHy_PIN;
    GPIO_InitStruct.Mode = GPIO_MODE_AF_PP;
    GPIO_InitStruct.Pull = GPIO_NOPULL;
    GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_VERY_HIGH;
    GPIO_InitStruct.Alternate = GPIO_AF_TIMx;
    HAL_GPIO_Init(TIMx_CHy_PORT, &GPIO_InitStruct);

    /* Set the parameters to be configured */
    hdma_tim.Init.Channel  = DMA_CHANNEL;
    hdma_tim.Init.Direction = DMA_PERIPH_TO_MEMORY;
    hdma_tim.Init.PeriphInc = DMA_PINC_DISABLE;
    hdma_tim.Init.MemInc = DMA_MINC_ENABLE;
    hdma_tim.Init.PeriphDataAlignment = DMA_PDATAALIGN_BYTE ; /* Reading in GPIO PC[7:0]*/
    hdma_tim.Init.MemDataAlignment = DMA_MDATAALIGN_WORD ;
    hdma_tim.Init.Mode = DMA_NORMAL;  /* double memory buffer used */
    hdma_tim.Init.Priority = DMA_PRIORITY_HIGH;
    hdma_tim.Init.FIFOMode = DMA_FIFOMODE_ENABLE; /* using FIFO mode since memory datasize=32bit and GPIO=8bits in our case */
    hdma_tim.Init.FIFOThreshold = DMA_FIFO_THRESHOLD_1QUARTERFULL; /* flushing FIFO at each 32bit reception (4 data) */
    hdma_tim.Init.MemBurst = DMA_MBURST_SINGLE;
    hdma_tim.Init.PeriphBurst = DMA_PBURST_SINGLE;

    /* Set hdma_tim instance */
    hdma_tim.Instance = DMA_STREAM;

    /* Link hdma_tim to hdma[CC1] */
    __HAL_LINKDMA(htim, hdma[TIMx_DMA_ID], hdma_tim);

    /* Initialize TIMx DMA handle */
    HAL_DMA_Init(htim->hdma[TIMx_DMA_ID]);

    /* NVIC configuration for TIMx output compare interrupt */
    HAL_NVIC_SetPriority(TIMx_IRQn, 0, 2);
    HAL_NVIC_EnableIRQ(TIMx_IRQn);

    /* Configure the NVIC for DMA                             */
    /* NVIC configuration for DMA transfer complete interrupt */
    HAL_NVIC_SetPriority(TIMx_DMA_IRQn, 0, 0);
    HAL_NVIC_EnableIRQ(TIMx_DMA_IRQn);

}

Code from main:

/* Initialize SDRAM */
BSP_SDRAM_Init();

/* Configure the Data GPIO in input mode  */
Data_GPIO_Config();

/* Set Timers instance */
TimHandle.Instance = TIMx;

/* Initialize global Timer parameters */
TimHandle.Init.Period            = MAX_COUNTER;
TimHandle.Init.Prescaler         = TIMx_PRESCALER - 1;
TimHandle.Init.ClockDivision     = TIM_CLOCKDIVISION_DIV1;
TimHandle.Init.CounterMode       = TIM_COUNTERMODE_UP;
TimHandle.Init.RepetitionCounter = 0;
if (HAL_TIM_Base_Init(&TimHandle) != HAL_OK)
{
    /* Initialization Error */
    Error_Handler();
}

//Initialize Timer "OC" channel for OC mode
sOConfig.OCMode       = TIM_OCMODE_TIMING/*TIM_OCMODE_TOGGLE*/;
sOConfig.OCPolarity   = TIM_OCPOLARITY_HIGH;
sOConfig.Pulse        = NB_COUNTER_CYCLE;
sOConfig.OCNPolarity  = TIM_OCPOLARITY_HIGH;
sOConfig.OCFastMode   = TIM_OCFAST_DISABLE;
sOConfig.OCNIdleState = TIM_OCNIDLESTATE_RESET;
sOConfig.OCIdleState  = TIM_OCIDLESTATE_RESET;
if (HAL_TIM_OC_ConfigChannel(&TimHandle, &sOConfig, TIMx_CHANNEL_OC) != HAL_OK)
{
    //Configuration Error
Error_Handler();
}

/* Initialize Timer "IC" channel for IC mode     */
sICConfig.ICPolarity  = CLK_LATCHING_DATA_EDGE;
sICConfig.ICSelection = TIM_ICSELECTION_DIRECTTI;
sICConfig.ICPrescaler = TIM_ICPSC_DIV1;
sICConfig.ICFilter    = TIM_IC_FILTER;  /* filter the clock signal over/undershoot */
if (HAL_TIM_IC_ConfigChannel(&TimHandle, &sICConfig, TIMx_CHANNEL_IC) != HAL_OK)
{
    /* Configuration Error */
    Error_Handler();
}

/* Set the DMA memory0 conversion complete callback */
TimHandle.hdma[TIMx_DMA_ID]->XferCpltCallback = TransferComplete;
/* Set the DMA memory1 conversion complete callback */
TimHandle.hdma[TIMx_DMA_ID]->XferM1CpltCallback = TransferComplete;
/* Set the DMA error callback */
TimHandle.hdma[TIMx_DMA_ID]->XferErrorCallback = TransferError ;

/* Update second memory address */
second_mem_address = (uint32_t)((SDRAM_BANK_ADDR + WRITE_READ_ADDR) + (DMA_MEM_BUFF_SIZE));

/* Start DMA multi buffer transfer */
if (HAL_DMAEx_MultiBufferStart_IT(TimHandle.hdma[TIMx_DMA_ID], GPIOx_IDR, (SDRAM_BANK_ADDR + WRITE_READ_ADDR), second_mem_address, DMA_MEM_BUFF_SIZE) != HAL_OK)
{
    /* Transfer Error */
    Error_Handler();
}

__HAL_TIM_ENABLE_DMA(&TimHandle, TIMx_DMA_CC);

/* Enable the TIMx OC channel interrupt */
__HAL_TIM_ENABLE_IT(&TimHandle, TIMx_IT_OC);
/* Enable the TIMX OC channel */
TIM_CCxChannelCmd(TimHandle.Instance, TIMx_CHANNEL_OC, TIM_CCx_ENABLE);

/* Enable the TIMx IC channel */
TIM_CCxChannelCmd(TimHandle.Instance, TIMx_CHANNEL_IC, TIM_CCx_ENABLE);

HAL_TIM_OC_Start(&TimHandle, TIMx_CHANNEL_OC); // enable counter

/* processing while Timeout not reached */
while (timeout_flag == 0);


来源: stackexchange

问:
How would you transpose a binary matrix?
I have binary matrices in C++ that I repesent with a vector of 8-bit values.

For example, the following matrix:

```<code>1 0 1 0 1 0 1
0 1 1 0 0 1 1
0 0 0 1 1 1 1
</code>```

is represented as:

```<code>const uint8_t matrix[] = {
    0b01010101,
    0b00110011,
    0b00001111,
};
</code>```

The reason why I'm doing it this way is because then computing the product of such a matrix and a 8-bit vector becomes really simple and efficient (just one bitwise AND and a parity computation, per row), which is much better than calculating each bit individually.

I'm now looking for an efficient way to transpose such a matrix, but I haven't been able to figure out how to do it without having to manually calculate each bit.

Just to clarify, for the above example, I'd like to get the following result from the transposition:

```<code>const uint8_t transposed[] = {
    0b00000000,
    0b00000100,
    0b00000010,
    0b00000110,
    0b00000001,
    0b00000101,
    0b00000011,
    0b00000111,
};
</code>```

NOTE: I would prefer an algorithm that can calculate this with arbitrary-sized matrices but am also interested in algorithms that can only handle certain sizes.

答:
Here's what I posted on gitub (mischasan/sse2/ssebmx.src)
Changing INP() and OUT() to use induction vars saves an IMUL each.
AVX256 does it twice as fast.
AVX512 is not an option, because there is no _mm512_movemask_epi8().

```<code>#include <stdint.h>
#include <emmintrin.h>

#define INP(x,y) inp[(x)*ncols/8 + (y)/8]
#define OUT(x,y) out[(y)*nrows/8 + (x)/8]

void ssebmx(char const *inp, char *out, int nrows, int ncols)
{
    int rr, cc, i, h;
    union { __m128i x; uint8_t b[16]; } tmp;

    // Do the main body in [16 x 8] blocks:
    for (rr = 0; rr <= nrows - 16; rr += 16)
        for (cc = 0; cc < ncols; cc += 8) {
            for (i = 0; i < 16; ++i)
                tmp.b[i] = INP(rr + i, cc);
            for (i = 8; i--; tmp.x = _mm_slli_epi64(tmp.x, 1))
                *(uint16_t*)&OUT(rr, cc + i) = _mm_movemask_epi8(tmp.x);
        }

    if (rr == nrows) return;

    // The remainder is a row of [8 x 16]* [8 x 8]?

    //  Do the [8 x 16] blocks:
    for (cc = 0; cc <= ncols - 16; cc += 16) {
        for (i = 8; i--;)
            tmp.b[i] = h = *(uint16_t const*)&INP(rr + i, cc),
            tmp.b[i + 8] = h >> 8;
        for (i = 8; i--; tmp.x = _mm_slli_epi64(tmp.x, 1))
            OUT(rr, cc + i) = h = _mm_movemask_epi8(tmp.x),
            OUT(rr, cc + i + 8) = h >> 8;
    }

    if (cc == ncols) return;

    //  Do the remaining [8 x 8] block:
    for (i = 8; i--;)
        tmp.b[i] = INP(rr + i, cc);
    for (i = 8; i--; tmp.x = _mm_slli_epi64(tmp.x, 1))
        OUT(rr, cc + i) = _mm_movemask_epi8(tmp.x);
}
</code>```

HTH.

ContentLicense: CC BY-SA 3.0

Body:
I have binary matrices in C++ that I repesent with a vector of 8-bit values.

For example, the following matrix:

1 0 1 0 1 0 1
0 1 1 0 0 1 1
0 0 0 1 1 1 1

is represented as:

const uint8_t matrix[] = {
    0b01010101,
    0b00110011,
    0b00001111,
};

The reason why I'm doing it this way is because then computing the product of such a matrix and a 8-bit vector becomes really simple and efficient (just one bitwise AND and a parity computation, per row), which is much better than calculating each bit individually.

I'm now looking for an efficient way to transpose such a matrix, but I haven't been able to figure out how to do it without having to manually calculate each bit.

Just to clarify, for the above example, I'd like to get the following result from the transposition:

const uint8_t transposed[] = {
    0b00000000,
    0b00000100,
    0b00000010,
    0b00000110,
    0b00000001,
    0b00000101,
    0b00000011,
    0b00000111,
};

NOTE: I would prefer an algorithm that can calculate this with arbitrary-sized matrices but am also interested in algorithms that can only handle certain sizes.

Body:
Here's what I posted on gitub (mischasan/sse2/ssebmx.src)
Changing INP() and OUT() to use induction vars saves an IMUL each.
AVX256 does it twice as fast.
AVX512 is not an option, because there is no _mm512_movemask_epi8().

#include <stdint.h>
#include <emmintrin.h>

#define INP(x,y) inp[(x)*ncols/8 + (y)/8]
#define OUT(x,y) out[(y)*nrows/8 + (x)/8]

void ssebmx(char const *inp, char *out, int nrows, int ncols)
{
    int rr, cc, i, h;
    union { __m128i x; uint8_t b[16]; } tmp;

    // Do the main body in [16 x 8] blocks:
    for (rr = 0; rr <= nrows - 16; rr += 16)
        for (cc = 0; cc < ncols; cc += 8) {
            for (i = 0; i < 16; ++i)
                tmp.b[i] = INP(rr + i, cc);
            for (i = 8; i--; tmp.x = _mm_slli_epi64(tmp.x, 1))
                *(uint16_t*)&OUT(rr, cc + i) = _mm_movemask_epi8(tmp.x);
        }

    if (rr == nrows) return;

    // The remainder is a row of [8 x 16]* [8 x 8]?

    //  Do the [8 x 16] blocks:
    for (cc = 0; cc <= ncols - 16; cc += 16) {
        for (i = 8; i--;)
            tmp.b[i] = h = *(uint16_t const*)&INP(rr + i, cc),
            tmp.b[i + 8] = h >> 8;
        for (i = 8; i--; tmp.x = _mm_slli_epi64(tmp.x, 1))
            OUT(rr, cc + i) = h = _mm_movemask_epi8(tmp.x),
            OUT(rr, cc + i + 8) = h >> 8;
    }

    if (cc == ncols) return;

    //  Do the remaining [8 x 8] block:
    for (i = 8; i--;)
        tmp.b[i] = INP(rr + i, cc);
    for (i = 8; i--; tmp.x = _mm_slli_epi64(tmp.x, 1))
        OUT(rr, cc + i) = _mm_movemask_epi8(tmp.x);
}

HTH.


问:
How can I send a body message with mpack?
How can I send a body message with mpack?

```<code>mpack -s "Test" /home/Desktop/text.txt example@exampledomain.com
</code>```

In this scenario, it will sent a text.txt file with the subject ''test'', but what if I want to send a message body with it.

I tried:

```<code>echo "Body Message" | mpack -s "Subject" file.txt myemail@test.com
</code>```

but it doesn't work.

答:
Include it as a description.

Example:

```<code>echo "this is the message body" > message_body.txt
mpack -s "Subject goes here.." -d message_body.txt email@example.com
rm message_body.txt
</code>```

Body:
How can I send a body message with mpack?

mpack -s "Test" /home/Desktop/text.txt example@exampledomain.com

In this scenario, it will sent a text.txt file with the subject ''test'', but what if I want to send a message body with it.

I tried:

echo "Body Message" | mpack -s "Subject" file.txt myemail@test.com

but it doesn't work.

Body:
Include it as a description.

Example:

echo "this is the message body" > message_body.txt
mpack -s "Subject goes here.." -d message_body.txt email@example.com
rm message_body.txt


问:
How to sum or add two values by using SQL command
How to add them together?
Need to be in vb.net

Two value statement as below:

```<code>(SELECT SUM(ChildName) FROM Child SA WHERE SA.Name=A.Name AND SA.Health_Status=1 AND SA.Parrent_ID IS NOT NULL) AS Present_CHILD

(SELECT SUM(LATE_COMING_CHILD) FROM LATE_COME SB WHERE SB.Name=A.Name) AS LATE_CHILD
</code>```

答:
In your example, if Table1 and Table2 have a reference that relate them to each other, you can add their fields. The best way is defining a foreign key for one of them, referring to primary key of other table.

For example you can define a new column in Table2 named Table1Id, and rewrite the query as bellow:

```<code>SELECT Table1.Name+Table2.Name
FROM Table2
  INNER JOIN Table1
  ON Table2.Table1Id=Table1.Id
</code>```

If there is no relation between Table1 and Table2, so there is no meaning for adding fields of these tables.

In the edited situation, the query may be as follows:

```<code>SELECT SA.ChildName+' '+SB.LATE_COMING_CHILD AS AllNames
FROM LATE_COME SB
  INNER JOIN Child SA
  ON SB.ChildId=SA.Id
WHERE
  SA.Health_Status=1
  AND
  SA.Parrent_ID IS NOT NULL
</code>```

I don't understand why all names of a person must use in one filed!
Additionally I suggest you learn SQL from scratch...

Body:
How to add them together?
Need to be in vb.net

Two value statement as below:

(SELECT SUM(ChildName) FROM Child SA WHERE SA.Name=A.Name AND SA.Health_Status=1 AND SA.Parrent_ID IS NOT NULL) AS Present_CHILD

(SELECT SUM(LATE_COMING_CHILD) FROM LATE_COME SB WHERE SB.Name=A.Name) AS LATE_CHILD

Body:
In your example, if Table1 and Table2 have a reference that relate them to each other, you can add their fields. The best way is defining a foreign key for one of them, referring to primary key of other table.

For example you can define a new column in Table2 named Table1Id, and rewrite the query as bellow:

SELECT Table1.Name+Table2.Name
FROM Table2
  INNER JOIN Table1
  ON Table2.Table1Id=Table1.Id

If there is no relation between Table1 and Table2, so there is no meaning for adding fields of these tables.

In the edited situation, the query may be as follows:

SELECT SA.ChildName+' '+SB.LATE_COMING_CHILD AS AllNames
FROM LATE_COME SB
  INNER JOIN Child SA
  ON SB.ChildId=SA.Id
WHERE
  SA.Health_Status=1
  AND
  SA.Parrent_ID IS NOT NULL

I don't understand why all names of a person must use in one filed!
Additionally I suggest you learn SQL from scratch...


问:
Python 3 Dictionary sorted with wrong output
I am currently doing an Assignment; however, I got some interesting output which confused me so much.

I am trying to sort the following dictionary:

```<code>result = {'A1': '9', 'A2': '14', 'A3': '16', 'A4': '0', 'B1': '53', 'B2': '267', 'B3': '75', 'B4': '22', 'C1': '19', 'C2': '407', 'C3': '171', 'C4': '56', 'C5': '10', 'D3': '47', 'D4': '34', 'D5': '10'}
</code>```

My sorting code with Python 3 is the following : (only sorted by value)

```<code>sortedList = [v for v in sorted(result.values())]
</code>```

The output is :

```<code>['0', '10', '10', '14', '16', '171', '19', '22', '267', '34', '407', '47', '53', '56', '75', '9']
</code>```

which is not fully sorted. The output is quite strange.

Why it is happened like this?
I have used another dict to test like this:

```<code>testD = {'A':'5','B': '9','c': '8','d': '6'}
</code>```

the output is right :

```<code>['5', '6', '8', '9']
</code>```

Is there something wrong with my result dictionary or is there something I am missing?

答:
Strings are compared one character at a time, so '30' < '4' because '3' < '4'. You need to use a key parameter to get the comparison based on the numeric value, not the string characters.

Also, it's redundant to use a list comprehension on something that already returns a list.

```<code>sortedList = sorted(result.values(), key=int)
</code>```

Body:
I am currently doing an Assignment; however, I got some interesting output which confused me so much.

I am trying to sort the following dictionary:

result = {'A1': '9', 'A2': '14', 'A3': '16', 'A4': '0', 'B1': '53', 'B2': '267', 'B3': '75', 'B4': '22', 'C1': '19', 'C2': '407', 'C3': '171', 'C4': '56', 'C5': '10', 'D3': '47', 'D4': '34', 'D5': '10'}

My sorting code with Python 3 is the following : (only sorted by value)

sortedList = [v for v in sorted(result.values())]

The output is :

['0', '10', '10', '14', '16', '171', '19', '22', '267', '34', '407', '47', '53', '56', '75', '9']

which is not fully sorted. The output is quite strange.

Why it is happened like this?
I have used another dict to test like this:

testD = {'A':'5','B': '9','c': '8','d': '6'}

the output is right :

['5', '6', '8', '9']

Is there something wrong with my result dictionary or is there something I am missing?

Body:
Strings are compared one character at a time, so '30' < '4' because '3' < '4'. You need to use a key parameter to get the comparison based on the numeric value, not the string characters.

Also, it's redundant to use a list comprehension on something that already returns a list.

sortedList = sorted(result.values(), key=int)


问:
Java enhanced enhanced for loop
Currently (as of Java 6), using Java's enhanced for-loop I do not know of any way to directly access the iterator index short of reverting to the old indexed for-loop or using an outside counter.

Are there plans (or perhaps a current way) to implement this "enhanced enhanced" for-loop where one would be able to access the index of the loop (and even possibly manipulate it)?

As an example where this might be needed, consider(this is from actual production code):

```<code>int i = 1;
for (final String action : actions) {
  parameters.set(String.valueOf(i++), action);
}
</code>```

答: No. Use an outside variable.</p>

Title: Java enhanced enhanced for loop

Body:
Currently (as of Java 6), using Java's enhanced for-loop I do not know of any way to directly access the iterator index short of reverting to the old indexed for-loop or using an outside counter.

Are there plans (or perhaps a current way) to implement this "enhanced enhanced" for-loop where one would be able to access the index of the loop (and even possibly manipulate it)?

As an example where this might be needed, consider(this is from actual production code):

int i = 1;
for (final String action : actions) {
  parameters.set(String.valueOf(i++), action);
}

Body: No. Use an outside variable.

ContentLicense: CC BY-SA 2.5


问:
Remove cells from word table with Novacode DocX
How do I remove a single cell from a word table using Novacode DocX?

I have tried:

```<code>table.Rows[0].Cells.RemoveAt(2);
</code>```

and

```<code>Cell c = table.Rows[0].Cells[2];
table.Rows[0].Cells.Remove(c);
</code>```

and

```<code>table.Rows[0].Cells.RemoveRange(2,4);
</code>```

None of them remove any cells.

答:
In the Table class you can use the methods

```<code>MergeCells(int, int)
</code>```

and

```<code>MergeCellsInColumn(int, int, int)
</code>```

to 'remove' cells.

See: https://docx.codeplex.com/SourceControl/latest#DocX/Table.cs

Body:
How do I remove a single cell from a word table using Novacode DocX?

I have tried:

table.Rows[0].Cells.RemoveAt(2);

and

Cell c = table.Rows[0].Cells[2];
table.Rows[0].Cells.Remove(c);

and

table.Rows[0].Cells.RemoveRange(2,4);

None of them remove any cells.

Body:
In the Table class you can use the methods

MergeCells(int, int)

and

MergeCellsInColumn(int, int, int)

to 'remove' cells.

See: https://docx.codeplex.com/SourceControl/latest#DocX/Table.cs


问:
How to parse RESTful API params with Dropwizard
Let's say I have:

```<code>@GET
public UserList fetch(@PathParam("user") String userId) {
    // Do stuff here
}
</code>```

Now, let's say I have my own type for userId, let's call it UserId. Is it possible to parse that String to UserId when it is passed into the fetch method, i.e.:

```<code>@GET
public UserList fetch(@PathParam("user") UserId userId) {
    // Do stuff here
}
</code>```

I realize I can parse the String once I am inside the method, but it would be more convenient that my method gets the type I want.

答:
Well you've attempted to make a GET call with a request body is what I find not very helpful. Do read Paul's answer here -

you can send a body with GET, and no, it is never useful to do so

What would be good to practice is, to make a PUT or a POST call (PUT vs POST in REST) as follows -

```<code>@POST
@Path("/some-path/{some-query-param}")
public Response getDocuments(@ApiParam("user") UserId userId,
                             @PathParam("some-query-param") String queryParam) {
    UserId userIdInstance = userId; // you can use the request body further
</code>```

Note - The ApiParam annotation used is imported from the com.wordnik.swagger.annotations package. You can similarily use FormParam,QueryParam according to your source of input.

Body:
Let's say I have:

@GET
public UserList fetch(@PathParam("user") String userId) {
    // Do stuff here
}

Now, let's say I have my own type for userId, let's call it UserId. Is it possible to parse that String to UserId when it is passed into the fetch method, i.e.:

@GET
public UserList fetch(@PathParam("user") UserId userId) {
    // Do stuff here
}

I realize I can parse the String once I am inside the method, but it would be more convenient that my method gets the type I want.

Body:
Well you've attempted to make a GET call with a request body is what I find not very helpful. Do read Paul's answer here -

you can send a body with GET, and no, it is never useful to do so

What would be good to practice is, to make a PUT or a POST call (PUT vs POST in REST) as follows -

@POST
@Path("/some-path/{some-query-param}")
public Response getDocuments(@ApiParam("user") UserId userId,
                             @PathParam("some-query-param") String queryParam) {
    UserId userIdInstance = userId; // you can use the request body further

Note - The ApiParam annotation used is imported from the com.wordnik.swagger.annotations package. You can similarily use FormParam,QueryParam according to your source of input.


问:
How to display output in HTML table based on output to determine which column it belongs to Flask
My Flask would called an exe program. And when it runs, it would concatenate the output and return a string to html like this:

File1.dll
Encryption Passed
Validation Passed
File2.dll
Encryption Passed
Validation Passed
File3.dll
Encryption Passed
Validation Passed

Then I loop it and display it in list from by splitting the
. My html looks like this:

```<code><ul>
{% for out in outputLog.split("<br>")%}
  <li>{{ out }} </li>
{% endfor %}
</ul>
</code>```

However, I want my output to display in this way in a table form where it will check the output of the message and determine which column it should belongs to.

My table headings are:

File Name | Encryption Status | Validation Status

I want to do something like this:

```<code>if out == "Encryption Passed":
   print at "Encryption Status" column
elif out == "Validation Passed":
   print at "Validation Status" column
else:
   print at "File Name" column
</code>```

Does it possible and how to do that? Or is there any better solution to this?

答:
You probably want to define a function that parses your data, and then use that in your template.

```<code>In [4]: def split_to_rows(result):
   ...:     items = result.split('< br >')
   ...:     row = []
   ...:     for item in items:
   ...:         if not (item.startswith('Encryption') or item.startswith('Validation')):
   ...:             if len(row) > 0: yield row
   ...:             row = []
   ...:         row.append(item)
   ...:     if len(row) > 0: yield row # make sure to yield final row
   ...:

In [5]: s = 'File1.dll< br >Encryption Passed< br >Validation Passed< br >File2.dll< br >Encryption Passed< br >Validation Passed< br >File3.dll< br >Encryption Passed< br >Valid
   ...: ation Passed< br >'

In [6]: list(split_to_rows(s)) # lets see what the output looks like
Out[6]:
[['File1.dll', 'Encryption Passed', 'Validation Passed'],
 ['File2.dll', 'Encryption Passed', 'Validation Passed'],
 ['File3.dll', 'Encryption Passed', 'Validation Passed'],
 ['']]
</code>```

Now the template will look something like:

```<code><table>
<thead> ... </thead>
<tbody>
{% for row in split_to_rows(outputLog) %}
<tr>
    {% for out in row %}
        <td>{{ out }} </td>
    {% endfor %}
</tr>
{% endfor %}
</tbody>
</table>
</code>```

Body:
My Flask would called an exe program. And when it runs, it would concatenate the output and return a string to html like this:

File1.dll
Encryption Passed
Validation Passed
File2.dll
Encryption Passed
Validation Passed
File3.dll
Encryption Passed
Validation Passed

Then I loop it and display it in list from by splitting the
. My html looks like this:

{% for out in outputLog.split("
")%}

{{ out }}

{% endfor %}

However, I want my output to display in this way in a table form where it will check the output of the message and determine which column it should belongs to.

My table headings are:

File Name | Encryption Status | Validation Status

I want to do something like this:

if out == "Encryption Passed":
   print at "Encryption Status" column
elif out == "Validation Passed":
   print at "Validation Status" column
else:
   print at "File Name" column

Does it possible and how to do that? Or is there any better solution to this?

Body:
You probably want to define a function that parses your data, and then use that in your template.

In [4]: def split_to_rows(result):
   ...:     items = result.split('< br >')
   ...:     row = []
   ...:     for item in items:
   ...:         if not (item.startswith('Encryption') or item.startswith('Validation')):
   ...:             if len(row) > 0: yield row
   ...:             row = []
   ...:         row.append(item)
   ...:     if len(row) > 0: yield row # make sure to yield final row
   ...:

In [5]: s = 'File1.dll< br >Encryption Passed< br >Validation Passed< br >File2.dll< br >Encryption Passed< br >Validation Passed< br >File3.dll< br >Encryption Passed< br >Valid
   ...: ation Passed< br >'

In [6]: list(split_to_rows(s)) # lets see what the output looks like
Out[6]:
[['File1.dll', 'Encryption Passed', 'Validation Passed'],
 ['File2.dll', 'Encryption Passed', 'Validation Passed'],
 ['File3.dll', 'Encryption Passed', 'Validation Passed'],
 ['']]

Now the template will look something like:

<table>
<thead> ... </thead>
<tbody>
{% for row in split_to_rows(outputLog) %}
<tr>
    {% for out in row %}
        <td>{{ out }} </td>
    {% endfor %}
</tr>
{% endfor %}
</tbody>
</table>


问:
Change image with MouseOver
I'm new to javascript and Html , Typed a code that changes the image when the mouse hovers over, it works but i was wondering if there is any better solution because it is very long and repetitive ;
Here is the code : </p>

```<code><doctype html>
<html>
<head>
</head>
<body>
    <table>
        <tr>
            <td>
                <img src="image1.jpg" height="200px" width="300px"
onmouseover="rollover(this)" onmouseout="mouseaway(this)/>
            </td>
            <td>
                <img src="image2.jpg" height="200px" width="300px"
onmouseover="rollover1(this)" onmouseout="mouseaway1(this)"/>
            </td>
        </tr>
        <tr>
            <td>
                <img src="image3.jpg" height="200px" width="300px"
onmouseover="rollover2(this)" onmouseout="mouseaway2(this)"/>
            </td>
            <td>
                <img src="image4.jpg" height="200px" width="300px"
onmouseover="rollover3(this)" onmouseout="mouseaway3(this)"/>
            </td>
        </tr>
    </table>
<script language="javascript">
function rollover(img1)
{
    img1.src = 'image2.jpg';
}
function mouseaway(img1)
{
    img1.src = "image1.jpg";
}
function rollover1(img2)
{
    img2.src='image3.jpg';
}
function mouseaway1(img2)
{
    img2.src='image2.jpg'
}
function rollover2(img3)
{
    img3.src='image4.jpg';
}
function mouseaway2(img3)
{
    img3.src='image3.jpg'
}
function rollover3(img4)
{
    img4.src='image1.jpg';
}
function mouseaway3(img4)
{
    img4.src='image4.jpg'
}

</script>
</body>
</html>
</code>```

答:
Simple answer is :</p>

```<code><img onmouseover="this.src='image2.jpg'" onmouseout="this.src='image1.jpg'" height="200px" width="300px" src="image1.jpg">
</code>```

Title: Change image with MouseOver

Body:
I'm new to javascript and Html , Typed a code that changes the image when the mouse hovers over, it works but i was wondering if there is any better solution because it is very long and repetitive ;
Here is the code :

<doctype html>

Body:
Simple answer is :

<img onmouseover="this.src='image2.jpg'" onmouseout="this.src='image1.jpg'" height="200px" width="300px" src="image1.jpg">


问:
*** Collection <__NSArrayM: 0x117d7320> was mutated while being enumerated.'
I made a bug when I implement the search function. I opened an asynchronous thread. But when deleting a character (a digit of a phone number), the app would crash.

Error:

*** Terminating app due to uncaught exception 'NSGenericException', reason: '*** Collection <__NSArrayM: 0x117d7320> was mutated while being enumerated.'

Code:

```<code>- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText{
    //
    self.isSearch = YES;

    //remove the last search all the contacts
    [self.resultArr removeAllObjects];
    //
    [self.rcs_SearchTableView reloadData];
    //
    dispatch_queue_t uploadQueue = dispatch_get_global_queue(0, 0);
    dispatch_queue_t getMainQueue = dispatch_get_main_queue();
    dispatch_async(uploadQueue, ^{

        NSMutableArray *phoneArr = (NSMutableArray *)[self rcs_GetPhoneNumberFromeDatabaseWithPhone:searchText];
        //
        //NSLog(@"清空上次搜索的数据:%@", self.resultArr);
        //NSLog(@"输入的关键字是---%@---%lu",searchText,(unsigned long)searchText.length);
        if (0 == searchText.length || [searchText isEqualToString:@" "]) {
            self.isSearch = NO;
            //[self.rcs_SearchTableView reloadData];
            [self.resultArr removeAllObjects];
        }
        //[self.rcs_SearchTableView reloadData];

        if (0 != phoneArr.count) {
            //
            for (NSUInteger i = 0; i < phoneArr.count; i ++) {

                RCSPhoneModel *flagPhoneModel = phoneArr[i];

                for (NSUInteger i = 0; i < self.rcsRecentSearchDataSource.count; i ++) {

                    RCSContactModel *flagModel = self.rcsRecentSearchDataSource[i];

                    if ([flagPhoneModel.serverId isEqualToString:flagModel.serverId] || [flagPhoneModel.phone isEqualToString:flagModel.name]) {

                        //the same contact has multiple Numbers To prevent repeated add the same contacts
                        if (![self.resultArr containsObject:flagModel]) {

                            [self.resultArr addObject:flagModel];
                            continue;
                        }
                    }
                }
            }

        }else{
            //search contacts by name

            for (NSInteger i = 0; i < self.rcsRecentSearchDataSource.count; i ++) {
                RCSContactModel *model = self.rcsRecentSearchDataSource[i];
                NSString *nameStr = model.name;
                if (nameStr.length >= searchText.length) {
                    //search all the name
                    if ([nameStr containsString:searchText]) {
                        [self.resultArr addObject:model];
                    }
                }
            }
        }
        //
        if (self.resultArr.count > 0) {
            self.isSearch = YES;
            //[self.rcs_SearchTableView reloadData];
        }
        //The phone contacts or local contact synchronized to the server
        dispatch_async(getMainQueue, ^{

            [self.rcs_SearchTableView reloadData];
        });
    });
}
</code>```

答:
A for loop should not enumerate anything that could change on any other thread or that could change within that loop.  You should only enumerate an object that you are certain is not going to change while being enumerated (either in another thread, or within the loop itself).  One way to do this is to only use a local copy of the array to enumerate over.

I can't see where anything being enumerated in your for loops is changed within the loop, so I would guess that in some other code in some other thread, you are changing either self.rcsRecentSearchDataSource or phoneArr.  This crashes the for loop that enumerates self.rcsRecentSearchDataSource or phoneArr because it is required to not change while being enumerated.

Does this really need to be run on a separate thread?

If so, use a thread-local copy of the array to enumerate over, instead of the original array.  That way you can be sure that nothing else can modify it, because it does not exist in any other scope.

Eg, there are two places where you could change your code to:

```<code>NSArray *localSearchDataSource = [self.rcsRecentSearchDataSource copy];

for (NSUInteger i = 0; i < localSearchDataSource.count; i ++) {
</code>```

and one place where you could change to:

```<code>NSArray *localPhoneArr = [[self rcs_GetPhoneNumberFromeDatabaseWithPhone:searchText] copy];

for (NSUInteger i = 0; i < localPhoneArr .count; i ++) {
</code>```

Body:
I made a bug when I implement the search function. I opened an asynchronous thread. But when deleting a character (a digit of a phone number), the app would crash.

Error:

*** Terminating app due to uncaught exception 'NSGenericException', reason: '*** Collection <__NSArrayM: 0x117d7320> was mutated while being enumerated.'

Code:

- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText{
    //
    self.isSearch = YES;

    //remove the last search all the contacts
    [self.resultArr removeAllObjects];
    //
    [self.rcs_SearchTableView reloadData];
    //
    dispatch_queue_t uploadQueue = dispatch_get_global_queue(0, 0);
    dispatch_queue_t getMainQueue = dispatch_get_main_queue();
    dispatch_async(uploadQueue, ^{

        NSMutableArray *phoneArr = (NSMutableArray *)[self rcs_GetPhoneNumberFromeDatabaseWithPhone:searchText];
        //
        //NSLog(@"清空上次搜索的数据:%@", self.resultArr);
        //NSLog(@"输入的关键字是---%@---%lu",searchText,(unsigned long)searchText.length);
        if (0 == searchText.length || [searchText isEqualToString:@" "]) {
            self.isSearch = NO;
            //[self.rcs_SearchTableView reloadData];
            [self.resultArr removeAllObjects];
        }
        //[self.rcs_SearchTableView reloadData];

        if (0 != phoneArr.count) {
            //
            for (NSUInteger i = 0; i < phoneArr.count; i ++) {

                RCSPhoneModel *flagPhoneModel = phoneArr[i];

                for (NSUInteger i = 0; i < self.rcsRecentSearchDataSource.count; i ++) {

                    RCSContactModel *flagModel = self.rcsRecentSearchDataSource[i];

                    if ([flagPhoneModel.serverId isEqualToString:flagModel.serverId] || [flagPhoneModel.phone isEqualToString:flagModel.name]) {

                        //the same contact has multiple Numbers To prevent repeated add the same contacts
                        if (![self.resultArr containsObject:flagModel]) {

                            [self.resultArr addObject:flagModel];
                            continue;
                        }
                    }
                }
            }

        }else{
            //search contacts by name

            for (NSInteger i = 0; i < self.rcsRecentSearchDataSource.count; i ++) {
                RCSContactModel *model = self.rcsRecentSearchDataSource[i];
                NSString *nameStr = model.name;
                if (nameStr.length >= searchText.length) {
                    //search all the name
                    if ([nameStr containsString:searchText]) {
                        [self.resultArr addObject:model];
                    }
                }
            }
        }
        //
        if (self.resultArr.count > 0) {
            self.isSearch = YES;
            //[self.rcs_SearchTableView reloadData];
        }
        //The phone contacts or local contact synchronized to the server
        dispatch_async(getMainQueue, ^{

            [self.rcs_SearchTableView reloadData];
        });
    });
}

Body:
A for loop should not enumerate anything that could change on any other thread or that could change within that loop.  You should only enumerate an object that you are certain is not going to change while being enumerated (either in another thread, or within the loop itself).  One way to do this is to only use a local copy of the array to enumerate over.

I can't see where anything being enumerated in your for loops is changed within the loop, so I would guess that in some other code in some other thread, you are changing either self.rcsRecentSearchDataSource or phoneArr.  This crashes the for loop that enumerates self.rcsRecentSearchDataSource or phoneArr because it is required to not change while being enumerated.

Does this really need to be run on a separate thread?

If so, use a thread-local copy of the array to enumerate over, instead of the original array.  That way you can be sure that nothing else can modify it, because it does not exist in any other scope.

Eg, there are two places where you could change your code to:

NSArray *localSearchDataSource = [self.rcsRecentSearchDataSource copy];

for (NSUInteger i = 0; i < localSearchDataSource.count; i ++) {

and one place where you could change to:

NSArray *localPhoneArr = [[self rcs_GetPhoneNumberFromeDatabaseWithPhone:searchText] copy];

for (NSUInteger i = 0; i < localPhoneArr .count; i ++) {


问:
Time complexity of c++ array loop
i have the following loop but am unable to calculate the complexity .I need help

```<code>int A[n][n];
for(int i=0; i<n;i++) {
    for(int j=0;j<n;j++) {
        int x;
        cin >> x;
        A[i][j] = x;
    }
}
int sumLine = 0;
for(int k=0;k<n;k++) {
    sumLine += A[k][0];
}
</code>```

i would appreciate

答:
You have three loops that you need to analyze.  The first two are a set of nested loops: every time the inner (j) loop runs n times, the outer (i) loop runs once.  Because the outer loop eventually runs n times, the whole set will run n*n = n^2 times, so we say that set of loops runs in O(n^2) time.  Once these loops complete, the third (k) loop runs n times, which is O(n) time.

When you have two separate operations with different big-O complexities and want to add the complexities together to get their total, you take the larger of the two.  Since O(n^2) is "larger" than O(n), we say that the entire program runs in O(n^2) time.

Title: Time complexity of c++ array loop

Body:
i have the following loop but am unable to calculate the complexity .I need help

int A[n][n];
for(int i=0; i<n;i++) {
    for(int j=0;j<n;j++) {
        int x;
        cin >> x;
        A[i][j] = x;
    }
}
int sumLine = 0;
for(int k=0;k<n;k++) {
    sumLine += A[k][0];
}

i would appreciate


问:
how to separate click event from siblings?
I finally got my nav to show and hide the submenu on click, but what's happening now is that when I click, to have it slideToggle, is affecting its siblings and opening and closing at the same time.

my structure look something like this:

Home

Item1

SubItem - 1

SubItem - 2

SubItem - 3

SubItem - 4

SubItem - 5

Item - 2

SubItem - 1

SubItem - 2

SubItem - 3

SubItem - 4

SubItem - 5

Item - 3

            <
SubItem - 1

SubItem - 2

SubItem - 3

SubItem - 4

SubItem - 5

Item - 4

Item - 5

About

Services

Blog

Contact

```
</div>
</div>
</p>

<p>and this is my jQuery:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>$('.has-children ul').click(function(e){
    e.stopPropagation();
    var el = (event.target || event.srcElement);
    console.log('clicked');
    $(this).find('ul.submenu').slideToggle();
     $(el).find('span').toggleClass('arrow-down arrow-up');
  });</code>```

So if I click on the li with the class of has children, all my uls with class of submenu are opening at the same time.
Perhaps I am doing more than I am supposed to here, all the help would be appreciate it.

答:
Your event listener should be on .has-children, and you only want to go one level deep in your $.find() which you can do with $.find('> ul')

$('.has-children').click(function(e) {
  e.stopPropagation();
  var el = (event.target || event.srcElement);
  console.log('clicked');
  $(this).find('> ul').slideToggle();
  $(el).find('span').toggleClass('arrow-down arrow-up');
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.submenu, .top-menu {
  display: none;
}</code>```

Home

Item1

SubItem - 1

SubItem - 2

SubItem - 3

SubItem - 4

SubItem - 5

Item - 2

SubItem - 1

SubItem - 2

SubItem - 3

SubItem - 4

SubItem - 5

Item - 3

SubItem - 1

SubItem - 2

SubItem - 3

SubItem - 4

SubItem - 5

Item - 4

Item - 5

About

Services

Blog

Contact

```

Body:
I finally got my nav to show and hide the submenu on click, but what's happening now is that when I click, to have it slideToggle, is affecting its siblings and opening and closing at the same time.

my structure look something like this:

Home

Item1

SubItem - 1

SubItem - 2

SubItem - 3

SubItem - 4

SubItem - 5

Item - 2

SubItem - 1

SubItem - 2

SubItem - 3

SubItem - 4

SubItem - 5

Item - 3

            <
SubItem - 1

SubItem - 2

SubItem - 3

SubItem - 4

SubItem - 5

Item - 4

Item - 5

About

Services

Blog

Contact

and this is my jQuery:

$('.has-children ul').click(function(e){
    e.stopPropagation();
    var el = (event.target || event.srcElement);
    console.log('clicked');
    $(this).find('ul.submenu').slideToggle();
     $(el).find('span').toggleClass('arrow-down arrow-up');
  });

So if I click on the li with the class of has children, all my uls with class of submenu are opening at the same time.
Perhaps I am doing more than I am supposed to here, all the help would be appreciate it.

Body:
Your event listener should be on .has-children, and you only want to go one level deep in your $.find() which you can do with $.find('> ul')

$('.has-children').click(function(e) {
  e.stopPropagation();
  var el = (event.target || event.srcElement);
  console.log('clicked');
  $(this).find('> ul').slideToggle();
  $(el).find('span').toggleClass('arrow-down arrow-up');
});

.submenu, .top-menu {
  display: none;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<nav>
  <ul>
    <li class="has-children"><a href="#">Home
      <span class="arrow arrow-down"></span>
      </a>
       <ul class="top-menu">
        <li class="has-children"><a href="#">Item1
          <span class="arrow arrow-down arrow-right"></span>
          </a>
           <ul class="submenu">
            <li><a href="#">SubItem - 1 </a></li>
            <li><a href="#">SubItem - 2 </a></li>
            <li><a href="#">SubItem - 3</a></li>
            <li><a href="#">SubItem - 4 </a></li>
            <li><a href="#">SubItem - 5 </a></li>
          </ul>
         </li>
        <li class="has-children"><a href="#">Item - 2
          <span class="arrow arrow-down arrow-right"></span>
          </a>
           <ul class="submenu">
            <li><a href="#">SubItem - 1 </a></li>
            <li><a href="#">SubItem - 2 </a></li>
            <li><a href="#">SubItem - 3</a></li>
            <li><a href="#">SubItem - 4 </a></li>
            <li><a href="#">SubItem - 5 </a></li>
          </ul>
         </li>
        <li class="has-children"><a href="#">Item - 3
          <span class="arrow arrow-down arrow-right"></span>
          </a>
           <ul class="submenu">
            <li><a href="#">SubItem - 1 </a></li>
            <li><a href="#">SubItem - 2 </a></li>
            <li><a href="#">SubItem - 3</a></li>
            <li><a href="#">SubItem - 4 </a></li>
            <li><a href="#">SubItem - 5 </a></li>
          </ul>
         </li>
        <li><a href="#">Item - 4 </a></li>
        <li><a href="#">Item - 5 </a></li>
      </ul>

    </li>
    <li><a href="#">About</a></li>
    <li><a href="#">Services</a></li>
    <li><a href="#">Blog</a></li>
    <li><a href="#">Contact</a></li>
  </ul>
</nav>


问:
product/add of dynamically added inputs not working jquery
I have a form, it is product of values in first row well

I have a form dynamically add input values. Here first row input qty*product = total is working fine, But next added element saving total of first input and passing to all next element.
    Here I want of get all individual of qty * product = total and calculate all total number of input values

Here is my working fiddle

https://jsfiddle.net/jvk3/595hek8y/3/

Here is my jquery script

```<code>    $(document).ready(function() {
        var total_input = 1;
        var temp_arr = [];

        function calculateFinal(){
            var final_val = 0;
            $('.total').each(function(){
                final_val += parseFloat($(this).val());
            });
            $('#final_total').val(final_val);
        }

        jQuery(document).ready(function($){

            temp_arr[0] = total_input;
            $('.my-form .add-box').click(function(){
                var n = $('.text-box').length + 1;
                if( 10 < n ) {
                    alert('Stop it!');
                    return false;
                }
                ++total_input;
                temp_arr.push(total_input);
                var box_html = $('<p class="text-box"> <input type="text" name="size['+total_input+']"  class="add" value="" id="box1' + total_input + '" /> <input type="text" name="qty['+total_input+']" class="add" value="" id="box2' + total_input + '" /> Sub-Total: <input name="sum['+total_input+']" class="total" value=""/> <a href="#" rel="'+total_input+'" class="remove-box">Remove</a></p>');
                jQuery('#my-form').append(box_html);
                box_html.hide();
                $('.my-form p.text-box:last').after(box_html);
                box_html.fadeIn('slow');
                return false;
            });

            $('.my-form').on('click', '.remove-box', function(){
                var this_rel = $(this).attr('rel');
                $(this).parent().css( 'background-color', '#FF6C6C' );
                $(this).parent().fadeOut("slow", function() {
                    var len = temp_arr.length;
                    for(i=0;i<len;i++){
                        if(temp_arr[i] == this_rel){
                            temp_arr.splice(i,1);
                        }
                    }
                    $(this).remove();
                    calculateFinal();
                    $('.box-number').each(function(index){
                        $(this).text( index + 1 );
                    });
                });
                $('span.total').html( $('input.add').sumValues() );

                return false;
            });
        });

        $.fn.sumValues = function(i) {
            var sum = 0;
            this.each(function() {
                if ( $(this).parent().find('input.add') ) {
                    var obj = $(this).parent().find('input.add');
                    if(obj.val()!='' || typeof obj != "undefined"){
                        var val = 0;
                        $(obj).each(function(){
                            val = parseFloat($("#box1").val()*$("#box2").val());

                        });
                        sum += parseFloat( ('0' + val).replace(/[^0-9-\.]/g, ''), 10 );
                        $('input[name="sum['+i+']"]').val(sum);
                    }

                }

            });

            return sum;
        };

        $(document).ready(function() {
            $(document).on('keyup','input.add', function() {
                var len = temp_arr.length;
                for(i=0;i<len;i++){
                    $('input.total').html( $('input[name="sum['+temp_arr[i]+']"]').sumValues(temp_arr[i]) );
                    calculateFinal();
                }
            });

        });
    });
</code>```

答:
Update you keyup event:

```<code>$(document).on('keyup', 'input.add', function() {
    var parent = $(this).closest('.text-box');//get the parent
    var val = parseFloat(parent.find("input:eq(0)").val()) * parseFloat(parent.find("input:eq(1)").val());//calculate using the parent inputs

    $(this).closest('.text-box').find('.total').val(val);//append to the parent total
    calculateFinal();//caculate the total
  });
</code>```

demo:https://jsfiddle.net/gzx5vx59/

for the NaN you can drop some default values in the forms or do some validations

https://jsfiddle.net/gzx5vx59/1/

Body:
I have a form, it is product of values in first row well

I have a form dynamically add input values. Here first row input qty*product = total is working fine, But next added element saving total of first input and passing to all next element.
    Here I want of get all individual of qty * product = total and calculate all total number of input values

Here is my working fiddle

https://jsfiddle.net/jvk3/595hek8y/3/

Here is my jquery script

    $(document).ready(function() {
        var total_input = 1;
        var temp_arr = [];

        function calculateFinal(){
            var final_val = 0;
            $('.total').each(function(){
                final_val += parseFloat($(this).val());
            });
            $('#final_total').val(final_val);
        }

        jQuery(document).ready(function($){

            temp_arr[0] = total_input;
            $('.my-form .add-box').click(function(){
                var n = $('.text-box').length + 1;
                if( 10 < n ) {
                    alert('Stop it!');
                    return false;
                }
                ++total_input;
                temp_arr.push(total_input);
                var box_html = $('
 <input type="text" name="size['+total_input+']"  class="add" value="" id="box1' + total_input + '" /> <input type="text" name="qty['+total_input+']" class="add" value="" id="box2' + total_input + '" /> Sub-Total: <input name="sum['+total_input+']" class="total" value=""/> Remove
');
                jQuery('#my-form').append(box_html);
                box_html.hide();
                $('.my-form p.text-box:last').after(box_html);
                box_html.fadeIn('slow');
                return false;
            });

            $('.my-form').on('click', '.remove-box', function(){
                var this_rel = $(this).attr('rel');
                $(this).parent().css( 'background-color', '#FF6C6C' );
                $(this).parent().fadeOut("slow", function() {
                    var len = temp_arr.length;
                    for(i=0;i<len;i++){
                        if(temp_arr[i] == this_rel){
                            temp_arr.splice(i,1);
                        }
                    }
                    $(this).remove();
                    calculateFinal();
                    $('.box-number').each(function(index){
                        $(this).text( index + 1 );
                    });
                });
                $('span.total').html( $('input.add').sumValues() );

                return false;
            });
        });

        $.fn.sumValues = function(i) {
            var sum = 0;
            this.each(function() {
                if ( $(this).parent().find('input.add') ) {
                    var obj = $(this).parent().find('input.add');
                    if(obj.val()!='' || typeof obj != "undefined"){
                        var val = 0;
                        $(obj).each(function(){
                            val = parseFloat($("#box1").val()*$("#box2").val());

                        });
                        sum += parseFloat( ('0' + val).replace(/[^0-9-\.]/g, ''), 10 );
                        $('input[name="sum['+i+']"]').val(sum);
                    }

                }

            });

            return sum;
        };

        $(document).ready(function() {
            $(document).on('keyup','input.add', function() {
                var len = temp_arr.length;
                for(i=0;i<len;i++){
                    $('input.total').html( $('input[name="sum['+temp_arr[i]+']"]').sumValues(temp_arr[i]) );
                    calculateFinal();
                }
            });

        });
    });

Body:
Update you keyup event:

$(document).on('keyup', 'input.add', function() {
    var parent = $(this).closest('.text-box');//get the parent
    var val = parseFloat(parent.find("input:eq(0)").val()) * parseFloat(parent.find("input:eq(1)").val());//calculate using the parent inputs

    $(this).closest('.text-box').find('.total').val(val);//append to the parent total
    calculateFinal();//caculate the total
  });

demo:https://jsfiddle.net/gzx5vx59/

for the NaN you can drop some default values in the forms or do some validations

https://jsfiddle.net/gzx5vx59/1/


答:
You should parse the data before it gets to Jinja, but to do it purely in Jinja:</p>

```<code><table>
    <tr>
        {% for out in outputLog.split("<br>") %}
            {% if loop.index % 3 == 0 %}
    </tr>
    <tr>
            {% endif %}
        <td>{{ out }} </td>
        {% endfor %}
    </tr>
</table>
</code>```

Title: How to display output in HTML table based on output to determine which column it belongs to Flask

Body:
You should parse the data before it gets to Jinja, but to do it purely in Jinja:

<table>
    <tr>
        {% for out in outputLog.split("<br>") %}
            {% if loop.index % 3 == 0 %}
    </tr>
    <tr>
            {% endif %}
        <td>{{ out }} </td>
        {% endfor %}
    </tr>
</table>


问:
How to extract records from Dstream and write into Cassandra (Spark Streaming)
I am fetching data from Kafka and processing in Spark Streaming and writing Data into Cassandra

I am trying to Filter the DStream records but it doesn't filter the records and write the complete records in Cassandra,

Any suggestion with sample/example Code to filter multiple columns of records and any help will be highly appreciated i have done a research on this but not able to get any solution.

```<code>class SparkKafkaConsumer1(val recordStream : org.apache.spark.streaming.dstream.DStream[String], val streaming : StreamingContext) {

val internationalAddress = recordStream.map(line => line.split("\\|")(10).toUpperCase)

def timeToStr(epochMillis: Long): String =
  DateTimeFormat.forPattern("YYYYMMddHHmmss").print(epochMillis)

if(internationalAddress =="INDIA")
{
print("-----------------------------------------------")
recordStream.print()
val riskScore = "1"
val timestamp: Long = System.currentTimeMillis
val formatedTimeStamp = timeToStr(timestamp)
var wc1 = recordStream.map(_.split("\\|")).map(r=>Row(r(0),r(1),r(2),r(3),r(4).toInt,r(5).toInt,r(6).toInt,r(7),r(8),r(9),r(10),r(11),r(12),r(13),r(14),r(15),r(16),riskScore.toInt,0,0,0,formatedTimeStamp))
implicit val rowWriter = SqlRowWriter.Factory
wc1.saveToCassandra("fraud", "fraudrating", SomeColumns("purchasetimestamp","sessionid","productdetails","emailid","productprice","itemcount","totalprice","itemtype","luxaryitem","shippingaddress","country","bank","typeofcard","creditordebitcardnumber","contactdetails","multipleitem","ipaddress","consumer1score","consumer2score","consumer3score","consumer4score","recordedtimestamp"))

}
</code>```

(Note: I am have records with internationalAddress = INDIA in Kafka and I am very much new to Scala)

答:
I'm not really sure what you're trying to do, but if you are simply trying to filter on records pertaining to India, you could do this:

```<code>implicit val rowWriter = SqlRowWriter.Factory
recordStream
   .filter(_.split("\\|")(10).toUpperCase) == "INDIA")
   .map(_.split("\\|"))
   .map(r => Row(...))
   .saveToCassandra(...)
</code>```

As a side note, I think case classes would be really helpful for you.

Body:
I am fetching data from Kafka and processing in Spark Streaming and writing Data into Cassandra

I am trying to Filter the DStream records but it doesn't filter the records and write the complete records in Cassandra,

Any suggestion with sample/example Code to filter multiple columns of records and any help will be highly appreciated i have done a research on this but not able to get any solution.

class SparkKafkaConsumer1(val recordStream : org.apache.spark.streaming.dstream.DStream[String], val streaming : StreamingContext) {

val internationalAddress = recordStream.map(line => line.split("\\|")(10).toUpperCase)

def timeToStr(epochMillis: Long): String =
  DateTimeFormat.forPattern("YYYYMMddHHmmss").print(epochMillis)

if(internationalAddress =="INDIA")
{
print("-----------------------------------------------")
recordStream.print()
val riskScore = "1"
val timestamp: Long = System.currentTimeMillis
val formatedTimeStamp = timeToStr(timestamp)
var wc1 = recordStream.map(_.split("\\|")).map(r=>Row(r(0),r(1),r(2),r(3),r(4).toInt,r(5).toInt,r(6).toInt,r(7),r(8),r(9),r(10),r(11),r(12),r(13),r(14),r(15),r(16),riskScore.toInt,0,0,0,formatedTimeStamp))
implicit val rowWriter = SqlRowWriter.Factory
wc1.saveToCassandra("fraud", "fraudrating", SomeColumns("purchasetimestamp","sessionid","productdetails","emailid","productprice","itemcount","totalprice","itemtype","luxaryitem","shippingaddress","country","bank","typeofcard","creditordebitcardnumber","contactdetails","multipleitem","ipaddress","consumer1score","consumer2score","consumer3score","consumer4score","recordedtimestamp"))

}

(Note: I am have records with internationalAddress = INDIA in Kafka and I am very much new to Scala)

Body:
I'm not really sure what you're trying to do, but if you are simply trying to filter on records pertaining to India, you could do this:

implicit val rowWriter = SqlRowWriter.Factory
recordStream
   .filter(_.split("\\|")(10).toUpperCase) == "INDIA")
   .map(_.split("\\|"))
   .map(r => Row(...))
   .saveToCassandra(...)

As a side note, I think case classes would be really helpful for you.


问:
TypeError: no implicit conversion of nil into String
Trying to decode a bin file in ruby script but after running the script I get the following error test.rb:57:in read': no implicit conversion of nil into String (TypeError) from script:57:in'

Any idea what could be the problem?

Thanks in advance

```<code>require 'bindata'

class Decode < BinData::Record # size 4+
  uint32le :record_count
  array    :records, :type => :cube_main_bin_record, :initial_length  => :record_count
end

begin
  f = ARGV[0] unless ARGV[0].nil?
  bin = File.read(f)

  Decode.read(bin).records.each_with_index do |rec, num|
    puts "Record #{num} #{rec.to_binary_s.length}"
    p rec
  end
end
</code>```

答:
Because File.read requires a string parameter and f defaults to nil when you invoke the script without a command line argument

```<code>f = ARGV[0] unless ARGV[0].nil?     # f defaults to nil when ARGV[0] is nil
bin = File.read(f)                  # bin = File.read(nil)   BOOM
</code>```

Here is a refactoring of your code:

```<code>...
f = ARGV[0]
abort "filename required" unless f
bin = File.read(f)
...
</code>```

These changes accomplish two things:

When the script is invoked without the required filename, it will gracefully abort with an explanation of the problem.

Simplifies the code by removing unless ARGV[0].nil? which doesn't do anything useful will be misleading to anyone maintaining your code in the future, including yourself

Body:
Trying to decode a bin file in ruby script but after running the script I get the following error test.rb:57:in read': no implicit conversion of nil into String (TypeError) from script:57:in'

Any idea what could be the problem?

Thanks in advance

require 'bindata'

class Decode < BinData::Record # size 4+
  uint32le :record_count
  array    :records, :type => :cube_main_bin_record, :initial_length  => :record_count
end

begin
  f = ARGV[0] unless ARGV[0].nil?
  bin = File.read(f)

  Decode.read(bin).records.each_with_index do |rec, num|
    puts "Record #{num} #{rec.to_binary_s.length}"
    p rec
  end
end

Body:
Because File.read requires a string parameter and f defaults to nil when you invoke the script without a command line argument

f = ARGV[0] unless ARGV[0].nil?     # f defaults to nil when ARGV[0] is nil
bin = File.read(f)                  # bin = File.read(nil)   BOOM

Here is a refactoring of your code:

...
f = ARGV[0]
abort "filename required" unless f
bin = File.read(f)
...

These changes accomplish two things:

When the script is invoked without the required filename, it will gracefully abort with an explanation of the problem.

Simplifies the code by removing unless ARGV[0].nil? which doesn't do anything useful will be misleading to anyone maintaining your code in the future, including yourself


问:
Copy External Folder to Target While Building Jar(Using Maven)
First of all sincere apologies if my question is duplicate, I tried searching but couldn’t find relevant answer to my question

Question: I am creating a Fat jar out of my project using Maven “maven-shade-plugin“, now addition to that I have another Config folder(having some .dll , properties, .init etc files) , which I am referring from project.

Now what I want is, somehow while jar creation(preferably at Maven Build Time),my “config” folder also get copied parallel to the jar.

Using : Maven 3.3.9

Current project Structure:

ProjectParentFolder
     --.git
     --.idea
     --src
     --config
     --pom.xml

Desired output

TargetFolder
        --ProjectParentFolder.jar
        --Config

Note** If this requires to copy config folder to inside some src folder , I can do that ,but after build I want it to be outside jar(preferably parallel to jar).

Please advise, as I have to automate this process in TeamCity/uDeploy as well.

答:
Try to write a shell script which will copy jars from source folder to the folder where it is required.

You can define all required jars in a text file.
Script will read required jars from file and copy it to destination folder.


问:
Replace 2 parts in a single string with other string using JAVA
I have a string like:

```<code>{abc} say hello to {def};
</code>```

or

```<code>You say hello to {abc};
</code>```

Now I want to replace this sentence like this:

```<code>Peter say hello to Sally;
</code>```

or

```<code>You say hello to Peter
</code>```

which {abc} and {def} are user's ID, so I need to get the string inside { }. Then replace these words. How can I get the words inside { }

I tried to use .indexOf and .substring to make it work. But I think it is not a good idea as it need a lot of codes to handle two kinds.
My method:

```<code>String sentence = {abc} say hello to {def};
int firstOpen = sentence.indexOf("{");
int firstClose = sentence.indexOf("}");
int secondOpen = sentence.lastIndexOf("{");
int secondClose = sentence.lastIndexOf("}");
String firstName = sentence.subSting(firstOpen + 1, firstClose);
String secondName = sentence.subSting(secondOpen + 1, secondClose);
...
sentence = "Peter" + sentence.substring(firstClose, secondOpen) .....
</code>```

答:
If you're not sure what word would be inside curly braces, then you can use these regex to make them generic

```<code>input = input.replaceFirst("^\\{([^}]*)\\}", "Peter").replaceFirst("\\{([^}]*)\\};$", "Sally");
</code>```

Output:

```<code>Peter say hello to Sally
</code>```

You can use this program if you want to save the group ids.

Output

```<code>first Id: abc
second Id: def
replaced String: Peter say hello to Sally
</code>```

Code #2

```<code>import java.util.regex.*;

public class HelloWorld {

    public static void main(String[] args) {
        String line = "{abc} say hello to {def};";

        Matcher m = Pattern.compile("^\\{([^}]*)\\}(.*)\\{([^}]*)\\};$").matcher(line);
        if (m.find()) {
            System.out.println("first Id: " + m.group(1));
            System.out.println("second Id: " + m.group(3));
            System.out.println("replaced String: " + "Peter" + m.group(2) + "Sally");
        }
    }
}
</code>```

Body:
I have a string like:

{abc} say hello to {def};

or

You say hello to {abc};

Now I want to replace this sentence like this:

Peter say hello to Sally;

or

You say hello to Peter

which {abc} and {def} are user's ID, so I need to get the string inside { }. Then replace these words. How can I get the words inside { }

I tried to use .indexOf and .substring to make it work. But I think it is not a good idea as it need a lot of codes to handle two kinds.
My method:

String sentence = {abc} say hello to {def};
int firstOpen = sentence.indexOf("{");
int firstClose = sentence.indexOf("}");
int secondOpen = sentence.lastIndexOf("{");
int secondClose = sentence.lastIndexOf("}");
String firstName = sentence.subSting(firstOpen + 1, firstClose);
String secondName = sentence.subSting(secondOpen + 1, secondClose);
...
sentence = "Peter" + sentence.substring(firstClose, secondOpen) .....

Body:
If you're not sure what word would be inside curly braces, then you can use these regex to make them generic

input = input.replaceFirst("^\\{([^}]*)\\}", "Peter").replaceFirst("\\{([^}]*)\\};$", "Sally");

Output:

Peter say hello to Sally

You can use this program if you want to save the group ids.

Output

first Id: abc
second Id: def
replaced String: Peter say hello to Sally

Code #2

import java.util.regex.*;

public class HelloWorld {

    public static void main(String[] args) {
        String line = "{abc} say hello to {def};";

        Matcher m = Pattern.compile("^\\{([^}]*)\\}(.*)\\{([^}]*)\\};$").matcher(line);
        if (m.find()) {
            System.out.println("first Id: " + m.group(1));
            System.out.println("second Id: " + m.group(3));
            System.out.println("replaced String: " + "Peter" + m.group(2) + "Sally");
        }
    }
}


问:
How can I tell which way a scrolling pane is scrolling in javascript?
I have the following jquery to handle scroll events on a particular div and write some content:

```<code>$('#myDiv').scroll(function(eventData) {
  if(eventData.isGoingUp)
    $('#myDiv').prepend('<p>Going up.</p>');
  else
    $('#myDiv').append('<p>Going down.</p>');
});
</code>```

Obviously, evt.isGoingUp doesn't actually exist. Is there anything that does exist that can accomplish this logic?

答:
Hopefully this solution is useful for you... it will work on all elements with class name 'scroll-track'. You must also provide a new attribute to the scrollable element:
data-scroll='{"x":"0", "y":"0"}'
You can test it here: http://jsfiddle.net/CgZDD/

-js-

```<code>$(document).ready(function(){
    // make sure overflow is set to 'scroll'
    $('.scroll-track').css({
        overflow: 'scroll'
    });

    $('.scroll-track').scroll(function() {
        var scrollData = $(this).data('scroll');

        if(scrollData.y > $(this).scrollTop()){
            $('#scrollDir').append($(this).attr('id') + ' up');
        }else if(scrollData.y != $(this).scrollTop()){
            $('#scrollDir').append($(this).attr('id') + ' down');
        }

        if(scrollData.x > $(this).scrollLeft()){
            $('#scrollDir').append($(this).attr('id') + ' left');
        }else if(scrollData.x != $(this).scrollLeft()){
            $('#scrollDir').append($(this).attr('id') + ' right');
        }

        $('#scrollDir').append('<br />');

        scrollData.x = $(this).scrollLeft();
        scrollData.y = $(this).scrollTop();
        $(this).data('scroll', scrollData);
    });
});
</code>```

Body:
I have the following jquery to handle scroll events on a particular div and write some content:

$('#myDiv').scroll(function(eventData) {
  if(eventData.isGoingUp)
    $('#myDiv').prepend('
Going up.
');
  else
    $('#myDiv').append('
Going down.
');
});

Obviously, evt.isGoingUp doesn't actually exist. Is there anything that does exist that can accomplish this logic?

Body:
Hopefully this solution is useful for you... it will work on all elements with class name 'scroll-track'. You must also provide a new attribute to the scrollable element:
data-scroll='{"x":"0", "y":"0"}'
You can test it here: http://jsfiddle.net/CgZDD/

-js-

$(document).ready(function(){
    // make sure overflow is set to 'scroll'
    $('.scroll-track').css({
        overflow: 'scroll'
    });

    $('.scroll-track').scroll(function() {
        var scrollData = $(this).data('scroll');

        if(scrollData.y > $(this).scrollTop()){
            $('#scrollDir').append($(this).attr('id') + ' up');
        }else if(scrollData.y != $(this).scrollTop()){
            $('#scrollDir').append($(this).attr('id') + ' down');
        }

        if(scrollData.x > $(this).scrollLeft()){
            $('#scrollDir').append($(this).attr('id') + ' left');
        }else if(scrollData.x != $(this).scrollLeft()){
            $('#scrollDir').append($(this).attr('id') + ' right');
        }

        $('#scrollDir').append('<br />');

        scrollData.x = $(this).scrollLeft();
        scrollData.y = $(this).scrollTop();
        $(this).data('scroll', scrollData);
    });
});


问:
ignore multiple keypresses in PyGame
I have a program where the user is presented with a word and has to make a two key decision based on it.

Every time the word is presented, I have some code below that monitors their key presses. If they've given an acceptable response (1 or 0), it returns that response, but also delays the program for 1000 ms before doing so, at which point the next word is presented:

```<code>  pygame.event.clear()
  while True:
    for event in pygame.event.get(): #check for keypresses
      if event.key == pygame.K_1:
        wait(1000) #wait 1000 ms if they make a response before the next word is presented
        return 1
      elif event.key == pygame.K_0:
        wait(1000)
        return 0
</code>```

The problem I'm having is that if on a given trial, the user gets impatient and starts pressing buttons during the wait(1000) call, those end up getting registered for the next couple of presented words when the above code is called.

The pygame.event.clear() at the beginning is supposed to clear the event queue, such that if the user has already pressed some keys, it clears the queue and only checks for new responses. What am I doing wrong here?

答:
Do not sleep. Instead, store the time and the key of the previous keypress event.

If the current event is the same key, and the time since the first keypress of this key is below 1 second, blink or beep somehow to indicate that the program is not hung, but does not accept this particular key.

If the key is different from last registered, store the time and the key, then process it as normal.

Always give users instant feedback to their actions, even if the feedback is "this action is not welcome".

Title: ignore multiple keypresses in PyGame

Body:
I have a program where the user is presented with a word and has to make a two key decision based on it.

Every time the word is presented, I have some code below that monitors their key presses. If they've given an acceptable response (1 or 0), it returns that response, but also delays the program for 1000 ms before doing so, at which point the next word is presented:

  pygame.event.clear()
  while True:
    for event in pygame.event.get(): #check for keypresses
      if event.key == pygame.K_1:
        wait(1000) #wait 1000 ms if they make a response before the next word is presented
        return 1
      elif event.key == pygame.K_0:
        wait(1000)
        return 0

The problem I'm having is that if on a given trial, the user gets impatient and starts pressing buttons during the wait(1000) call, those end up getting registered for the next couple of presented words when the above code is called.

The pygame.event.clear() at the beginning is supposed to clear the event queue, such that if the user has already pressed some keys, it clears the queue and only checks for new responses. What am I doing wrong here?


问:
JSON data not showed through phone
Hello guys i have problem where cant display json through phone.Before i don't have this kind of problem.I already check both device using same network.Hope you guys can help me solve this problem.Thank You.

Below Show through my laptop
Below Show through my phone

答:
You need input

```<code>192.168.1.105/android/notis_android.php
</code>```

in your android browser address.

And you need to make sure your Android device and your PC have connected to the same network.

Title: JSON data not showed through phone

Body:
You need input

192.168.1.105/android/notis_android.php

in your android browser address.

And you need to make sure your Android device and your PC have connected to the same network.


答:
You want to make one function and give them an argument as to which image to display. Something like this:

```<code>function rollover(img, src) {
   img.src = src
}
</code>```

Then call the same function on over and out:

```<code><img src="image4.jpg" height="200px" width="300px"
onmouseover="rollover(this,'image1.jpg')" onmouseout="rollover(this,'image4.jpg')"/>
</code>```

This is even easier if you load a library such as jquery. Here's an example using it. You don't even have to have the events repeated. Just give each image a class

```<code><img src="image4.jpg" class="rollover">
</code>```

Then assign events using the class name (classes are identified by the leading .)

```<code>$(document).ready( function() {
     $('.rollover').mouseover( function(e) {
         this.old_src = this.src; // remember what the old src was
         this.src = 'image1.jpg';
     });
     $('.rollover').mouseout( function(e) {
         this.src = this.old_src;
     });
});
</code>```

You wrap it in $(document).ready(...) to ensure the page has loaded before the events are attached.

Title: Change image with MouseOver

Body:
I'm new to javascript and Html , Typed a code that changes the image when the mouse hovers over, it works but i was wondering if there is any better solution because it is very long and repetitive ;
Here is the code :

<doctype html>

Body:
You want to make one function and give them an argument as to which image to display. Something like this:

function rollover(img, src) {
   img.src = src
}

Then call the same function on over and out:

<img src="image4.jpg" height="200px" width="300px"
onmouseover="rollover(this,'image1.jpg')" onmouseout="rollover(this,'image4.jpg')"/>

This is even easier if you load a library such as jquery. Here's an example using it. You don't even have to have the events repeated. Just give each image a class

<img src="image4.jpg" class="rollover">

Then assign events using the class name (classes are identified by the leading .)

$(document).ready( function() {
     $('.rollover').mouseover( function(e) {
         this.old_src = this.src; // remember what the old src was
         this.src = 'image1.jpg';
     });
     $('.rollover').mouseout( function(e) {
         this.src = this.old_src;
     });
});

You wrap it in $(document).ready(...) to ensure the page has loaded before the events are attached.


问:
Mapping a square texture to a triangle
I started to play with a OpenGL ES 1.0 and I run into some (beginners) problem: I tried to map a square texture to the cube described by triangles.

```<code>    // Turn necessary features on
    glEnable(GL_TEXTURE_2D);
    glEnable(GL_BLEND);
    glBlendFunc(GL_ONE, GL_SRC_COLOR);
    glEnable(GL_CULL_FACE);
    //glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);

    // Bind the number of textures we need, in this case one.
    glGenTextures(1, &texture[0]);
    glBindTexture(GL_TEXTURE_2D, texture[0]);
    glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR);

    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);

//Drawing code
static GLfloat rot = 0.0;

static const Vertex3D vertices[] = {
    -1.0f,-1.0f,-1.0f, //0  00
     1.0f,-1.0f,-1.0f, //1  10
     1.0f, 1.0f,-1.0f, //2  11
    -1.0f, 1.0f,-1.0f, //3  01
};

static const int vertexCnt = 3 * 2;

static const GLubyte cube[] = {
    3,0,2,
    1,2,0,
};

static const GLfloat texCoords[] = {
    0,1,
    0,0,
    1,1,
    1,0,
    1,1,
    0,0,
};

glClearColor(0.0, 0.0, 0.0, 1.0);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

glLoadIdentity();

glTranslatef(0.0f, 0.0f, -3.0f);

glBindTexture(GL_TEXTURE_2D, texture[0]);

glEnableClientState(GL_VERTEX_ARRAY);
//glEnableClientState(GL_COLOR_ARRAY);
glEnableClientState(GL_NORMAL_ARRAY);
glEnableClientState(GL_TEXTURE_COORD_ARRAY);
glEnable(GL_COLOR_MATERIAL);

glTexCoordPointer(2, GL_FLOAT, 0, texCoords);
glVertexPointer(3, GL_FLOAT, 0, vertices);

//glColorPointer(4, GL_FLOAT, 0, colors);
glNormalPointer(GL_FLOAT, 0, normals);

glDrawElements(GL_TRIANGLES, vertexCnt, GL_UNSIGNED_BYTE, cube);

glDisableClientState(GL_VERTEX_ARRAY);
//glDisableClientState(GL_COLOR_ARRAY);
glDisableClientState(GL_NORMAL_ARRAY);
glDisableClientState(GL_TEXTURE_COORD_ARRAY);
</code>```

Now, after a zillion attempts, I just can't get it work for other sides...
Is there some rule of thumb for case when mapping square texture to triangles?

EDIT: I think I figure out how the mapping should be done. But it doesn't work for this example (one face). Can someone just please verify if I done mapping correctly (assuming that the rest of code is working)?

Many thanks

答:
I haven't tried to piece through your vertex lists, but my guess is that you have your coordinates entirely messed up and mapping wrong, you have specified your index buffer format incorrectly, or you have back-face culling turned on, and some of your vertices are in the wrong order.

As for the texture coordinates themselves, there should be no trick with mapping to triangles in comparison to quads.  You'll just have to have 6 texture coordinates where previously you would have had four, since there are 6 vertices (two duplicates per face).  You may be able to avoid duplication using an index buffer, as you have with your cube.

As for a potential back-face culling problem, you have to define your vertices in the same order every time.  All clockwise, with respect to the direction the texture will be facing, or all counter-clockwise.

What commands are you using to set up your OpenGL pipeline, and what commands are you using to draw those vertices?  Please add the corresponding code to the question.

Title: Mapping a square texture to a triangle

Body:
I started to play with a OpenGL ES 1.0 and I run into some (beginners) problem: I tried to map a square texture to the cube described by triangles.

    // Turn necessary features on
    glEnable(GL_TEXTURE_2D);
    glEnable(GL_BLEND);
    glBlendFunc(GL_ONE, GL_SRC_COLOR);
    glEnable(GL_CULL_FACE);
    //glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);

    // Bind the number of textures we need, in this case one.
    glGenTextures(1, &texture[0]);
    glBindTexture(GL_TEXTURE_2D, texture[0]);
    glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR);

    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);

//Drawing code
static GLfloat rot = 0.0;

static const Vertex3D vertices[] = {
    -1.0f,-1.0f,-1.0f, //0  00
     1.0f,-1.0f,-1.0f, //1  10
     1.0f, 1.0f,-1.0f, //2  11
    -1.0f, 1.0f,-1.0f, //3  01
};

static const int vertexCnt = 3 * 2;

static const GLubyte cube[] = {
    3,0,2,
    1,2,0,
};

static const GLfloat texCoords[] = {
    0,1,
    0,0,
    1,1,
    1,0,
    1,1,
    0,0,
};

glClearColor(0.0, 0.0, 0.0, 1.0);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

glLoadIdentity();

glTranslatef(0.0f, 0.0f, -3.0f);

glBindTexture(GL_TEXTURE_2D, texture[0]);

glEnableClientState(GL_VERTEX_ARRAY);
//glEnableClientState(GL_COLOR_ARRAY);
glEnableClientState(GL_NORMAL_ARRAY);
glEnableClientState(GL_TEXTURE_COORD_ARRAY);
glEnable(GL_COLOR_MATERIAL);

glTexCoordPointer(2, GL_FLOAT, 0, texCoords);
glVertexPointer(3, GL_FLOAT, 0, vertices);

//glColorPointer(4, GL_FLOAT, 0, colors);
glNormalPointer(GL_FLOAT, 0, normals);

glDrawElements(GL_TRIANGLES, vertexCnt, GL_UNSIGNED_BYTE, cube);

glDisableClientState(GL_VERTEX_ARRAY);
//glDisableClientState(GL_COLOR_ARRAY);
glDisableClientState(GL_NORMAL_ARRAY);
glDisableClientState(GL_TEXTURE_COORD_ARRAY);

Now, after a zillion attempts, I just can't get it work for other sides...
Is there some rule of thumb for case when mapping square texture to triangles?

EDIT: I think I figure out how the mapping should be done. But it doesn't work for this example (one face). Can someone just please verify if I done mapping correctly (assuming that the rest of code is working)?

Many thanks


问:
Getting date and time from a .txt
I am trying to get the date and time from a file I have which is something like this

```<code>"Run01"
"‹L˜^’·","ŽžŠÔŽ²","ÄØ¶Þ“ú•t","ÄØ¶ÞŽž"
"70000 DIV","100ms (1ms/S)","17-03-25","06:16:15.49"

"Á¬ÈÙ","±ÝÌß","“dˆ³Ž²","ºÒÝÄ","½¹°ØÝ¸Þ","•ÏŠ·”ä","µÌ¾¯Ä","Ì¨ÙÀ"
"CH1-1","8956 H-SPEED","200mV","Detector11","OFF","-","-","OFF"
"CH1-2","8956 H-SPEED","200mV","Detector12","OFF","-","-","OFF"
"CH2-1","8956 H-SPEED","200mV","Detector21","OFF","-","-","OFF"
"CH2-2","8956 H-SPEED","200mV","Detector22","OFF","-","-","OFF"
"CH3-1","8956 H-SPEED","200mV","Detector31","OFF","-","-","OFF"
"CH3-2","8956 H-SPEED","200mV","Detector32","OFF","-","-","OFF"
"CH4-1","8956 H-SPEED","200mV","Detector41","OFF","-","-","OFF"
"CH4-2","8956 H-SPEED","200mV","Detector42","OFF","-","-","OFF"

"ŽžŠÔ[s]","CH1-1[V]","CH1-2[V]","CH2-1[V]","CH2-2[V]","CH3-1[V]","CH3-2[V]","CH4-1[V]","CH4-2[V]"
</code>```

where the date and time is located in line 3 after the 2 comma(,)

I'm a bit confused from the examples found on google. Anyone have any idea on how I might do this?

edit*I add some bit of what I done so far,

```<code>#include <iostream>
#include <fstream>
#include <string>

const int LINE = 4;

int draft(){
    std::ifstream fdate("DataFile0001/DataFile_B0001_info.txt");
    std::string s;

    for (int i = 1; i<= LINE; i++)
        std::getline(f,s);

    std::cout << s;
    return 0;
}
</code>```

TO be honest I do not want to compile and run this but rather just root draft.cc as I am going to use it to process the root file I have. But as this is more of a c++ problem rather than root. asking here I think is more appropriate

答:
```<code>for (int i = 1; i<= LINE; i++)
{
    std::getline(f,s);

    if(i == 3)
    {
        size_t pos = s.find_first_of(",");
        pos = s.find_first_of("," , pos+1);

        std::string date = s.substr(pos+2 , s.find_first_of("," , pos+1)-pos-3);

        pos = s.find_first_of("," , pos+1);

        std::string time = s.substr(pos+2 , s.length()-pos-3);

        std::cout << date << std::endl;
        std::cout << time << std::endl;
        break;
    }
}
</code>```

Title: Getting date and time from a .txt

Body:
I am trying to get the date and time from a file I have which is something like this

"Run01"
"‹L˜^’·","ŽžŠÔŽ²","ÄØ¶Þ“ú•t","ÄØ¶ÞŽž"
"70000 DIV","100ms (1ms/S)","17-03-25","06:16:15.49"

"Á¬ÈÙ","±ÝÌß","“dˆ³Ž²","ºÒÝÄ","½¹°ØÝ¸Þ","•ÏŠ·”ä","µÌ¾¯Ä","Ì¨ÙÀ"
"CH1-1","8956 H-SPEED","200mV","Detector11","OFF","-","-","OFF"
"CH1-2","8956 H-SPEED","200mV","Detector12","OFF","-","-","OFF"
"CH2-1","8956 H-SPEED","200mV","Detector21","OFF","-","-","OFF"
"CH2-2","8956 H-SPEED","200mV","Detector22","OFF","-","-","OFF"
"CH3-1","8956 H-SPEED","200mV","Detector31","OFF","-","-","OFF"
"CH3-2","8956 H-SPEED","200mV","Detector32","OFF","-","-","OFF"
"CH4-1","8956 H-SPEED","200mV","Detector41","OFF","-","-","OFF"
"CH4-2","8956 H-SPEED","200mV","Detector42","OFF","-","-","OFF"

"ŽžŠÔ[s]","CH1-1[V]","CH1-2[V]","CH2-1[V]","CH2-2[V]","CH3-1[V]","CH3-2[V]","CH4-1[V]","CH4-2[V]"

where the date and time is located in line 3 after the 2 comma(,)

I'm a bit confused from the examples found on google. Anyone have any idea on how I might do this?

edit*I add some bit of what I done so far,

#include <iostream>
#include <fstream>
#include <string>

const int LINE = 4;

int draft(){
    std::ifstream fdate("DataFile0001/DataFile_B0001_info.txt");
    std::string s;

    for (int i = 1; i<= LINE; i++)
        std::getline(f,s);

    std::cout << s;
    return 0;
}

TO be honest I do not want to compile and run this but rather just root draft.cc as I am going to use it to process the root file I have. But as this is more of a c++ problem rather than root. asking here I think is more appropriate


问:
Convert T-SQL statement into LINQ expression
i am quite new to linq and actually fighting to convert the following t-sql statement into an linq to sql or linq to entities expression:</p>

```<code>SELECT TOP 1
    vm.EventID,
    vmm.VotingMatrixID,
    PersonAcceptedCount = SUM( CAST( vmm.IsAccepted AS INT) )

FROM    VotingMatrixMember vmm

JOIN    VotingMatrix vm
    ON vmm.VotingMatrixID = vm.ID

WHERE vm.EventID = 'abbe3077-24de-45d8-ac04-13dba97c1567'
    AND vm.Deleted = 0
    AND vmm.Deleted = 0

GROUP BY vm.EventID, vmm.VotingMatrixID

ORDER BY PersonAcceptedCount DESC
</code>```

答:
Try this, can not test</p>

```<code>        var firstItem = (
                        from vmm in db.VotingMatrixMember
                        join vm in db.VotingMatrix on vmm.VotingMatrixID equals vm.ID
                        where vm.EventID =  "abbe3077-24de-45d8-ac04-13dba97c1567"
                                                && vm.Deleted = 0
                                                && vmm.Deleted = 0
                        group new {vm, vmm} by new {vm.EventID, vmm.VotingMatrixID} into gr
                        select new
                        {
                            EventID = gr.Key.EventID,
                            VotingMatrixID = gr.Key.VotingMatrixID,
                            PersonAcceptedCount = gr.Sum(x => Convert.ToInt32(x.IsAccepted))
                        }
                        into groupedItem
                        orderby  groupedItem.PersonAcceptedCount descending
                        select groupedItem
                         ).FirstOrDefault();
</code>```

Body:
i am quite new to linq and actually fighting to convert the following t-sql statement into an linq to sql or linq to entities expression:

SELECT TOP 1
    vm.EventID,
    vmm.VotingMatrixID,
    PersonAcceptedCount = SUM( CAST( vmm.IsAccepted AS INT) )

FROM    VotingMatrixMember vmm

JOIN    VotingMatrix vm
    ON vmm.VotingMatrixID = vm.ID

WHERE vm.EventID = 'abbe3077-24de-45d8-ac04-13dba97c1567'
    AND vm.Deleted = 0
    AND vmm.Deleted = 0

GROUP BY vm.EventID, vmm.VotingMatrixID

ORDER BY PersonAcceptedCount DESC

Body:
Try this, can not test

        var firstItem = (
                        from vmm in db.VotingMatrixMember
                        join vm in db.VotingMatrix on vmm.VotingMatrixID equals vm.ID
                        where vm.EventID =  "abbe3077-24de-45d8-ac04-13dba97c1567"
                                                && vm.Deleted = 0
                                                && vmm.Deleted = 0
                        group new {vm, vmm} by new {vm.EventID, vmm.VotingMatrixID} into gr
                        select new
                        {
                            EventID = gr.Key.EventID,
                            VotingMatrixID = gr.Key.VotingMatrixID,
                            PersonAcceptedCount = gr.Sum(x => Convert.ToInt32(x.IsAccepted))
                        }
                        into groupedItem
                        orderby  groupedItem.PersonAcceptedCount descending
                        select groupedItem
                         ).FirstOrDefault();


问:
angular 2 display array of images
i am new to angular 2 , i have an array of images and i want to display all the images in a row but none of them is being displayed even the array is not empty
i am using the img tag as shown in the code

html code:

```<code><div fxLayout="column">

    <div >

    </div>

    <div fxLayout="row" *ngIf="doneLoadingProjectData" >
      <div  *ngFor="let image of images" >
          <img src='image'/>
      </div>

    </div>

</div>
</code>```

答:
Also I believe that the array of images needs to be array (better to use JSON)of links to the images only then will the image show up on the browser when ngFor is used to display each image

```<code><div *ngIf="images">
<ul>
  <li *ngFor="let image of images">
        <img [src]="image.href" />
  </li>
</ul>
</code>```

Also I think Maybe a better would be to use ngOnInit so that all initialization is done when that div is called

```<code><div ngOnInit>
<ul>
  <li *ngFor="let image of images">
        <img [src]="image.href" />
  </li>
</ul>
</code>```

And in the component you can run your code as you wish

```<code> images = [];
 ngOnInit() { type your code here it is similar to a constructor, here you can call your service or factory to get array of images you can initialize images here }
</code>```

Where the image array is something like this

{
    "images" : [
      {
          "name" : "image1",
          "href" : "http://east-nj1.photos.example.org/987/nj1-1234"
      },
      {
          "name" : "image2",
          "href" : "http://east-nj1.photos.example.org/987/nj1-1234"
      },
      {
          "name" : "image3",
          "href" : "http://east-nj1.photos.example.org/987/nj1-1234"
      },
      {
          "name" : "image4",
          "href" : "http://east-nj1.photos.example.org/987/nj1-1234"
      }
    ]
  }

Copy Paste this blockquote in this link you will get an idea how the data is passed link you can access each property of the JSON value as image.name and image.href. Hope you find this usefull

Title: angular 2 display array of images

Body:
Also I believe that the array of images needs to be array (better to use JSON)of links to the images only then will the image show up on the browser when ngFor is used to display each image

<div *ngIf="images">
<ul>
  <li *ngFor="let image of images">
        <img [src]="image.href" />
  </li>
</ul>

Also I think Maybe a better would be to use ngOnInit so that all initialization is done when that div is called

<div ngOnInit>
<ul>
  <li *ngFor="let image of images">
        <img [src]="image.href" />
  </li>
</ul>

And in the component you can run your code as you wish

 images = [];
 ngOnInit() { type your code here it is similar to a constructor, here you can call your service or factory to get array of images you can initialize images here }

Where the image array is something like this

{
    "images" : [
      {
          "name" : "image1",
          "href" : "http://east-nj1.photos.example.org/987/nj1-1234"
      },
      {
          "name" : "image2",
          "href" : "http://east-nj1.photos.example.org/987/nj1-1234"
      },
      {
          "name" : "image3",
          "href" : "http://east-nj1.photos.example.org/987/nj1-1234"
      },
      {
          "name" : "image4",
          "href" : "http://east-nj1.photos.example.org/987/nj1-1234"
      }
    ]
  }

Copy Paste this blockquote in this link you will get an idea how the data is passed link you can access each property of the JSON value as image.name and image.href. Hope you find this usefull