问:
Only printing last line of txt file when reading into struct array in C
I am reading from a txt file into an array of structures. Example txt:

```<code>-4.5 -1 0 0
4.0 1 0 0
8 0 1 2
12.1 0 -6 1
-3.2 2.5 -3.0 4
</code>```

The 4 values of each line correspond to the 4 values in the structure. The file may contain up to 100 lines (MAX is defined as 100). With the following code I am trying to store each line into the respective index of the struct array and then print:

```<code>FILE *fileName = NULL;
typedef struct chargeData_struct {
    double Q, x, y, z;
} ChargeData;
ChargeData values[MAX], *p = values;

fileName = fopen("charge2.txt", "r");
if (fileName == NULL)
{
    printf("ERROR: Could not open file.");
}

int k = 0;
while (fscanf(fileName, "%lf %lf %lf %lf", &p[k].Q, &p[k].x, &p[k].y, &p[k].z) != EOF);
{
    printf("%f %f %f %f\n", p[k].Q, p[k].x, p[k].y, p[k].z);
    k++;
}
fclose(fileName);
</code>```

However, only the last line of the txt file is printed. Is the same index of the struct array being overwritten each time?

答:
```<code>#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>

#define LINE_BUFFER_LEN   (512)
#define RESERVE_NEWLINDE          0
#define AUTO_FILTER_NEWLINDE      1

typedef int (* LINE_READER)(char * pstrLine, int uiBufferLen, void * pvData);

typedef struct st_HW_SSP_CONFIG
{
    const char * pstrConfigPath;
    LINE_READER pfLineReader;
    FILE * pstFile;
    void * pvData;
    int CurrentLine;
    int Flag;
} CONFIG_ST;

int CloseConfig(CONFIG_ST * pstConfig)
{
    if (!pstConfig)
    {
        // record error
        return -1;
    }
    if (fclose(pstConfig->pstFile))
    {
        // record error
    }
    return 0;
}

int OpenConfigFile(const char * pstrFilePath, CONFIG_ST * pstConfig)
{
    FILE * pstFile = NULL;
    if ((!pstrFilePath) || (!pstConfig))
    {
        return -1;
    }
    pstFile = fopen(pstrFilePath, "r");
    if (!pstFile)
    {
        return -1;
    }
    pstConfig->pstFile = pstFile;
    pstConfig->pstrConfigPath = pstrFilePath;
    pstConfig->Flag = RESERVE_NEWLINDE;
    return 0;
}

int IsNullStr(const char *pcStr)
{
    const char *pcTmp = pcStr;
    while ('\0' != *pcTmp)
    {
        if (!isspace(*pcTmp))
        {
            return 0;
        }

        pcTmp++;
    }
    return 1;
}

int IsEffectiveLine(char acFileLineBuffer[LINE_BUFFER_LEN])
{
    if (0 == strlen(&acFileLineBuffer[0]))
    {
        return 0;
    }
    if ('#' == acFileLineBuffer[0]) // strip as a comment line
    {
        return 0;
    }
    if (IsNullStr(&acFileLineBuffer[0]))
    {
        return 0;
    }
    return 1;
}

void FilterNewLine(char* pcLine,  int MaxNumLen)
{
    int uiLen = strlen(pcLine);
    if (uiLen > 1)
    {
        if ('\n' == pcLine[uiLen - 1])
        {
            pcLine[uiLen - 1] = '\0';

            if (uiLen > 2)
            {
                if ('\r' == pcLine[uiLen - 2])
                {
                    pcLine[uiLen - 2] = '\0';
                }
            }
        }
    }
    return;
}

int ReadConfigFile(CONFIG_ST * pstConfig)
{
    char acFileLineBuffer[LINE_BUFFER_LEN] = {0};
    char * pstrRead = NULL;
    int Ret = 0;

    if (!pstConfig)
    {
        return -1;
    }
    if ((!pstConfig->pstFile) || (!pstConfig->pfLineReader))
    {
        return -1;
    }

    rewind(pstConfig->pstFile);
    pstConfig->CurrentLine = 0;

    do
    {
        memset((void *)&acFileLineBuffer[0], 0, LINE_BUFFER_LEN);
        pstrRead = fgets(&acFileLineBuffer[0], LINE_BUFFER_LEN - 1, pstConfig->pstFile);
        if (pstrRead)
        {
            pstConfig->CurrentLine ++;

            if (0 == IsEffectiveLine(acFileLineBuffer))
            {
                continue;
            }

            if (AUTO_FILTER_NEWLINDE == pstConfig->Flag)
            {
                FilterNewLine(acFileLineBuffer, LINE_BUFFER_LEN - 1);
            }

            if (pstConfig->pfLineReader)
            {
                Ret = pstConfig->pfLineReader(&acFileLineBuffer[0],
                                              LINE_BUFFER_LEN,
                                              pstConfig->pvData);

                if (Ret)
                {
                    break;
                }
            }
        }
    }
    while (pstrRead);
    return Ret;
}

int ReadConfigFileEx(const char * pFilePath,
                     LINE_READER pfReader,
                     void * pData, int Flag)
{
    int Ret = 0;
    CONFIG_ST stConfig = {0};

    Ret = OpenConfigFile(pFilePath, &stConfig);
    if (Ret)
    {
        return Ret;
    }

    stConfig.pfLineReader = pfReader;
    stConfig.pvData = pData;
    stConfig.Flag = Flag;
    Ret = ReadConfigFile(&stConfig);
    CloseConfig(&stConfig);
    return Ret;
}

int StringSplit(char *pcStr, char cFlag,
                char * pstArray[], int MaxNum,
                int *pNum)
{
    char * pcStrTemp = 0;
    unsigned int uiIndex = 0;

    pcStrTemp = pcStr;

    while (pcStrTemp)
    {
        pstArray[uiIndex] = pcStrTemp;
        pcStrTemp = strchr(pcStrTemp, cFlag);
        if (pcStrTemp)
        {
            *pcStrTemp = '\0';
            pcStrTemp ++;
            uiIndex ++;
        }
        if (uiIndex >= MaxNum)
        {
            break;
        }
    }

    if (0 != MaxNum)
    {
        *pNum = uiIndex >= MaxNum ? (MaxNum - 1) : uiIndex;
    }
    else
    {
        *pNum = 0;
    }

    return 0;
}

int MyLineReader(char * pstrLine, int uiBufferLen, void * pvData)
{
    printf("Read line:[%s]\r\n", pstrLine);

    char *pArray[8] = {0};
    int Num = 0;
    int index = 0;
    StringSplit(pstrLine, ' ', pArray, 8, &Num);
    for (index = 0; index <= Num; index ++)
    {
        printf("Get value :[%s]\r\n", pArray[index]);
    }

    return 0;
}

int main(int argc, char * argv[])
{
    int ret = 0;

    if (argc != 2)
    {
        printf("Please input file to read.\r\n");
        return 0;
    }

    ret = ReadConfigFileEx(argv[1], MyLineReader, NULL, AUTO_FILTER_NEWLINDE);
    if (ret)
    {
        printf("Open file error.\r\n");
    }

    return 0;
}
</code>```

Body:
I am reading from a txt file into an array of structures. Example txt:

-4.5 -1 0 0
4.0 1 0 0
8 0 1 2
12.1 0 -6 1
-3.2 2.5 -3.0 4

The 4 values of each line correspond to the 4 values in the structure. The file may contain up to 100 lines (MAX is defined as 100). With the following code I am trying to store each line into the respective index of the struct array and then print:

FILE *fileName = NULL;
typedef struct chargeData_struct {
    double Q, x, y, z;
} ChargeData;
ChargeData values[MAX], *p = values;

fileName = fopen("charge2.txt", "r");
if (fileName == NULL)
{
    printf("ERROR: Could not open file.");
}

int k = 0;
while (fscanf(fileName, "%lf %lf %lf %lf", &p[k].Q, &p[k].x, &p[k].y, &p[k].z) != EOF);
{
    printf("%f %f %f %f\n", p[k].Q, p[k].x, p[k].y, p[k].z);
    k++;
}
fclose(fileName);

However, only the last line of the txt file is printed. Is the same index of the struct array being overwritten each time?


来源: stackexchange

