问:
Docker with Angular 4 and Django is compiled successfully but localhost:4200 is not working
I would like to dockerize Angular 4 frontend with Django backend and postgresql database. At this moment my files looks as shown below. I am note sure if this is done properly? When I try docker-compose up I get information that both frontend with Angular 4 and backend with Django started successfully. Unfortunately when I open http://localhost:4200 it doesn't work (localhost:8001 seems working):

```<code>django_1   | Django version 1.11, using settings 'project.settings'
django_1   | Starting development server at http://0.0.0.0:8001/
django_1   | Quit the server with CONTROL-C.
angular_1  | ** NG Live Development Server is listening on localhost:4200, open your browser on http://localhost:4200 **
angular_1  | Time: 20657ms
angular_1  | chunk    {0} polyfills.bundle.js, polyfills.bundle.js.map (polyfills) 232 kB {4} [initial] [rendered]
angular_1  | chunk    {1} main.bundle.js, main.bundle.js.map (main) 222 kB {3} [initial] [rendered]
angular_1  | chunk    {2} styles.bundle.js, styles.bundle.js.map (styles) 11.6 kB {4} [initial] [rendered]
angular_1  | chunk    {3} vendor.bundle.js, vendor.bundle.js.map (vendor) 4.41 MB [initial] [rendered]
angular_1  | chunk    {4} inline.bundle.js, inline.bundle.js.map (inline) 0 bytes [entry] [rendered]
angular_1  | webpack: Compiled successfully.
</code>```

Structure of my files:

```<code>├── Backend
│   ├── AI
│   │   ├── __init__.py
│   │   ├── __pycache__
│   │   │   ├── __init__.cpython-36.pyc
│   │   │   ├── settings.cpython-36.pyc
│   │   │   ├── urls.cpython-36.pyc
│   │   │   └── wsgi.cpython-36.pyc
│   │   ├── settings.py
│   │   ├── urls.py
│   │   └── wsgi.py
│   └── manage.py
├── Dockerfile
├── Frontend
│   └── angularProject
        ├── Dockerfile
│       └── all files in my angular project
├── docker-compose.yml
└── requirements.txt
</code>```

Dockerfile from frontend:

```<code># Create image based on the official Node 6 image from dockerhub
FROM node:6

# Create a directory where our app will be placed
RUN mkdir -p /usr/src/app

# Change directory so that our commands run inside this new directory
WORKDIR /usr/src/app

# Copy dependency definitions
COPY package.json /usr/src/app

# Install dependecies
RUN npm install

# Get all the code needed to run the app
COPY . /usr/src/app

# Expose the port the app runs in
EXPOSE 4200

# Serve the app
CMD ["npm", "start"]
</code>```

Dockerfile from main directory:

```<code>FROM python:3.6.1
ENV PYTHONUNBUFFERED 1
RUN mkdir /code
WORKDIR /code
ADD requirements.txt /code/
RUN pip3 install -r requirements.txt
ADD . /code/
</code>```

docker-compose.yml:

```<code>version: '3'

services:
  db:
    image: postgres
    environment:
      POSTGRES_USER: aso
      POSTGRES_PASSWORD: somepass
  django:
    build: .
    command: python3 MainDirectory/backend/myProject/manage.py runserver 0.0.0.0:8001
    volumes:
      - .:/code
    ports:
      - "8001:8001"
    depends_on:
      - db
  angular:
    build: MainDirectory/frontend
    ports:
      - "4200:4200"
    depends_on:
      - django
</code>```

答:
The server is running on port 4200 but you're exposing port 80 on 8010 with:

```<code>  angular:
    build: MainDirectory/frontend
    ports:
      - "8010:80"  # <==== HERE
    depends_on:
      - django
</code>```

You should probably use:

```<code>  angular:
    build: MainDirectory/frontend
    ports:
      - "4200:4200"
    depends_on:
      - django
</code>```

You might also have to get your server (npm start script) to bind on 0.0.0.0.

Body:
I would like to dockerize Angular 4 frontend with Django backend and postgresql database. At this moment my files looks as shown below. I am note sure if this is done properly? When I try docker-compose up I get information that both frontend with Angular 4 and backend with Django started successfully. Unfortunately when I open http://localhost:4200 it doesn't work (localhost:8001 seems working):

django_1   | Django version 1.11, using settings 'project.settings'
django_1   | Starting development server at http://0.0.0.0:8001/
django_1   | Quit the server with CONTROL-C.
angular_1  | ** NG Live Development Server is listening on localhost:4200, open your browser on http://localhost:4200 **
angular_1  | Time: 20657ms
angular_1  | chunk    {0} polyfills.bundle.js, polyfills.bundle.js.map (polyfills) 232 kB {4} [initial] [rendered]
angular_1  | chunk    {1} main.bundle.js, main.bundle.js.map (main) 222 kB {3} [initial] [rendered]
angular_1  | chunk    {2} styles.bundle.js, styles.bundle.js.map (styles) 11.6 kB {4} [initial] [rendered]
angular_1  | chunk    {3} vendor.bundle.js, vendor.bundle.js.map (vendor) 4.41 MB [initial] [rendered]
angular_1  | chunk    {4} inline.bundle.js, inline.bundle.js.map (inline) 0 bytes [entry] [rendered]
angular_1  | webpack: Compiled successfully.

Structure of my files:

├── Backend
│   ├── AI
│   │   ├── __init__.py
│   │   ├── __pycache__
│   │   │   ├── __init__.cpython-36.pyc
│   │   │   ├── settings.cpython-36.pyc
│   │   │   ├── urls.cpython-36.pyc
│   │   │   └── wsgi.cpython-36.pyc
│   │   ├── settings.py
│   │   ├── urls.py
│   │   └── wsgi.py
│   └── manage.py
├── Dockerfile
├── Frontend
│   └── angularProject
        ├── Dockerfile
│       └── all files in my angular project
├── docker-compose.yml
└── requirements.txt

Dockerfile from frontend:

# Create image based on the official Node 6 image from dockerhub
FROM node:6

# Create a directory where our app will be placed
RUN mkdir -p /usr/src/app

# Change directory so that our commands run inside this new directory
WORKDIR /usr/src/app

# Copy dependency definitions
COPY package.json /usr/src/app

# Install dependecies
RUN npm install

# Get all the code needed to run the app
COPY . /usr/src/app

# Expose the port the app runs in
EXPOSE 4200

# Serve the app
CMD ["npm", "start"]

Dockerfile from main directory:

FROM python:3.6.1
ENV PYTHONUNBUFFERED 1
RUN mkdir /code
WORKDIR /code
ADD requirements.txt /code/
RUN pip3 install -r requirements.txt
ADD . /code/

docker-compose.yml:

version: '3'

services:
  db:
    image: postgres
    environment:
      POSTGRES_USER: aso
      POSTGRES_PASSWORD: somepass
  django:
    build: .
    command: python3 MainDirectory/backend/myProject/manage.py runserver 0.0.0.0:8001
    volumes:
      - .:/code
    ports:
      - "8001:8001"
    depends_on:
      - db
  angular:
    build: MainDirectory/frontend
    ports:
      - "4200:4200"
    depends_on:
      - django

Body:
The server is running on port 4200 but you're exposing port 80 on 8010 with:

  angular:
    build: MainDirectory/frontend
    ports:
      - "8010:80"  # <==== HERE
    depends_on:
      - django

You should probably use:

  angular:
    build: MainDirectory/frontend
    ports:
      - "4200:4200"
    depends_on:
      - django

You might also have to get your server (npm start script) to bind on 0.0.0.0.


来源: stackexchange

问:
Change default "symbolic link" folder in laravel 5.4 (storage folder)
I'm making a new version of my site with laravel 5.4 and want to keep the same links than my old site has.

My old site has links images like this:
domain.com/uploaded/cat.jpg

In laravel, its necesary to create a symbolic link to show the stored images but it saved them with a default folder named storage", like this:
domain.com/storage/cat.jpg

How can i change the default name to "uploaded" or whatever?

I tried to change url inside the file \config\filesystems.php with this:

Before

```<code>'public' => [
        'driver' => 'local',
        'root' => storage_path('app/public'),
        'url' => env('APP_URL').'/storage',
        'visibility' => 'public',
    ],
</code>```

After

```<code>'public' => [
        'driver' => 'local',
        'root' => storage_path('app/public'),
        'url' => env('APP_URL').'/uploaded',
        'visibility' => 'public',
    ],
</code>```

and my controller

```<code>$request->file('image')->storeAs('public', 'example.jpg');
</code>```

答:
Make sure you've created a symlink.

According to your configuration, you can run this command :

```<code>ln -s storage/app/public public/uploaded
</code>```

Then, you can access your files :

```<code>Storage::disk('public')->url('example.jpg')
</code>```

Or simply using asset() helper :

```<code>asset('uploaded/example.jpg');
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm making a new version of my site with laravel 5.4 and want to keep the same links than my old site has.

My old site has links images like this:
domain.com/uploaded/cat.jpg

In laravel, its necesary to create a symbolic link to show the stored images but it saved them with a default folder named storage", like this:
domain.com/storage/cat.jpg

How can i change the default name to "uploaded" or whatever?

I tried to change url inside the file \config\filesystems.php with this:

Before

'public' => [
        'driver' => 'local',
        'root' => storage_path('app/public'),
        'url' => env('APP_URL').'/storage',
        'visibility' => 'public',
    ],

After

'public' => [
        'driver' => 'local',
        'root' => storage_path('app/public'),
        'url' => env('APP_URL').'/uploaded',
        'visibility' => 'public',
    ],

and my controller

$request->file('image')->storeAs('public', 'example.jpg');

Body:
Make sure you've created a symlink.

According to your configuration, you can run this command :

ln -s storage/app/public public/uploaded

Then, you can access your files :

Storage::disk('public')->url('example.jpg')

Or simply using asset() helper :

asset('uploaded/example.jpg');


问:
Change vertical axis labels with pylab
When I wrote this program I first tried with matlab, then with gnu octave and they couldn't do it. So I wrote my own script for it in python:

```<code>from pylab import *
f, ax = plt.subplots(1)
xdata = [256, 512, 1024, 2048]
labels = [256, 512, 1024, 2048]

ydata = [1, 1, 30, 150]
plt.xscale('log', basex=2)
plt.yscale('log', basey=2)
ax.scatter(xdata, ydata)

y2data = [1, 1, 30, 150]
ax.scatter(xdata, y2data, marker='x')
x3data = [256, 512]
y3data = [29, 140]
ax.scatter(x3data, y3data, marker='d')
plt.xticks(xdata, labels, rotation='vertical')

