问:
Docker compose not prepending project name to the container names when running multiple instances
I have a set of docker that I run using docker-compose up -d pretty basic so far

I want to run multiple instances of my project and I have read this  Run multiple docker compose

Now when running docker-compose up -p PRNAME -d compose is not prepending project name to containers like prname_container1 and I'm getting the following error :

```<code>ERROR: for container1  Cannot create container for service service1: Conflict. The container name "/container1" is already in use by container "f7aeb2ef782556ae5b0". You have to remove (or rename) that container to be able to reuse that name.
</code>```

I might be missing something out here.

A part of my docker-compose.yml looks like

```<code>services:
  service1:
    image: "${PROJECT_REPO}:image"
    container_name: "container1"
    ports:
      - 443:443
      - 8000:80
    networks:
      - db
      - proxy
      - oauth
    depends_on:
      - db
</code>```

答:
When you explicitly set container_name: in your docker-compose.yml file, the container name will be exactly what you specify; Docker Compose won't add its per-directory prefix to it.

Usually this doesn't matter to you at all, and it's safe to remove container_name:.  You will still be able to reach other containers using their service name in docker-compose.yml as hostnames, and the docker-compose CLI provides wrappers for management commands like docker-compose stop that will act on the correct container.

You will also hit trouble with ports: and there is less of a clear solution here.  Only one container or process can bind to a specific port on the host.  You can leave off the first port number in ports:, and Docker will pick a port for you

```<code>ports:
  - '80'
  - '443'
</code>```

but then you need to manually look up the corresponding host port number

```<code>docker-compose port service1 80
</code>```

Body:
I have a set of docker that I run using docker-compose up -d pretty basic so far

I want to run multiple instances of my project and I have read this  Run multiple docker compose

Now when running docker-compose up -p PRNAME -d compose is not prepending project name to containers like prname_container1 and I'm getting the following error :

ERROR: for container1  Cannot create container for service service1: Conflict. The container name "/container1" is already in use by container "f7aeb2ef782556ae5b0". You have to remove (or rename) that container to be able to reuse that name.

I might be missing something out here.

A part of my docker-compose.yml looks like

services:
  service1:
    image: "${PROJECT_REPO}:image"
    container_name: "container1"
    ports:
      - 443:443
      - 8000:80
    networks:
      - db
      - proxy
      - oauth
    depends_on:
      - db

Body:
When you explicitly set container_name: in your docker-compose.yml file, the container name will be exactly what you specify; Docker Compose won't add its per-directory prefix to it.

Usually this doesn't matter to you at all, and it's safe to remove container_name:.  You will still be able to reach other containers using their service name in docker-compose.yml as hostnames, and the docker-compose CLI provides wrappers for management commands like docker-compose stop that will act on the correct container.

You will also hit trouble with ports: and there is less of a clear solution here.  Only one container or process can bind to a specific port on the host.  You can leave off the first port number in ports:, and Docker will pick a port for you

ports:
  - '80'
  - '443'

but then you need to manually look up the corresponding host port number

docker-compose port service1 80


来源: stackexchange

问:
why 10-fold cross validation is even faster than 1-fold fit when using LGB?
I am using LGB to handle a machine leaning task. But I found when I use the sklearn API cross_val_score and set cv=10, the time cost is less than single fold fit. I splited dataset useing train_test_split, then fit a LGBClassifier on training set. The time cost of latter is much more than former, why?

Sorry for my bad English.

Environment: Python 3.5, scikit-learn 0.20.3, lightgbm 2.2.3
Inter Xeon CPU E5-2650 v4
Memory 128GB

X = train_df.drop(['uId', 'age'], axis=1)
Y = train_df.loc[:, 'age']
X_test = test_df.drop(['uId'], axis=1)

X_train, X_val, Y_train, Y_val = train_test_split(X, Y, test_size=0.1,
                                                  stratify=Y)

# (1809000, 12) (1809000,) (201000, 12) (201000,) (502500, 12)
print(X_train.shape, Y_train.shape, X_val.shape, Y_val.shape, X_test.shape)

from lightgbm import LGBMClassifier
from sklearn.preprocessing import LabelEncoder
from sklearn.model_selection import cross_val_score
from sklearn.metrics import accuracy_score
import time

lgb = LGBMClassifier(n_jobs=-1)

tic = time.time()
scores = cross_val_score(lgb, X, Y,
                         scoring='accuracy', cv=10, n_jobs=-1)
toc = time.time()
# 0.3738402985074627 0.0009231167322574765 300.1487271785736
print(np.mean(scores), np.std(scores), toc-tic)

tic = time.time()
lgb.fit(X_train, Y_train)
toc = time.time()
# 0.3751492537313433 472.1763586997986 (is much more than 300)
print(accuracy_score(Y_val, lgb.predict(X_val)), toc-tic)
```

答: Sorry, I found the answer. Here writtens in documentation of LightGBM: 'for the best speed, set this to the number of real CPU cores, not the number of threads'. So set n_jobs=-1 is not a best choice.

ContentLicense: CC BY-SA 4.0


问:
Foreign key problems in sqlite3
I get an error "unknown column "CustID" in foreign key definition"
and "no such table: serviceticket"

Can anyone help me?

```<code>drop table if exists customer;
drop table if exists serviceticket;

PRAGMA foreign_keys = ON;

create table customer (CustID char(6) not null primary key UNIQUE,
    CustNAME TEXT,
    STREET TEXT,
    CITY TEXT,
    ZIP INT(5),
    EMAIL VARCHAR,
    PHONENUMBER INT(10)
    );

create table serviceticket (TicketID char(4) not null primary key,
    TicketNO char(5),
    WatchID char(6),
    DateRecieved char(6),
    ExpectedDelivery char(6),
    COMMENTS text,
    DateReturned char(6),
    FOREIGN KEY (CustID) REFERENCES customer (CustID)
    );

insert into customer (CustID, CustNAME, STREET, CITY, ZIP, PHONENUMBER, EMAIL)
    values (170362, 'James', 'Vvegen', New York, 12345, 8170710520, 'brt92@outlook.com');

insert into serviceticket (TicketID, WatchID, CustID, DateRecieved, DateReturned, ExpectedDelivery, COMMENTS, DateReturned)
    values (6745, 87463, 098636, 124319, 362836, 683743, 'Nothing to say', 583728);
</code>```

答:
You did not define CustID prior of the definition of the foreign key:

```<code>create table serviceticket (TicketID char(4) not null primary key,
    TicketNO char(5),
    WatchID char(6),
    DateRecieved char(6),
    ExpectedDelivery char(6),
    COMMENTS text,
    DateReturned char(6),
    CustID char(6),
    FOREIGN KEY (CustID) REFERENCES customer(CustID)
    );
</code>```

Title: Foreign key problems in sqlite3

Body:
I get an error "unknown column "CustID" in foreign key definition"
and "no such table: serviceticket"

Can anyone help me?

drop table if exists customer;
drop table if exists serviceticket;

PRAGMA foreign_keys = ON;

create table customer (CustID char(6) not null primary key UNIQUE,
    CustNAME TEXT,
    STREET TEXT,
    CITY TEXT,
    ZIP INT(5),
    EMAIL VARCHAR,
    PHONENUMBER INT(10)
    );

create table serviceticket (TicketID char(4) not null primary key,
    TicketNO char(5),
    WatchID char(6),
    DateRecieved char(6),
    ExpectedDelivery char(6),
    COMMENTS text,
    DateReturned char(6),
    FOREIGN KEY (CustID) REFERENCES customer (CustID)
    );

insert into customer (CustID, CustNAME, STREET, CITY, ZIP, PHONENUMBER, EMAIL)
    values (170362, 'James', 'Vvegen', New York, 12345, 8170710520, 'brt92@outlook.com');

insert into serviceticket (TicketID, WatchID, CustID, DateRecieved, DateReturned, ExpectedDelivery, COMMENTS, DateReturned)
    values (6745, 87463, 098636, 124319, 362836, 683743, 'Nothing to say', 583728);

Body:
You did not define CustID prior of the definition of the foreign key:

create table serviceticket (TicketID char(4) not null primary key,
    TicketNO char(5),
    WatchID char(6),
    DateRecieved char(6),
    ExpectedDelivery char(6),
    COMMENTS text,
    DateReturned char(6),
    CustID char(6),
    FOREIGN KEY (CustID) REFERENCES customer(CustID)
    );


问:
Can't Show custom error message for is_unique in codeigniter
I am using these form_validation rule to show an error message for a duplicate entry, but instead it shows default error message.</p>

```<code>$this->form_validation->set_rules('email',
                                  'Email',
                                  'required|is_unique[users.email]',
                                  'A User is already registered with this E-mail');