问:
Append compiler flags when running make
I would like to append flags to the compiler flags when running make, without altering the Makefile in anyway, e.g.

```<code>make CXX_FLAGS+='-DDEBUG'
</code>```

The above treats "+=" as "=", so it's not the correct symbol.

答:
You just have to modify the variable as override in your Makefile once. And then you can do what you want to do.

Here's the example,

Makefile:

```<code>override CFLAGS+=-g

app: main.c
  gcc $(CFLAGS) -o app main.c
</code>```

Run the make:

```<code>$ make
gcc -g -o app main.c
</code>```

Append the '-Wall' to $CFLAGS from the command:

```<code>$ make CFLAGS=-Wall
gcc -Wall -g -o app main.c
</code>```

Work fine here. And here's manual you can reference.

ContentLicense: CC BY-SA 3.0

Title: Append compiler flags when running make

Body:
I would like to append flags to the compiler flags when running make, without altering the Makefile in anyway, e.g.

make CXX_FLAGS+='-DDEBUG'

The above treats "+=" as "=", so it's not the correct symbol.

Body:
You just have to modify the variable as override in your Makefile once. And then you can do what you want to do.

Here's the example,

Makefile:

override CFLAGS+=-g

app: main.c
  gcc $(CFLAGS) -o app main.c

Run the make:

$ make
gcc -g -o app main.c

Append the '-Wall' to $CFLAGS from the command:

$ make CFLAGS=-Wall
gcc -Wall -g -o app main.c

Work fine here. And here's manual you can reference.


问:
Convert String[][] to ArrayList
I have question about converting String[][] to ArrayList.
For example, I have this data:

```<code>String[][] getList = [ [1, A[B]C, abc],
                       [2, D[,EF, def],
                       [3, GHI,   ghi] ];
</code>```

On ABC and DEF, I put [] and , which mean I can't use replace() method to remove it or all this symbol will be removed. It will processing in servlet and jsp.

I try to use this code below, but still have [] as a result.

```<code>for(int i = 0; i < getList.length; i ++) {
              for(int s = 0; s < getList[i].length; s ++) {
                  list.add(Arrays.asList(getList[i][s]));
              }
         }
</code>```

The result from code above:

```<code>[1]  [A[B]C]  [abc]
[2]  [D[,EF]  [def]
[3]  [GHI]    [ghi]
</code>```

Anyone know how to get only value from String[][] getList and create the result like:

```<code>1  A[B]C  abc
2  D[,EF  def
3  GHI    ghi
</code>```

Should I convert to ArrayList first or String? Thank you...

答:
Your syntax is a little confusing, but assuming you are using Java 8+, you could use a Stream and join each array - and then collect and print it. Like,

```<code>String[][] getList = { { "1", "A[B]C", "abc" }, //
        { "2", "D[,EF", "def" }, //
        { "3", "GHI", "ghi" } };
System.out.print(Stream.of(getList).map(x -> String.join(" ", x)) //
        .collect(Collectors.joining(System.lineSeparator())));
</code>```

Which prints

```<code>1 A[B]C abc
2 D[,EF def
3 GHI ghi
</code>```

Title: Convert String[][] to ArrayList

Body:
I have question about converting String[][] to ArrayList.
For example, I have this data:

String[][] getList = [ [1, A[B]C, abc],
                       [2, D[,EF, def],
                       [3, GHI,   ghi] ];

On ABC and DEF, I put [] and , which mean I can't use replace() method to remove it or all this symbol will be removed. It will processing in servlet and jsp.

I try to use this code below, but still have [] as a result.

for(int i = 0; i < getList.length; i ++) {
              for(int s = 0; s < getList[i].length; s ++) {
                  list.add(Arrays.asList(getList[i][s]));
              }
         }

The result from code above:

[1]  [A[B]C]  [abc]
[2]  [D[,EF]  [def]
[3]  [GHI]    [ghi]

Anyone know how to get only value from String[][] getList and create the result like:

1  A[B]C  abc
2  D[,EF  def
3  GHI    ghi

Should I convert to ArrayList first or String? Thank you...

Body:
Your syntax is a little confusing, but assuming you are using Java 8+, you could use a Stream and join each array - and then collect and print it. Like,

String[][] getList = { { "1", "A[B]C", "abc" }, //
        { "2", "D[,EF", "def" }, //
        { "3", "GHI", "ghi" } };
System.out.print(Stream.of(getList).map(x -> String.join(" ", x)) //
        .collect(Collectors.joining(System.lineSeparator())));

Which prints

1 A[B]C abc
2 D[,EF def
3 GHI ghi


问:
Error with chinese encoding with php
I have a file that contain Chinese character Like this :

```<code>合作伙伴
</code>```

problem and result looks like this :

```<code>ºÏ×÷»ï°é£º
</code>```

Even if I try to print the content in the browser , I get the same encoding problem.

I m sure it's an encoding problem but I can't fix it.

答:
Chinese character encoding is usually gb2312.

try to gb2312 convert to utf-8

$str = iconv('gb2312', 'utf-8', $str);

make sure your file is utf-8 encoding.

Content-type: text/html; charset=utf-8

Title: Error with chinese encoding with php

Body:
I have a file that contain Chinese character Like this :

合作伙伴

problem and result looks like this :

ºÏ×÷»ï°é£º

Even if I try to print the content in the browser , I get the same encoding problem.

I m sure it's an encoding problem but I can't fix it.


问:
Find pid of a process while its rinning on background
I have python sunning on my PC in a Linux machine .

```<code>ps -eaf | grep python
</code>```

But now i dont know the process name say . Python is running on the port 7777. I only know the port no on which python with the bellow command .

```<code>netstat
</code>```

Now i want to find out the pid no of python which is running on port 7777.
as i dont know the process name i only know port no 7777 . are there any command for the same problem .

答:
```<code>sudo netstat -tunlp | grep :7777
</code>```

You can use either netstat (deprecated) or ss, with the same options which are mnemonic:

```<code>-t = TCP
-u = UDP
-n = numeric output
-l = listening ports
-p = pid
</code>```

Another commands that works, apart, from lsof, is fuser (the Linux one because the BSD's is different).

```<code>sudo fuser -n tcp -n 7777
</code>```

Body:
I have python sunning on my PC in a Linux machine .

ps -eaf | grep python

But now i dont know the process name say . Python is running on the port 7777. I only know the port no on which python with the bellow command .

netstat

Now i want to find out the pid no of python which is running on port 7777.
as i dont know the process name i only know port no 7777 . are there any command for the same problem .

Body:
sudo netstat -tunlp | grep :7777

You can use either netstat (deprecated) or ss, with the same options which are mnemonic:

-t = TCP
-u = UDP
-n = numeric output
-l = listening ports
-p = pid

Another commands that works, apart, from lsof, is fuser (the Linux one because the BSD's is different).

sudo fuser -n tcp -n 7777


问:
Remove ith item from a C++ std::vector
How do I remove the ith item from a std::vector?

I know I want to delete the ith element. I have int i; and std::vector<process> pList; where process is a struct. I want to do something equivalent to the following:

```<code>pList.remove(i);
</code>```

答:
An approach to save yourself from linear complexity!

Since vector.erase() is linear complexity, I would suggest that just swap the ith element with the last element and then erase the element at the end (which is actually ith element); that way, you possibly can save yourself from linear complexity. That is just my thought!

Title: Remove ith item from a C++ std::vector

Body:
How do I remove the ith item from a std::vector?

I know I want to delete the ith element. I have int i; and std::vector<process> pList; where process is a struct. I want to do something equivalent to the following:

pList.remove(i);

ContentLicense: CC BY-SA 2.5


答:
You have to use following :

```<code>lsof -i :7777
</code>```

I will show you pid without knowing the process name , but knowing the port no

Title: Find pid of a process while its rinning on background

Body:
You have to use following :

lsof -i :7777

I will show you pid without knowing the process name , but knowing the port no


问:
Detect text on an image & calculate the area used using OpenCv
I want to detect the percentage of the area the text blocks are using on an image. The idea is to reject images that have more than 40% text on it. I saw a very informative and detailed post in detecting text here. The link is having C++ used. I think I can get the idea to use it in python.

However, am not sure what would be the best way to measure the percentage of the area it is using. Is there any implementation of something similar that we could use? I am just getting started with Cv.

I am getting my text as below using python. This is a code I found to work from a forum online.

```<code>import cv2

def captch_ex(file_name):
    img = cv2.imread(file_name)
    img_final = cv2.imread(file_name)
    img2gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    ret, mask = cv2.threshold(img2gray, 180, 255, cv2.THRESH_BINARY)
    image_final = cv2.bitwise_and(img2gray, img2gray, mask=mask)
    ret, new_img = cv2.threshold(image_final, 180, 255, cv2.THRESH_BINARY)

    kernel = cv2.getStructuringElement(cv2.MORPH_CROSS, (3,3))
    dilated = cv2.dilate(new_img, kernel, iterations=9)

    contours, hierarchy = cv2.findContours(dilated, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)

    for contour in contours:

        [x, y, w, h] = cv2.boundingRect(contour)

        if w < 35 and h < 35:
            continue

        cv2.rectangle(img, (x, y), (x + w, y + h), (255, 0, 255), 2)

    cv2.imshow('captcha_result', img)
    cv2.waitKey()

file_name = 'my_image.jpg'
captch_ex(file_name)
</code>```

However, how do I proceed further?

答:
A good starting point is to

Calculate the total area (w*h) of bounding boxes. This corresponds to the total area of the image covered with text.

Compare that with the total number of pixels in the image (rows*cols)

Do note that this value will not be accurate as it is, because there can be different font sizes and line spacings. To determine the exact margin where 40% of the image is covered with text, you should find the threshold by picking several images with around 40% covered with text, both above and below that amount, as identified by humans.

Body:
I want to detect the percentage of the area the text blocks are using on an image. The idea is to reject images that have more than 40% text on it. I saw a very informative and detailed post in detecting text here. The link is having C++ used. I think I can get the idea to use it in python.

However, am not sure what would be the best way to measure the percentage of the area it is using. Is there any implementation of something similar that we could use? I am just getting started with Cv.

I am getting my text as below using python. This is a code I found to work from a forum online.

import cv2

def captch_ex(file_name):
    img = cv2.imread(file_name)
    img_final = cv2.imread(file_name)
    img2gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    ret, mask = cv2.threshold(img2gray, 180, 255, cv2.THRESH_BINARY)
    image_final = cv2.bitwise_and(img2gray, img2gray, mask=mask)
    ret, new_img = cv2.threshold(image_final, 180, 255, cv2.THRESH_BINARY)

    kernel = cv2.getStructuringElement(cv2.MORPH_CROSS, (3,3))
    dilated = cv2.dilate(new_img, kernel, iterations=9)

    contours, hierarchy = cv2.findContours(dilated, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)

    for contour in contours:

        [x, y, w, h] = cv2.boundingRect(contour)

        if w < 35 and h < 35:
            continue

        cv2.rectangle(img, (x, y), (x + w, y + h), (255, 0, 255), 2)

    cv2.imshow('captcha_result', img)
    cv2.waitKey()

file_name = 'my_image.jpg'
captch_ex(file_name)

However, how do I proceed further?


问:
how to create a rank with data on firebase using Angular
I need to create a rank type for my application to list the most qualified products. Any idea?

my firebase

```
products-
| id--
|  |  liked:2
|  |  name: x
| id--
|  |  liked:1
|  |  name: y
| id--
|  |  liked:3
|  |  name: z
```

my application

```
X 2
y 1
z 3
```

i need

```
z 3
X 2
y 1
```

I found this.
Used to invert the

```<code>var ref = new Firebase('https//buzzg**.firebaseio.com/comments');
query = ref.orderByChild('timestamp');
comments = [];
query.once('value', function(snap) {
    snap.forEach(function(ss) {
      comments.push(ss.val());
    });
    comments = comments.reverse();
 });
</code>```

but i don't know implement. because of error in function(ss) inside into (foreach)

答:
```<code>this.rankedItems$ = this.angularfireDatabase.list('products')
  .map(products => products.sort((a, b) => b.liked - a.liked));
</code>```

This will give you an observable of arrays, each of which contains {liked, name} objects, sorted by liked in descending order. You can use this in your template as follows:

```<code><h3>Products ranked by likes</h3>
<ul>
  <li *ngFor="let item of rankedItems$ | async">
    {{item.name}}
  </li>
</ul>
</code>```

Or, you could do

```<code>this.angularfireDatabase.list('products', {query:
  orderByChild: 'liked'
}};
</code>```

but this is limited to sorting in ascending order.

Body:
I need to create a rank type for my application to list the most qualified products. Any idea?

my firebase

products-
| id--
|  |  liked:2
|  |  name: x
| id--
|  |  liked:1
|  |  name: y
| id--
|  |  liked:3
|  |  name: z

my application

X 2
y 1
z 3

i need

z 3
X 2
y 1

I found this.
Used to invert the

var ref = new Firebase('https//buzzg**.firebaseio.com/comments');
query = ref.orderByChild('timestamp');
comments = [];
query.once('value', function(snap) {
    snap.forEach(function(ss) {
      comments.push(ss.val());
    });
    comments = comments.reverse();
 });

but i don't know implement. because of error in function(ss) inside into (foreach)

Body:
this.rankedItems$ = this.angularfireDatabase.list('products')
  .map(products => products.sort((a, b) => b.liked - a.liked));

This will give you an observable of arrays, each of which contains {liked, name} objects, sorted by liked in descending order. You can use this in your template as follows:

<h3>Products ranked by likes</h3>
<ul>
  <li *ngFor="let item of rankedItems$ | async">
    {{item.name}}
  </li>
</ul>

Or, you could do

this.angularfireDatabase.list('products', {query:
  orderByChild: 'liked'
}};

but this is limited to sorting in ascending order.


问:
Converting Sybase ASE-specific *= and =* into LEFT/RIGHT OUTER JOIN
I have some PHP applications running on Sybase ASE 15.0.2, and I need to port them to MicroSoft SQL Server 2008 R2.
Many of the queries use the Sybase-only syntax with *= and =*
Is there an automatic way to convert a query from the Sybase syntax to the standard syntax using LEFT/RIGHT OUTER JOIN ?

答: For future conversion issues experienced by others (we're going from SAP ASE 16.0 to SQL Server 2016) simply select the query in SSMS, execute CTRL+SHIFT+Q to open the query designer. This will convert to SQL Server ANSI standard where possible.</p>


问:
unable to get url as query string parameter in node express js
How do i take URL as query string parameter in node.js.

For eg : When i hit browser with the below url:

http://localhost:3000/key1/https://www.google.com/key2/c , I'm unable to get value1 as "https://www.google.com". I'm getting error in browser saying cannot get querystring. But my code works if I replace url with some random string or number.

答:
The reason it is not working is because your url paramater is not url encoded. If you have slashes, or a variety of other symbols such as :, it will break your params.

For example,

```<code>param1 = thisisastring,
param2 = thisisalsoastring

<ip:port>/param1/param2
</code>```

Okay!

```<code>param1 = thisisastring/somethingelse,
param2 = thisisalsoastring

<ip:port>/param1/param2
</code>```

Broken!

Why?

express sees 3 parameters:

```<code>thisisastring somethingelse thisisalsoastring
</code>```

Solution: URL encode your requests. There are a ton of libraries to do this.

https://www.google.com should be encoded as: https%3A%2F%2Fwww.google.com

Notice no slashes or colons. ;)

Body:
The reason it is not working is because your url paramater is not url encoded. If you have slashes, or a variety of other symbols such as :, it will break your params.

For example,

param1 = thisisastring,
param2 = thisisalsoastring

<ip:port>/param1/param2

Okay!

param1 = thisisastring/somethingelse,
param2 = thisisalsoastring

<ip:port>/param1/param2

Broken!

Why?

express sees 3 parameters:

thisisastring somethingelse thisisalsoastring

Solution: URL encode your requests. There are a ton of libraries to do this.

https://www.google.com should be encoded as: https%3A%2F%2Fwww.google.com

Notice no slashes or colons. ;)


问:
apt-get install overwrite ruby on docker of ubuntu14.04
I do some test in the docker which use clean ubuntu14.04.
I use the below code to install ruby2.0 in the dockerfile:

```<code>RUN apt-add-repository ppa:brightbox/ruby-ng
RUN apt-get update && apt-get -y install \
    ruby2.0 \
    ruby2.0-dev
</code>```

Then i enter the docker.
The issue occur:
when i use

```<code>apt-get install ruby2.0
</code>```

there is no question.
when i use

```<code>apt-get install ruby
</code>```

after apt-get update, apt will find ruby1.9 to install and overwrite the link(/usr/bin/ruby), which means the default ruby version is 1.9 now.

For further development, i can not specify version. And also, i need to let this operation run well at ubuntu14.04 even i know it can pass at ubuntu16.
How can i fix this issue?

And is the apt source in the docker different from ubuntu14.04?

答:
The apt-add-repository doesn't exist. And the official ubuntu:14.04 image doesn't include add-apt-repository by default. You need to install it with

```<code>apt-get update && apt-get install software-properties-common
</code>```

After this, you can install your ruby by,

```<code>add-apt-repository -y ppa:brightbox/ruby-ng
apt-get update && apt-get -y install ruby2.0 ruby2.0-dev
</code>```

I am not sure how your Dockerfile can run without error. But there a tip for you to write a Dockerfile. Always run the command in the container first, before write it to the Dockerfile.

Body:
I do some test in the docker which use clean ubuntu14.04.
I use the below code to install ruby2.0 in the dockerfile:

RUN apt-add-repository ppa:brightbox/ruby-ng
RUN apt-get update && apt-get -y install \
    ruby2.0 \
    ruby2.0-dev

Then i enter the docker.
The issue occur:
when i use

apt-get install ruby2.0

there is no question.
when i use

apt-get install ruby

after apt-get update, apt will find ruby1.9 to install and overwrite the link(/usr/bin/ruby), which means the default ruby version is 1.9 now.

For further development, i can not specify version. And also, i need to let this operation run well at ubuntu14.04 even i know it can pass at ubuntu16.
How can i fix this issue?

And is the apt source in the docker different from ubuntu14.04?

Body:
The apt-add-repository doesn't exist. And the official ubuntu:14.04 image doesn't include add-apt-repository by default. You need to install it with

apt-get update && apt-get install software-properties-common

After this, you can install your ruby by,

add-apt-repository -y ppa:brightbox/ruby-ng
apt-get update && apt-get -y install ruby2.0 ruby2.0-dev

I am not sure how your Dockerfile can run without error. But there a tip for you to write a Dockerfile. Always run the command in the container first, before write it to the Dockerfile.


问:
JavaScript file inclusion. Should I not link in ?
I'm watching Douglas Crockfords "Theory of the DOM" and he mentioned that the location of my script tags can greatly affect the load time of my applications.  Furthermore, he asserts that a script tag should be included as far towards the bottom of the document body as possible.

Is this accurate?

OR

Is this video out of date? (which he actually sites as a reason he didn't lecture on the DOM sooner).

答:
You can also use http://labjs.com/ .

As stated in the project's page:

LABjs (Loading And Blocking JavaScript) is an open-source (MIT license) project supported by Getify Solutions. The core purpose of LABjs is to be an all-purpose, on-demand JavaScript loader, capable of loading any JavaScript resource, from any location, into any page, at any time. Loading your scripts with LABjs reduces resource blocking during page-load, which is an easy and effective way to optimize your site's performance.

LABjs by default will load (and execute) all scripts in parallel as fast as the browser will allow. However, you can easily specify which scripts have execution order dependencies and LABjs will ensure proper execution order. This makes LABjs safe to use for virtually any JavaScript resource, whether you control/host it or not, and whether it is standalone or part of a larger dependency tree of resources.

Using LABjs will replace all that ugly " tag soup" -- that is all the  tags that commonly appear in the  or end of the  of your HTML page. The API is expressive and chaining, to let you specify which scripts to load, and when to wait ("block"), if necessary, for execution before proceeding with further execution. The API also easily allows inline code execution coupling (think: inline  tags).

LABjs is now privileged to benefit from collaboration with Steve Souders, and is aiming to be the single best solution for optimized, flexible, general script loading available.

Title: JavaScript file inclusion. Should I not link in <head>?


问:
2 second interval before the auto save button in form
Can I Make a 2 second interval before the auto-save perform? this code shows my webpage with a single textbox in it, and it auto show my DTRSearch.php result. This code is working perfectly.

```<code><div id="search">
<input type="text" placeholder="Scan" id="t1" name="t1" onkeyup="aa();"
autofocus/></div>

<script type="text/javascript">
function aa(){
xmlhttp=new XMLHttpRequest();
xmlhttp.open("GET","DTRSearch.php?
nmnm="+document.getElementById("t1").value,false);
xmlhttp.send(null);
document.getElementById("searchdiv").innerHTML=xmlhttp.responseText;
document.getElementById("searchdiv").style.visibility='visible';
}
</script>
<div id="searchdiv" style="visibility:hidden; position:absolute">
</div>
</code>```

DTRSearch.php it query a single row, this a simple form with a submit button, i want this form to perform an auto-save but before that it should show the form for 2 second

```<code><form action="GetDTRSearch.php" method="get">
        <input type="text" value="<?php echo  $id_number;>" name="ID_Number" /><br />
        <input type="text" value="<?php echo  $fullname; ?>"name="Fullname" /><br />
        <p class="Ok"><input type="submit" value="Click Confirm" /></p>
</code>```

答:
Change the button to a simple button instead of an input type submit. Instead, add a click listener to the Submit button. The click listener should call a setTimeout() function to execute the form submission after 2 seconds.

```<code><form id="theForm" action="DTRSearch.php" method="get">
        <input type="text" value="<?php echo  $id_number;>" name="ID_Number" /><br />
        <input type="text" value="<?php echo  $fullname; ?>"name="Fullname" /><br />
        <p class="Ok"><button id="submitButton" value="Click Confirm" /></p>
</code>```

Then, assuming you have JQuery, add the following script:

```<code><script>
$(document).ready(function() {
    $("#submitButton").click(function() {
        setTimeout(function() {
            $("#theForm").submit();
        }, 2000);
    });
});
</script>
</code>```

Body:
Can I Make a 2 second interval before the auto-save perform? this code shows my webpage with a single textbox in it, and it auto show my DTRSearch.php result. This code is working perfectly.

<input type="text" placeholder="Scan" id="t1" name="t1" onkeyup="aa();"
autofocus/>

DTRSearch.php it query a single row, this a simple form with a submit button, i want this form to perform an auto-save but before that it should show the form for 2 second

<form action="GetDTRSearch.php" method="get">
        <input type="text" value="<?php echo  $id_number;>" name="ID_Number" />

        <input type="text" value="<?php echo  $fullname; ?>"name="Fullname" />

<input type="submit" value="Click Confirm" />

Body:
Change the button to a simple button instead of an input type submit. Instead, add a click listener to the Submit button. The click listener should call a setTimeout() function to execute the form submission after 2 seconds.

<form id="theForm" action="DTRSearch.php" method="get">
        <input type="text" value="<?php echo  $id_number;>" name="ID_Number" /><br />
        <input type="text" value="<?php echo  $fullname; ?>"name="Fullname" /><br />
        <p class="Ok"><button id="submitButton" value="Click Confirm" /></p>

Then, assuming you have JQuery, add the following script:

<script>
$(document).ready(function() {
    $("#submitButton").click(function() {
        setTimeout(function() {
            $("#theForm").submit();
        }, 2000);
    });
});
</script>


问:
How to restructure the line with proper alignment in shell script
I am trying to get the Software Information from Red Hat. As far as I have tried,

```<code>rpm -qi <softwarename>
</code>```

provides the enough information

from the above information, I do require Name, Version, Release, Vendor, Build Date, & Install Date.

I could able to get the Name Version Release & Install Date by using the following command.(here I have grepped only name and version for simplicity)

```<code>rpm -qi perl-Git | grep -E '^Name      :|^Version     :' | awk -F 'Relocations:|Vendor:' '{print $1}'
</code>```

I have no clue to get the Right side of the Information, since I could not able to find a split string between two fields.
Any suggestions ??

答:
Use --queryformat

```<code>$ rpm -q --queryformat "%{NAME}\n%{VERSION}\n%{RELEASE}\n%{VENDOR}\n%{BUILDTIME}\n%{INSTALLTIME}\n" perl-Git
perl-Git
2.8.0
1.WANdisco.308
(none)
1459260423
1493311622
</code>```

Then you can print it how you like, and parse it how you like.

Body:
I am trying to get the Software Information from Red Hat. As far as I have tried,

rpm -qi <softwarename>

provides the enough information

from the above information, I do require Name, Version, Release, Vendor, Build Date, & Install Date.

I could able to get the Name Version Release & Install Date by using the following command.(here I have grepped only name and version for simplicity)

rpm -qi perl-Git | grep -E '^Name      :|^Version     :' | awk -F 'Relocations:|Vendor:' '{print $1}'

I have no clue to get the Right side of the Information, since I could not able to find a split string between two fields.
Any suggestions ??

Body:
Use --queryformat

$ rpm -q --queryformat "%{NAME}\n%{VERSION}\n%{RELEASE}\n%{VENDOR}\n%{BUILDTIME}\n%{INSTALLTIME}\n" perl-Git
perl-Git
2.8.0
1.WANdisco.308
(none)
1459260423
1493311622

Then you can print it how you like, and parse it how you like.


问:
PHP array_reduce with initial parameter as an array
I have this initial array:

```<code>[
    0 => ['id' => 5, 'value' => 50],
    1 => ['id' => 6, 'value' => 60],
    2 => ['id' => 7, 'value' => 70],
]
</code>```

and want to convert it to:

```<code>[
    5 => ['value' => 50],
    6 => ['value' => 60],
    7 => ['value' => 70],
]
</code>```

At first, I tried to use map, but it can't modify the array keys, so I thought reduce would solve the problem because it reduces the array to a single value, in this case, an array. So I tried:

```<code>array_reduce(
    $array,
    function($carry, $item) {
        return $carry[$item['id']] = $item['value'];
    },
    []
);
</code>```

But it returns this error Cannot use a scalar value as an array. What am I doing wrong? Does array_reduce cannot receive an array as an initial value?

答:
You can do it functionally. I suspect it's not actually more readable however.

```<code>array_combine(
    array_column($a, 'id'),
    array_map(function($v) { return ['value' => $v['value']]; }, $a)
);
</code>```

Or even...

```<code>array_map(
  function($v) { return ['value' => $v['value']]; },
  array_column($a, null, 'id')
)
</code>```

Body:
I have this initial array:

[
    0 => ['id' => 5, 'value' => 50],
    1 => ['id' => 6, 'value' => 60],
    2 => ['id' => 7, 'value' => 70],
]

and want to convert it to:

[
    5 => ['value' => 50],
    6 => ['value' => 60],
    7 => ['value' => 70],
]

At first, I tried to use map, but it can't modify the array keys, so I thought reduce would solve the problem because it reduces the array to a single value, in this case, an array. So I tried:

array_reduce(
    $array,
    function($carry, $item) {
        return $carry[$item['id']] = $item['value'];
    },
    []
);

But it returns this error Cannot use a scalar value as an array. What am I doing wrong? Does array_reduce cannot receive an array as an initial value?

Body:
You can do it functionally. I suspect it's not actually more readable however.

array_combine(
    array_column($a, 'id'),
    array_map(function($v) { return ['value' => $v['value']]; }, $a)
);

Or even...

array_map(
  function($v) { return ['value' => $v['value']]; },
  array_column($a, null, 'id')
)


问:
How to enable C++11 in Qt Creator?
The title is pretty self-descriptive. I've downloaded Qt Creator 2.7.0, and I am trying to compile some basic C++11 code:

```<code>int my_array[5] = {1, 2, 3, 4, 5};
for(int &x : my_array)
{
  x *= 2;
}
</code>```

I'm receiving the following error:

```<code>range based for loops are not allowed in c++ 98 mode
</code>```

Yet, according to this article this version of Qt Creator supports C++11. So how do I enable it?

答:
The only place I have successfully make it work is by searching in:

...\Qt\{5.9; or your version}\mingw{53_32; or your
  version}\mkspecs\win32-g++\qmake.conf:

Then at the line:

```<code>QMAKE_CFLAGS           += -fno-keep-inline-dllexport
</code>```

Edit :

```<code>QMAKE_CFLAGS           += -fno-keep-inline-dllexport -std=c++11
</code>```

Title: How to enable C++11 in Qt Creator?

Body:
The title is pretty self-descriptive. I've downloaded Qt Creator 2.7.0, and I am trying to compile some basic C++11 code:

int my_array[5] = {1, 2, 3, 4, 5};
for(int &x : my_array)
{
  x *= 2;
}

I'm receiving the following error:

range based for loops are not allowed in c++ 98 mode

Yet, according to this article this version of Qt Creator supports C++11. So how do I enable it?

Body:
The only place I have successfully make it work is by searching in:

...\Qt\{5.9; or your version}\mingw{53_32; or your
  version}\mkspecs\win32-g++\qmake.conf:

Then at the line:

QMAKE_CFLAGS           += -fno-keep-inline-dllexport

Edit :

QMAKE_CFLAGS           += -fno-keep-inline-dllexport -std=c++11

ContentLicense: CC BY-SA 4.0


问:
Password Protect HTM files in SPSS?
I created an HTM web report file through the export function after selecting a descriptive statistic report in the output table of SPSS. I want to password protect these HTM files. I cannot see if this option is available through the software itself. Do I have to do this outside of the software on my own, or does SPSS have the ability to provide this protection for me? </p>

答: OUTPUT EXPORT does not provide password-protected encryption,so you would need to do this afterwards.  There is a web report output option including password protection, but it is designed for the Collaboration and Deployment Services system, so it would not be useful for most SPSS Statistics users, student or otherwise.</p>

Title: Password Protect HTM files in SPSS?


问:
java.lang.NoClassDefFoundError: org/hamcrest/SelfDescribing
While running junit test in eclipse I am getting this Exception:

```<code>java.lang.NoClassDefFoundError: org/hamcrest/SelfDescribing
</code>```

I've added junit.jar library file.

I've tried different versions of junit.jar: 4.4, 4.8, etc.

How do I fix this Exception?

答:
This problem is because of your classpath miss hamcrest-core-1.3.jar. To resolve this add hamcrest-core-1.3.jar as you add junit-4.XX.jar into your classpath.

At first, I encounter this problem too, but after I refer to the official site and add hamcrest-core-1.3.jar into classpath with command line, it works properly finally.

```<code>javac -d ../../../../bin/ -cp ~/libs/junit-4.12.jar:/home/limxtop/projects/algorithms/bin  MaxHeapTest.java

java -cp ../../../../bin/:/home/limxtop/libs/junit-4.12.jar:/home/limxtop/libs/hamcrest-core-1.3.jar org.junit.runner.JUnitCore com.limxtop.heap.MaxHeapTest
</code>```

Body:
While running junit test in eclipse I am getting this Exception:

java.lang.NoClassDefFoundError: org/hamcrest/SelfDescribing

I've added junit.jar library file.

I've tried different versions of junit.jar: 4.4, 4.8, etc.

How do I fix this Exception?

Body:
This problem is because of your classpath miss hamcrest-core-1.3.jar. To resolve this add hamcrest-core-1.3.jar as you add junit-4.XX.jar into your classpath.

At first, I encounter this problem too, but after I refer to the official site and add hamcrest-core-1.3.jar into classpath with command line, it works properly finally.

javac -d ../../../../bin/ -cp ~/libs/junit-4.12.jar:/home/limxtop/projects/algorithms/bin  MaxHeapTest.java

java -cp ../../../../bin/:/home/limxtop/libs/junit-4.12.jar:/home/limxtop/libs/hamcrest-core-1.3.jar org.junit.runner.JUnitCore com.limxtop.heap.MaxHeapTest


问:
How to recode variables in table 1 using info from table 2 (in SAS)

The overal goal is to stratify quantitative variables based on their percentile. I would like to break it up into 10 levels (e.g. 10th, 20th, ...100th percentile) and recode it as 1 if it falls into the 10th percentile, 2 if it falls into the 20th percentile, etc. This method needs to be applicable across any data set I plug in and I want this process to be as automated as possible. Below I have generated some test data:

```<code>data test (drop=i);
do i=1 to 1000;
a=round(uniform(1)*4,.01);
b=round(uniform(1)*10,.01);
c=round(uniform(1)*7.5,.01);
output;
end;
stop;
run;
</code>```

The following macro is used to create a table of values that tells you the cut off for the 10 percentiles of each variable. I have added a picture of the example output below the code.

```<code>/*Recode variables based on quartiles from boxplot*/
%macro percentiles(var);
     /* Count the number of values in the strinrecode */
     %let count=%sysfunc(countw(&var));
     /* Loop throurecodeh the total number of values */
     %do i = 1 %to &count;
      %let variables=%qscan(&var,&i,%str(,));
proc univariate data=test noprint;
   var &variables;
   output out=pcts pctlpts  = 10 20 30 40 50 60 70 80 90 100
                    pctlpre  = &variables;
run;
proc transpose data=pcts out=&variables (rename=(col1=&variables) drop=_NAME_ _LABEL_);
run;
     %end;
data percentiles (drop=i);
do i=1 to 10;
recode=i;
percentile=i*10;
output;
end;
stop;
run;

data pcts;
merge percentiles %sysfunc(tranwrd(&var.,%str(,),%str( )));
run;
%mend;
%percentiles(%str(a,b,c));
</code>```

output from above macro

The following code is how I am currently recoding my variables. I use the table generated in the above macro to fill in the cut off points for each percentile for each variable. As you can see, this is very tedious and will become prohibitive if I have a large number of variables to recode. Is there a better process for this or preferably a way I could automate this part?

```<code>data test;
set test;
if a <= .415 then recode_a = 1; else if a <= .785 then recode_a = 2; else if a <= 1.255 then recode_a = 3;
else if a <= 1.61 then recode_a = 4;   else if a <= 2.03 then recode_a = 5; else if a <= 2.42 then recode_a = 6;
else if a <= 2.76 then recode_a = 7; else if a <= 3.18 then recode_a = 8; else if a <= 3.64 then recode_a = 9;
else if a <= 3.99 then recode_a = 10;
if b <= .845 then recode_b = 1; else if b <= 1.88 then recode_b = 2; else if b <= 2.86 then recode_b = 3;
else if b <= 4.005 then recode_b = 4;   else if b <= 5.03 then recode_b = 5; else if b <= 6.07 then recode_b = 6;
else if b <= 6.995 then recode_b = 7; else if b <= 8.035 then recode_b = 8; else if b <= 9.16 then recode_b = 9;
else if b <= 10 then recode_b = 10;
if c <= .86 then recode_c = 1; else if c <= 1.58 then recode_c = 2; else if c <= 2.34 then recode_c = 3;
else if c <= 3.15 then recode_c = 4;   else if c <= 3.85 then recode_c = 5; else if c <= 4.615 then recode_c = 6;
else if c <= 5.315 then recode_c = 7; else if c <= 5.96 then recode_c = 8; else if c <= 6.75 then recode_c = 9;
else if c <= 7.5 then recode_c = 10;
run;

proc print data=test (obs=5);
run;
</code>```

sample of desired output

答:
A different option - PROC RANK. You could probably make it more 'automated' but it's pretty straightforward. Using PROC RANK you could also specify different ways of dealing with ties. Note that it would go from 0 to 9 rather than 1 to 10 but that's trivial to change. </p>

```<code>data test (drop=i);
do i=1 to 1000;
a=round(uniform(1)*4,.01);
b=round(uniform(1)*10,.01);
c=round(uniform(1)*7.5,.01);
output;
end;
stop;
run;

proc rank data=test out=want groups=10;
var a b c;
ranks rankA rankB rankC;
run;
</code>```

Body:
The overal goal is to stratify quantitative variables based on their percentile. I would like to break it up into 10 levels (e.g. 10th, 20th, ...100th percentile) and recode it as 1 if it falls into the 10th percentile, 2 if it falls into the 20th percentile, etc. This method needs to be applicable across any data set I plug in and I want this process to be as automated as possible. Below I have generated some test data:

data test (drop=i);
do i=1 to 1000;
a=round(uniform(1)*4,.01);
b=round(uniform(1)*10,.01);
c=round(uniform(1)*7.5,.01);
output;
end;
stop;
run;

The following macro is used to create a table of values that tells you the cut off for the 10 percentiles of each variable. I have added a picture of the example output below the code.

/*Recode variables based on quartiles from boxplot*/
%macro percentiles(var);
     /* Count the number of values in the strinrecode */
     %let count=%sysfunc(countw(&var));
     /* Loop throurecodeh the total number of values */
     %do i = 1 %to &count;
      %let variables=%qscan(&var,&i,%str(,));
proc univariate data=test noprint;
   var &variables;
   output out=pcts pctlpts  = 10 20 30 40 50 60 70 80 90 100
                    pctlpre  = &variables;
run;
proc transpose data=pcts out=&variables (rename=(col1=&variables) drop=_NAME_ _LABEL_);
run;
     %end;
data percentiles (drop=i);
do i=1 to 10;
recode=i;
percentile=i*10;
output;
end;
stop;
run;

data pcts;
merge percentiles %sysfunc(tranwrd(&var.,%str(,),%str( )));
run;
%mend;
%percentiles(%str(a,b,c));

output from above macro

The following code is how I am currently recoding my variables. I use the table generated in the above macro to fill in the cut off points for each percentile for each variable. As you can see, this is very tedious and will become prohibitive if I have a large number of variables to recode. Is there a better process for this or preferably a way I could automate this part?

data test;
set test;
if a <= .415 then recode_a = 1; else if a <= .785 then recode_a = 2; else if a <= 1.255 then recode_a = 3;
else if a <= 1.61 then recode_a = 4;   else if a <= 2.03 then recode_a = 5; else if a <= 2.42 then recode_a = 6;
else if a <= 2.76 then recode_a = 7; else if a <= 3.18 then recode_a = 8; else if a <= 3.64 then recode_a = 9;
else if a <= 3.99 then recode_a = 10;
if b <= .845 then recode_b = 1; else if b <= 1.88 then recode_b = 2; else if b <= 2.86 then recode_b = 3;
else if b <= 4.005 then recode_b = 4;   else if b <= 5.03 then recode_b = 5; else if b <= 6.07 then recode_b = 6;
else if b <= 6.995 then recode_b = 7; else if b <= 8.035 then recode_b = 8; else if b <= 9.16 then recode_b = 9;
else if b <= 10 then recode_b = 10;
if c <= .86 then recode_c = 1; else if c <= 1.58 then recode_c = 2; else if c <= 2.34 then recode_c = 3;
else if c <= 3.15 then recode_c = 4;   else if c <= 3.85 then recode_c = 5; else if c <= 4.615 then recode_c = 6;
else if c <= 5.315 then recode_c = 7; else if c <= 5.96 then recode_c = 8; else if c <= 6.75 then recode_c = 9;
else if c <= 7.5 then recode_c = 10;
run;

proc print data=test (obs=5);
run;

sample of desired output

Body:
A different option - PROC RANK. You could probably make it more 'automated' but it's pretty straightforward. Using PROC RANK you could also specify different ways of dealing with ties. Note that it would go from 0 to 9 rather than 1 to 10 but that's trivial to change.

data test (drop=i);
do i=1 to 1000;
a=round(uniform(1)*4,.01);
b=round(uniform(1)*10,.01);
c=round(uniform(1)*7.5,.01);
output;
end;
stop;
run;

proc rank data=test out=want groups=10;
var a b c;
ranks rankA rankB rankC;
run;


问:
seaborn pairplot seperate bins in diagonal
```<code>sns.pairplot(iris, hue='class', palette='husl',kind='reg')
plt.show()
</code>```

That is the code I used to generate the plot(picture below).
There is also a picture of how I want it to look.

This is how it looks now:

This is how I want it to look:

答:
```<code>import seaborn as sns;
iris = sns.load_dataset("iris")
sns.pairplot(iris, hue='class')
</code>```

Body:
sns.pairplot(iris, hue='class', palette='husl',kind='reg')
plt.show()

That is the code I used to generate the plot(picture below).
There is also a picture of how I want it to look.

This is how it looks now:

This is how I want it to look:


问:
Export CSV from Mainframe DB2 in batch mode
how can I export in a CSV file the result of a SELECT query from Mainframe DB2 in Batch mode?
I have tried the FILE MANAGER online mode and it works but I need to use the batch mode for a better performance.
I can also use ISQL but I don't know which parameters I have to use to create a CSV file.
Thanks</p>

答:
As you're looking for improved performance I'd suggest you CALL the DSNUTILU stored procedure with the UNLOAD utility using DELIMITED COLDEL ',' and SHRLEVEL CHANGE ISOLATION UR parameters for CSV and to maximise concurrency on your DB2 for z/OS table. There are many other option depending on your requirements.

For reference refer to DSNUTILU stored procedure and Syntax and options of the UNLOAD control statement


问:
I need to escape! Angular $sce not handling links to audio files (Strict Contextual Escaping)
I have Angular and $sce working on my project for displaying HTML special characters, and for a video player's links to video files in my database. But I can't get $sce to connect the HTML audio player to audio files on the same database.

This HTML works:

```<code><audio controls ng-src="https://mydatabase.com/aa6df923">
</code>```

This is the project HTML:

```<code><audio controls ng-src="{{audioSource}}">
</code>```

This doesn't work:

```<code>$scope.audioSource = "https://mydatabase.com/aa6df923";
</code>```

This also doesn't work:

```<code>app.controller('MyController', function($scope, $sce) {
    $scope.audioSource = $sce.trustAsResourceUrl("https://mydatabase.com/aa6df923");
});
</code>```

This doesn't work either:

```<code>app.controller('MyController', function($scope, $sce) {
    $scope.audioSource = $sce.trustAsResourceUrl("https://mydatabase.com/aa6df923");
    $scope.$apply();
});
</code>```

Not this one either:

```<code>$scope.audioSource = "../audio/myFile.mp3";
</code>```

And, finally, this filter works to escape HTML special characters but don't work to link the audio files:

```<code><audio controls ng-src="{{audioSource | trustAsHtml}}">

app.filter('trustAsHtml', [$sce', function($sce) {
    return function(html) {
        return $sce.trustAsHtml(html);
    };
}]);
</code>```

What am I missing?

答: I've started to figure it out. $scope.audioSource is inside a function, which puts it on a new $scope. I.e., {{audioSource}} and $scope.audioSource are on different scopes. I'll work on returning values out of functions and onto the controller's $scope.

Body:
I have Angular and $sce working on my project for displaying HTML special characters, and for a video player's links to video files in my database. But I can't get $sce to connect the HTML audio player to audio files on the same database.

This HTML works:

<audio controls ng-src="https://mydatabase.com/aa6df923">

This is the project HTML:

<audio controls ng-src="{{audioSource}}">

This doesn't work:

$scope.audioSource = "https://mydatabase.com/aa6df923";

This also doesn't work:

app.controller('MyController', function($scope, $sce) {
    $scope.audioSource = $sce.trustAsResourceUrl("https://mydatabase.com/aa6df923");
});

This doesn't work either:

app.controller('MyController', function($scope, $sce) {
    $scope.audioSource = $sce.trustAsResourceUrl("https://mydatabase.com/aa6df923");
    $scope.$apply();
});

Not this one either:

$scope.audioSource = "../audio/myFile.mp3";

And, finally, this filter works to escape HTML special characters but don't work to link the audio files:

<audio controls ng-src="{{audioSource | trustAsHtml}}">

app.filter('trustAsHtml', [$sce', function($sce) {
    return function(html) {
        return $sce.trustAsHtml(html);
    };
}]);

What am I missing?


问:
is there a way to change case to low or high whole block in visual mode vim?
Want to change case to lower in whole block in visual mode.
If i want to change case of a single character, i can press ~, but what i need to use in visual mode for changing in selected area into low or high case ?</p>

答:
The ~ command works on a visually selected block as well.

For example, if you:

Press v to enter visual mode

Highlight the area of text to modify

Press ~

It changes the case of all the highlighted text.


问:
$.focus() not working
The last example of jQuery's focus() documentation states

```<code>$('#id').focus()
</code>```

should make the input focused (active). I can't seem to get this working.

Even in the console on this site, I'm trying it for the search box

```<code>$('input[name="q"]').focus()
</code>```

and I'm getting nothing. Any ideas?

答:
if you use bootstrap + modal, this worked for me :</p>

```<code>  $(myModal).modal('toggle');
  $(myModal).on('shown.bs.modal', function() {
    $('#modalSearchBox').focus()
  });
</code>```

Title: $.focus() not working

Body:
The last example of jQuery's focus() documentation states

$('#id').focus()

should make the input focused (active). I can't seem to get this working.

Even in the console on this site, I'm trying it for the search box

$('input[name="q"]').focus()

and I'm getting nothing. Any ideas?

Body:
if you use bootstrap + modal, this worked for me :

  $(myModal).modal('toggle');
  $(myModal).on('shown.bs.modal', function() {
    $('#modalSearchBox').focus()
  });


问:
Yahoo Finance API / URL not working: Python fix for Pandas DataReader
Yahoo Finance URL has not been accessible using the Pandas DataReader's "yahoo" method since 16 May 2017. I have yet to test this fix-yahoo-finance: https://pypi.python.org/pypi/fix-yahoo-finance that was posted just yesterday, with the statement: "Yahoo! finance has decommissioned their historical data API".

EDIT August 2, 2017: I have since followed the steps in https://pypi.python.org/pypi/fix-yahoo-finance to: $ pip3 install fix_yahoo_finance --upgrade --no-cache-dir, upgraded pandas_datareader to work with "fix-yahoo-finance 0.0.6", and amended codes:

```<code>from pandas_datareader import data as pdr
import fix_yahoo_finance

data = pdr.get_data_yahoo('AAPL', start='2017-04-23', end='2017-05-24')
</code>```

Note that the order of the last 2 data columns are 'Adj Close' and 'Volume' ie. not the previous format. For my purpose, they are simply reset to the original format:

```<code>cols = ['Date', 'Open', 'High', 'Low', 'Close', 'Volume', 'Adj Close']
data.reindex(columns=cols)
</code>```

答:
I like user3443068 answer as it's simple.

I also would suggest looking at using Google as your source as the yahoo instance is probably going to go through many deprecated versions given where the company's going.

```<code>def get_ret(tickers_ls, start_dt, end_dt):
        #create dataframe
        df_ret=pd.DataFrame()

        #get prices for all tickers
        for tk in tickers:
            p = wb.DataReader(tk, "google", start_date, end_date).Close
            df_ret_tmp = p.to_frame()['Close'].reset_index()
            df_ret_tmp['Ticker']=tk
        ## append
            df_ret=df_ret.append(df_ret_tmp)

        #pivot and get into single dataframe
        pivoted = df_ret.pivot(index='Date', columns='Ticker')
        pivoted.columns = pivoted.columns.droplevel(0)

        return pivoted
</code>```

Body:
Yahoo Finance URL has not been accessible using the Pandas DataReader's "yahoo" method since 16 May 2017. I have yet to test this fix-yahoo-finance: https://pypi.python.org/pypi/fix-yahoo-finance that was posted just yesterday, with the statement: "Yahoo! finance has decommissioned their historical data API".

EDIT August 2, 2017: I have since followed the steps in https://pypi.python.org/pypi/fix-yahoo-finance to: $ pip3 install fix_yahoo_finance --upgrade --no-cache-dir, upgraded pandas_datareader to work with "fix-yahoo-finance 0.0.6", and amended codes:

from pandas_datareader import data as pdr
import fix_yahoo_finance

data = pdr.get_data_yahoo('AAPL', start='2017-04-23', end='2017-05-24')

Note that the order of the last 2 data columns are 'Adj Close' and 'Volume' ie. not the previous format. For my purpose, they are simply reset to the original format:

cols = ['Date', 'Open', 'High', 'Low', 'Close', 'Volume', 'Adj Close']
data.reindex(columns=cols)

Body:
I like user3443068 answer as it's simple.

I also would suggest looking at using Google as your source as the yahoo instance is probably going to go through many deprecated versions given where the company's going.

def get_ret(tickers_ls, start_dt, end_dt):
        #create dataframe
        df_ret=pd.DataFrame()

        #get prices for all tickers
        for tk in tickers:
            p = wb.DataReader(tk, "google", start_date, end_date).Close
            df_ret_tmp = p.to_frame()['Close'].reset_index()
            df_ret_tmp['Ticker']=tk
        ## append
            df_ret=df_ret.append(df_ret_tmp)

        #pivot and get into single dataframe
        pivoted = df_ret.pivot(index='Date', columns='Ticker')
        pivoted.columns = pivoted.columns.droplevel(0)

        return pivoted


问:
Pass certain touches through UIScrollView to underlying views
I've got a view that has two subviews:

Subview A, a UIView (contains other views, which contain UIButtons, views with gesturerecognizer ...)

Subview B, a UIScrollView (contains some views, but has transparent regions).

The scrollview is on top of Subview A and has the full device width/height. I want the user to be able to interact - through the transparent regions - with all those buttons and gesture reconizers below the scrollview, while still being able to scroll (so passing on the hittest is out).

Seems like an easy enough task, but I can't get it to work. The scrollview is always blocking all touches.

Any idea how I would accomplish that? Thanks!

答:
Based in René's answer, this works if the background view is fixed (f.e. at the top of the view) and the bottom scroll has bounce.

```<code>#pragma mark - Scroll delegate

-(void)scrollViewDidScroll:(UIScrollView *)scrollView {
    [self updateBottomViewPosition];
}

- (void)updateBottomViewPosition {
    CGPoint contentOffset = self.scrollView.contentOffset;

    CGFloat y = MAX(contentOffset.y, 0);

    CGRect frame = self.fixedView.frame;
    if (y > 0) {
        frame.origin.y = y;
    } else {
        frame.origin.y = 0;
    }
    self.fixedView.frame = frame;
}
</code>```

You can use this to create also a nice paralax effect, if you don't want it to be fixed you should change the y value to your wanted transition movement.

Body:
Based in René's answer, this works if the background view is fixed (f.e. at the top of the view) and the bottom scroll has bounce.

#pragma mark - Scroll delegate

-(void)scrollViewDidScroll:(UIScrollView *)scrollView {
    [self updateBottomViewPosition];
}

- (void)updateBottomViewPosition {
    CGPoint contentOffset = self.scrollView.contentOffset;

    CGFloat y = MAX(contentOffset.y, 0);

    CGRect frame = self.fixedView.frame;
    if (y > 0) {
        frame.origin.y = y;
    } else {
        frame.origin.y = 0;
    }
    self.fixedView.frame = frame;
}

You can use this to create also a nice paralax effect, if you don't want it to be fixed you should change the y value to your wanted transition movement.


问:
How do I initiate a fancybox 3 slideshow by clicking on a single image or button
How do I initiate a fancybox 3 slideshow by clicking on a single image or button. There appears to be a good example on the Fancyapps site with the Custom Demo but no coding example specific to this case.</p>

答:
This is an example of how to open a fancyBox gallery by clicking on an image:

```<code><a href="image_1.jpg" data-fancybox="my_gallery" data-caption="Caption #1">
    <img src="thumbnail_1.jpg" alt="" />
</a>
<a href="image_2.jpg" data-fancybox="my_gallery" data-caption="Caption #2">
    <img src="thumbnail_2.jpg" alt="" />
</a>
</code>```

You just need to encapsulate your images in ancors and give these anchors the same data-fancybox attribute value, in the example above it is "my_gallery".

This way each one of you images will become clickable and will open a fancyBox gallery containing all images from the same gallery (data-fancybox attribute value)

And in order to open the fancyBox by clicking a button, you need to add the button

```<code><button class="open-gallery">Open gallery</button>
</code>```

And in your JS code, add a click event handler to that button that will open your gallery

```<code>$(document).ready(function() {
    $('button.open-gallery').click(function() {
        $('a[data-fancybox="my_gallery"]').first().trigger('click');
    });
});
</code>```

Body:
This is an example of how to open a fancyBox gallery by clicking on an image:

<a href="image_1.jpg" data-fancybox="my_gallery" data-caption="Caption #1">
    <img src="thumbnail_1.jpg" alt="" />
</a>
<a href="image_2.jpg" data-fancybox="my_gallery" data-caption="Caption #2">
    <img src="thumbnail_2.jpg" alt="" />
</a>

You just need to encapsulate your images in ancors and give these anchors the same data-fancybox attribute value, in the example above it is "my_gallery".

This way each one of you images will become clickable and will open a fancyBox gallery containing all images from the same gallery (data-fancybox attribute value)

And in order to open the fancyBox by clicking a button, you need to add the button

<button class="open-gallery">Open gallery</button>

And in your JS code, add a click event handler to that button that will open your gallery

$(document).ready(function() {
    $('button.open-gallery').click(function() {
        $('a[data-fancybox="my_gallery"]').first().trigger('click');
    });
});


问:
Rxjs: Create Observable that is a delayed offset of another observable
Is there an easy way to create an observable that is an offset of another?

For example, let's say Observable1 emits [1,2,3,4,5].

How would I create Observable2 from Observable1 such that Observable2 emits [1,2,3,4]  (so, it emits nothing when Observable1 emits 1, it emits 1 when Observable1 emits 2, etc.)

Obs1 Start
  -------1--------2----------3------------4-------------5----------------->

Obs2 Start
  -----------------1----------2------------3-------------4----------------->

Thanks!

答:
You can use the bufferCount and map operators to do what you want:

const source = new Rx.Subject();
const offset = source.bufferCount(2, 1).map(values => values[0]);

source.subscribe(value => console.log(`source = ${value}`));
offset.subscribe(value => console.log(`offset = ${value}`));

source.next(1);
source.next(2);
source.next(3);
source.next(4);
source.next(5);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper { max-height: 100% !important; top: 0; }</code>```

```

bufferCount(2, 1) will emit a two-value buffer each time a value is received - once there are two values in the buffer, that is. So the first value in the buffer will be offset by one source emission.

You could substitute bufferCount(2, 1) with pairwise() which does the same thing.

Body:
You can use the bufferCount and map operators to do what you want:

const source = new Rx.Subject();
const offset = source.bufferCount(2, 1).map(values => values[0]);

source.subscribe(value => console.log(`source = ${value}`));
offset.subscribe(value => console.log(`offset = ${value}`));

source.next(1);
source.next(2);
source.next(3);
source.next(4);
source.next(5);

.as-console-wrapper { max-height: 100% !important; top: 0; }

<script src="https://unpkg.com/rxjs@5/bundles/Rx.min.js"></script>

bufferCount(2, 1) will emit a two-value buffer each time a value is received - once there are two values in the buffer, that is. So the first value in the buffer will be offset by one source emission.

You could substitute bufferCount(2, 1) with pairwise() which does the same thing.


问:
JavaScript Crashing Chrome (Infinite Recursion )
When I run this my browser freezes and crashes but I can't figure out how to fix it. I am new to JavaScript and I need some help.</p>

```<code>function Start() {

if (Key1 === true) {
    alert ("1")
    Key1 = false
} else if (Key2 === true) {
    alert ("2")
    Key2 = false
} else {
    window.setTimeout(Start, 1000);
    Start()
}

}
</code>```

答:
You should remove the excess Function Start().</p>

```<code>function Start() {

if (Key1 === true) {
    alert ("1")
    Key1 = false
} else if (Key2 === true) {
    alert ("2")
    Key2 = false
} else {
    window.setTimeout(Start, 1000);
}
}
</code>```

Body:
When I run this my browser freezes and crashes but I can't figure out how to fix it. I am new to JavaScript and I need some help.

function Start() {

if (Key1 === true) {
    alert ("1")
    Key1 = false
} else if (Key2 === true) {
    alert ("2")
    Key2 = false
} else {
    window.setTimeout(Start, 1000);
    Start()
}

}

Body:
You should remove the excess Function Start().

function Start() {

if (Key1 === true) {
    alert ("1")
    Key1 = false
} else if (Key2 === true) {
    alert ("2")
    Key2 = false
} else {
    window.setTimeout(Start, 1000);
}
}