f.suptitle('Benchmark results', fontsize=20)
plt.xlabel('memory (bytes)', fontsize=18)
plt.ylabel('time (seconds)', fontsize=16)
plt.show(f)
</code>```

The graph looks alright (but I had to resize it to make the text at the bottom appear).

Now for the vertical exponential/logarithmic axis I would like to write it in decimal notation just like the horizontal axis. Can it be done?

Instead of "2²" I would like it to say just 4 plainly.

答: Why not just do the same thing you did for the horizontal axis? Create a list of labels manually and then set it using plt.yticks, and put the full numbers instead of powers of 2.</p>

Title: Change vertical axis labels with pylab

Body:
When I wrote this program I first tried with matlab, then with gnu octave and they couldn't do it. So I wrote my own script for it in python:

from pylab import *
f, ax = plt.subplots(1)
xdata = [256, 512, 1024, 2048]
labels = [256, 512, 1024, 2048]

ydata = [1, 1, 30, 150]
plt.xscale('log', basex=2)
plt.yscale('log', basey=2)
ax.scatter(xdata, ydata)

y2data = [1, 1, 30, 150]
ax.scatter(xdata, y2data, marker='x')
x3data = [256, 512]
y3data = [29, 140]
ax.scatter(x3data, y3data, marker='d')
plt.xticks(xdata, labels, rotation='vertical')

f.suptitle('Benchmark results', fontsize=20)
plt.xlabel('memory (bytes)', fontsize=18)
plt.ylabel('time (seconds)', fontsize=16)
plt.show(f)

The graph looks alright (but I had to resize it to make the text at the bottom appear).

Now for the vertical exponential/logarithmic axis I would like to write it in decimal notation just like the horizontal axis. Can it be done?

Instead of "2²" I would like it to say just 4 plainly.


问:
Why can't we create an RDD using Spark session
We see that,

```<code>Spark context available as 'sc'.
Spark session available as 'spark'.
</code>```

I read spark session includes spark context, streaming context, hive context ...  If so, then why are we not able to create an rdd by using a spark session instead of a spark context.

```<code>scala> val a = sc.textFile("Sample.txt")
17/02/17 16:16:14 WARN util.SizeEstimator: Failed to check whether UseCompressedOops is set; assuming yes
a: org.apache.spark.rdd.RDD[String] = Sample.txt MapPartitionsRDD[1] at textFile at <console>:24

scala> val a = spark.textFile("Sample.txt")
<console>:23: error: value textFile is not a member of org.apache.spark.sql.SparkSession
       val a = spark.textFile("Sample.txt")
</code>```

As shown above, sc.textFile succeeds in creating an RDD but not spark.textFile.

答:
In Spark 2+, Spark Context is available via Spark Session, so all you need to do is:

```<code>spark.sparkContext().textFile(yourFileOrURL)
</code>```

see the documentation on this access method here.

Note that in PySpark this would become:

```<code>spark.sparkContext.textFile(yourFileOrURL)
</code>```

see the documentation here.

Body:
We see that,

Spark context available as 'sc'.
Spark session available as 'spark'.

I read spark session includes spark context, streaming context, hive context ...  If so, then why are we not able to create an rdd by using a spark session instead of a spark context.

scala> val a = sc.textFile("Sample.txt")
17/02/17 16:16:14 WARN util.SizeEstimator: Failed to check whether UseCompressedOops is set; assuming yes
a: org.apache.spark.rdd.RDD[String] = Sample.txt MapPartitionsRDD[1] at textFile at <console>:24

scala> val a = spark.textFile("Sample.txt")
<console>:23: error: value textFile is not a member of org.apache.spark.sql.SparkSession
       val a = spark.textFile("Sample.txt")

As shown above, sc.textFile succeeds in creating an RDD but not spark.textFile.

Body:
In Spark 2+, Spark Context is available via Spark Session, so all you need to do is:

spark.sparkContext().textFile(yourFileOrURL)

see the documentation on this access method here.

Note that in PySpark this would become:

spark.sparkContext.textFile(yourFileOrURL)

see the documentation here.


问:
UDP port scanner issues, C
So I am trying to create a functional udp port scanner. The code I have so far seems to be missing something such maybe switch, use of iwreq or simply a linked list for the scanned ports, not sure. I am new to C programming so would appreciate any help.</p>

```<code>#include <erno.h>
#include <stdio.h>
#include <netdb.h>
#include <sys/time.h>
#include <sys/socket.h>
#include <unistd.h>
#include <sys/types.h>
#include <netinet/ip.h>
#include <netinet/ip_icmp.h>
#include <iwlib.h>
#include <wireless.h>

#define MAXSIZE 0