</code>```

答:
Please check this :</p>

```<code>$this->form_validation->set_rules(
        'email', 'Email',
        'required|is_unique[users.email]',
        array(
                'is_unique'     => 'A User is already registered with this E-mail : %s'
        )
);
</code>```

Body:
I am using these form_validation rule to show an error message for a duplicate entry, but instead it shows default error message.

$this->form_validation->set_rules('email',
                                  'Email',
                                  'required|is_unique[users.email]',
                                  'A User is already registered with this E-mail');

Body:
Please check this :

$this->form_validation->set_rules(
        'email', 'Email',
        'required|is_unique[users.email]',
        array(
                'is_unique'     => 'A User is already registered with this E-mail : %s'
        )
);


问:
add a counter to lapply(do.call) - R
I have a file which includes many folders. I wrote the following code to get the address of all files, import them into R and bind them that works well. The problem is, some of the file has different number of columns, which resulted in showing an error. My question is how can add a counter to the third line of my code? I basically want to check when my counter stops, and then I manually drop that file that has different number of columns from others.
Thanks</p>

```<code>file_names <- list.files(path="D:/ABCDE", recursive=TRUE)
setwd("D:/ ABCDE ")
all_dta <- do.call(rbind, lapply(file_names, function(x) read.csv(file=x,header = FALSE)))
</code>```

答:
To add a counter to lapply I would just do:

```<code>file_names <- list.files(path="D:/ABCDE", recursive=TRUE)
idx=1:length(filenames) #this will server as your 'counter'
lapply(idx, function(i) {print(file_names[i]); read.csv(file=file_names[i],header = FALSE)}) # this will print the file and when the loop stops you'll see the file that is faulty
</code>```

However as another solution- both to know which files are faulty and skip them naturally- I would do:

```<code>wanted=c()
for(f in file_names){
    first_line=system(paste0('head -n 1',f),intern=T) # sends prompt to command line to print first line of files. intern=T means one can set this to a variable
if(nchar(first_line > quota)){ #set quota to provide threshold for a number of columns
     wanted=c(wanted,f)
}
}
</code>```

You could also do the above with sapply.

And then:

```<code>all_dta <- do.call(rbind, lapply(wanted, function(x) read.csv(file=x,header = FALSE)))
</code>```

And if you want to know which files are faulty (i.e. which ones don't contain enough columns). Just find the files that have less than the quota number of columns:

```<code>unwanted=c()
for(f in file_names){
    first_line=system(paste0('head -n 1',f),intern=T) # sends prompt to command line to print first line of files. intern=T means one can set this to a variable
if(nchar(first_line < quota)){
     unwanted=c(unwanted,f)
}
}
</code>```

Title: add a counter to lapply(do.call) - R

Body:
I have a file which includes many folders. I wrote the following code to get the address of all files, import them into R and bind them that works well. The problem is, some of the file has different number of columns, which resulted in showing an error. My question is how can add a counter to the third line of my code? I basically want to check when my counter stops, and then I manually drop that file that has different number of columns from others.
Thanks

file_names <- list.files(path="D:/ABCDE", recursive=TRUE)
setwd("D:/ ABCDE ")
all_dta <- do.call(rbind, lapply(file_names, function(x) read.csv(file=x,header = FALSE)))

Body:
To add a counter to lapply I would just do:

file_names <- list.files(path="D:/ABCDE", recursive=TRUE)
idx=1:length(filenames) #this will server as your 'counter'
lapply(idx, function(i) {print(file_names[i]); read.csv(file=file_names[i],header = FALSE)}) # this will print the file and when the loop stops you'll see the file that is faulty

However as another solution- both to know which files are faulty and skip them naturally- I would do:

wanted=c()
for(f in file_names){
    first_line=system(paste0('head -n 1',f),intern=T) # sends prompt to command line to print first line of files. intern=T means one can set this to a variable
if(nchar(first_line > quota)){ #set quota to provide threshold for a number of columns
     wanted=c(wanted,f)
}
}

You could also do the above with sapply.

And then:

all_dta <- do.call(rbind, lapply(wanted, function(x) read.csv(file=x,header = FALSE)))

And if you want to know which files are faulty (i.e. which ones don't contain enough columns). Just find the files that have less than the quota number of columns:

unwanted=c()
for(f in file_names){
    first_line=system(paste0('head -n 1',f),intern=T) # sends prompt to command line to print first line of files. intern=T means one can set this to a variable
if(nchar(first_line < quota)){
     unwanted=c(unwanted,f)
}
}


问:
Why am I getting this error message-"Invalid project ID: marveltrivia-8680d (The caller does not have permission). Parameter: marveltrivia-8680d"?
I have already deployed an action in google assistant, but now I've made a few changes to my action and now when i try to submit my action for production, i get an error message stating Invalid project ID: marveltrivia-8680d (The caller does not have permission). Parameter: marveltrivia-8680d.Can anybody please tell me why am i getting this error and please suggest  me a way to resolve it.

答:
It may happen because there might be too many accounts are logged in to google at the same time.
Try it in 'Incognito Mode'. Your problem will be solved like mine.</p>


问:
How can I use findstr with newline regular expression
I'm on windows dos prompt. I have log file which contains log like:

```<code>Timestamp: Order received for Item No. 26551
Timestamp: Exception: OutOfRangeException
Timestamp: Message: Inventory Item is not stock. Item No. 23423
Timestamp: Order received for Item No. 23341
</code>```

I want to extract all the item number who has give some sort of exception. I'm using findstr command for this. how can I use newline in my regular expression? I want to all lines which have Exception word and from next line the item no.

any help?

答:
If you are on Vista or Windows 7 (or if you install it manually on XP), you can use PowerShell for this:

```<code>$resultlist = new-object System.Collections.Specialized.StringCollection
$regex = [regex] '(?m)^.*Exception.*\r\n.*Item No\. (\d+)'
$match = $regex.Match($subject)
while ($match.Success) {
    $resultlist.Add($match.Groups[1].Value) | out-null
    $match = $match.NextMatch()
}
</code>```

$resultlist will then contain a list of all item numbers that follow a line with Exception in it.

ContentLicense: CC BY-SA 3.0

Body:
I'm on windows dos prompt. I have log file which contains log like:

Timestamp: Order received for Item No. 26551
Timestamp: Exception: OutOfRangeException
Timestamp: Message: Inventory Item is not stock. Item No. 23423
Timestamp: Order received for Item No. 23341

I want to extract all the item number who has give some sort of exception. I'm using findstr command for this. how can I use newline in my regular expression? I want to all lines which have Exception word and from next line the item no.

any help?

Body:
If you are on Vista or Windows 7 (or if you install it manually on XP), you can use PowerShell for this:

$resultlist = new-object System.Collections.Specialized.StringCollection
$regex = [regex] '(?m)^.*Exception.*\r\n.*Item No\. (\d+)'
$match = $regex.Match($subject)
while ($match.Success) {
    $resultlist.Add($match.Groups[1].Value) | out-null
    $match = $match.NextMatch()
}

$resultlist will then contain a list of all item numbers that follow a line with Exception in it.


问:
With GitLab CI how to disable repository clone for one job?
I need to speed up job 'deploy'. It does not need sources of project but needs ONLY ARTIFACTS.

How to disable project cloning for the only job?

Typical .gitlab-ci.yml (pseudo) looks like:

```<code>image: gcc

build:
  stage: build
  script:
  - ./configure
  - mkdir build && cd $_
  - cmake ..
  - make -sj8
artifacts:
  paths:
  - "build/*.elf"