int main(){

struct timeval timesec;
int sockfd;
int ipleng;

int port= 1020;
struct hostent hostent;
struct sockaddr my_addre;
struct imcmphdr IC;
struct sockaddr_in my_addr;
struct ip ipp;
struct iw_range rang;
struct iwreq iwq;
char message="  ";
h_addr_list[0];

scan();
if(scan==NULL){
perror("scan not done");
exit(1);

}
int scan(){
ioctl(socket,SIOCSIWSCAN,&iwq);
iw_get_range_info(sockfd,wlan0,&rang);
  if(iw_get_range_info(sockfd, wlan0, &rang)>0){
    rang=1;
  }
   r=iw_get_range_info(sockfd,wlan0,&rang);
char serve [50];
int hlen;
int slen;
for(int i=0; port<r; i++){
if(hostt=getnameinfo(struct hostent  *host, MAXSIZE, host, hlen, serve,
slen, NULL)==NULL){

if(haddrinfo=getaddrinfo(struct hostent *host, MAXSIZE, host, hlen, serve,
slen, NULL)==NULL){
exit(1);
}
else{
printf("IP address");
addrlist=h_addr_list;
for(i=0; addrlist[i]>0; i++){
printf("host: %s\n", arrdlist[i],  hostt);
printf("server: %s\n", haddrinfo);

if(sockfd=socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP))<0 {
   perror("socket not created");
   return -1;

if(rsock=sockfd(AF_INET, SOCK_RAW, IPPROTO_ICMP))<0){
    perror("socket fail");
    exit(1);
    else{

memset(&my_addr,0,sizeof(my_addr));
my_addr.sin_family=AF_INET;
my_addr.sin_port=htons(1020);
my_addr.sin_addr.s_addr=inet_addr();
my_addr.sin_addr(struct in_addr*)hostt->h_addr;

if(sendto(sockfd,MAXSIZE,0,0,(struct sockaddr*)&my_addre,sizeof(my_addre))
<0){
    perror("can't send");
    return -1;
   }
  }
 }
}
if(setsockopt(sockfd,SOL_SOCKET,SO_BROADCAST,&host,sizeof(host))== -1){
    perror("setsockopt(SOL_BROADCAST)");
    return -1;
    else
        timesec.tv_sec=3;
     while(1);
    {
    FD_ISSET(&my_addr);
    FD_ZERO(&readfds);
    FD_SET(&rsock,&readfds);
    ipleng=ip->ip_hl<<2;
    if(select(rsock+1,&readfds,NULL,NULL,&timsec);
    for(;;){
        if(select(rsock+1,&readfds,NULL,NULL,&timesec){
        if(FD_ISSET(rsock,&readfds0{
            siz=read(rsock,(struct icmphdr*)&IC,sizeof(IC));
            if(siz=0){
                printf("can't read");
            }

         }

        }
  }
        ipp=(struct ip*)MAXSIZE;
        message=(struct icmp*)(MAXSIZE+ipleng);
        if(recvfrom(rsock,MAXSIZE,sizeof(MAXSIZE),NULL,my_addre,hlen)<0){
            perror("ICMP error");
            printf("port closed");
            if(message->icmp_type==ICMP_UNREACH)&&message->icmp_code==ICMP_UNREACH_PORT{
                exit(1);
            }
            else{
                if(message==0){
                    printf("p;ort open");
                    port=getservbyport(htons(addrlist[i], "port");
                    printf("udp port %d %s is open\n", addrlist[i], port->s_addr);
                    if(port==NULL){
                        printf("unknown");
                    }

                }

            }

          }

        }
       }

      }

    }

  }

  }
 }

fflush(sockfd);
return 0;

}
</code>```

答:
A thing like 'UDP port scanner' does not technically exist because UDP is stateless, so there is no connection.

Instead, what "UDP port scanners" do is send 'payloads' in order to try to get a response.

Basically a correct payload to test UDP 53 is a DNS request.

So you implement payloads, and you test all payloads on a port. Then you have a sort of UDP scanner.

Well I guess this does not answer your question but I hope it helps you perform a better scanner.

Title: UDP port scanner issues, C

Body:
So I am trying to create a functional udp port scanner. The code I have so far seems to be missing something such maybe switch, use of iwreq or simply a linked list for the scanned ports, not sure. I am new to C programming so would appreciate any help.

#include <erno.h>
#include <stdio.h>
#include <netdb.h>
#include <sys/time.h>
#include <sys/socket.h>
#include <unistd.h>
#include <sys/types.h>
#include <netinet/ip.h>
#include <netinet/ip_icmp.h>
#include <iwlib.h>
#include <wireless.h>

#define MAXSIZE 0

int main(){

struct timeval timesec;
int sockfd;
int ipleng;

int port= 1020;
struct hostent hostent;
struct sockaddr my_addre;
struct imcmphdr IC;
struct sockaddr_in my_addr;
struct ip ipp;
struct iw_range rang;
struct iwreq iwq;
char message="  ";
h_addr_list[0];

scan();
if(scan==NULL){
perror("scan not done");
exit(1);

}
int scan(){
ioctl(socket,SIOCSIWSCAN,&iwq);
iw_get_range_info(sockfd,wlan0,&rang);
  if(iw_get_range_info(sockfd, wlan0, &rang)>0){
    rang=1;
  }
   r=iw_get_range_info(sockfd,wlan0,&rang);
char serve [50];
int hlen;
int slen;
for(int i=0; port<r; i++){
if(hostt=getnameinfo(struct hostent  *host, MAXSIZE, host, hlen, serve,
slen, NULL)==NULL){

if(haddrinfo=getaddrinfo(struct hostent *host, MAXSIZE, host, hlen, serve,
slen, NULL)==NULL){
exit(1);
}
else{
printf("IP address");
addrlist=h_addr_list;
for(i=0; addrlist[i]>0; i++){
printf("host: %s\n", arrdlist[i],  hostt);
printf("server: %s\n", haddrinfo);

if(sockfd=socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP))<0 {
   perror("socket not created");
   return -1;

if(rsock=sockfd(AF_INET, SOCK_RAW, IPPROTO_ICMP))<0){
    perror("socket fail");
    exit(1);
    else{

memset(&my_addr,0,sizeof(my_addr));
my_addr.sin_family=AF_INET;
my_addr.sin_port=htons(1020);
my_addr.sin_addr.s_addr=inet_addr();
my_addr.sin_addr(struct in_addr*)hostt->h_addr;

if(sendto(sockfd,MAXSIZE,0,0,(struct sockaddr*)&my_addre,sizeof(my_addre))
<0){
    perror("can't send");
    return -1;
   }
  }
 }
}
if(setsockopt(sockfd,SOL_SOCKET,SO_BROADCAST,&host,sizeof(host))== -1){
    perror("setsockopt(SOL_BROADCAST)");
    return -1;
    else
        timesec.tv_sec=3;
     while(1);
    {
    FD_ISSET(&my_addr);
    FD_ZERO(&readfds);
    FD_SET(&rsock,&readfds);
    ipleng=ip->ip_hl<<2;
    if(select(rsock+1,&readfds,NULL,NULL,&timsec);
    for(;;){
        if(select(rsock+1,&readfds,NULL,NULL,&timesec){
        if(FD_ISSET(rsock,&readfds0{
            siz=read(rsock,(struct icmphdr*)&IC,sizeof(IC));
            if(siz=0){
                printf("can't read");
            }

         }

        }
  }
        ipp=(struct ip*)MAXSIZE;
        message=(struct icmp*)(MAXSIZE+ipleng);
        if(recvfrom(rsock,MAXSIZE,sizeof(MAXSIZE),NULL,my_addre,hlen)<0){
            perror("ICMP error");
            printf("port closed");
            if(message->icmp_type==ICMP_UNREACH)&&message->icmp_code==ICMP_UNREACH_PORT{
                exit(1);
            }
            else{
                if(message==0){
                    printf("p;ort open");
                    port=getservbyport(htons(addrlist[i], "port");
                    printf("udp port %d %s is open\n", addrlist[i], port->s_addr);
                    if(port==NULL){
                        printf("unknown");
                    }

                }

            }

          }

        }
       }

      }

    }

  }

  }
 }

fflush(sockfd);
return 0;

}


问:
Panda's DataFrame - renaming multiple identically named columns
I have several columns named the same in a df. I need to rename them but the problem is that the df.rename method renames them all the same way. How I can rename the below blah(s) to blah1, blah4, blah5?

```<code>df = pd.DataFrame(np.arange(2*5).reshape(2,5))
df.columns = ['blah','blah2','blah3','blah','blah']
df

#     blah  blah2  blah3  blah  blah
# 0   0     1      2      3     4
# 1   5     6      7      8     9
</code>```

Here is what happens when using the df.rename method:

```<code>df.rename(columns={'blah':'blah1'})

#     blah1  blah2  blah3  blah1  blah1
# 0   0      1      2      3      4
# 1   5      6      7      8      9
</code>```

答:
You could use this:

```<code>def df_column_uniquify(df):
    df_columns = df.columns
    new_columns = []
    for item in df_columns:
        counter = 0
        newitem = item
        while newitem in new_columns:
            counter += 1
            newitem = "{}_{}".format(item, counter)
        new_columns.append(newitem)
    df.columns = new_columns
    return df
</code>```

Then

```<code>import numpy as np
import pandas as pd

df=pd.DataFrame(np.arange(2*5).reshape(2,5))
df.columns=['blah','blah2','blah3','blah','blah']
</code>```

so that df:

```<code>   blah  blah2  blah3   blah   blah
0     0      1      2      3      4
1     5      6      7      8      9
</code>```

then

```<code>df = df_column_uniquify(df)
</code>```

so that df:

```<code>   blah  blah2  blah3  blah_1  blah_2
0     0      1      2       3       4
1     5      6      7       8       9
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have several columns named the same in a df. I need to rename them but the problem is that the df.rename method renames them all the same way. How I can rename the below blah(s) to blah1, blah4, blah5?

df = pd.DataFrame(np.arange(2*5).reshape(2,5))
df.columns = ['blah','blah2','blah3','blah','blah']
df

#     blah  blah2  blah3  blah  blah
# 0   0     1      2      3     4
# 1   5     6      7      8     9

Here is what happens when using the df.rename method:

df.rename(columns={'blah':'blah1'})

#     blah1  blah2  blah3  blah1  blah1
# 0   0      1      2      3      4
# 1   5      6      7      8      9

Body:
You could use this:

def df_column_uniquify(df):
    df_columns = df.columns
    new_columns = []
    for item in df_columns:
        counter = 0
        newitem = item
        while newitem in new_columns:
            counter += 1
            newitem = "{}_{}".format(item, counter)
        new_columns.append(newitem)
    df.columns = new_columns
    return df

Then

import numpy as np
import pandas as pd

df=pd.DataFrame(np.arange(2*5).reshape(2,5))
df.columns=['blah','blah2','blah3','blah','blah']

so that df:

   blah  blah2  blah3   blah   blah
0     0      1      2      3      4
1     5      6      7      8      9

then

df = df_column_uniquify(df)

so that df:

   blah  blah2  blah3  blah_1  blah_2
0     0      1      2       3       4
1     5      6      7       8       9


问:
Akka http -ERROR :Substream Source cannot be materialized more than once If Payload size increased
I am working with Akka Http, where I have defined a route as

```<code>val route = (path(HttpConstants.CreateJob) & post) {
    (entity(as[JobDetailsEntity]) & entity(as[JobEntity])) {
      (jobDetailsEntity: JobDetailsEntity, jobEntity: JobEntity) =>
        val updatedJobEntity = jobEntity.copy(runningSince = DateTime.now().getMillis)
        val updatedJobDetailsEntity = jobDetailsEntity.copy(runningSince = DateTime.now().getMillis).copy(modify_date = DateTime.now().getMillis)
        complete {
          createJobDetails(updatedJobDetailsEntity).map(_.asJson)
          createJob(updatedJobEntity).map(_.asJson)
        }
    }
</code>```

Here I am trying to unmarshal two entites in the same POST call which works when my json Payload id small i.e few bytes then its works fine , as soon as the payload size increases i.e around 10-20 kb it throws error :

Substream Source cannot be materialized more than once

答:
Please see https://github.com/akka/akka-http/issues/745#issuecomment-271571342

In short, if you need to unmarshal your entity twice you should use the toStrict first to make sure the entire entity is buffered in memory, otherwise it will be drained by the first unmarshalling process and not available for the second.

Only accidentally it happens to work without toStrict if the entity is small enough that it fits in akka's internal buffer, then there's actually no draining involved.

Body:
I am working with Akka Http, where I have defined a route as

val route = (path(HttpConstants.CreateJob) & post) {
    (entity(as[JobDetailsEntity]) & entity(as[JobEntity])) {
      (jobDetailsEntity: JobDetailsEntity, jobEntity: JobEntity) =>
        val updatedJobEntity = jobEntity.copy(runningSince = DateTime.now().getMillis)
        val updatedJobDetailsEntity = jobDetailsEntity.copy(runningSince = DateTime.now().getMillis).copy(modify_date = DateTime.now().getMillis)
        complete {
          createJobDetails(updatedJobDetailsEntity).map(_.asJson)
          createJob(updatedJobEntity).map(_.asJson)
        }
    }

Here I am trying to unmarshal two entites in the same POST call which works when my json Payload id small i.e few bytes then its works fine , as soon as the payload size increases i.e around 10-20 kb it throws error :

Substream Source cannot be materialized more than once


问:
Extjs 4 grouped columns header dynamic text modification
I have the following grouped headers grid :

```<code>var lestore =  Ext.create('Ext.data.Store', {
       proxy: {
                type: 'memory'
                },
        autoDestroy: true,
        data:objstore
    });

 thegrid = Ext.create('Ext.grid.Panel', {
        store: lestore,
        columnLines: true,
        columns: [{text:'date'},{text:'TV',columns:{text:'400',columns:[{text:'tt1'},{text:'tt2'}]}]  ,
        title:'my title'  ,
        selModel: {
            selType: 'cellmodel'
        },
        renderTo: 'gridmpoff',
            plugins: [Ext.create('Ext.grid.plugin.CellEditing', {clicksToEdit: 1}
                )
                 ],

        listeners: {'edit': function(editor,e) {updtitle(editor,e);}
        },
        viewConfig: {
            stripeRows: true
        },

    });
</code>```

I need to change the columns texts (tt1,tt2 etc)  after the grid creation, without changing the header grouping.

I Tried modifying the columns property, but that doesn't help, only thing that worked so far is a reconfigure which messes with the editor.

Please advice

答:
I know this is an old thread but you can use the code Michael posted :

```<code>grid.columns[0].ownerCt.setText('Total Number');
</code>```

and then use the column name in your groupHeaderTpl and have something like this :

```<code>{columnName}: {name}
</code>```

This way it will dynamically change it to the values you want.

Body:
I have the following grouped headers grid :

var lestore =  Ext.create('Ext.data.Store', {
       proxy: {
                type: 'memory'
                },
        autoDestroy: true,
        data:objstore
    });

 thegrid = Ext.create('Ext.grid.Panel', {
        store: lestore,
        columnLines: true,
        columns: [{text:'date'},{text:'TV',columns:{text:'400',columns:[{text:'tt1'},{text:'tt2'}]}]  ,
        title:'my title'  ,
        selModel: {
            selType: 'cellmodel'
        },
        renderTo: 'gridmpoff',
            plugins: [Ext.create('Ext.grid.plugin.CellEditing', {clicksToEdit: 1}
                )
                 ],

        listeners: {'edit': function(editor,e) {updtitle(editor,e);}
        },
        viewConfig: {
            stripeRows: true
        },

    });

I need to change the columns texts (tt1,tt2 etc)  after the grid creation, without changing the header grouping.

I Tried modifying the columns property, but that doesn't help, only thing that worked so far is a reconfigure which messes with the editor.

Please advice

Body:
I know this is an old thread but you can use the code Michael posted :

grid.columns[0].ownerCt.setText('Total Number');

and then use the column name in your groupHeaderTpl and have something like this :

{columnName}: {name}

This way it will dynamically change it to the values you want.


问:
Using fprintf to output variables side by side
I'm having trouble using fprintf. I'm trying to print variables side by side. For example, the way it has to look like is A1 then another value. Then new line, A2 and another value. New line, A3 and another value from variable 'A' and so on.

```<code>f2 = 1:124;
fprintf(fileID,'A%f \t %f \n',f2',A);
</code>```

This code prints:

```<code>A1 2
A3 4
A5 6
</code>```

and so on. How can I fix this?

答:
You could iterate through them all:</p>

```<code>for i = 1:124
  fprintf(fileID,'A%f \t %f \n',f2(i),A(i))
end
</code>```

Body:
I'm having trouble using fprintf. I'm trying to print variables side by side. For example, the way it has to look like is A1 then another value. Then new line, A2 and another value. New line, A3 and another value from variable 'A' and so on.

f2 = 1:124;
fprintf(fileID,'A%f \t %f \n',f2',A);

This code prints:

A1 2
A3 4
A5 6

and so on. How can I fix this?

Body:
You could iterate through them all:

for i = 1:124
  fprintf(fileID,'A%f \t %f \n',f2(i),A(i))
end


问:
Populate subdocument in parent document Array Mongoose
I'm very new to JavaScript and Mongoose. I'm building a small project using express, mongoose and node.js.
I have a mongoose model - Client that has an Array of Transactions

```<code>    var Client = mongoose.model('Client', {
 name: {
   type: String,
   required: true,
   minlength: 1
 },
 email: {
   type: String
 },
 phone: {
   type: Number
 },
 createdAt: {
   type: Number,
   default: null
 },
 transactions: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Transaction' }],
 _creator: {
   type: mongoose.Schema.Types.ObjectId,
   required: true
 }
});

module.exports = {Client};
</code>```

This is Transaction model:

```<code>var Client = require('./client');

var Transaction = mongoose.model('Transaction',{
  _creator : { type: mongoose.Schema.Types.ObjectId, ref: 'Client' },
  amount : {type: Number, min: 0},
  date : {type: Number,default: null},
  total: {type: Number,default: null}
});

module.exports = {Transaction};
</code>```

When I POST a new Transaction it goes through and saves in db:

```<code> app.post('/clients/:id/transactions', authenticate, (req, res) => {
  var id = req.params.id;
  var transaction = new Transaction({
    amount: req.body.amount,
    date: new Date().getTime(),
    total: req.body.total,
    _creator: req.params.id
  })
  if (!ObjectID.isValid(id)) {
  return res.status(404).send();
  }

  transaction.save().then((doc) => {

    Client.findOneAndUpdate({
      _id: id,
      _creator: req.user._id,
      transactions: req.body.transaction
    });

    res.send(doc);
  }, (e) => {
    res.status(400).send(e);
  });

});
</code>```

I am also able to GET all the transactions associated with the client:

```<code>  app.get('/clients/:id/transactions', authenticate, (req, res) => {
  var id = req.params.id;
  if (!ObjectID.isValid(id)) {
  return res.status(404).send();
 }
 Transaction.find({
   _creator: id
 }).then((transactions) => {
  res.send({transactions});
 }).catch((e) => {
  res.status(400).send();
 });
});
</code>```

But when I make a GET call to '/clients' - Array of Transactions is empty:

```<code>    {
  "clients": [
    {
      "_id": "1095d6de3867001108b803",
      "name": "Peter",
      "email": "peter@gmail.com",
      "phone": 1232321,
      "_creator": "5321df6d57868ec7001108b801",
      "__v": 0,
      "transactions": [],
      "createdAt": null
    } ]
}
</code>```

And this is the GET call to /clients

```<code>    app.get('/clients', authenticate,  (req, res) => {
  Client.find({
    _creator: req.user._id,
  })
  .populate('transactions.transaction')
  .then((clients) => {
    res.send({clients});
  }, (e) => {
    res.status(400).send(e);
    console.log('Unable to get clients', e);
  })
});
</code>```

I know that I'm likely doing something completely wrong but I don't know where I need to look for my mistake. Please help!

答:
so first of all i don't exactly know what _creator key in Client model representing, it's probably user identifier who has some clients, but if I'm wrong please correct me.

Honestly I don't know why you are making two way document connection, (keeping client in transactions, and also keeping transactions in clients) in my opinion first option is better for mongodb and using that you can easily get transaction's list with find, or mongodb aggregation, but you can't get data using populate.

In second option you need to remember that one document could have maximum 16MB. And also keeping thousands of transactions in one array is not well for performance. Think about example that you have 5000 transaction and you want to show list with pagination (50 records per page), with array option you have to get whole document, and splice array to 50 records. In first option you could use mongodb skip and limit. Please think about it.

Returning to question, mistake you are doing is here:
    transaction.save().then((doc) => {

```<code>Client.findOneAndUpdate({
  _id: id,
  _creator: req.user._id,
  transactions: req.body.transaction
});

res.send(doc);
</code>```

Here you don't exactly say how this document should have to updated about.

Mongoose in method findOneAndUpdate using mongodb findAndModify method. But params are used from update.
https://docs.mongodb.com/manual/reference/method/db.collection.update/

And also documentation says that you what params like:
Query#findOneAndUpdate([query], [doc], [options], [options.passRawResult], [options.strict], [callback])

So first query param is mongo query to find one document in database, next param is object with updating query, and after that you could send some additional options in third param. So your code should looks like this:

```<code>transaction.save().then((doc) => {

Client.findOneAndUpdate({
  _id: id,
  _creator: req.user._id,
}, {
    $addToSet:  {
        transactions: doc._id,
    }
});

res.send(doc);
</code>```

You could use addToSet or push both are putting element into array, but addToSet avoiding duplicates in array. And as you se we push new transaction identifier into this array. And after all you only populate transaction key.

I hope I helped. If you have any questions please ask.

Body:
I'm very new to JavaScript and Mongoose. I'm building a small project using express, mongoose and node.js.
I have a mongoose model - Client that has an Array of Transactions

    var Client = mongoose.model('Client', {
 name: {
   type: String,
   required: true,
   minlength: 1
 },
 email: {
   type: String
 },
 phone: {
   type: Number
 },
 createdAt: {
   type: Number,
   default: null
 },
 transactions: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Transaction' }],
 _creator: {
   type: mongoose.Schema.Types.ObjectId,
   required: true
 }
});

module.exports = {Client};

This is Transaction model:

var Client = require('./client');

var Transaction = mongoose.model('Transaction',{
  _creator : { type: mongoose.Schema.Types.ObjectId, ref: 'Client' },
  amount : {type: Number, min: 0},
  date : {type: Number,default: null},
  total: {type: Number,default: null}
});

module.exports = {Transaction};

When I POST a new Transaction it goes through and saves in db:

 app.post('/clients/:id/transactions', authenticate, (req, res) => {
  var id = req.params.id;
  var transaction = new Transaction({
    amount: req.body.amount,
    date: new Date().getTime(),
    total: req.body.total,
    _creator: req.params.id
  })
  if (!ObjectID.isValid(id)) {
  return res.status(404).send();
  }

  transaction.save().then((doc) => {

    Client.findOneAndUpdate({
      _id: id,
      _creator: req.user._id,
      transactions: req.body.transaction
    });

    res.send(doc);
  }, (e) => {
    res.status(400).send(e);
  });

});

I am also able to GET all the transactions associated with the client:

  app.get('/clients/:id/transactions', authenticate, (req, res) => {
  var id = req.params.id;
  if (!ObjectID.isValid(id)) {
  return res.status(404).send();
 }
 Transaction.find({
   _creator: id
 }).then((transactions) => {
  res.send({transactions});
 }).catch((e) => {
  res.status(400).send();
 });
});

But when I make a GET call to '/clients' - Array of Transactions is empty:

    {
  "clients": [
    {
      "_id": "1095d6de3867001108b803",
      "name": "Peter",
      "email": "peter@gmail.com",
      "phone": 1232321,
      "_creator": "5321df6d57868ec7001108b801",
      "__v": 0,
      "transactions": [],
      "createdAt": null
    } ]
}

And this is the GET call to /clients

    app.get('/clients', authenticate,  (req, res) => {
  Client.find({
    _creator: req.user._id,
  })
  .populate('transactions.transaction')
  .then((clients) => {
    res.send({clients});
  }, (e) => {
    res.status(400).send(e);
    console.log('Unable to get clients', e);
  })
});

I know that I'm likely doing something completely wrong but I don't know where I need to look for my mistake. Please help!

Body:
so first of all i don't exactly know what _creator key in Client model representing, it's probably user identifier who has some clients, but if I'm wrong please correct me.

Honestly I don't know why you are making two way document connection, (keeping client in transactions, and also keeping transactions in clients) in my opinion first option is better for mongodb and using that you can easily get transaction's list with find, or mongodb aggregation, but you can't get data using populate.

In second option you need to remember that one document could have maximum 16MB. And also keeping thousands of transactions in one array is not well for performance. Think about example that you have 5000 transaction and you want to show list with pagination (50 records per page), with array option you have to get whole document, and splice array to 50 records. In first option you could use mongodb skip and limit. Please think about it.

Returning to question, mistake you are doing is here:
    transaction.save().then((doc) => {

Client.findOneAndUpdate({
  _id: id,
  _creator: req.user._id,
  transactions: req.body.transaction
});

res.send(doc);

Here you don't exactly say how this document should have to updated about.

Mongoose in method findOneAndUpdate using mongodb findAndModify method. But params are used from update.
https://docs.mongodb.com/manual/reference/method/db.collection.update/

And also documentation says that you what params like:
Query#findOneAndUpdate([query], [doc], [options], [options.passRawResult], [options.strict], [callback])

So first query param is mongo query to find one document in database, next param is object with updating query, and after that you could send some additional options in third param. So your code should looks like this:

transaction.save().then((doc) => {

Client.findOneAndUpdate({
  _id: id,
  _creator: req.user._id,
}, {
    $addToSet:  {
        transactions: doc._id,
    }
});

res.send(doc);

You could use addToSet or push both are putting element into array, but addToSet avoiding duplicates in array. And as you se we push new transaction identifier into this array. And after all you only populate transaction key.

I hope I helped. If you have any questions please ask.


问:
SQL Query to return new column based on first two columns
I have a table that looks like this:

```<code>username    manager
emp001      emp006
emp002      emp006
emp003      emp006
emp004      emp007
emp005      emp007
emp006      emp009
emp007      emp010
emp008      emp010
emp009      emp011
emp010      null
emp011      null
</code>```

I would like to create a select query that returns a third column like this - where the new column is based taking the manager item and referring back to the first column and getting manager of that row.

```<code>username    manager    director
emp001      emp006     emp009
emp002      emp006     emp009
emp003      emp006     emp009
emp004      emp007     emp010
emp005      emp007     emp010
emp006      emp009     emp011
emp007      emp010     null
emp008      emp010     null
emp009      emp011     null
emp010      null       null
emp011      null       null
</code>```

I'm lost on this one.

Thanks for any advise. I've tried various combinations of selects and joins but nothing seems to do what I want.

Thank you!

答:
Join the same table using another alias name :

```<code>select a.username,a.manager,b.manager as director
from TableName a left join
TableName b on a.manager=b.username
</code>```

Result:

```<code>username    manager     director
emp001      emp006      emp009
emp002      emp006      emp009
emp003      emp006      emp009
emp004      emp007      emp010
emp005      emp007      emp010
emp006      emp009      emp011
emp007      emp010      (null)
emp008      emp010      (null)
emp009      emp011      (null)
emp010      (null)      (null)
emp011      (null)      (null)
</code>```

See result in SQL Fiddle

Body:
I have a table that looks like this:

username    manager
emp001      emp006
emp002      emp006
emp003      emp006
emp004      emp007
emp005      emp007
emp006      emp009
emp007      emp010
emp008      emp010
emp009      emp011
emp010      null
emp011      null

I would like to create a select query that returns a third column like this - where the new column is based taking the manager item and referring back to the first column and getting manager of that row.

username    manager    director
emp001      emp006     emp009
emp002      emp006     emp009
emp003      emp006     emp009
emp004      emp007     emp010
emp005      emp007     emp010
emp006      emp009     emp011
emp007      emp010     null
emp008      emp010     null
emp009      emp011     null
emp010      null       null
emp011      null       null

I'm lost on this one.

Thanks for any advise. I've tried various combinations of selects and joins but nothing seems to do what I want.

Thank you!

Body:
Join the same table using another alias name :

select a.username,a.manager,b.manager as director
from TableName a left join
TableName b on a.manager=b.username

Result:

username    manager     director
emp001      emp006      emp009
emp002      emp006      emp009
emp003      emp006      emp009
emp004      emp007      emp010
emp005      emp007      emp010
emp006      emp009      emp011
emp007      emp010      (null)
emp008      emp010      (null)
emp009      emp011      (null)
emp010      (null)      (null)
emp011      (null)      (null)

See result in SQL Fiddle


问:
filter between two dates from API with angularjs
i retrieve details of an account from an API statement based on the user ID with the below script

```<code>    $http.post("http://testingserver.net/statement.php",{'id':$scope.account_number}).success
    (function(data){
    console.log(JSON.stringify(data));
$scope.statement=data;
    });
</code>```

From the log i'm able to get the data in detail. The data from the log contains a field called Date which is formatted 2017-02-01T00:00:00Z and what i want to achieve is to let the user select from two date ranges and push back the results to the user.

From the HTML below they are two fields namely sdate and edate

HTML

```<code><form method="post" name="statement" id="statement">
<div class="list">
  <label class="item item-input">
    <span class="input-label">Search From</span>
    <input type="date" ng-model="sdate">
  </label>
  <label class="item item-input">
    <span class="input-label">Search To</span>
    <input type="date" ng-model="edate">
  </label>
</div>
</form>
</br>
<div align="center">
<p><button class="button button-positive" ng-disabled="statement.$invalid" ng-click="state_request()">
  <i class="icon ion-android-search icon"></i> Search
</button></p>
</div>
</code>```

HTML for results

```<code><div ng-repeat="item in statement">
  <table width="100%" border="0" cellspacing="5" cellpadding="5">
    <tr>
      <td width="70%"><div align="left">
        <p><strong> Period</strong>      </p>
      </div></td>
      <td width="82%">{{item.Date |date: 'MMMM yyyy'}}</td>
    </tr>
    <tr>
      <td><p><strong>Category</strong></p></td>
      <td>{{item.Category}}</td>
    </tr>
    <tr>
      <td><div align="left">
        <p><strong>Amount</strong>      </p>
      </div></td>
      <td><div align="left">{{item.Amount}}</div></td>
    </tr>
    <tr>
      <td colspan="2"> </td>
    </tr>
  </table>
</div>
</code>```

答:
If you are attempting to format the date you might want to use momentjs javascript time/date lib

It makes it incredibly easy to format and work with dates, especially concerning time inputs.

Body:
i retrieve details of an account from an API statement based on the user ID with the below script

    $http.post("http://testingserver.net/statement.php",{'id':$scope.account_number}).success
    (function(data){
    console.log(JSON.stringify(data));
$scope.statement=data;
    });

From the log i'm able to get the data in detail. The data from the log contains a field called Date which is formatted 2017-02-01T00:00:00Z and what i want to achieve is to let the user select from two date ranges and push back the results to the user.

From the HTML below they are two fields namely sdate and edate

HTML

<form method="post" name="statement" id="statement">

    Search From
    <input type="date" ng-model="sdate">

    Search To
    <input type="date" ng-model="edate">

</form>

<button class="button button-positive" ng-disabled="statement.$invalid" ng-click="state_request()">
   Search
</button>

HTML for results

 Period

      {{item.Date |date: 'MMMM yyyy'}}

Category

      {{item.Category}}

Amount

{{item.Amount}}


问:
Assign a different macro per click of VBA Button
I have an excel button that hides columns "S-U" when I click it. I want to click the button a 2nd time and it hides columns "P-R" and etc. Can you manipulate an excel button per click?</p>

答:
If there are just a few things you want it to do (it sounds like it), I would have my macro evaluate the current state and act accordingly.

In your example, you indicate that you first want it to hide S-U, then P-R on a second click. This will do that:

```<code>Sub HideColumns()

    If Sheets("Sheet1").Range("S:S").EntireColumn.Hidden = False Then
        Sheets("Sheet1").Range("S:U").EntireColumn.Hidden = True
    Else
        Sheets("Sheet1").Range("P:R").EntireColumn.Hidden = True
    End If

End Sub
</code>```

Of course, you can extend this with additional conditions and actions.. like changing the text of the button to represent what it will do next:

Assume you have it labeled "Hide Rows S:U" to start, you can change it inside VBA to indicate what it would do on the next click:

```<code>Sub HideColumnsUpdateText()

    If Sheets("Sheet1").Range("S:S").EntireColumn.Hidden = False Then

        Sheets("Sheet1").Range("S:U").EntireColumn.Hidden = True
        Sheets("Sheet1").Buttons("Button 1").Text = "Hide Rows P:R"

    Else
        Sheets("Sheet1").Range("P:R").EntireColumn.Hidden = True

    End If

End Sub
</code>```

There's really no end to what you can do once you start evaluating the current state (extend using ElseIf, or even use Case). You just have to keep the logic straight.

Edit to further expand:
If your situation is linear - that is, if want to hide more and more columns in the same order, you just need to do else ifs to evaluate the situation, and step through the order that you want to hide them.

Personal note: I find that "IF whatever =true" statements are a little easier to follow than "if whatever = false" (and technically, you don't even have to have type the "=True"). But it means you need to start at the last possibility, and work backwards. Otherwise you need to evaluate by  "= False" (like I first demonstrated), but I find it a little harder to follow. Your results may vary.

You indicated that you want these hidden in order: "S:U","P:R","M:O","J:L","G:I" . Here is a script that, once all of those rows are hidden, the button would then show them all. So I start by evaluating if the last possibility is true -that is- are Rows G:I hidden already? If so, then show them all. I've also included updating the button text, but that's optional.

```<code>Sub hideSetsOfColumnsProgressively()
    ' progressive order of button function: "S:U","P:R","M:O","J:L","G:I","Unhide Rows"
    If Sheets("Sheet1").Range("G:I").EntireColumn.Hidden = True Then
       Sheets("Sheet1").Range("G:U").EntireColumn.Hidden = False 'shows all rows
       'optionally change the text of the button to indicate the next function:
       Sheets("Sheet1").Buttons("Button 1").Text = "Hide Rows S:U"

    ElseIf Sheets("Sheet1").Range("J:L").EntireColumn.Hidden = True Then
    'then we've already hidden all of the other columns, so do the last set
        Sheets("Sheet1").Range("G:I").EntireColumn.Hidden = True
        Sheets("Sheet1").Buttons("Button 1").Text = "Unhide Rows"

    ElseIf Sheets("Sheet1").Range("M:O").EntireColumn.Hidden = True Then
        Sheets("Sheet1").Range("J:L").EntireColumn.Hidden = True
        Sheets("Sheet1").Buttons("Button 1").Text = "Hide Rows G:I"

    ElseIf Sheets("Sheet1").Range("P:R").EntireColumn.Hidden = True Then
        Sheets("Sheet1").Range("M:O").EntireColumn.Hidden = True
        Sheets("Sheet1").Buttons("Button 1").Text = "Hide Rows J:L"

    ElseIf Sheets("Sheet1").Range("S:U").EntireColumn.Hidden = True Then
        Sheets("Sheet1").Range("P:R").EntireColumn.Hidden = True
        Sheets("Sheet1").Buttons("Button 1").Text = "Hide Rows M:O"

    Else
        Sheets("Sheet1").Range("S:U").EntireColumn.Hidden = True
        Sheets("Sheet1").Buttons("Button 1").Text = "Hide Rows P:R"
    End If

End Sub
</code>```

The nice part about this script is that it loops. You can just keep clicking it and it will hide progressively more and more rows, then show them all.

I hope this answers your question. Keep in mind that the logic has to be solid, or you'll get unexpected results.

Body:
If there are just a few things you want it to do (it sounds like it), I would have my macro evaluate the current state and act accordingly.

In your example, you indicate that you first want it to hide S-U, then P-R on a second click. This will do that:

Sub HideColumns()

    If Sheets("Sheet1").Range("S:S").EntireColumn.Hidden = False Then
        Sheets("Sheet1").Range("S:U").EntireColumn.Hidden = True
    Else
        Sheets("Sheet1").Range("P:R").EntireColumn.Hidden = True
    End If

End Sub

Of course, you can extend this with additional conditions and actions.. like changing the text of the button to represent what it will do next:

Assume you have it labeled "Hide Rows S:U" to start, you can change it inside VBA to indicate what it would do on the next click:

Sub HideColumnsUpdateText()

    If Sheets("Sheet1").Range("S:S").EntireColumn.Hidden = False Then

        Sheets("Sheet1").Range("S:U").EntireColumn.Hidden = True
        Sheets("Sheet1").Buttons("Button 1").Text = "Hide Rows P:R"

    Else
        Sheets("Sheet1").Range("P:R").EntireColumn.Hidden = True

    End If

End Sub

There's really no end to what you can do once you start evaluating the current state (extend using ElseIf, or even use Case). You just have to keep the logic straight.

Edit to further expand:
If your situation is linear - that is, if want to hide more and more columns in the same order, you just need to do else ifs to evaluate the situation, and step through the order that you want to hide them.

Personal note: I find that "IF whatever =true" statements are a little easier to follow than "if whatever = false" (and technically, you don't even have to have type the "=True"). But it means you need to start at the last possibility, and work backwards. Otherwise you need to evaluate by  "= False" (like I first demonstrated), but I find it a little harder to follow. Your results may vary.

You indicated that you want these hidden in order: "S:U","P:R","M:O","J:L","G:I" . Here is a script that, once all of those rows are hidden, the button would then show them all. So I start by evaluating if the last possibility is true -that is- are Rows G:I hidden already? If so, then show them all. I've also included updating the button text, but that's optional.

Sub hideSetsOfColumnsProgressively()
    ' progressive order of button function: "S:U","P:R","M:O","J:L","G:I","Unhide Rows"
    If Sheets("Sheet1").Range("G:I").EntireColumn.Hidden = True Then
       Sheets("Sheet1").Range("G:U").EntireColumn.Hidden = False 'shows all rows
       'optionally change the text of the button to indicate the next function:
       Sheets("Sheet1").Buttons("Button 1").Text = "Hide Rows S:U"

    ElseIf Sheets("Sheet1").Range("J:L").EntireColumn.Hidden = True Then
    'then we've already hidden all of the other columns, so do the last set
        Sheets("Sheet1").Range("G:I").EntireColumn.Hidden = True
        Sheets("Sheet1").Buttons("Button 1").Text = "Unhide Rows"

    ElseIf Sheets("Sheet1").Range("M:O").EntireColumn.Hidden = True Then
        Sheets("Sheet1").Range("J:L").EntireColumn.Hidden = True
        Sheets("Sheet1").Buttons("Button 1").Text = "Hide Rows G:I"

    ElseIf Sheets("Sheet1").Range("P:R").EntireColumn.Hidden = True Then
        Sheets("Sheet1").Range("M:O").EntireColumn.Hidden = True
        Sheets("Sheet1").Buttons("Button 1").Text = "Hide Rows J:L"

    ElseIf Sheets("Sheet1").Range("S:U").EntireColumn.Hidden = True Then
        Sheets("Sheet1").Range("P:R").EntireColumn.Hidden = True
        Sheets("Sheet1").Buttons("Button 1").Text = "Hide Rows M:O"

    Else
        Sheets("Sheet1").Range("S:U").EntireColumn.Hidden = True
        Sheets("Sheet1").Buttons("Button 1").Text = "Hide Rows P:R"
    End If

End Sub

The nice part about this script is that it loops. You can just keep clicking it and it will hide progressively more and more rows, then show them all.

I hope this answers your question. Keep in mind that the logic has to be solid, or you'll get unexpected results.


问:
Receiving Thread 1: Signal SIGABRT error in App Delegate.swift, I am a brand new developer
I have looked everywhere and was not able to get an Answer that worked out. I am doing the Apple Tutorial Here. After I reached a checkpoint where it said run the App to make sure everything works I ran into this issue. Any help will be greatly appreciated. I am new developer so every advise I get from you guys will help me out in the future. If more information is necessary let me know and I will gladly provide it! </p>

答:
First, add view controller class to your view controller on storyboard

Next drag button and text field

Then, connect to your code. Text field is connected as IBOutLet and button is connected as action

Then, add your code like this

```<code>@IBOutlet weak var text: UITextField!

@IBAction func click(_ sender: Any) {
    text.text = "show up"
}
</code>```

Finally, test your result

Body:
First, add view controller class to your view controller on storyboard

Next drag button and text field

Then, connect to your code. Text field is connected as IBOutLet and button is connected as action

Then, add your code like this

@IBOutlet weak var text: UITextField!

@IBAction func click(_ sender: Any) {
    text.text = "show up"
}

Finally, test your result


问:
Why Is XDocument.Descendants().Count() > 0 for an Empty Document?
Here's my method:

```<code>var document = XDocument.Parse(source);
if (document.Descendants().Count() > 0)
{
    // Some code that shouldn't execute
}
else
{
    // Code that should execute
}
</code>```

This code breaks when this is in the 'document' variable:

```<code><ipb></ipb>
</code>```

Since this DOESN'T have descendants, why is it entering the IF conditional? Is shouldn't try to load anything, yet it does and breaks when it finds nothing to scrape.

Using Breakpoints I can confirm that the document variable has the content I posted above when it breaks and it does enter the if.

答: ipb is your first descendant on the document, right?  Don't you want document.Root.Descendants() ?

OwnerDisplayName: delete

ContentLicense: CC BY-SA 2.5

Body:
Here's my method:

var document = XDocument.Parse(source);
if (document.Descendants().Count() > 0)
{
    // Some code that shouldn't execute
}
else
{
    // Code that should execute
}

This code breaks when this is in the 'document' variable:

<ipb></ipb>

Since this DOESN'T have descendants, why is it entering the IF conditional? Is shouldn't try to load anything, yet it does and breaks when it finds nothing to scrape.

Using Breakpoints I can confirm that the document variable has the content I posted above when it breaks and it does enter the if.


问:
Place API - getting place photo as marker icon
I follow this guide
https://developers.google.com/maps/documentation/javascript/places#places_photos
to create place photo as marker icon. This is my map initialization code:

```<code>var map;

function initMap() {
    // Create a map centered in Pyrmont, Sydney (Australia).
      map = new google.maps.Map(document.getElementById('map'), {
        center: {lat: -6.920812, lng: 107.604116},
        zoom: 13
      });

      var request = {
        location: map.getCenter(),
        radius: '5000',
        type: ['shopping_mall']
      };

      var service = new google.maps.places.PlacesService(map);
      service.textSearch(request, callback);
}

// Checks that the PlacesServiceStatus is OK, and adds a marker
// using the place ID and location from the PlacesService.
function callback(results, status) {
  console.log(results);
  if (status == google.maps.places.PlacesServiceStatus.OK) {
      for (var i = 0; i < results.length; i++) {
        var place = results[i];
        createPhotoMarker(place);
      }
  }
}

google.maps.event.addDomListener(window, 'load', initMap);
</code>```

this is the createPhotoMarker function

```<code>function createPhotoMarker(place) {
      var photos = place.photos;
      if (!photos) {
        var marker = new google.maps.Marker({
            map: map,
            position: place.geometry.location,
            title: place.name
          });
          return;
      }

      var marker = new google.maps.Marker({
        map: map,
        position: place.geometry.location,
        title: place.name,
        icon: photos[0].getUrl({'maxWidth': 35, 'maxHeight': 35})
      });
}
</code>```

the function will create regular marker if place photo is not available. But for the place with photo available, I get this error :

Failed to load resource: the server responded with a status of 404 () lh3.googleusercontent.com/w35-h35-p/AF1QipOIL6GVVmtqp_cw_hBEQxdILZSa8poMO0HAqFHd=k

And the map only shows regular marker.
What did I do wrong?

This is the fiddle http://jsfiddle.net/v90fmrhp/

==========Update 2017-07-07============

Thanks for the answers and fixes

It seems the issue solved. My fiddle is working now
https://issuetracker.google.com/issues/63298126

Marked as Fixed

  Good news! We have fixed this issue. Thanks for your patience.

Happy Mapping!

答:
I also ran into this with google places api.  Everything was working fine then randomly it stopped.  It seems likely that it is due to google making changes as they get ready for releasing a better maps api to support vector</p>

<p>@DKinnison saved me with his solution so I just wanted to post my ES6 solution for parsing a received place.  I commented out the other properties I am personally not using in case you need to.  </p>

```<code>const PHOTO_WIDTH = 600;
const PHOTO_HEIGHT = 600;

export function parseGooglePlace(place) {
  if (!place) {
    return;
  }
  const {
    // address_components,
    formatted_address,
    geometry,
    // icon,
    // id,
    // international_phone_number,
    name,
    // rating,
    // reviews,
    // opening_hours,
    photos: _photos = [],
    place_id,
    // reference,
    types = [],
    // url: mapsURL,
    // utc_offset,
    // vicinity,
    website,
  } = place;

  const photos = _photos.map(p =>
    p
      .getUrl({ maxWidth: PHOTO_WIDTH, maxHeight: PHOTO_HEIGHT })
      .replace(`w${PHOTO_WIDTH}-h${PHOTO_HEIGHT}-p`, 'p'),
  );

  return {
    website,
    name,
    photos,
    address: formatted_address,
    placeId: place_id,
    geometry,
    types,
  };
}
</code>```

Body:
I follow this guide
https://developers.google.com/maps/documentation/javascript/places#places_photos
to create place photo as marker icon. This is my map initialization code:

var map;

function initMap() {
    // Create a map centered in Pyrmont, Sydney (Australia).
      map = new google.maps.Map(document.getElementById('map'), {
        center: {lat: -6.920812, lng: 107.604116},
        zoom: 13
      });

      var request = {
        location: map.getCenter(),
        radius: '5000',
        type: ['shopping_mall']
      };

      var service = new google.maps.places.PlacesService(map);
      service.textSearch(request, callback);
}

// Checks that the PlacesServiceStatus is OK, and adds a marker
// using the place ID and location from the PlacesService.
function callback(results, status) {
  console.log(results);
  if (status == google.maps.places.PlacesServiceStatus.OK) {
      for (var i = 0; i < results.length; i++) {
        var place = results[i];
        createPhotoMarker(place);
      }
  }
}

google.maps.event.addDomListener(window, 'load', initMap);

this is the createPhotoMarker function

function createPhotoMarker(place) {
      var photos = place.photos;
      if (!photos) {
        var marker = new google.maps.Marker({
            map: map,
            position: place.geometry.location,
            title: place.name
          });
          return;
      }

      var marker = new google.maps.Marker({
        map: map,
        position: place.geometry.location,
        title: place.name,
        icon: photos[0].getUrl({'maxWidth': 35, 'maxHeight': 35})
      });
}

the function will create regular marker if place photo is not available. But for the place with photo available, I get this error :

Failed to load resource: the server responded with a status of 404 () lh3.googleusercontent.com/w35-h35-p/AF1QipOIL6GVVmtqp_cw_hBEQxdILZSa8poMO0HAqFHd=k

And the map only shows regular marker.
What did I do wrong?

This is the fiddle http://jsfiddle.net/v90fmrhp/

==========Update 2017-07-07============

Thanks for the answers and fixes

It seems the issue solved. My fiddle is working now
https://issuetracker.google.com/issues/63298126

Marked as Fixed

  Good news! We have fixed this issue. Thanks for your patience.

Happy Mapping!

Body:
I also ran into this with google places api.  Everything was working fine then randomly it stopped.  It seems likely that it is due to google making changes as they get ready for releasing a better maps api to support vector

@DKinnison saved me with his solution so I just wanted to post my ES6 solution for parsing a received place.  I commented out the other properties I am personally not using in case you need to.

const PHOTO_WIDTH = 600;
const PHOTO_HEIGHT = 600;

export function parseGooglePlace(place) {
  if (!place) {
    return;
  }
  const {
    // address_components,
    formatted_address,
    geometry,
    // icon,
    // id,
    // international_phone_number,
    name,
    // rating,
    // reviews,
    // opening_hours,
    photos: _photos = [],
    place_id,
    // reference,
    types = [],
    // url: mapsURL,
    // utc_offset,
    // vicinity,
    website,
  } = place;

  const photos = _photos.map(p =>
    p
      .getUrl({ maxWidth: PHOTO_WIDTH, maxHeight: PHOTO_HEIGHT })
      .replace(`w${PHOTO_WIDTH}-h${PHOTO_HEIGHT}-p`, 'p'),
  );

  return {
    website,
    name,
    photos,
    address: formatted_address,
    placeId: place_id,
    geometry,
    types,
  };
}


问:
Can I use insertAdjacentHTML to insert DOM element
insertAdjacentHTML expects 2 arguments:

position ("beforebegin", "afterbegin", "beforeend", "afterend")

html (will be converted from text to DOM)

Can I pass DOM element as the second argument?

答:
.insertAdjacentHTML() only accept string that will be parsed as HTML and inserted (like innerHTML)

To insert DOM element you can use .insertAdjacentElement()

MDN: https://developer.mozilla.org//docs/Web/API/Element/insertAdjacentElement


问:
hl-line-mode emacs color change
Emacs' hl-line-mode is just what i need but i would like to change it's horrible yellow color, anyone know how can i do that?</p>

答:
M-x customize-group RET hl-line RET

and modify "Hl Line face".

Alternatively, you could use (for example):

(set-face-background 'hl-line "#333333")

edit: cheeso's answer would be the more robust approach for that second version.

Title: hl-line-mode emacs color change


问:
Using forceRootUrl() breaks some routing
I have my Laravel app running from a subdirectory, so in order to be able to use the URL helper like this: {{ url('users') }} instead of like this {{ url('subdirectory/users') }} I use the forceRouteUrl() method in my AppServiceProvider.php file. It looks like this:

```<code>public function boot()
    {
        URL::forceRootUrl(Config::get('app.url'));

...
</code>```

And my .env: APP_URL=http://app.dev/subdirectory

So far so good, except when returning routes. For example I have a sorting method that does this:

```<code>function sort_schedule($column, $order)
{
    return route('schedule', [
                 'sortBy' => $column,
                 'sortOrder' => $order,
            ]
         );
}
</code>```

But the link it generates is this: http://app.dev/subdirectory/subdirectory/...

The same thing happens when I use Kyslik's Column Sortable package.

How can I fix this?

答:
It seems that while other helpers like url() or asset() don't have this issue, the route() helper tends to duplicate the subpath when laravel isn't accessible directly from the site root and forceRootUrl() is used.
I'm using laravel 5.4 but this problem is present on previous versions too.

To solve this issue i found three possible solutions:

Use url() instead of route() and manually create your urls

Everytime you use route() remember to pass false as the third parameter, it will use relative paths that don't have this issue

Override the default route() helper with a custom one

I opted for the third option and created a CustomHelper.php file that contains my new route() helper.
Here are the instructions on how to override default helpers:
https://laracasts.com/discuss/channels/general-discussion/override-functions-in-supporthelpersphp

Inside my CustomHelper.php file I added this

```<code>function route($name, $parameters = [], $absolute = true)
{
    $appUrl = config('app.url'); // in your case: http://app.dev
    $appUrlSuffix = config('app.url_suffix'); // in your case: subdirectory

    // Additional check, do the workaround only when a suffix is present and only when urls are absolute
    if ($appUrlSuffix && $absolute) {
        // Add the relative path to the app root url
        $relativePath = app('url')->route($name, $parameters, false);
        $url = $appUrl.$relativePath;
    } else {
        // This is the default behavior of route() you can find in laravel\vendor\laravel\framework\src\Illuminate\Foundation\helpers.php
        $url = app('url')->route($name, $parameters, $absolute);
    }

    return $url;
}
</code>```

The app.url_suffix is a custom variable that i defined in config/app.php

```<code>'url_suffix' => env('APP_URL_SUFFIX', null),
</code>```

and in the .env config file

```<code>APP_URL_SUFFIX=subdirectory
</code>```

Body:
I have my Laravel app running from a subdirectory, so in order to be able to use the URL helper like this: {{ url('users') }} instead of like this {{ url('subdirectory/users') }} I use the forceRouteUrl() method in my AppServiceProvider.php file. It looks like this:

public function boot()
    {
        URL::forceRootUrl(Config::get('app.url'));

...

And my .env: APP_URL=http://app.dev/subdirectory

So far so good, except when returning routes. For example I have a sorting method that does this:

function sort_schedule($column, $order)
{
    return route('schedule', [
                 'sortBy' => $column,
                 'sortOrder' => $order,
            ]
         );
}

But the link it generates is this: http://app.dev/subdirectory/subdirectory/...

The same thing happens when I use Kyslik's Column Sortable package.

How can I fix this?

Body:
It seems that while other helpers like url() or asset() don't have this issue, the route() helper tends to duplicate the subpath when laravel isn't accessible directly from the site root and forceRootUrl() is used.
I'm using laravel 5.4 but this problem is present on previous versions too.

To solve this issue i found three possible solutions:

Use url() instead of route() and manually create your urls

Everytime you use route() remember to pass false as the third parameter, it will use relative paths that don't have this issue

Override the default route() helper with a custom one

I opted for the third option and created a CustomHelper.php file that contains my new route() helper.
Here are the instructions on how to override default helpers:
https://laracasts.com/discuss/channels/general-discussion/override-functions-in-supporthelpersphp

Inside my CustomHelper.php file I added this

function route($name, $parameters = [], $absolute = true)
{
    $appUrl = config('app.url'); // in your case: http://app.dev
    $appUrlSuffix = config('app.url_suffix'); // in your case: subdirectory

    // Additional check, do the workaround only when a suffix is present and only when urls are absolute
    if ($appUrlSuffix && $absolute) {
        // Add the relative path to the app root url
        $relativePath = app('url')->route($name, $parameters, false);
        $url = $appUrl.$relativePath;
    } else {
        // This is the default behavior of route() you can find in laravel\vendor\laravel\framework\src\Illuminate\Foundation\helpers.php
        $url = app('url')->route($name, $parameters, $absolute);
    }

    return $url;
}

The app.url_suffix is a custom variable that i defined in config/app.php

'url_suffix' => env('APP_URL_SUFFIX', null),

and in the .env config file

APP_URL_SUFFIX=subdirectory


问:
Am I saving myself anything by checking for Zone?
I have a global function that lets me run a function inside an Angular zone when I don't know if that part of the code was run from outside of Angular.

Here's the function:

```<code>export class Zones {
    public static maybe(zone: NgZone, callee: () => any) {
        return NgZone.isInAngularZone()
            ? callee()
            : zone.run(callee);
    }
}
</code>```

After I started using this function. I started to wonder if this check was redundant. Maybe the NgZone.run() method already calls isInAngularZone and does the above logic also.

I tried looking at the Angular source code, but zones are handled by another library and I got lost trying to follow the execution path.

Here's the zone project:

https://github.com/angular/zone.js/

So I continue to use the above function but want to verify that it's needed.

答:
NgZone.run() is just a delegate to Zone.prototype.run() for the angular zone and does not prevent additional frames. Rather, it tracks the nesting depth of the current angular zone so that it can defer zone turn operations (e.g., change detection) until after all frames within the angular zone have completed. Because of this, your guard would provide a small performance boost in certain cases. Keep in mind that the cost of adding an additional zone frame should be very small, though, so this would likely be most useful for functions that get called very frequently.

The NgZone source can be found here:
https://github.com/angular/angular/blob/bebedfed24d6fbfa492e97f071e1d1b41e411280/packages/core/src/zone/ng_zone.ts#L233

The invocation of a task on NgZone.inner (the angular zone) triggers the onEnter() and onLeave() functions, which manage the nesting level and trigger angular zone turn events when necessary.

And the ApplicationRef_ source, which is where many (all?) of Angular's primary hooks into zone turns are applied, can be found here:
https://github.com/angular/angular/blob/c59c390cdcd825cca67a422bc8738f7cd9ad42c5/packages/core/src/application_ref.ts#L443

The key statement for change detection is this.tick(). The ApplicationRef.tick() function is what triggers the change detection cycle.

Body:
I have a global function that lets me run a function inside an Angular zone when I don't know if that part of the code was run from outside of Angular.

Here's the function:

export class Zones {
    public static maybe(zone: NgZone, callee: () => any) {
        return NgZone.isInAngularZone()
            ? callee()
            : zone.run(callee);
    }
}

After I started using this function. I started to wonder if this check was redundant. Maybe the NgZone.run() method already calls isInAngularZone and does the above logic also.

I tried looking at the Angular source code, but zones are handled by another library and I got lost trying to follow the execution path.

Here's the zone project:

https://github.com/angular/zone.js/

So I continue to use the above function but want to verify that it's needed.


问:
Winston logger not write to file
I want to use winston logger in node app for log error to file. But winston not write to file.

```<code>var logger = new (winston.Logger)({
             transports: [
                new (winston.transports.Console)(),
                new (winston.transports.File)({ filename: 'somefile.log' })
              ]
            });

 logger.error('test');
</code>```

file somefile.log is created but empty.

答:
You need to define a level in the constructor.</p>

```<code>var tsFormat = () => (new Date()).toLocaleTimeString();
var log = new (winston.Logger)({
    transports: [
        new (winston.transports.Console)({
            timestamp: tsFormat,
            colorize: true,
            level: 'info'
        }),
        new (winston.transports.File)({
            filename: 'somefile.log',
            level: 'error'
        })
    ]
});

log.error('test'); // writes to log and console out
log.info('testing info'); // writes just in console
</code>```

Title: Winston logger not write to file

Body:
I want to use winston logger in node app for log error to file. But winston not write to file.

var logger = new (winston.Logger)({
             transports: [
                new (winston.transports.Console)(),
                new (winston.transports.File)({ filename: 'somefile.log' })
              ]
            });

 logger.error('test');

file somefile.log is created but empty.

Body:
You need to define a level in the constructor.

var tsFormat = () => (new Date()).toLocaleTimeString();
var log = new (winston.Logger)({
    transports: [
        new (winston.transports.Console)({
            timestamp: tsFormat,
            colorize: true,
            level: 'info'
        }),
        new (winston.transports.File)({
            filename: 'somefile.log',
            level: 'error'
        })
    ]
});

log.error('test'); // writes to log and console out
log.info('testing info'); // writes just in console


问:
Why are Angular Material tooltips breaking my unit tests?
I have the following unit test file, which is a duplicate of a working file from another similar component and not too far from boilerplate Angular CLI output:

```<code>import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { Http, HttpModule } from '@angular/http';
import { MockBackend } from '@angular/http/testing';
import { CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';

import { PageHeaderComponent } from './page-header.component';
import { UserService } from '../user.service';
import { PreloadService } from '../preload.service';

describe('PageHeaderComponent', () => {
    let component: PageHeaderComponent;
    let fixture: ComponentFixture<PageHeaderComponent>;

    beforeEach(() => {
        TestBed.configureTestingModule({
            declarations: [PageHeaderComponent],
            providers: [
                {
                    provide: Http,
                    deps: [MockBackend]
                },
                PreloadService,
                UserService
            ],
            schemas: [CUSTOM_ELEMENTS_SCHEMA]
        });

        fixture = TestBed.createComponent(PageHeaderComponent);
        component = fixture.componentInstance;
    });

    it('should be created', () => {
        expect(component).toBeTruthy();
    });
});
</code>```

However, this one fails due to a problem with mdTooltip. It results in this error:

PhantomJS 2.1.1 (Linux 0.0.0) PageHeaderComponent should be created FAILED

Error: Template parse errors:
          Can't bind to 'mdTooltipDisabled' since it isn't a known property of 'button'. ("fxLayoutAlign="start center" class="text-medium">
                      ][mdTooltipDisabled]="showHeaderTooltip">
                          view_agenda
                      ][mdTooltipDisabled]="showHeaderTooltip">
                          directions
                      ][mdTooltipDisabled]="showHeaderTooltip" href="{{environment?.search_url}}">
                          http://localhost:9876/_karma_webpack_/vendor.bundle.js (line 25078)
          parse@http://localhost:9876/_karma_webpack_/vendor.bundle.js:25078:72
          _compileTemplate@http://localhost:9876/_karma_webpack_/vendor.bundle.js:39124:44

....

Here's an example of the markup:

```<code><button md-button mdTooltip="Topics" [mdTooltipDisabled]="showHeaderTooltip">
    <md-icon>view_agenda</md-icon> <span fxShow.xs="false">Topics</span>
</button>
</code>```

Here is my version table:

```<code>@angular/cli: 1.1.2
node: 6.11.0
os: linux x64
@angular/animations: 4.2.3
@angular/common: 4.2.3
@angular/compiler: 4.2.3
@angular/core: 4.2.3
@angular/forms: 4.2.3
@angular/http: 4.2.3
@angular/platform-browser: 4.2.3
@angular/platform-browser-dynamic: 4.2.3
@angular/router: 4.2.3
@angular/cli: 1.1.2
@angular/compiler-cli: 4.2.3
@angular/flex-layout: 2.0.0-beta.8
@angular/language-service: 4.2.3
@angular/material: 2.0.0-beta.7
</code>```

What do I need to provide to mock or otherwise handle the mdTooltip service, which apparently involves an observable?

Update: Apparently this occurs for other AM services as well, such as mdMenuTriggerFor.

答:
Take a look at this:

https://github.com/angular/material2/issues/2478

"Fixed by importing ‘MaterialModule’ to TestBed.configureTestingModule in failing spec."

As in:

```<code>   TestBed.configureTestingModule({
        declarations: [PageHeaderComponent],
        providers: [
            {
                imports: [RouterTestingModule.withRoutes([]), MaterialModule],
                provide: Http,
                deps: [MockBackend]
            },
            PreloadService,
            UserService
        ],
        schemas: [CUSTOM_ELEMENTS_SCHEMA]
    });
</code>```

Body:
I have the following unit test file, which is a duplicate of a working file from another similar component and not too far from boilerplate Angular CLI output:

import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { Http, HttpModule } from '@angular/http';
import { MockBackend } from '@angular/http/testing';
import { CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';

import { PageHeaderComponent } from './page-header.component';
import { UserService } from '../user.service';
import { PreloadService } from '../preload.service';

describe('PageHeaderComponent', () => {
    let component: PageHeaderComponent;
    let fixture: ComponentFixture<PageHeaderComponent>;

    beforeEach(() => {
        TestBed.configureTestingModule({
            declarations: [PageHeaderComponent],
            providers: [
                {
                    provide: Http,
                    deps: [MockBackend]
                },
                PreloadService,
                UserService
            ],
            schemas: [CUSTOM_ELEMENTS_SCHEMA]
        });

        fixture = TestBed.createComponent(PageHeaderComponent);
        component = fixture.componentInstance;
    });

    it('should be created', () => {
        expect(component).toBeTruthy();
    });
});

However, this one fails due to a problem with mdTooltip. It results in this error:

PhantomJS 2.1.1 (Linux 0.0.0) PageHeaderComponent should be created FAILED

Error: Template parse errors:
          Can't bind to 'mdTooltipDisabled' since it isn't a known property of 'button'. ("fxLayoutAlign="start center" class="text-medium">
                      ][mdTooltipDisabled]="showHeaderTooltip">
                          view_agenda
                      ][mdTooltipDisabled]="showHeaderTooltip">
                          directions
                      ][mdTooltipDisabled]="showHeaderTooltip" href="{{environment?.search_url}}">
                          http://localhost:9876/_karma_webpack_/vendor.bundle.js (line 25078)
          parse@http://localhost:9876/_karma_webpack_/vendor.bundle.js:25078:72
          _compileTemplate@http://localhost:9876/_karma_webpack_/vendor.bundle.js:39124:44

....

Here's an example of the markup:

<button md-button mdTooltip="Topics" [mdTooltipDisabled]="showHeaderTooltip">
    <md-icon>view_agenda</md-icon> Topics
</button>

Here is my version table:

@angular/cli: 1.1.2
node: 6.11.0
os: linux x64
@angular/animations: 4.2.3
@angular/common: 4.2.3
@angular/compiler: 4.2.3
@angular/core: 4.2.3
@angular/forms: 4.2.3
@angular/http: 4.2.3
@angular/platform-browser: 4.2.3
@angular/platform-browser-dynamic: 4.2.3
@angular/router: 4.2.3
@angular/cli: 1.1.2
@angular/compiler-cli: 4.2.3
@angular/flex-layout: 2.0.0-beta.8
@angular/language-service: 4.2.3
@angular/material: 2.0.0-beta.7

What do I need to provide to mock or otherwise handle the mdTooltip service, which apparently involves an observable?

Update: Apparently this occurs for other AM services as well, such as mdMenuTriggerFor.

Body:
Take a look at this:

https://github.com/angular/material2/issues/2478

"Fixed by importing ‘MaterialModule’ to TestBed.configureTestingModule in failing spec."

As in:

   TestBed.configureTestingModule({
        declarations: [PageHeaderComponent],
        providers: [
            {
                imports: [RouterTestingModule.withRoutes([]), MaterialModule],
                provide: Http,
                deps: [MockBackend]
            },
            PreloadService,
            UserService
        ],
        schemas: [CUSTOM_ELEMENTS_SCHEMA]
    });


问:
Safari - How do I create pixel-perfect layouts without PixelPlugin (firefox addon)?
PixelPerfect is an FF addon that overlays an image onto the browser viewport. Is there an alternative or port of this addon/extension for safari?</p>

答: This will only be useful if it's you own site, but maybe: http://codecanyon.net/item/xprecise/78685</p>


问:
How does Java know which class to use in this example?
I am beginning to learn the principles of OOP and inheritance, and I came across this question while writing some code:

Suppose there is a package which contains a class called ClassA. Then, in a separate folder, I have another class called MyClass. Inside the same folder as MyClass, I have another class called ClassA, which is unrelated to the ClassA in the package. When I write the code for MyClass, I make it extend ClassA.

Which ClassA does MyClass extend from? Does MyClass inherit the ClassA which is in the imported package, or does MyClass inherit the ClassA which is in the same folder as MyClass? Would the code even compile?

I am trying to understand this from a theory perspective before diving into examples.

答:
what you're looking at is a Statically scoped language which will work its way out of its inner scope, all the way to its outter scopes.
In this case, since import Class A is declared directly inside the file to which it is first called, it will use import Class A and stop.This will be its default behavior.
It will not carry on to look at the packaged Class A because it found one already, declared inside of the same class file.

This is the default behavior of java's (static) scope hierarchy.

IF it had not found an import of Class A imported inside the same file, it would reach out to its package to search for one.

This is very useful when declaring like variables. Do a little research how statically scope languages work.

If it is easier for you to understand, you can be explicit in your intentions by declaring exactly which Class A you would like though.

Just a side note- this is more of a programming languages question than directly a java question, but since you ask specifically for java, we only need to cover the simple specific answer. if you would like to know more, i can direct you (or tell you) more about statically vs dynamically scoped languages.

I suppose it is worth noting that if you decide to import both Class As even from your package (which you do NOT need to do) you would have to explicitly declare which you would like.


问:
Ignite Select query on Cache load time
I am developing an Ignite c++ application. When I try to update cache from Cassandra table using loadcache() function its load the entire table.
 I want to execute a select query during the load time. In Java, we can do this just like loadcache (query). Is there any similar function available on c++.

答: No, currently there is only LoadCache without parameters available.

Title: Ignite Select query on Cache load time


问:
thread synchronization between c# and c++
I have a C# WPF app that needs to call an unmanaged C++ DLL and get a simple event notification from it.  The DLL will wait for a keyboard event that can't be seen in .NET (VK_MEDIA_PLAY_PAUSE while the app doesn't have the input focus), and notify the main app.  I've found an example for using semaphores for cross-process syncing, but that seems like overkill.  Likewise, using named pipes, COM, sockets, or p/invoke seems like more than I should need.

Specifically, I'll be starting a worked thread in the WPF app that will wait for the keyboard event to be signaled, and then notify the main UI thread to do something once it has.

Thanks in advance.

答: Once I got pointed in the direction of Named Events, the solution became clear.  On the C++ side, CreateEvent creates named events.  But on the C# side, the 2 event types that come up first are AutoResetEvent and ManualResetEvent, which do not accept names, while EventWaitHandle does.  Once I found that class, the rest fell into place.  In my project, the event gets set on the C++ side in response to the desired key stroke, and the C# side waits for the event in a BackgroundWorker thread and acts on it when it occurs.</p>


问:
Uncaught ReferenceError: Navbar is not defined
I develop react + meteor app, then I got error like this,

I try to add navigation https://react-bootstrap.github.io/components.html#navigation, get data in this tutorial  . I try to add this const like below way

MainComponent

```<code>import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import { Meteor } from 'meteor/meteor';
import { createContainer } from 'meteor/react-meteor-data';
import { Button } from 'react-bootstrap';

import AccountsUIWrapper from './AccountsUIWrapper.jsx';

// App component - represents the whole app
export default class Home extends Component {
    constructor(props) {
        super(props);

        this.state = {
            hideCompleted: false,
        };
    }

    render() {
        const navbarInstance = (
            <Navbar>
                <Navbar.Header>
                    <Navbar.Brand>
                        <a href="#">React-Bootstrap</a>
                    </Navbar.Brand>
                </Navbar.Header>
                <Nav>
                    <NavItem eventKey={1} href="#">Link</NavItem>
                    <NavItem eventKey={2} href="#">Link</NavItem>
                    <NavDropdown eventKey={3} title="Dropdown" id="basic-nav-dropdown">
                        <MenuItem eventKey={3.1}>Action</MenuItem>
                        <MenuItem eventKey={3.2}>Another action</MenuItem>
                        <MenuItem eventKey={3.3}>Something else here</MenuItem>
                        <MenuItem divider />
                        <MenuItem eventKey={3.4}>Separated link</MenuItem>
                    </NavDropdown>
                </Nav>
            </Navbar>
        );

        return (
            <div>
                {navbarInstance}

                <div className="container">
                    <div className="row">
                        <div className="navbar nav-inline">
                            <AccountsUIWrapper />
                        </div>
                    </div>

                    <header>
                        <h1>School Attendance</h1>
                        <h3>Lecturer Report</h3>
                    </header>

                    <h4>This is home</h4>
                </div>
            </div>
        );
    }
}
</code>```

but I got bellow error. and there reason as like me.

There add some import

```<code>import { Button, Navbar, Nav, NavItem, NavDropdown, MenuItem } from 'react-bootstrap';
</code>```

like this then vanish the error, but I got like this

I want to correct way to Navbar add

答:
The classes you call in render are not defined.

Where you have import {Button} from 'react-bootstrap' you need to import every component that you plan on using in your file ( that is part of that framework ).

The solution would be adding Navbar, like so:

```<code>import { Button, Navbar } from 'react-bootstrap'
</code>```

Also have you included Bootstrap styles in your project?
https://react-bootstrap.github.io/getting-started/introduction

Body:
I develop react + meteor app, then I got error like this,

I try to add navigation https://react-bootstrap.github.io/components.html#navigation, get data in this tutorial  . I try to add this const like below way

MainComponent

import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import { Meteor } from 'meteor/meteor';
import { createContainer } from 'meteor/react-meteor-data';
import { Button } from 'react-bootstrap';

import AccountsUIWrapper from './AccountsUIWrapper.jsx';

// App component - represents the whole app
export default class Home extends Component {
    constructor(props) {
        super(props);

        this.state = {
            hideCompleted: false,
        };
    }

    render() {
        const navbarInstance = (
            <Navbar>
                <Navbar.Header>
                    <Navbar.Brand>
                        React-Bootstrap
                    </Navbar.Brand>
                </Navbar.Header>

                    <NavItem eventKey={1} href="#">Link</NavItem>
                    <NavItem eventKey={2} href="#">Link</NavItem>
                    <NavDropdown eventKey={3} title="Dropdown" id="basic-nav-dropdown">
                        <MenuItem eventKey={3.1}>Action</MenuItem>
                        <MenuItem eventKey={3.2}>Another action</MenuItem>
                        <MenuItem eventKey={3.3}>Something else here</MenuItem>
                        <MenuItem divider />
                        <MenuItem eventKey={3.4}>Separated link</MenuItem>
                    </NavDropdown>

            </Navbar>
        );

        return (

                {navbarInstance}

                            <AccountsUIWrapper />

School Attendance

Lecturer Report

This is home

        );
    }
}

but I got bellow error. and there reason as like me.

There add some import

import { Button, Navbar, Nav, NavItem, NavDropdown, MenuItem } from 'react-bootstrap';

like this then vanish the error, but I got like this

I want to correct way to Navbar add

Body:
The classes you call in render are not defined.

Where you have import {Button} from 'react-bootstrap' you need to import every component that you plan on using in your file ( that is part of that framework ).

The solution would be adding Navbar, like so:

import { Button, Navbar } from 'react-bootstrap'

Also have you included Bootstrap styles in your project?
https://react-bootstrap.github.io/getting-started/introduction