deploy:
  image: artifactory
  variables:
  - DO_NOT_CLONE: 1  ## WANT THIS OPTION
  stage: deploy
  script:
  - push_artifacts build/*.elf
</code>```

答:
Checkout the variable GIT_STRATEGY:

```<code>variables:
  GIT_STRATEGY: none
</code>```

From the documentation:

none also re-uses the project workspace, but skips all Git operations (including GitLab Runner’s pre-clone script, if present). It is mostly useful for jobs that operate exclusively on artifacts (e.g., deploy).

https://docs.gitlab.com/ee/ci/runners/configure_runners.html#git-strategy

Body:
I need to speed up job 'deploy'. It does not need sources of project but needs ONLY ARTIFACTS.

How to disable project cloning for the only job?

Typical .gitlab-ci.yml (pseudo) looks like:

image: gcc

build:
  stage: build
  script:
  - ./configure
  - mkdir build && cd $_
  - cmake ..
  - make -sj8
artifacts:
  paths:
  - "build/*.elf"

deploy:
  image: artifactory
  variables:
  - DO_NOT_CLONE: 1  ## WANT THIS OPTION
  stage: deploy
  script:
  - push_artifacts build/*.elf

Body:
Checkout the variable GIT_STRATEGY:

variables:
  GIT_STRATEGY: none

From the documentation:

none also re-uses the project workspace, but skips all Git operations (including GitLab Runner’s pre-clone script, if present). It is mostly useful for jobs that operate exclusively on artifacts (e.g., deploy).

https://docs.gitlab.com/ee/ci/runners/configure_runners.html#git-strategy


问:
How to enable automatic resampling on zoom in datashader with holoviews together with a (live) data stream through a pipe into a DynamicMap?
While I have a data flow through a pipe together with a holoviews.DynamicMap containing a Curve, on which holoviews.operation.datashader.datashade() is applied: when use the zoom tool the view does not resample (as for static data) leading to a very pixelated visualization of my data. What do I need to do to enable this resampling?

I run the whole thing in a jupyter notebook with python3

When I setup my holoviews.DynamicMap just with static data and I have no pipe running it works properly.

When I start to fill the pipe (without ever using it) the resampling does not take place anymore. (I do not use the pipe at all)

Problem Scenario:

(3 cells in jupyter notebook)

(1) Import

```<code>import time
import numpy as np
import holoviews as hv

from holoviews.operation.datashader import datashade

from holoviews import opts
from holoviews.streams import Pipe

hv.extension('bokeh')
</code>```

(2) Setup Pipe and Plot

```<code>#no of samples
N=100000

pipe2 = Pipe(data=[])
data_dmap = hv.DynamicMap(hv.Curve, streams=[pipe2])

data_dmap_opt = datashade(data_dmap, streams=[hv.streams.RangeXY])
data_dmap_opt.opts(width=900,xlim=(0, N),ylim=(0, 1))
</code>```

(3) Generate Data Stream

```<code>def makeBigData(N):
    x = np.arange(N)
    y = np.random.rand(N)

    while True:
        time.sleep(1)
        y = np.random.rand(N)
        pipe2.send((x,y))
</code>```

Debugging Scenarios:

alternative to cell (2)

(alternative 2) Setup Pipe and Plot with static Plot

```<code>#default Data
N=100000
x = np.arange(N)
y = np.random.rand(N)

pipe2 = Pipe(data=[])
data_dmap = hv.DynamicMap(hv.Curve((x,y)))

data_dmap_opt = datashade(data_dmap, streams=[hv.streams.RangeXY])
data_dmap_opt.opts(width=900,xlim=(0, 100000),ylim=(0, 1))
</code>```

(this works as long as cell (3) is not executed, then this alternative stops working)

Expected result:

continuously updating plot with noise (at a later stage with real data)

Therefore the actual graph is sampled into an image, when zooming in the sampling should be adjusted to the actual view

Real results:

zooming in does not trigger adjustment of sampling into image.

答:
The problem you are having is that if you trigger the updates from a while loop the kernel will be permanently busy, which means that it never gets freed up to respond to the events arriving from JS which tell it to resample. You need to schedule the events on the pipe asynchronously in some form. In the notebook you can do this using a tornado PeriodicCallback, e.g.:

```<code>from tornado.ioloop import PeriodicCallback
from tornado import gen

N = 100
x = np.arange(N)

@gen.coroutine
def f():
    y = np.random.rand(N)
    pipe.send((x, y))

cb = PeriodicCallback(f, 1000)
cb.start()
</code>```

Body:
While I have a data flow through a pipe together with a holoviews.DynamicMap containing a Curve, on which holoviews.operation.datashader.datashade() is applied: when use the zoom tool the view does not resample (as for static data) leading to a very pixelated visualization of my data. What do I need to do to enable this resampling?

I run the whole thing in a jupyter notebook with python3

When I setup my holoviews.DynamicMap just with static data and I have no pipe running it works properly.

When I start to fill the pipe (without ever using it) the resampling does not take place anymore. (I do not use the pipe at all)

Problem Scenario:

(3 cells in jupyter notebook)

(1) Import

import time
import numpy as np
import holoviews as hv

from holoviews.operation.datashader import datashade

from holoviews import opts
from holoviews.streams import Pipe

hv.extension('bokeh')

(2) Setup Pipe and Plot

#no of samples
N=100000

pipe2 = Pipe(data=[])
data_dmap = hv.DynamicMap(hv.Curve, streams=[pipe2])

data_dmap_opt = datashade(data_dmap, streams=[hv.streams.RangeXY])
data_dmap_opt.opts(width=900,xlim=(0, N),ylim=(0, 1))

(3) Generate Data Stream

def makeBigData(N):
    x = np.arange(N)
    y = np.random.rand(N)

    while True:
        time.sleep(1)
        y = np.random.rand(N)
        pipe2.send((x,y))

Debugging Scenarios:

alternative to cell (2)

(alternative 2) Setup Pipe and Plot with static Plot

#default Data
N=100000
x = np.arange(N)
y = np.random.rand(N)

pipe2 = Pipe(data=[])
data_dmap = hv.DynamicMap(hv.Curve((x,y)))

data_dmap_opt = datashade(data_dmap, streams=[hv.streams.RangeXY])
data_dmap_opt.opts(width=900,xlim=(0, 100000),ylim=(0, 1))

(this works as long as cell (3) is not executed, then this alternative stops working)

Expected result:

continuously updating plot with noise (at a later stage with real data)

Therefore the actual graph is sampled into an image, when zooming in the sampling should be adjusted to the actual view

Real results:

zooming in does not trigger adjustment of sampling into image.

Body:
The problem you are having is that if you trigger the updates from a while loop the kernel will be permanently busy, which means that it never gets freed up to respond to the events arriving from JS which tell it to resample. You need to schedule the events on the pipe asynchronously in some form. In the notebook you can do this using a tornado PeriodicCallback, e.g.:

from tornado.ioloop import PeriodicCallback
from tornado import gen

N = 100
x = np.arange(N)

@gen.coroutine
def f():
    y = np.random.rand(N)
    pipe.send((x, y))

cb = PeriodicCallback(f, 1000)
cb.start()


问:
Distributed systems with large number of different types of jobs
I want to create a distributed system that can support around 10,000 different types of jobs. One single machine can host only 500 such jobs, as each job needs some data to be pre-loaded into memory, which can't be kept in a cache. Each job must have redundancy for availability.

I had explored open-source libraries like zookeeper, hadoop, but none solves my problem.
The easiest solution that I can think of, is to maintain a map of job type, with its hosted machine. But how can I support dynamic allocation of job type on my fleet? How to handle machine failures, to make sure that each job type must be available on atleast 1 machine, at any point of time.

答:
Based on the answers that you mentioned in the comments, I propose you to go for a MQ-based (Message Queue) architecture. What I propose in this answer is to:

Get the input from users and push them into a distributed message queue. It means that you should set up a message queue (Such as ActiveMQ or RabbitMQ) on several servers. This MQ technology, helps you to replicate the input requests for fault tolerance issues. It also provides a full end-to-end asynchronous system.

After preparing this MQ layer, you can setup you computing servers layers. This means that some computing servers (~20 servers in your case) will read the requests from the message queue and start a job based on the request. Because this MQ is distributed, you can make sure that a good level of load balancing can happen in your computing servers. In addition, each server is capable of running as much as jobs that you want (~500 in your case) based on the requests that it reads from the MQ.

Regarding the failures, the computing servers may only pop from the MQ, if and only if the job is completed. If one server is crashing, the job is still in the MQ and another server can work on it. If the job is saving some state somewhere or updates something, you should manage its duplicate run then.

The good point about this approach is that it is very salable. It means that if in future you have more jobs to handle, by adding a computing server and connecting it to the MQ, you can process more requests on the servers without any change to the system. In addition, some nice features in the MQ like priority-based queuing, helps you to prioritize the requests and process them based on the job type.

p.s. Your Q does not provide any details about the type and parameters of the system. This is a draft solution that I can propose. If you provide more details, maybe the community can help you more.


问:
Display only text without image for UITabBarItem?
I want to display only title for tabbar item without image. Is it possible? When I tried setting

```<code>let tabItem = UITabBarItem()
tabItem.title = "Tab1"
tabItem.selectedImage = nil
tabItem.image = nil
tabViewController?.tabBarItem = tabItem
</code>```

I'm just getting a blank space which is tapable, but no title or image.

答:
In case you want it to be done programmatically:</p>

```<code>tabItem.titlePositionAdjustment = UIOffset(horizontal: 0, vertical: -16)
</code>```

Body:
I want to display only title for tabbar item without image. Is it possible? When I tried setting

let tabItem = UITabBarItem()
tabItem.title = "Tab1"
tabItem.selectedImage = nil
tabItem.image = nil
tabViewController?.tabBarItem = tabItem

I'm just getting a blank space which is tapable, but no title or image.

Body:
In case you want it to be done programmatically:

tabItem.titlePositionAdjustment = UIOffset(horizontal: 0, vertical: -16)


问:
Selecting an item from Drop Down list in Espresso
I am trying to write the Espresso test that will navigate to search, type 2 letters to get incremental search and tap on 2nd item on the list.

The results are displayed in adapter.

Of course, I do the first part well, but when I need to click on the item in the list, there is a problem.

I already tried something like

```<code>onData(anything()).inAdapterView(withId(R.id.searchContainer)).atPosition(1).perform(click())
</code>```

and

```<code>onData(withChild(withText("Some Search"))).atPosition(1).perform(click())
</code>```

(where Some Search is the complete text of the result)

and

```<code>onData(withId(android.R.id.text1)).atPosition(1).perform(click())
</code>```

(where text1 is id of the result field)

```<code>    @Test
    fun searchForSandwich() {

        onView(withId(R.id.textSearch)).perform(typeText("ha"))

        onData(withChild(withText("Ham Sandwich"))).atPosition(1).perform(click())
</code>```

It should click the result and open new screen / activity and I will do my assertion there.

Currently, I am getting this error:

```<code>Caused by: java.lang.RuntimeException: Action will not be performed because the target view does not match one or more of the following constraints:
(is assignable from class: class android.widget.AdapterView and is displayed on the screen to the user)
Target view: "ce{id=-1, visibility=GONE, width=0, height=0, has-focus=false, has-focusable=false, has-window-focus=true, is-clickable=true, is-enabled=true, is-focused=false, is-focusable=false, is-layout-requested=true, is-selected=false, layout-params=android.widget.RelativeLayout$LayoutParams@4d102dd, tag=null, root-is-layout-requested=false, has-input-connection=false, x=0.0, y=0.0, child-count=0}"
</code>```

Any suggestions, It's driving me crazy... Thanks :)

答:
I need to see the view to make sure but %99 percent you don't need to use onData and can just get away with onView(withText(containsString(yourSearchFilter))).perform(click()).

There is also probably a withSubstring(text) which corresponds to withText(containsString(text))

Body:
I am trying to write the Espresso test that will navigate to search, type 2 letters to get incremental search and tap on 2nd item on the list.

The results are displayed in adapter.

Of course, I do the first part well, but when I need to click on the item in the list, there is a problem.

I already tried something like

onData(anything()).inAdapterView(withId(R.id.searchContainer)).atPosition(1).perform(click())

and

onData(withChild(withText("Some Search"))).atPosition(1).perform(click())

(where Some Search is the complete text of the result)

and

onData(withId(android.R.id.text1)).atPosition(1).perform(click())

(where text1 is id of the result field)

    @Test
    fun searchForSandwich() {

        onView(withId(R.id.textSearch)).perform(typeText("ha"))

        onData(withChild(withText("Ham Sandwich"))).atPosition(1).perform(click())

It should click the result and open new screen / activity and I will do my assertion there.

Currently, I am getting this error:

Caused by: java.lang.RuntimeException: Action will not be performed because the target view does not match one or more of the following constraints:
(is assignable from class: class android.widget.AdapterView and is displayed on the screen to the user)
Target view: "ce{id=-1, visibility=GONE, width=0, height=0, has-focus=false, has-focusable=false, has-window-focus=true, is-clickable=true, is-enabled=true, is-focused=false, is-focusable=false, is-layout-requested=true, is-selected=false, layout-params=android.widget.RelativeLayout$LayoutParams@4d102dd, tag=null, root-is-layout-requested=false, has-input-connection=false, x=0.0, y=0.0, child-count=0}"

Any suggestions, It's driving me crazy... Thanks :)


问:
Ink to memorystream problem
I was trying to convert an ink from Microsoft.Ink namespace to memorystream, so to convert it to image, but I don't understand why it's getting an error in the memorystream. I kind of felt that it was an error from Convert.FromBase64String()

But I don't know what other choices I have to convert it to image.

Please help me

Here is my code:

```<code>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using Microsoft.Ink;

namespace testPaint
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        InkCollector ink;

        private void Form1_Load(object sender, EventArgs e)
        {
            ink = new InkCollector(pictureBox1);
            ink.Enabled = true;
            ink.AutoRedraw = true;
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            UTF8Encoding utf8 = new UTF8Encoding();
            ink.Enabled = false;

            string strInk = Convert.ToBase64String(ink.Ink.Save(PersistenceFormat.Base64InkSerializedFormat, CompressionMode.Maximum));
            textBox1.Text = strInk;
            ink.Enabled = true;
        }

        private void btnClr_Click(object sender, EventArgs e)
        {
            ink.Enabled = false;
            ink.Ink = new Microsoft.Ink.Ink();
            ink.Enabled = true;
            pictureBox1.Invalidate();
        }

        private void btnExport_Click(object sender, EventArgs e)
        {
            byte[] byImage = Convert.FromBase64String(textBox1.Text);
            MemoryStream ms = new MemoryStream();
            ms.Write(byImage, 0, byImage.Length);
            Image img = Image.FromStream(ms);
            img.Save("test.gif", System.Drawing.Imaging.ImageFormat.Gif);
            ink.Enabled = true;

        }
    }
}
</code>```

答:
The documentation is very preliminary but I think you are probably using the wrong PersistenceFormat tag: you are using Base64 as the output format but you clearly want PersistenceFormat.Gif.

Apart from that, your conversion to and from a string is really not at all meaningful. Just use a private byte[] variable to store the ink data. Furthermore, your detour via a MemoryStream and a System.Graphics.Image makes no sense either.

```<code>// using System.IO;

private byte[] inkData;

private void btnSave_Click(object sender, EventArgs e)
{
    inkData = ink.Ink.Save(PersistenceFormat.Gif, CompressionMode.Maximum);
}

private void btnExport_Click(object sender, EventArgs e)
{
    // Data is already in GIF format, write directly to file!
    using (var stream = new FileStream("filename", FileMode.Create, FileAccess.Write))
         stream.Write(inkData, 0, inkData.Length);
}
</code>```

Title: Ink to memorystream problem

Body:
I was trying to convert an ink from Microsoft.Ink namespace to memorystream, so to convert it to image, but I don't understand why it's getting an error in the memorystream. I kind of felt that it was an error from Convert.FromBase64String()

But I don't know what other choices I have to convert it to image.

Please help me

Here is my code:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using Microsoft.Ink;

namespace testPaint
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        InkCollector ink;

        private void Form1_Load(object sender, EventArgs e)
        {
            ink = new InkCollector(pictureBox1);
            ink.Enabled = true;
            ink.AutoRedraw = true;
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            UTF8Encoding utf8 = new UTF8Encoding();
            ink.Enabled = false;

            string strInk = Convert.ToBase64String(ink.Ink.Save(PersistenceFormat.Base64InkSerializedFormat, CompressionMode.Maximum));
            textBox1.Text = strInk;
            ink.Enabled = true;
        }

        private void btnClr_Click(object sender, EventArgs e)
        {
            ink.Enabled = false;
            ink.Ink = new Microsoft.Ink.Ink();
            ink.Enabled = true;
            pictureBox1.Invalidate();
        }

        private void btnExport_Click(object sender, EventArgs e)
        {
            byte[] byImage = Convert.FromBase64String(textBox1.Text);
            MemoryStream ms = new MemoryStream();
            ms.Write(byImage, 0, byImage.Length);
            Image img = Image.FromStream(ms);
            img.Save("test.gif", System.Drawing.Imaging.ImageFormat.Gif);
            ink.Enabled = true;

        }
    }
}

Body:
The documentation is very preliminary but I think you are probably using the wrong PersistenceFormat tag: you are using Base64 as the output format but you clearly want PersistenceFormat.Gif.

Apart from that, your conversion to and from a string is really not at all meaningful. Just use a private byte[] variable to store the ink data. Furthermore, your detour via a MemoryStream and a System.Graphics.Image makes no sense either.

// using System.IO;

private byte[] inkData;

private void btnSave_Click(object sender, EventArgs e)
{
    inkData = ink.Ink.Save(PersistenceFormat.Gif, CompressionMode.Maximum);
}

private void btnExport_Click(object sender, EventArgs e)
{
    // Data is already in GIF format, write directly to file!
    using (var stream = new FileStream("filename", FileMode.Create, FileAccess.Write))
         stream.Write(inkData, 0, inkData.Length);
}


问:
Open Command Prompt through scheduler
I have a batch process which opens the command prompt and fires some commands on the command prompt.
Now i am trying to schedule the batch through the windows task scheduler.
When i manually run the batch process , the command prompt is opened and i can see the command in the batch file being executed.
However when i run the scheduler, the status for the scheduler is shown as running, but i am unable to view the command prompt.

The code from the batch file is :

```<code>cd\
cd C:\Users\vinayak\
"C:\Program Files (x86)\Common Files\Oracle\Java\javapath\java.exe" -jar "C:\Users\vinayak\Desktop\Pramod C - UI Path\UI_Path_Gen.jar"
 pause
</code>```

I expected the command prompt to be open and waiting for any key to be pressed but instead the command prompt is not shown and i am unable to enter the key.

答:
I have to assume either your task scheduler is not pointed at the batch file at all, or the task scheduler user does not have proper permissions to run the bat file. I was able to reproduce your issue by pointing to a batch file that isn't there.

Can you verify that it's pointed at the right file, and that it has permissions to run the bat file AND the java command?

Title: Open Command Prompt through scheduler

Body:
I have a batch process which opens the command prompt and fires some commands on the command prompt.
Now i am trying to schedule the batch through the windows task scheduler.
When i manually run the batch process , the command prompt is opened and i can see the command in the batch file being executed.
However when i run the scheduler, the status for the scheduler is shown as running, but i am unable to view the command prompt.

The code from the batch file is :

cd\
cd C:\Users\vinayak\
"C:\Program Files (x86)\Common Files\Oracle\Java\javapath\java.exe" -jar "C:\Users\vinayak\Desktop\Pramod C - UI Path\UI_Path_Gen.jar"
 pause

I expected the command prompt to be open and waiting for any key to be pressed but instead the command prompt is not shown and i am unable to enter the key.


问:
Custom allocators as alternatives to vector of smart pointers?
This question is about owning pointers, consuming pointers, smart pointers, vectors, and allocators.

I am a little bit lost on my thoughts about code architecture. Furthermore, if this  question has already an answer somewhere, 1. sorry, but I haven't found a satisfying answer so far and 2. please point me to it.

My problem is the following:

I have several "things" stored in a vector and several "consumers" of those "things". So, my first try was like follows:

```<code>std::vector<thing> i_am_the_owner_of_things;
thing* get_thing_for_consumer() {
    // some thing-selection logic
    return &i_am_the_owner_of_things[5]; // 5 is just an example
}

...

// somewhere else in the code:
class consumer {
    consumer() {
       m_thing = get_thing_for_consumer();
    }

    thing* m_thing;
};
</code>```

In my application, this would be safe because the "things" outlive the "consumers" in any case. However, more "things" can be added during runtime and that can become a problem because if the std::vector<thing> i_am_the_owner_of_things; gets reallocated, all the thing* m_thing pointers become invalid.

A fix to this scenario would be to store unique pointers to "things" instead of "things" directly, i.e. like follows:

```<code>std::vector<std::unique_ptr<thing>> i_am_the_owner_of_things;
thing* get_thing_for_consumer() {
    // some thing-selection logic
    return i_am_the_owner_of_things[5].get(); // 5 is just an example
}

...

// somewhere else in the code:
class consumer {
    consumer() {
       m_thing = get_thing_for_consumer();
    }

    thing* m_thing;
};
</code>```

The downside here is that memory coherency between "things" is lost. Can this memory coherency be re-established by using custom allocators somehow? I am thinking of something like an allocator which would always allocate memory for, e.g., 10 elements at a time and whenever required, adds more 10-elements-sized chunks of memory.

Example:

initially:

v = ☐☐☐☐☐☐☐☐☐☐

more elements:

v = ☐☐☐☐☐☐☐☐☐☐  ☐☐☐☐☐☐☐☐☐☐

and again:

v = ☐☐☐☐☐☐☐☐☐☐  ☐☐☐☐☐☐☐☐☐☐  ☐☐☐☐☐☐☐☐☐☐

Using such an allocator, I wouldn't even have to use std::unique_ptrs of "things" because at std::vector's reallocation time, the memory addresses of the already existing elements would not change.

As alternative, I can only think of referencing the "thing" in "consumer" via a std::shared_ptr<thing> m_thing, as opposed to the current thing* m_thing but that seems like the worst approach to me, because a "thing" shall not own a "consumer" and with shared pointers I would create shared ownership.

So, is the allocator-approach a good one? And if so, how can it be done? Do I have to implement the allocator by myself or is there an existing one?

答:
There is no single right answer to this question, since it depends a lot on the exact access patterns and desired performance characteristics.

Having said that, here is my recommendation:

Continue storing the data contiguously as you are, but do not store aliasing pointers to that data. Instead, consider a safer alternative (this is a proven method) where you fetch the pointer based on an ID right before using it -- as a side-note, in a multi-threaded application you can lock attempts to resize the underlying store whilst such a weak reference lives.

So your consumer will store an ID, and will fetch a pointer to the data from the "store" on demand. This also gives you control over all "fetches", so that you can track them, implement safety measure, etc.

```<code>void consumer::foo() {
    thing *t = m_thing_store.get(m_thing_id);
    if (t) {
        // do something with t
    }
}
</code>```

Or more advanced alternative to help with synchronization in multi-threaded scenario:

```<code>void consumer::foo() {
    reference<thing> t = m_thing_store.get(m_thing_id);
    if (!t.empty()) {
        // do something with t
    }
}
</code>```

Where reference would be some thread-safe RAII "weak pointer".

There are multiple ways of implementing this. You can either use an open-addressing hash table and use the ID as a key; this will give you roughly O(1) access time if you balance it properly.

Another alternative (best-case O(1), worst-case O(N)) is to use a "reference" structure, with a 32-bit ID and a 32-bit index (so same size as 64-bit pointer) -- the index serves as a sort-of cache. When you fetch, you first try the index, if the element in the index has the expected ID you are done. Otherwise, you get a "cache miss" and you do a linear scan of the store to find the element based on ID, and then you store the last-known index value in your reference.

Body:
This question is about owning pointers, consuming pointers, smart pointers, vectors, and allocators.

I am a little bit lost on my thoughts about code architecture. Furthermore, if this  question has already an answer somewhere, 1. sorry, but I haven't found a satisfying answer so far and 2. please point me to it.

My problem is the following:

I have several "things" stored in a vector and several "consumers" of those "things". So, my first try was like follows:

std::vector<thing> i_am_the_owner_of_things;
thing* get_thing_for_consumer() {
    // some thing-selection logic
    return &i_am_the_owner_of_things[5]; // 5 is just an example
}

...

// somewhere else in the code:
class consumer {
    consumer() {
       m_thing = get_thing_for_consumer();
    }

    thing* m_thing;
};

In my application, this would be safe because the "things" outlive the "consumers" in any case. However, more "things" can be added during runtime and that can become a problem because if the std::vector<thing> i_am_the_owner_of_things; gets reallocated, all the thing* m_thing pointers become invalid.

A fix to this scenario would be to store unique pointers to "things" instead of "things" directly, i.e. like follows:

std::vector<std::unique_ptr<thing>> i_am_the_owner_of_things;
thing* get_thing_for_consumer() {
    // some thing-selection logic
    return i_am_the_owner_of_things[5].get(); // 5 is just an example
}

...

// somewhere else in the code:
class consumer {
    consumer() {
       m_thing = get_thing_for_consumer();
    }

    thing* m_thing;
};

The downside here is that memory coherency between "things" is lost. Can this memory coherency be re-established by using custom allocators somehow? I am thinking of something like an allocator which would always allocate memory for, e.g., 10 elements at a time and whenever required, adds more 10-elements-sized chunks of memory.

Example:

initially:

v = ☐☐☐☐☐☐☐☐☐☐

more elements:

v = ☐☐☐☐☐☐☐☐☐☐  ☐☐☐☐☐☐☐☐☐☐

and again:

v = ☐☐☐☐☐☐☐☐☐☐  ☐☐☐☐☐☐☐☐☐☐  ☐☐☐☐☐☐☐☐☐☐

Using such an allocator, I wouldn't even have to use std::unique_ptrs of "things" because at std::vector's reallocation time, the memory addresses of the already existing elements would not change.

As alternative, I can only think of referencing the "thing" in "consumer" via a std::shared_ptr<thing> m_thing, as opposed to the current thing* m_thing but that seems like the worst approach to me, because a "thing" shall not own a "consumer" and with shared pointers I would create shared ownership.

So, is the allocator-approach a good one? And if so, how can it be done? Do I have to implement the allocator by myself or is there an existing one?

Body:
There is no single right answer to this question, since it depends a lot on the exact access patterns and desired performance characteristics.

Having said that, here is my recommendation:

Continue storing the data contiguously as you are, but do not store aliasing pointers to that data. Instead, consider a safer alternative (this is a proven method) where you fetch the pointer based on an ID right before using it -- as a side-note, in a multi-threaded application you can lock attempts to resize the underlying store whilst such a weak reference lives.

So your consumer will store an ID, and will fetch a pointer to the data from the "store" on demand. This also gives you control over all "fetches", so that you can track them, implement safety measure, etc.

void consumer::foo() {
    thing *t = m_thing_store.get(m_thing_id);
    if (t) {
        // do something with t
    }
}

Or more advanced alternative to help with synchronization in multi-threaded scenario:

void consumer::foo() {
    reference<thing> t = m_thing_store.get(m_thing_id);
    if (!t.empty()) {
        // do something with t
    }
}

Where reference would be some thread-safe RAII "weak pointer".

There are multiple ways of implementing this. You can either use an open-addressing hash table and use the ID as a key; this will give you roughly O(1) access time if you balance it properly.

Another alternative (best-case O(1), worst-case O(N)) is to use a "reference" structure, with a 32-bit ID and a 32-bit index (so same size as 64-bit pointer) -- the index serves as a sort-of cache. When you fetch, you first try the index, if the element in the index has the expected ID you are done. Otherwise, you get a "cache miss" and you do a linear scan of the store to find the element based on ID, and then you store the last-known index value in your reference.


问:
NextJS - window is not defined
I'm trying to import Typewriter Effect into my NextJS project, but whenever I do, I get this error that reads the following:

ReferenceError: window is not defined

and from what I've read, the error is displaying because it's trying to load the library on the server-side rather than the client-side.

So when I simply try to import it like this:

import Typewriter from 'typewriter-effect'

the error promptly displays.

People suggested that I try something like this:

```<code>let Typewriter
if (typeof window !== 'undefined') {
  Typewriter = require( 'typewriter-effect' )
}
</code>```

however, it doesn't work like this either. I get an error that reads the following:

Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined.

I've searched a lot of places for a potential solution to this problem, but I've been unsuccessful with my attempts.

答:
What you need to do is dynamic import with No SSR

Try this:

```<code>import React, { Component } from 'react';
import dynamic from 'next/dynamic';

const Typewriter = dynamic(
    () => import('typewriter-effect'),
    {
        ssr: false
    }
)

class Home extends Component {
    render() {
        return (
            <Typewriter
                onInit={(typewriter) => {
                    typewriter.typeString('Hello World!')
                        .callFunction(() => {
                            console.log('String typed out');
                    })
                        .pauseFor(2500)
                        .deleteAll()
                        .callFunction(() => {
                            console.log('All strings were deleted');
                    })
                        .start();
            }}
            />
        )
    }
}

export default Home;
</code>```

Title: NextJS - window is not defined

Body:
I'm trying to import Typewriter Effect into my NextJS project, but whenever I do, I get this error that reads the following:

ReferenceError: window is not defined

and from what I've read, the error is displaying because it's trying to load the library on the server-side rather than the client-side.

So when I simply try to import it like this:

import Typewriter from 'typewriter-effect'

the error promptly displays.

People suggested that I try something like this:

let Typewriter
if (typeof window !== 'undefined') {
  Typewriter = require( 'typewriter-effect' )
}

however, it doesn't work like this either. I get an error that reads the following:

Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined.

I've searched a lot of places for a potential solution to this problem, but I've been unsuccessful with my attempts.

Body:
What you need to do is dynamic import with No SSR

Try this:

import React, { Component } from 'react';
import dynamic from 'next/dynamic';

const Typewriter = dynamic(
    () => import('typewriter-effect'),
    {
        ssr: false
    }
)

class Home extends Component {
    render() {
        return (
            <Typewriter
                onInit={(typewriter) => {
                    typewriter.typeString('Hello World!')
                        .callFunction(() => {
                            console.log('String typed out');
                    })
                        .pauseFor(2500)
                        .deleteAll()
                        .callFunction(() => {
                            console.log('All strings were deleted');
                    })
                        .start();
            }}
            />
        )
    }
}

export default Home;


问:
How to get value by dynamic field Name using sql select query
I am passing dynamic column name base that column name  to get the value and below i my table

```<code>Table_CandidateInfo

Id     Name        Age    City

1      Mazhar      30     Gulbarga

20     Khan        29     Bidar
</code>```

Example1

```<code>Declare @ColumnName varchar(100), @Id int

set @ColumnName='Age'
set @Id=20

select * from Table_CandidateInfo where ID=@Id and
</code>```

I am not able to pass ColumnName with and query because column name is dynamic pass by code. My output should be

```<code>29
</code>```

Example2: If my @ColumnName='City'  and @Id=20 then output should be like below

```<code>Bidar
</code>```

答:
I think what you are actually after is the below:</p>

```<code>DECLARE @ColumnName sysname, @Id int;
SET @Id = 29;
SET @ColumnName = N'Age';

DECLARE @SQL nvarchar(MAX);
SET @SQL = N'SELECT ' + QUOTENAME(@ColumnName) + N' FROM dbo.Table_CandidateInfo WHERE Id = @Id;';
--PRINT @SQL; --Your debugging friend
EXEC sp_executesql @SQL, N'@Id int', @Id = @Id;
</code>```

Body:
I am passing dynamic column name base that column name  to get the value and below i my table

Table_CandidateInfo

Id     Name        Age    City

1      Mazhar      30     Gulbarga

20     Khan        29     Bidar

Example1

Declare @ColumnName varchar(100), @Id int

set @ColumnName='Age'
set @Id=20

select * from Table_CandidateInfo where ID=@Id and

I am not able to pass ColumnName with and query because column name is dynamic pass by code. My output should be

29

Example2: If my @ColumnName='City'  and @Id=20 then output should be like below

Bidar

Body:
I think what you are actually after is the below:

DECLARE @ColumnName sysname, @Id int;
SET @Id = 29;
SET @ColumnName = N'Age';

DECLARE @SQL nvarchar(MAX);
SET @SQL = N'SELECT ' + QUOTENAME(@ColumnName) + N' FROM dbo.Table_CandidateInfo WHERE Id = @Id;';
--PRINT @SQL; --Your debugging friend
EXEC sp_executesql @SQL, N'@Id int', @Id = @Id;


问:
Mojave problem with Naoqi python (dynamic module not initialized properly)
I have installed the Python SDK for the Pepper (as indicated here: http://doc.aldebaran.com/2-5/dev/python/install_guide.html#python-install-guide). I have Mac OS 10.14.3 (Mojave) and running python 2.7.
When I am trying to import naoqi, I get the following error:

```<code>Traceback (most recent call last):
  File "/usr/local/bin/../Cellar/python@2/2.7.16/bin/../Frameworks/Python.framework/Versions/2.7/lib/python2.7/site.py", line 539, in <module>
    main()
  File "/usr/local/bin/../Cellar/python@2/2.7.16/bin/../Frameworks/Python.framework/Versions/2.7/lib/python2.7/site.py", line 521, in main
    known_paths = addusersitepackages(known_paths)
  File "/usr/local/bin/../Cellar/python@2/2.7.16/bin/../Frameworks/Python.framework/Versions/2.7/lib/python2.7/site.py", line 266, in addusersitepackages
    user_site = getusersitepackages()
  File "/usr/local/bin/../Cellar/python@2/2.7.16/bin/../Frameworks/Python.framework/Versions/2.7/lib/python2.7/site.py", line 241, in getusersitepackages
    user_base = getuserbase() # this will also set USER_BASE
  File "/usr/local/bin/../Cellar/python@2/2.7.16/bin/../Frameworks/Python.framework/Versions/2.7/lib/python2.7/site.py", line 231, in getuserbase
    USER_BASE = get_config_var('userbase')
  File "/usr/local/Cellar/python@2/2.7.16/Frameworks/Python.framework/Versions/2.7/lib/python2.7/sysconfig.py", line 525, in get_config_var
    return get_config_vars().get(name)
  File "/usr/local/Cellar/python@2/2.7.16/Frameworks/Python.framework/Versions/2.7/lib/python2.7/sysconfig.py", line 458, in get_config_vars
    import re
  File "/usr/local/Cellar/python@2/2.7.16/Frameworks/Python.framework/Versions/2.7/lib/python2.7/re.py", line 108, in <module>
    import _locale
SystemError: dynamic module not initialized properly
</code>```

I have added the following lines in my .bash_profile:

```<code>export PYTHONPATH=$robotology_dir/pynaoqi-python2.7-2.5.7.1-mac64/lib/python2.7/site-packages:${PYTHONPATH}
export DYLD_LIBRARY_PATH=$robotology_dir/pynaoqi-python2.7-2.5.7.1-mac64/lib:${DYLD_LIBRARY_PATH}
export DYLD_FRAMEWORK_PATH=$robotology_dir/pynaoqi-python2.7-2.5.7.1-mac64:${DYLD_FRAMEWORK_PATH}
</code>```

I saw that here there was a similar error: Python for Naoqi (dynamic module not initialized properly)
I even tried the csrutil status --> and disabled it but still there was no change in the error I received.

Any help would be highly appreciated!
Thank you very much!

答:
Currently, you are using python 2.7.16 which is not supported.

You have to download exactly this python (https://www.python.org/downloads/release/python-2710/) and then use it via /usr/local/bin/python2.7 - You should see that version name is:

```<code>Python 2.7.10 (v2.7.10:15c95b7d81dc, May 23 2015, 09:33:12)
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
</code>```

Body:
I have installed the Python SDK for the Pepper (as indicated here: http://doc.aldebaran.com/2-5/dev/python/install_guide.html#python-install-guide). I have Mac OS 10.14.3 (Mojave) and running python 2.7.
When I am trying to import naoqi, I get the following error:

Traceback (most recent call last):
  File "/usr/local/bin/../Cellar/python@2/2.7.16/bin/../Frameworks/Python.framework/Versions/2.7/lib/python2.7/site.py", line 539, in <module>
    main()
  File "/usr/local/bin/../Cellar/python@2/2.7.16/bin/../Frameworks/Python.framework/Versions/2.7/lib/python2.7/site.py", line 521, in main
    known_paths = addusersitepackages(known_paths)
  File "/usr/local/bin/../Cellar/python@2/2.7.16/bin/../Frameworks/Python.framework/Versions/2.7/lib/python2.7/site.py", line 266, in addusersitepackages
    user_site = getusersitepackages()
  File "/usr/local/bin/../Cellar/python@2/2.7.16/bin/../Frameworks/Python.framework/Versions/2.7/lib/python2.7/site.py", line 241, in getusersitepackages
    user_base = getuserbase() # this will also set USER_BASE
  File "/usr/local/bin/../Cellar/python@2/2.7.16/bin/../Frameworks/Python.framework/Versions/2.7/lib/python2.7/site.py", line 231, in getuserbase
    USER_BASE = get_config_var('userbase')
  File "/usr/local/Cellar/python@2/2.7.16/Frameworks/Python.framework/Versions/2.7/lib/python2.7/sysconfig.py", line 525, in get_config_var
    return get_config_vars().get(name)
  File "/usr/local/Cellar/python@2/2.7.16/Frameworks/Python.framework/Versions/2.7/lib/python2.7/sysconfig.py", line 458, in get_config_vars
    import re
  File "/usr/local/Cellar/python@2/2.7.16/Frameworks/Python.framework/Versions/2.7/lib/python2.7/re.py", line 108, in <module>
    import _locale
SystemError: dynamic module not initialized properly

I have added the following lines in my .bash_profile:

export PYTHONPATH=$robotology_dir/pynaoqi-python2.7-2.5.7.1-mac64/lib/python2.7/site-packages:${PYTHONPATH}
export DYLD_LIBRARY_PATH=$robotology_dir/pynaoqi-python2.7-2.5.7.1-mac64/lib:${DYLD_LIBRARY_PATH}
export DYLD_FRAMEWORK_PATH=$robotology_dir/pynaoqi-python2.7-2.5.7.1-mac64:${DYLD_FRAMEWORK_PATH}

I saw that here there was a similar error: Python for Naoqi (dynamic module not initialized properly)
I even tried the csrutil status --> and disabled it but still there was no change in the error I received.

Any help would be highly appreciated!
Thank you very much!

Body:
Currently, you are using python 2.7.16 which is not supported.

You have to download exactly this python (https://www.python.org/downloads/release/python-2710/) and then use it via /usr/local/bin/python2.7 - You should see that version name is:

Python 2.7.10 (v2.7.10:15c95b7d81dc, May 23 2015, 09:33:12)
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin


问:
How to check if element exists in an Object?
How to use *ngIf to check if an element exists in an Object?

.ts file

```<code>this.data = ["cat", "dog"];

</code>```

I want to check, in my html file, if cat exists in the object this.data or not. Can I do that with an *ngIf ?

答:
you can create a function in your ts file to check if the wanted string exists in the array or not like this :

```<code>doesExist(animal: string): boolean {
return this.data.includes(animal);
}
</code>```

and then call it in your html file :

```<code><div *ngIf="doesExist('cat')"> [...] </div>
</code>```

Body:
How to use *ngIf to check if an element exists in an Object?

.ts file

this.data = ["cat", "dog"];

I want to check, in my html file, if cat exists in the object this.data or not. Can I do that with an *ngIf ?

Body:
you can create a function in your ts file to check if the wanted string exists in the array or not like this :

doesExist(animal: string): boolean {
return this.data.includes(animal);
}

and then call it in your html file :

<div *ngIf="doesExist('cat')"> [...] </div>


问:
How to calculate mean of columns from array lists in python using numpy?
I am trying to calculate the mean average of columns from a list of arrays.

```<code>f1_score = [array([0.807892  , 0.91698113, 0.73846154]),
            array([0.80041797, 0.9056244 , 0.72017837]),
            array([0.80541103, 0.91493384, 0.70282486])]
</code>```

I also tried as mentioned below, but I couldn't get the mean value for columns.

```<code>output = []
for i in range(len(f1_score)):
   output.append(np.mean(f1_score[i], axis = 0))
</code>```

I get the mean values for rows:

```<code>[0.8211115582302323, 0.8087402497928408, 0.8077232421210242]
</code>```

But I need the mean values for columns:

```<code>array([0.8045736667, 0.9125131233, 0.7204882567])
</code>```

Thanks in advance for your answer.

Body:
I am trying to calculate the mean average of columns from a list of arrays.

f1_score = [array([0.807892  , 0.91698113, 0.73846154]),
            array([0.80041797, 0.9056244 , 0.72017837]),
            array([0.80541103, 0.91493384, 0.70282486])]

I also tried as mentioned below, but I couldn't get the mean value for columns.

output = []
for i in range(len(f1_score)):
   output.append(np.mean(f1_score[i], axis = 0))

I get the mean values for rows:

[0.8211115582302323, 0.8087402497928408, 0.8077232421210242]

But I need the mean values for columns:

array([0.8045736667, 0.9125131233, 0.7204882567])

Thanks in advance for your answer.

Body:
Try this:

f1_score = [[0.807892  , 0.91698113, 0.73846154],[0.80041797, 0.9056244 ,0.72017837],[0.80541103, 0.91493384, 0.70282486]]
temp=[]
output = []
for i in range(len(f1_score)):
    for j in range(len(f1_score)):
        temp.append(f1_score[j][i])
    output.append(np.mean(temp))
print(output)


问:
Tensorflow: delete nodes from graph
I'm trying to delete some nodes from graph and save it in .pb

Only needed nodes can be added to new mod_graph_def graph, but the problem that graph still have some references to deleted node in other nodes inputs, but I can't modify inputs of node:

```<code>def delete_ops_from_graph():
    with open(input_model_filepath, 'rb') as f:
        graph_def = tf.GraphDef()
        graph_def.ParseFromString(f.read())

    nodes = []
    for node in graph_def.node:
        if 'Neg' in node.name:
            print('Drop', node.name)
        else:
            nodes.append(node)

    mod_graph_def = tf.GraphDef()
    mod_graph_def.node.extend(nodes)

    # The problem that graph still have some references to deleted node in other nodes inputs
    for node in mod_graph_def.node:
        inp_names = []
        for inp in node.input:
            if 'Neg' in inp:
                pass
            else:
                inp_names.append(inp)

        node.input = inp_names # TypeError: Can't set composite field

    with open(output_model_filepath, 'wb') as f:
        f.write(mod_graph_def.SerializeToString())
</code>```

答:
```<code>def delete_ops_from_graph():
    with open(input_model_filepath, 'rb') as f:
        graph_def = tf.GraphDef()
        graph_def.ParseFromString(f.read())

    # Delete nodes
    nodes = []
    for node in graph_def.node:
        if 'Neg' in node.name:
            print('Drop', node.name)
        else:
            nodes.append(node)

    mod_graph_def = tf.GraphDef()
    mod_graph_def.node.extend(nodes)

    # Delete references to deleted nodes
    for node in mod_graph_def.node:
        inp_names = []
        for inp in node.input:
            if 'Neg' in inp:
                pass
            else:
                inp_names.append(inp)

        del node.input[:]
        node.input.extend(inp_names)

    with open(output_model_filepath, 'wb') as f:
        f.write(mod_graph_def.SerializeToString())
</code>```

Title: Tensorflow: delete nodes from graph

Body:
I'm trying to delete some nodes from graph and save it in .pb

Only needed nodes can be added to new mod_graph_def graph, but the problem that graph still have some references to deleted node in other nodes inputs, but I can't modify inputs of node:

def delete_ops_from_graph():
    with open(input_model_filepath, 'rb') as f:
        graph_def = tf.GraphDef()
        graph_def.ParseFromString(f.read())

    nodes = []
    for node in graph_def.node:
        if 'Neg' in node.name:
            print('Drop', node.name)
        else:
            nodes.append(node)

    mod_graph_def = tf.GraphDef()
    mod_graph_def.node.extend(nodes)

    # The problem that graph still have some references to deleted node in other nodes inputs
    for node in mod_graph_def.node:
        inp_names = []
        for inp in node.input:
            if 'Neg' in inp:
                pass
            else:
                inp_names.append(inp)

        node.input = inp_names # TypeError: Can't set composite field

    with open(output_model_filepath, 'wb') as f:
        f.write(mod_graph_def.SerializeToString())


问:
Deleting null rows from HTML table with Javascript
I have an HTML table that is pulling from a database. Some of the rows are coming in with the text null and I would like to loop through this table and delete or hide any rows that have the text null in them.

The first column will be the column to loop through and find the 'null' text and delete that row but I can't figure out how to do it.

    <col width="120">
    <col width="120">
    <col width="120">

      Item
      Price
      Sale Price

```

答:
Try the following:</p>

```<code>var rowTag = document.getElementsByTagName("TD")
if(rowTag.textContent == "null"){
  rowTag.parentNode.removeChild()
}
</code>```

Body:
Try the following:

var rowTag = document.getElementsByTagName("TD")
if(rowTag.textContent == "null"){
  rowTag.parentNode.removeChild()
}


问:
Service Error : Expected 0 arguments, but got 1.ts(2554)
while creating the new service using ng g s serviceName i am getting the error Expected 0 arguments, but got 1.

this is my package.json

```<code>{
  "name": "rapid",
  "version": "1.1.9",
  "license": "MIT",
  "scripts": {
    "ng": "ng",
    "start": "ng serve",
    "build": "ng build --prod",
    "test": "ng test",
    "lint": "ng lint",
    "e2e": "ng e2e"
  },
  "private": true,
  "dependencies": {
    "@angular/animations": "^5.2.0",
    "@angular/common": "^5.2.0",
    "@angular/compiler": "^5.2.0",
    "@angular/core": "^5.2.11",
    "@angular/forms": "^5.2.0",
    "@angular/http": "^5.2.0",
    "@angular/platform-browser": "^5.2.0",
    "@angular/platform-browser-dynamic": "^5.2.0",
    "@angular/router": "^5.2.0",
    "@asymmetrik/ngx-leaflet": "^4.0.0",
    "@dvsl/zoomcharts": "^1.18.4",
    "@ng-bootstrap/ng-bootstrap": "^4.0.3",
    "@types/c3": "^0.6.0",
    "@types/mixpanel": "^2.14.1",
    "angular-2-dropdown-multiselect": "^1.8.1",
    "angular-confirmation-popover": "^4.2.0",
    "angular-datatables": "^6.0.0",
    "angular2-tag-input": "^1.2.3",
    "angular2-toaster": "^6.1.0",
    "aws-sdk": "^2.271.1",
    "bootstrap": "^3.3.7",
    "bootstrap-daterangepicker": "^3.0.3",
    "c3": "^0.6.6",
    "core-js": "^2.4.1",
    "crypto-js": "^3.1.9-1",
    "datatables.net": "^1.10.18",
    "datatables.net-dt": "^1.10.18",
    "file-saver": "^2.0.0",
    "jquery": "^3.3.1",
    "leaflet": "^1.3.4",
    "mixpanel-browser": "^2.28.0",
    "moment": "^2.22.2",
    "ng-multiselect-dropdown": "^0.1.9",
    "ng-recaptcha": "^4.2.1",
    "ng2-table": "^1.3.2",
    "ng2-tooltip-directive": "^2.1.6",
    "ngx-bootstrap": "^3.1.2",
    "ngx-cookie-service": "^1.0.10",
    "ngx-popover": "0.0.16",
    "ngx-tooltip": "0.0.9",
    "ngx-webstorage": "^2.0.1",
    "popper.js": "^1.14.3",
    "rxjs": "^5.5.6",
    "tslib": "^1.9.0",
    "xlsx": "^0.14.1",
    "zone.js": "^0.8.19"
  },
  "devDependencies": {
    "@angular-devkit/build-angular": "^0.12.4",
    "@angular/cli": "^7.2.1",
    "@angular/compiler-cli": "^5.2.0",
    "@angular/language-service": "^5.2.0",
    "@types/datatables.net": "^1.10.11",
    "@types/jasmine": "~2.8.3",
    "@types/jasminewd2": "~2.0.2",
    "@types/jquery": "^3.3.4",
    "@types/node": "~6.0.60",
    "codelyzer": "^4.0.1",
    "jasmine-core": "~2.8.0",
    "jasmine-spec-reporter": "~4.2.1",
    "karma": "^3.0.0",
    "karma-chrome-launcher": "~2.2.0",
    "karma-coverage-istanbul-reporter": "^1.2.1",
    "karma-jasmine": "~1.1.0",
    "karma-jasmine-html-reporter": "^0.2.2",
    "protractor": "^5.4.0",
    "ts-node": "~4.1.0",
    "tslint": "~5.9.1",
    "typescript": "~2.5.3"
  }
}
</code>```

by taking out the providedIn parameter from @Injectable the service works as the same or i need to modify my code to solve this error i created service by ng g s serviceName to generate the service.ts file

答:
As mentioned by others, the providedIn syntax is new starting from Angular 6. You are using Angular 5, so this won't work.
In Angular 5 you need to list your services in one of your modules. If you want a singleton service(like the one that would be created with the angular 6 syntax) you need to provide the service in your root module. This is most likely the app.module (if you used the angular cli to create the app. See also: https://angular.io/guide/singleton-services.
If it doesn't need te be singleton service, I would advice to provide the service in the module where you will use it.
Independent of where you decide to provide the service, it should look something like this: </p>

```<code>@NgModule({
  imports: [.. some imports...],
  providers: [MixPanelService],
  declarations: [..some components from your module...],
  exports: [...some components that need to be available outside of your module...],
})
export class MyModule{}
</code>```

Body:
while creating the new service using ng g s serviceName i am getting the error Expected 0 arguments, but got 1.

this is my package.json

{
  "name": "rapid",
  "version": "1.1.9",
  "license": "MIT",
  "scripts": {
    "ng": "ng",
    "start": "ng serve",
    "build": "ng build --prod",
    "test": "ng test",
    "lint": "ng lint",
    "e2e": "ng e2e"
  },
  "private": true,
  "dependencies": {
    "@angular/animations": "^5.2.0",
    "@angular/common": "^5.2.0",
    "@angular/compiler": "^5.2.0",
    "@angular/core": "^5.2.11",
    "@angular/forms": "^5.2.0",
    "@angular/http": "^5.2.0",
    "@angular/platform-browser": "^5.2.0",
    "@angular/platform-browser-dynamic": "^5.2.0",
    "@angular/router": "^5.2.0",
    "@asymmetrik/ngx-leaflet": "^4.0.0",
    "@dvsl/zoomcharts": "^1.18.4",
    "@ng-bootstrap/ng-bootstrap": "^4.0.3",
    "@types/c3": "^0.6.0",
    "@types/mixpanel": "^2.14.1",
    "angular-2-dropdown-multiselect": "^1.8.1",
    "angular-confirmation-popover": "^4.2.0",
    "angular-datatables": "^6.0.0",
    "angular2-tag-input": "^1.2.3",
    "angular2-toaster": "^6.1.0",
    "aws-sdk": "^2.271.1",
    "bootstrap": "^3.3.7",
    "bootstrap-daterangepicker": "^3.0.3",
    "c3": "^0.6.6",
    "core-js": "^2.4.1",
    "crypto-js": "^3.1.9-1",
    "datatables.net": "^1.10.18",
    "datatables.net-dt": "^1.10.18",
    "file-saver": "^2.0.0",
    "jquery": "^3.3.1",
    "leaflet": "^1.3.4",
    "mixpanel-browser": "^2.28.0",
    "moment": "^2.22.2",
    "ng-multiselect-dropdown": "^0.1.9",
    "ng-recaptcha": "^4.2.1",
    "ng2-table": "^1.3.2",
    "ng2-tooltip-directive": "^2.1.6",
    "ngx-bootstrap": "^3.1.2",
    "ngx-cookie-service": "^1.0.10",
    "ngx-popover": "0.0.16",
    "ngx-tooltip": "0.0.9",
    "ngx-webstorage": "^2.0.1",
    "popper.js": "^1.14.3",
    "rxjs": "^5.5.6",
    "tslib": "^1.9.0",
    "xlsx": "^0.14.1",
    "zone.js": "^0.8.19"
  },
  "devDependencies": {
    "@angular-devkit/build-angular": "^0.12.4",
    "@angular/cli": "^7.2.1",
    "@angular/compiler-cli": "^5.2.0",
    "@angular/language-service": "^5.2.0",
    "@types/datatables.net": "^1.10.11",
    "@types/jasmine": "~2.8.3",
    "@types/jasminewd2": "~2.0.2",
    "@types/jquery": "^3.3.4",
    "@types/node": "~6.0.60",
    "codelyzer": "^4.0.1",
    "jasmine-core": "~2.8.0",
    "jasmine-spec-reporter": "~4.2.1",
    "karma": "^3.0.0",
    "karma-chrome-launcher": "~2.2.0",
    "karma-coverage-istanbul-reporter": "^1.2.1",
    "karma-jasmine": "~1.1.0",
    "karma-jasmine-html-reporter": "^0.2.2",
    "protractor": "^5.4.0",
    "ts-node": "~4.1.0",
    "tslint": "~5.9.1",
    "typescript": "~2.5.3"
  }
}

by taking out the providedIn parameter from @Injectable the service works as the same or i need to modify my code to solve this error i created service by ng g s serviceName to generate the service.ts file

Body:
As mentioned by others, the providedIn syntax is new starting from Angular 6. You are using Angular 5, so this won't work.
In Angular 5 you need to list your services in one of your modules. If you want a singleton service(like the one that would be created with the angular 6 syntax) you need to provide the service in your root module. This is most likely the app.module (if you used the angular cli to create the app. See also: https://angular.io/guide/singleton-services.
If it doesn't need te be singleton service, I would advice to provide the service in the module where you will use it.
Independent of where you decide to provide the service, it should look something like this:

@NgModule({
  imports: [.. some imports...],
  providers: [MixPanelService],
  declarations: [..some components from your module...],
  exports: [...some components that need to be available outside of your module...],
})
export class MyModule{}


问:
Python Socket: how to detect and list connected clients in server in the other clients and how to update it when a client disconnected?
I have wrote a server for receiving multiple clients and it can communicate to the clients separately. Here i can list the connected clients in the server, but it doesn't remove the clients from the server when the client is disconnected.

```<code>Server.py

import socket
from threading import Thread

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
ip = '0.0.0.0'
port = 4141
s.bind((ip, port))
s.listen(5)

connected_clients=[]

def handle_client(c, addr):

    while True:
        try:
            message = input("You: ")
            message = message.encode("ascii")
            c.send(message)
        except:
            print("Disconnected for sending..")

        reply = c.recv(4141)
        if not reply:
            print("Disconnected for receiving..")

        else:
            reply = reply.decode('ascii')
            print("Other : ", reply)

while True:

    c, addr = s.accept()
    # print('Connected:', addr)
    connected_clients.append(addr[0])
    print(connected_clients)

    t = Thread(target=handle_client, args=(c, addr))
    t.setDaemon(True)
    t.start()

Client.py

import socket

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
port = 4141

ip = input('Enter the IP Address::')

s.connect((ip, port))

while True:

    message = input("You: ")
    message = message.encode("ascii")
    s.send(message)

    reply = s.recv(4141)
    reply = reply.decode('ascii')
    print("Other : ", reply)

s.close()
</code>```

1)  list the connected clients in the server and other clients(every clients need to list which all are the clients are currently active in the server)

2) Also have to remove the clients when it is disconnected from the server, this updated connected clients information have to be passed into all currently connected clients.

I have research through the following answers, but its not working  out.

1st

2nd

3rd

答:
I'm not that much into server development, but this might help:

for client in connected_clients:
    connected=str(connected_clients)
    s.send(connected.encode())
```

<p>This can be done on request, like:</p>

<pre class="lang-py prettyprint-override"><code>data = s.recv(1024)
if data == <command name here as string>:
    #Call the code above.
</code>```

For deleting inactive users, you can do:

whoLeft = s.recv(1024)
if whoLeft in connected_clients:
    connected_clients.remove(whoLeft)
```

You will have to adjust the client so that before disconnecting it sends its address, but otherwise this should be fine.

Body:
I have wrote a server for receiving multiple clients and it can communicate to the clients separately. Here i can list the connected clients in the server, but it doesn't remove the clients from the server when the client is disconnected.

Server.py

import socket
from threading import Thread

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
ip = '0.0.0.0'
port = 4141
s.bind((ip, port))
s.listen(5)

connected_clients=[]

def handle_client(c, addr):

    while True:
        try:
            message = input("You: ")
            message = message.encode("ascii")
            c.send(message)
        except:
            print("Disconnected for sending..")

        reply = c.recv(4141)
        if not reply:
            print("Disconnected for receiving..")

        else:
            reply = reply.decode('ascii')
            print("Other : ", reply)

while True:

    c, addr = s.accept()
    # print('Connected:', addr)
    connected_clients.append(addr[0])
    print(connected_clients)

    t = Thread(target=handle_client, args=(c, addr))
    t.setDaemon(True)
    t.start()

Client.py

import socket

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
port = 4141

ip = input('Enter the IP Address::')

s.connect((ip, port))

while True:

    message = input("You: ")
    message = message.encode("ascii")
    s.send(message)

    reply = s.recv(4141)
    reply = reply.decode('ascii')
    print("Other : ", reply)

s.close()

1)  list the connected clients in the server and other clients(every clients need to list which all are the clients are currently active in the server)

2) Also have to remove the clients when it is disconnected from the server, this updated connected clients information have to be passed into all currently connected clients.

I have research through the following answers, but its not working  out.

1st

2nd

3rd

Body:
I'm not that much into server development, but this might help:

for client in connected_clients:
    connected=str(connected_clients)
    s.send(connected.encode())

This can be done on request, like:

data = s.recv(1024)
if data == <command name here as string>:
    #Call the code above.

For deleting inactive users, you can do:

whoLeft = s.recv(1024)
if whoLeft in connected_clients:
    connected_clients.remove(whoLeft)

You will have to adjust the client so that before disconnecting it sends its address, but otherwise this should be fine.


问:
Python for Naoqi (dynamic module not initialized properly)
Hi guys I am having a problem with Python and Naoqi for Pepper robot. I've set the right path to NaoqiSDK and when I run "import naoqi" I get this error:

```<code>>>> import naoqi
Traceback (most recent call last):
File"/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site.py", line 548, in <module>
 main()
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site.py", line 530, in main
 known_paths = addusersitepackages(known_paths)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site.py", line 266, in addusersitepackages
user_site = getusersitepackages()
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site.py", line 241, in getusersitepackages
user_base = getuserbase() # this will also set USER_BASE
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site.py", line 231, in getuserbase
USER_BASE = get_config_var('userbase')
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/sysconfig.py", line 520, in get_config_var
return get_config_vars().get(name)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/sysconfig.py", line 453, in get_config_vars
import re
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/re.py", line 108, in <module>
import _locale
SystemError: dynamic module not initialized properly
</code>```

Is there anyone who knows anything about this, how to fix it?

I would appreciate any help about this. Thank you

P.s. I'm running this on OSX

答:
You have to use python2.7.10 downloaded directly from https://www.python.org/downloads/release/python-2710/

It is not enough to use any other 2.7.10.* python version

Body:
Hi guys I am having a problem with Python and Naoqi for Pepper robot. I've set the right path to NaoqiSDK and when I run "import naoqi" I get this error:

>>> import naoqi
Traceback (most recent call last):
File"/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site.py", line 548, in <module>
 main()
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site.py", line 530, in main
 known_paths = addusersitepackages(known_paths)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site.py", line 266, in addusersitepackages
user_site = getusersitepackages()
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site.py", line 241, in getusersitepackages
user_base = getuserbase() # this will also set USER_BASE
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site.py", line 231, in getuserbase
USER_BASE = get_config_var('userbase')
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/sysconfig.py", line 520, in get_config_var
return get_config_vars().get(name)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/sysconfig.py", line 453, in get_config_vars
import re
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/re.py", line 108, in <module>
import _locale
SystemError: dynamic module not initialized properly

Is there anyone who knows anything about this, how to fix it?

I would appreciate any help about this. Thank you

P.s. I'm running this on OSX


问:
Stack of polymorphed classes
dear C++ professionals. I got a problem. I have a program, which has 1 abstract class base_class and 2 derived classes: sippeers and dbget. It also has 2 threads. First thread gets commands from user, second thread pocesses these commands. Both derived classes represent different commands. So, I have to create some kind of stack, where I should put user commands from first thread and get them in second thread to process. To make one stack for all commands, I got to use polymorphism. First, I tried to use std::list. But there was first problem: I can't make a list of abstract classes. Then I tried to use boost::ptr_list, but there was the second problem: classes, created in the first thread, dissappear with end of procedure, that created them. So pointers become illegal. The question: what kind of realization should I use? It looks like I must store every copy of derived class. But where?</p>

答:
An std::queue of shared_ptr<base_class> is the most straightforward solution to pass classes from 1 thread to another without worring about memory management.  Combined with a conditional variable to signal that the queue is not empty, so the consumer-thread can wait.

For the polymorphism part, have an extra virtual function (execute()?), so the consumer thread  shouldn't be aware what class it actually receives.

Title: Stack of polymorphed classes


问:
How to access ref of a component through a function in React Native?
I've imported a custom component into my screen and rendered it in the render() function. Then, created a ref to that custom component. Now, the render() function simply looks like this.

```<code>render() {
  return (
    <View>
      <MyComponent ref={component => this.myComponent1 = component} />
      <MyComponent ref={component => this.myComponent2 = component} />
      <MyComponent ref={component => this.myComponent3 = component} />
    </View>
  )
}
</code>```

Then, In the same screen file, I've created another function to access the state of my custom component. I wrote it like this.

```<code>myFunction = (ref) => {
  ref.setState({ myState: myValue })
}
</code>```

Then, I want to call that function for those separate components separately like this. (In the screen file)

```<code>this.myFunction(this.myComponent1)
this.myFunction(this.myComponent2)
this.myFunction(this.myComponent3)
</code>```

But, it does not work. It gives me the following error.

null is not an object (evaluating 'ref.setState')

Actually what I need this myFunction to do is,

```<code>this.myComponent1.setState({ myState: myValue })
this.myComponent2.setState({ myState: myValue })
this.myComponent3.setState({ myState: myValue })
</code>```

The state myState is in the component while I want to access it through the myFunction() in my screen file.

Can you please help me to solve this problem?

答:
This is not good practice to setState of child component from parent component.
I am assuming you want to set some value to your child component's state by trying this approach.

You can keep these values in your local state and pass it to props and your child component will re-render / get updated value there.

```<code>class Component {
  constructor() {
    this.state = {
      myValues: {
        component1: "abc",
        component2: "xyz",
        component3: "123",
      }
    }
  }

  myFunction(componentName, newValue) {
    this.setState({
      myValues: {
        ...this.state.myValues,
        [componentName]: newValue
      }
    })
  }

  render() {
    return (
      <View>
        <MyComponent value={this.state.myValues.component1} />
        <MyComponent value={this.state.myValues.component2} />
        <MyComponent value={this.state.myValues.component3} />
      </View>
    )
  }
};
</code>```

Body:
I've imported a custom component into my screen and rendered it in the render() function. Then, created a ref to that custom component. Now, the render() function simply looks like this.

render() {
  return (
    <View>
      <MyComponent ref={component => this.myComponent1 = component} />
      <MyComponent ref={component => this.myComponent2 = component} />
      <MyComponent ref={component => this.myComponent3 = component} />
    </View>
  )
}

Then, In the same screen file, I've created another function to access the state of my custom component. I wrote it like this.

myFunction = (ref) => {
  ref.setState({ myState: myValue })
}

Then, I want to call that function for those separate components separately like this. (In the screen file)

this.myFunction(this.myComponent1)
this.myFunction(this.myComponent2)
this.myFunction(this.myComponent3)

But, it does not work. It gives me the following error.

null is not an object (evaluating 'ref.setState')

Actually what I need this myFunction to do is,

this.myComponent1.setState({ myState: myValue })
this.myComponent2.setState({ myState: myValue })
this.myComponent3.setState({ myState: myValue })

The state myState is in the component while I want to access it through the myFunction() in my screen file.

Can you please help me to solve this problem?

Body:
This is not good practice to setState of child component from parent component.
I am assuming you want to set some value to your child component's state by trying this approach.

You can keep these values in your local state and pass it to props and your child component will re-render / get updated value there.

class Component {
  constructor() {
    this.state = {
      myValues: {
        component1: "abc",
        component2: "xyz",
        component3: "123",
      }
    }
  }

  myFunction(componentName, newValue) {
    this.setState({
      myValues: {
        ...this.state.myValues,
        [componentName]: newValue
      }
    })
  }

  render() {
    return (
      <View>
        <MyComponent value={this.state.myValues.component1} />
        <MyComponent value={this.state.myValues.component2} />
        <MyComponent value={this.state.myValues.component3} />
      </View>
    )
  }
};


问:
Remove duplicate values on each string in R
i have a dataframe with two columns:

```<code> VAR1.                     VAR2.

  A.              102 million; 102 million

  B.      0.1 million; 2 million; 0.1 million; 2 million
</code>```

I want to remove duplicate values of VAR2. for each row, obtaining

```<code> VAR1.           VAR2.

  A.          102 million

  B.     0.1 million; 2 million
</code>```

How can I do?

thank you for your suggestions.

答:
Here is a solution using sub which seems to work:

```<code>x <- "0.1 million; 2 million; 0.1 million; 2 million"
gsub("\\b(\\d+(?:\\.\\d+)?) ([^;]+); (?=.*\\b\\1 \\2\\b)", "", x, perl=TRUE)

[1] "0.1 million; 2 million"
</code>```

The general strategy used here is to match a number, with an optional decimal component, followed by another word, provided that this number-word term appears at least once downstream in the input string.  If it does appear again, then we remove the first terms by replacing with empty string.  Note that the last occurrence of a pair of terms would not be deleted, owing to that the positive lookahead would fail.

Body:
i have a dataframe with two columns:

 VAR1.                     VAR2.

  A.              102 million; 102 million

  B.      0.1 million; 2 million; 0.1 million; 2 million

I want to remove duplicate values of VAR2. for each row, obtaining

 VAR1.           VAR2.

  A.          102 million

  B.     0.1 million; 2 million

How can I do?

thank you for your suggestions.

Body:
Here is a solution using sub which seems to work:

x <- "0.1 million; 2 million; 0.1 million; 2 million"
gsub("\\b(\\d+(?:\\.\\d+)?) ([^;]+); (?=.*\\b\\1 \\2\\b)", "", x, perl=TRUE)

[1] "0.1 million; 2 million"

The general strategy used here is to match a number, with an optional decimal component, followed by another word, provided that this number-word term appears at least once downstream in the input string.  If it does appear again, then we remove the first terms by replacing with empty string.  Note that the last occurrence of a pair of terms would not be deleted, owing to that the positive lookahead would fail.


问:
How can we get view object outside it's own controller in sap ui5? and how can we access the controls of a view outside it's controller in sap ui5?
Suppose I have a view

How can I get a control of this view by Id from a different controller.

I have tried to set up an ID for the view and tried to access the view by
sap.ui.getCore().byId("mainViewID") in another controller but it didnt work.
It took only the dynamic view id what you can find from the html elements.

答:
Getting a control from another view is discouraged and is generally indicative of bad design.
In case what you need to do is access data in another view or to change a property of a control based on user input, the better method is to bind those properties to a model and then access that model from the second view.
You can do this by attaching the model to the core, thereby making it accessible throughout the application. For example:

```<code>var oModel = new sap.ui.model.json.JSONModel();
this.getCore.setModel(oModel,"modelName");
</code>```

Alternatively, you can create this model in the manifest file.

Body:
Getting a control from another view is discouraged and is generally indicative of bad design.
In case what you need to do is access data in another view or to change a property of a control based on user input, the better method is to bind those properties to a model and then access that model from the second view.
You can do this by attaching the model to the core, thereby making it accessible throughout the application. For example:

var oModel = new sap.ui.model.json.JSONModel();
this.getCore.setModel(oModel,"modelName");

Alternatively, you can create this model in the manifest file.