问:
How to add a separator in a TinyMCE dropdown menu
I am working on a WordPress plugin and I can add TinyMCE buttons that present a dropdown menu when clicked. However, I would like to add a horizontal separator (i.e., a horizontal line) to that drop down menu to group options.

I have googled this for some time and the only information I have found is about adding a vertical separator (i.e., a vertical line) between buttons on the menu itself.

Is it possible to add a horizontal separator to a dropdown menu in TinyMCE, and if so, how can I do it? Or is my only option to group these other items by using a submenu?

```<code>            ed.addButton('d12-mb-button-2', {
            title:'Add a message block with a custom title',
            type:'menubutton',
            image: url + '/d12-mb-mce-button-2.png',
            menu: [
                    {
                    text: 'Part of a series',
                    value: 'Part',
                    icon: 'icon d12mb-part',
                    onclick: function() {
                        ed.windowManager.open( {
                            title: 'Please enter the data for this message box',
                            body: [{
                                type: 'textbox',
                                name: 'title',
                                label: 'This series of articles is about:'
                            },
                            {
                                type: 'textbox',
                                minHeight: 200,
                                minWidth: 400,
                                multiline: 'true',
                                name: 'description',
                                label: 'Description of this series:'
                            }
                            ],
                            onsubmit: function( epart ) {
                                ed.selection.setContent('[d12-part series="' + epart.data.title + '"]' + epart.data.description + '[/d12-part]');
                            }
                        });
                    }
                }, // End of "Part"
                {
                    text: 'Add a support message',
                    value: 'Support',
                    icon: 'icon d12mb-support',
                    onclick: function() {
                        ed.windowManager.open( {
                            title: 'Please enter the support information',
                            body: [{
                                type: 'textbox',
                                name: 'title',
                                label: 'Support title:'
                            },
                            {
                                type: 'textbox',
                                minHeight: 200,
                                minWidth: 400,
                                multiline: 'true',
                                name: 'description',
                                label: 'Support message:'
                            }
                            ],
                            onsubmit: function( esupport ) {
                                ed.selection.setContent('[d12-support title="' + esupport.data.title + '"]' + esupport.data.description + '[/d12-support]');
                            }
                        });
                    }
                }, // End of "Support"
</code>```

I need to add a horizontal separator right after the 'end of "Part"' item.

(FWIW, the entire file I am working on is here.)

答:
All of the documentation I've found is for inserting vertical separators between groups of icons on the menu bar. I haven't been able to find any information on adding horizontal separators between groups of items in a drop-down menu.

However, after a lot of experimentation, I found that this code:

```<code>                    {
                    text: '|'
                },
</code>```

will add a horizontal separator.

Body:
I am working on a WordPress plugin and I can add TinyMCE buttons that present a dropdown menu when clicked. However, I would like to add a horizontal separator (i.e., a horizontal line) to that drop down menu to group options.

I have googled this for some time and the only information I have found is about adding a vertical separator (i.e., a vertical line) between buttons on the menu itself.

Is it possible to add a horizontal separator to a dropdown menu in TinyMCE, and if so, how can I do it? Or is my only option to group these other items by using a submenu?

            ed.addButton('d12-mb-button-2', {
            title:'Add a message block with a custom title',
            type:'menubutton',
            image: url + '/d12-mb-mce-button-2.png',
            menu: [
                    {
                    text: 'Part of a series',
                    value: 'Part',
                    icon: 'icon d12mb-part',
                    onclick: function() {
                        ed.windowManager.open( {
                            title: 'Please enter the data for this message box',
                            body: [{
                                type: 'textbox',
                                name: 'title',
                                label: 'This series of articles is about:'
                            },
                            {
                                type: 'textbox',
                                minHeight: 200,
                                minWidth: 400,
                                multiline: 'true',
                                name: 'description',
                                label: 'Description of this series:'
                            }
                            ],
                            onsubmit: function( epart ) {
                                ed.selection.setContent('[d12-part series="' + epart.data.title + '"]' + epart.data.description + '[/d12-part]');
                            }
                        });
                    }
                }, // End of "Part"
                {
                    text: 'Add a support message',
                    value: 'Support',
                    icon: 'icon d12mb-support',
                    onclick: function() {
                        ed.windowManager.open( {
                            title: 'Please enter the support information',
                            body: [{
                                type: 'textbox',
                                name: 'title',
                                label: 'Support title:'
                            },
                            {
                                type: 'textbox',
                                minHeight: 200,
                                minWidth: 400,
                                multiline: 'true',
                                name: 'description',
                                label: 'Support message:'
                            }
                            ],
                            onsubmit: function( esupport ) {
                                ed.selection.setContent('[d12-support title="' + esupport.data.title + '"]' + esupport.data.description + '[/d12-support]');
                            }
                        });
                    }
                }, // End of "Support"

I need to add a horizontal separator right after the 'end of "Part"' item.

(FWIW, the entire file I am working on is here.)

Body:
All of the documentation I've found is for inserting vertical separators between groups of icons on the menu bar. I haven't been able to find any information on adding horizontal separators between groups of items in a drop-down menu.

However, after a lot of experimentation, I found that this code:

                    {
                    text: '|'
                },

will add a horizontal separator.


来源: stackexchange

问:
ASP MVC - Form input types and model binding issues
I am playing around with server-side form validation, model binding and ModelState and I’ve noticed the following:

If I have an input of type “email” and I insert an invalid email
address (such as ‘hello’), model binding doesn’t work – the value
shows up as ‘null’.

However, if I insert a valid email address,
everything works out.

Can someone explain to me why this happens?
Thanks in advance!

Form:

```<code><form name="contactForm" id="contactF" ng-controller="Contacts"  ng-submit="contactForm.$invalid ? sendMessage() : return;" novalidate>
    <input type="email" name="email" ng-model="model.EmailAddress" required placeholder="Email"/>
    <div ng-messages="contactForm.email.$error" ng-if="contactForm.email.$touched || contactForm.$submitted">
        <div ng-messages-include="/Helpers/error-messages.html"></div>
    </div>

    <textarea name="message" ng-model="model.message" required placeholder="Escreva a sua mensagem aqui."></textarea>
    <div ng-messages="contactForm.message.$error" ng-if="contactForm.message.$touched || contactForm.$submitted">
        <div ng-messages-include="/Helpers/error-messages.html"></div>
    </div>
    <br />
    <input type="submit" value="Enviar"/>
</form>
</code>```

Model:

```<code>public class HomeContactVM
{
    [Required(ErrorMessage = "Error message here")]
    public string Name { get; set; }

    [Required(ErrorMessage = "Error msg here.")]
    [EmailAddress(ErrorMessage = "Please use a valid email address.")]
    public string EmailAddress { get; set; }

    [Required(ErrorMessage = "Error msg here.")]
    public string Message { get; set; }
}
</code>```

Action method:

```<code>[HttpPost]
public JsonResult Contact(HomeContactVM model)
{
    string message;
    if (ModelState.IsValid)
    {
        using (SmtpClient client = new SmtpClient())
        {
            MailMessage msg = new MailMessage()
            {
                Body = model.Message,
                BodyEncoding = Encoding.UTF8,
                Subject = "New message from " + model.EmailAddress,
                From = new MailAddress(model.EmailAddress),
                Sender = new MailAddress("xxx@gmail.com", "xx")
            };

            int retries = 5;
            bool retry = true;
            while (retry)
            {
                try
                {
                    client.Send(msg);
                    message = "Your message was sent.";
                    return Json(message, JsonRequestBehavior.AllowGet);
                }
                catch (Exception)
                {
                    if (retries > 0) {
                                retries--;
                    }
                    else {
                        retry = false;
                        message = "Something went wrong. Please try again later.";
                        return Json(message, JsonRequestBehavior.AllowGet);
                    }
                }
            }
        }
    }
    message = "Your model is not valid.";
    return Json( message, JsonRequestBehavior.AllowGet);
}
</code>```

答:
So, if anyone is facing the same problem, here's what I found: the problem is not related to ASP, it's due to Angular's default behaviour.
If an input fails validation, Angular sets its value to undefined and it doesn't pass it to the model, hence it showing up as null. A possible workaround is to set ng-model-options="{allowInvalid: true}"

You can find more about this behaviour here: Angular.js - ngModel value is undefined when ng-pattern is set in directive and Get "raw" value from invalid input field

Hope this helps!

ContentLicense: CC BY-SA 3.0

Body:
I am playing around with server-side form validation, model binding and ModelState and I’ve noticed the following:

If I have an input of type “email” and I insert an invalid email
address (such as ‘hello’), model binding doesn’t work – the value
shows up as ‘null’.

However, if I insert a valid email address,
everything works out.

Can someone explain to me why this happens?
Thanks in advance!

Form:

<form name="contactForm" id="contactF" ng-controller="Contacts"  ng-submit="contactForm.$invalid ? sendMessage() : return;" novalidate>
    <input type="email" name="email" ng-model="model.EmailAddress" required placeholder="Email"/>

    <textarea name="message" ng-model="model.message" required placeholder="Escreva a sua mensagem aqui."></textarea>

    <input type="submit" value="Enviar"/>
</form>

Model:

public class HomeContactVM
{
    [Required(ErrorMessage = "Error message here")]
    public string Name { get; set; }

    [Required(ErrorMessage = "Error msg here.")]
    [EmailAddress(ErrorMessage = "Please use a valid email address.")]
    public string EmailAddress { get; set; }

    [Required(ErrorMessage = "Error msg here.")]
    public string Message { get; set; }
}

Action method:

[HttpPost]
public JsonResult Contact(HomeContactVM model)
{
    string message;
    if (ModelState.IsValid)
    {
        using (SmtpClient client = new SmtpClient())
        {
            MailMessage msg = new MailMessage()
            {
                Body = model.Message,
                BodyEncoding = Encoding.UTF8,
                Subject = "New message from " + model.EmailAddress,
                From = new MailAddress(model.EmailAddress),
                Sender = new MailAddress("xxx@gmail.com", "xx")
            };

            int retries = 5;
            bool retry = true;
            while (retry)
            {
                try
                {
                    client.Send(msg);
                    message = "Your message was sent.";
                    return Json(message, JsonRequestBehavior.AllowGet);
                }
                catch (Exception)
                {
                    if (retries > 0) {
                                retries--;
                    }
                    else {
                        retry = false;
                        message = "Something went wrong. Please try again later.";
                        return Json(message, JsonRequestBehavior.AllowGet);
                    }
                }
            }
        }
    }
    message = "Your model is not valid.";
    return Json( message, JsonRequestBehavior.AllowGet);
}


问:
How to design DAO, REST Service layer
I am working on REST and JPA technology and want to design Service and Dao layer generically.
I want to follow the decouple rule for each layer. So that in future at any point of time these layer can be changed if required without much modification. So to do the same for DAO layer I am following Factory pattern.

Please have a look what i did till now.

```<code>public abstract class AbstractDao {

    @PersistenceUnit(name = "Services")
    private EntityManagerFactory factory;

    public AbstractDao() {
    this.factory = Persistence.createEntityManagerFactory("Services");
    }

    public void save(AbstractEntity entity) {
    EntityManager em = getEntityManager();
    EntityTransaction tx = em.getTransaction();
    tx.begin();
    em.persist(entity);
    tx.commit();
    }

    public void delete(AbstractEntity entity) {
    getEntityManager().remove(entity);
    }

    public List<AbstractEntity> findAll() {
    CriteriaBuilder cb = getEntityManager().getCriteriaBuilder();

    CriteriaQuery<AbstractEntity> cq = cb.createQuery(AbstractEntity.class);
    Root<AbstractEntity> from = cq.from(AbstractEntity.class);

    cq.select(from);
    TypedQuery<AbstractEntity> q = getEntityManager().createQuery(cq);

    List<AbstractEntity> allitems = q.getResultList();
    return allitems;
    }

    private EntityManager getEntityManager() {
    EntityManager em = factory.createEntityManager();
    return em;
    }

}
</code>```

So this the design what I used for DAO layer. But not sure is it the right approach or it can be much better like AbstractFactory patter or etc.

Now come to REST Service layer where I am accessing this DAO layer for CRUD.

So this the way how I am accessing the DAO layer on Service layer. But again I am thinking to way some other better way to access this DAO layer.
One more thing I want to ask, would it be good idea if I introduce business layer and follow like this.

Client -> Service Layer-> Business Layer -> DAO Layer

Could someone help me to design the different layer of project.

Thanks in advance.

答:
please use this type of directory structure:

use Spring  framework and use Spring Restful service annotations, for example refer this link :

https://dzone.com/articles/exporting-spring-data-jpa

Title: How to design DAO, REST Service layer

Body:
I am working on REST and JPA technology and want to design Service and Dao layer generically.
I want to follow the decouple rule for each layer. So that in future at any point of time these layer can be changed if required without much modification. So to do the same for DAO layer I am following Factory pattern.

Please have a look what i did till now.

public abstract class AbstractDao {

    @PersistenceUnit(name = "Services")
    private EntityManagerFactory factory;

    public AbstractDao() {
    this.factory = Persistence.createEntityManagerFactory("Services");
    }

    public void save(AbstractEntity entity) {
    EntityManager em = getEntityManager();
    EntityTransaction tx = em.getTransaction();
    tx.begin();
    em.persist(entity);
    tx.commit();
    }

    public void delete(AbstractEntity entity) {
    getEntityManager().remove(entity);
    }

    public List<AbstractEntity> findAll() {
    CriteriaBuilder cb = getEntityManager().getCriteriaBuilder();

    CriteriaQuery<AbstractEntity> cq = cb.createQuery(AbstractEntity.class);
    Root<AbstractEntity> from = cq.from(AbstractEntity.class);

    cq.select(from);
    TypedQuery<AbstractEntity> q = getEntityManager().createQuery(cq);

    List<AbstractEntity> allitems = q.getResultList();
    return allitems;
    }

    private EntityManager getEntityManager() {
    EntityManager em = factory.createEntityManager();
    return em;
    }

}

So this the design what I used for DAO layer. But not sure is it the right approach or it can be much better like AbstractFactory patter or etc.

Now come to REST Service layer where I am accessing this DAO layer for CRUD.

So this the way how I am accessing the DAO layer on Service layer. But again I am thinking to way some other better way to access this DAO layer.
One more thing I want to ask, would it be good idea if I introduce business layer and follow like this.

Client -> Service Layer-> Business Layer -> DAO Layer

Could someone help me to design the different layer of project.

Thanks in advance.


问:
Which type of path to store in MySQL database?
When I come to build a simple site using PHP and MySQL, what is the best method for storing paths of files and images?

Inserting paths to Mysql as (system path C:/----)

Inserting paths to Mysql as (HTTP path http://----)

答: It depends on how you use your data. When you want as example edit your file the best solution is to use the system path. And when you want, as example link to another page you can use the HTTP path</p>

ContentLicense: CC BY-SA 2.5


问:
PHP not recognized by server
I have been looking at this issue for a few hours. I looked at many Stackoverflow posts, and I couldn't find the solution to my problem.

I scrapped my website a few months ago, and just started a new one shortly thereafter. However, my website does not seem to accept PHP. I don't know if the issue is with the server (when I renewed my hosting), or something else. Even calling an external PHP file, using the include function, does not work.

Anyhow, after placing the following code (along other simple coding), I see this in my PHP file when I browse the source code - meaning PHP is not working:

```<code><?php phpinfo() ; ?>
</code>```

Also, my htaccess file says the following (but I honestly have no clue what any of it means. Though I always hear people say that this file can make a difference:

```<code># BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>

# END WordPress
</code>```

答:
It is a bit hard to understand what the actual cause is. Do you run your own webserver? If so, is it apache httpd or IIS? If you have an external hosting partner, they should be able to help you.

Why do you have a htaccess file? You only need it for things like redirect rules. If you don't use that, delete this file or empty it.

Installation of LAMP stacks :https://www.digitalocean.com/community/tutorials/how-to-install-linux-apache-mysql-php-lamp-stack-on-ubuntu-16-04

Title: PHP not recognized by server

Body:
I have been looking at this issue for a few hours. I looked at many Stackoverflow posts, and I couldn't find the solution to my problem.

I scrapped my website a few months ago, and just started a new one shortly thereafter. However, my website does not seem to accept PHP. I don't know if the issue is with the server (when I renewed my hosting), or something else. Even calling an external PHP file, using the include function, does not work.

Anyhow, after placing the following code (along other simple coding), I see this in my PHP file when I browse the source code - meaning PHP is not working:

<?php phpinfo() ; ?>

Also, my htaccess file says the following (but I honestly have no clue what any of it means. Though I always hear people say that this file can make a difference:

# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>

# END WordPress


问:
How to run rails app in docker container with nginx running on host machine?
I'm working on the scenario where I need to have:
1. nginx running on the host machine
2. rails app running inside docker container

My initial work included adding Dockerfile into rails app directory on host which looks like this:

```<code>ubuntu@ubuntu-xenial:~/rails_docker$ cat Dockerfile
FROM ruby:2.1-onbuild

ENV HOME /home/rails/webapp

RUN apt-get update -qq && apt-get install -y build-essential libpq-dev nodejs

WORKDIR $HOME

# Install gems
ADD Gemfile* $HOME/
RUN bundle install

# Add the app code
ADD . $HOME

EXPOSE 8080
EXPOSE 5432
</code>```

Since I already have nginx on host, it is configured to look at directory where rails application exists on host machine:

```<code>ubuntu@ubuntu-xenial:~$ cat /etc/nginx/sites-available/www.testblog.io.conf
# MANAGED BY PUPPET
server {
  listen *:8080;
  server_name           www.testblog.io;

  index  index.html index.htm index.php;

  access_log            /var/log/nginx/www.testblog.io.access.log combined;
  error_log             /var/log/nginx/www.testblog.io.error.log;

  location / {
    root      /home/ubuntu/rails_docker/public;
    index     index.html index.htm index.php;
  }
  passenger_enabled on;
  passenger_ruby /usr/local/rvm/wrappers/default/ruby;
}
</code>```

I'm able to build docker image and my next idea is following:
1. Declare /home/ubuntu/rails_docker as a host volume when running "rails container"
2. Expose ports 8080:8080 and 5432:5432

Command I use is following:

```<code>ubuntu@ubuntu-xenial:~/rails_docker$ docker run -d -p 8080:8080 --name examplerails -v /home/ubuntu/rails_docker:/home/rails/webapp railsapptest
82c8aa45b8c1a405e198a565feabf105d1afcbb1c37f8b7b11bf764395ed8c4e
</code>```

When I check logs:

```<code>ubuntu@ubuntu-xenial:~/rails_docker$ docker logs -f examplerails
Switch to inspect mode.
</code>```

For some reason, it goes into irb mode. Any idea what I'm doing wrong?

Thanks in advance,
Bakir

答:
You need to have a CMD instruction in your Dockerfile. That is the command that is run when you start up your Docker container. If you don't specify a command, it will run whatever your FROM image uses, which you can see is 'irb' if you look at the Ruby docker image.

You can read more about the CMD instruction and everything else about Dockerfiles in the Docker documentation.

Body:
I'm working on the scenario where I need to have:
1. nginx running on the host machine
2. rails app running inside docker container

My initial work included adding Dockerfile into rails app directory on host which looks like this:

ubuntu@ubuntu-xenial:~/rails_docker$ cat Dockerfile
FROM ruby:2.1-onbuild

ENV HOME /home/rails/webapp

RUN apt-get update -qq && apt-get install -y build-essential libpq-dev nodejs

WORKDIR $HOME

# Install gems
ADD Gemfile* $HOME/
RUN bundle install

# Add the app code
ADD . $HOME

EXPOSE 8080
EXPOSE 5432

Since I already have nginx on host, it is configured to look at directory where rails application exists on host machine:

ubuntu@ubuntu-xenial:~$ cat /etc/nginx/sites-available/www.testblog.io.conf
# MANAGED BY PUPPET
server {
  listen *:8080;
  server_name           www.testblog.io;

  index  index.html index.htm index.php;

  access_log            /var/log/nginx/www.testblog.io.access.log combined;
  error_log             /var/log/nginx/www.testblog.io.error.log;

  location / {
    root      /home/ubuntu/rails_docker/public;
    index     index.html index.htm index.php;
  }
  passenger_enabled on;
  passenger_ruby /usr/local/rvm/wrappers/default/ruby;
}

I'm able to build docker image and my next idea is following:
1. Declare /home/ubuntu/rails_docker as a host volume when running "rails container"
2. Expose ports 8080:8080 and 5432:5432

Command I use is following:

ubuntu@ubuntu-xenial:~/rails_docker$ docker run -d -p 8080:8080 --name examplerails -v /home/ubuntu/rails_docker:/home/rails/webapp railsapptest
82c8aa45b8c1a405e198a565feabf105d1afcbb1c37f8b7b11bf764395ed8c4e

When I check logs:

ubuntu@ubuntu-xenial:~/rails_docker$ docker logs -f examplerails
Switch to inspect mode.

For some reason, it goes into irb mode. Any idea what I'm doing wrong?

Thanks in advance,
Bakir


问:
Unable to assign ACL permissions to uploaded file when using S3FS node js lib
I am using S3FS lib (in node.js app) to upload files to my AWS S3 directory. (referring documentation https://www.npmjs.com/package/s3fs) and  stackoverflow answer here

s3fs object init

s3fsImpl = new s3fs(bucketPath, {
            accessKeyId: xxxxx,
            secretAccessKey: xxxxx,
            ACL: 'public-read'
        })

method writeFile: s3fsImpl.writeFile(fileName, stream)

file is uploaded successfully and I am getting "ETag" in response. However, uploaded file is not accessible publicly.

How can I give proper ACL permissions to make it accessible for public-read?

答:
You can provide the ACL as the third option in writeFile method as

s3fsImpl.writeFile(fileName, stream,{ ACL: 'public-read'})


问:
Hide elements when width change
I have question because I'm try hide menu when window width is more than 766px. This is my code but not work

HTML

```<code><div class="menu">
    <div class="burger-menu">
        <span></span>
        <span></span>
        <span></span>
    </div>
    <ul class="submenu">
        <li><a href="#about-me">O mnie</a></li>
        <li><a href="">Prace</a></li>
        <li><a href="">Certyfikty</a></li>
        <li><a href="">Cennik</a></li>
        <li><a href="">Kontakt</a></li>
    </ul>
</div>
</code>```

JQuery

```<code>//Burger menu

$('.burger-menu').click(function(){

  $(this).toggleClass('open');

});

//Menu list

$('.burger-menu').click(function(){
    $('.submenu').slideToggle();
});

if($(window).width() > 766){
    $('.submenu').hide();
}else {
    console.log('halo');
};
</code>```

Everything works but when I click burger and menu slide for example on 677px and then resize window to more than 766px menu still there. Thanks for every help

答:
you should call the resize function in jquery
    //the function to hide the div
    function hideDiv(){

```<code>if ($(window).width() < 1024) {

        $("#floatdiv").fadeOut("slow");

}else{

    $("#floatdiv").fadeIn("slow");

}

}

//run on document load and on window resize
$(document).ready(function () {

//on load
hideDiv();

//on resize
$(window).resize(function(){
    hideDiv();
  });

});
</code>```

or you can do it with css media query :

```<code>   /* always assume on smaller screen first */

 #floatdiv {
  display:none;
 }

/* if screen size gets wider than 1024 */

 @media screen and (min-width:1024px){
    #floatdiv {
      display:block;
  }
 }
</code>```

Title: Hide elements when width change

Body:
I have question because I'm try hide menu when window width is more than 766px. This is my code but not work

HTML

O mnie

Prace

Certyfikty

Cennik

Kontakt

JQuery

//Burger menu

$('.burger-menu').click(function(){

  $(this).toggleClass('open');

});

//Menu list

$('.burger-menu').click(function(){
    $('.submenu').slideToggle();
});

if($(window).width() > 766){
    $('.submenu').hide();
}else {
    console.log('halo');
};

Everything works but when I click burger and menu slide for example on 677px and then resize window to more than 766px menu still there. Thanks for every help

Body:
you should call the resize function in jquery
    //the function to hide the div
    function hideDiv(){

if ($(window).width() < 1024) {

        $("#floatdiv").fadeOut("slow");

}else{

    $("#floatdiv").fadeIn("slow");

}

}

//run on document load and on window resize
$(document).ready(function () {

//on load
hideDiv();

//on resize
$(window).resize(function(){
    hideDiv();
  });

});

or you can do it with css media query :

   /* always assume on smaller screen first */

 #floatdiv {
  display:none;
 }

/* if screen size gets wider than 1024 */

 @media screen and (min-width:1024px){
    #floatdiv {
      display:block;
  }
 }


问:
Can I print a list without the brackets?
```<code>from itertools import product
A=((1,2),(3,4))
B= list(product(*A))
print (B)
</code>```

my output is

```<code>[(1, 3), (1, 4), (2, 3), (2, 4)]
</code>```

but I want my output

```<code>(1, 3) (1, 4) (2, 3) (2, 4)
</code>```

Body:
from itertools import product
A=((1,2),(3,4))
B= list(product(*A))
print (B)

my output is

[(1, 3), (1, 4), (2, 3), (2, 4)]

but I want my output

(1, 3) (1, 4) (2, 3) (2, 4)

Body:
simply use:

print (*B)

outputs:

(1, 3) (1, 4) (2, 3) (2, 4)


问:
Javascript - How many arguments are there for confirm?
How many arguments are there for confirm box?

What does var del=confirm("Are you sure?","Delete",""); mean?

答:
confirm accepts only one argument:

```<code>var ans=confirm('Your message');
</code>```

It will display your message with OK and Cancel buttons.

Body:
confirm accepts only one argument:

var ans=confirm('Your message');

It will display your message with OK and Cancel buttons.


问:
Why a statement written after iterating over an empty list does not work python
To my knowledge, the following code will not work:

```<code>empty_list = []
if empty_list:
    print("It's an empty list, duh...")
</code>```

However, I came across the following situation:

```<code>arr = []
for r in arr:
    print(r)
    print("Why?")
</code>```

While it's understandable that arr is empty, therefore print(r) will return nothing, why the following piece of code does not work?

Does for also tests for boolean?

答:
The for loop simply iterates over whatever it is given. If the iterable that is being iterated over is empty, then the for loop will never run. Thus, the body will never be executed.

The normal for loop

```<code>for var in []:
    print(var)
</code>```

is basically syntactic sugar for this

```<code>iterator = iter([])
while True:
    try:
        var = next(iterator)
        print(var)
    except StopIteration:
        break
</code>```

That is essentially what Python is doing behind the scenes. It creates an iterator from what is passed in, and continues to ask for the next element from the iterator until it is exhausted and a StopIteration exception is raised.

Since the iterable above is empty, on the first attempt Python makes to get an element from the iterator, it raises a StopIteration. Thus, Python skips the body of the loop, and goes to the except clause, which breaks the loop. The same behavior happens in your example. A StopIteration is immediately raised because arr is empty, so the for loop body is never executed.

Here is an example to further demonstrate this:

```<code>>>> arr = []
>>> iterator = iter(arr)
>>> next(iterator)
Traceback (most recent call last):
  File "<pyshell#2>", line 1, in <module>
    next(iterator)
StopIteration
>>>
</code>```

As you can see, the first call to next() causes a StopIteration exception to be raised. This is the same thing that happens in your for loop body.

Body:
To my knowledge, the following code will not work:

empty_list = []
if empty_list:
    print("It's an empty list, duh...")

However, I came across the following situation:

arr = []
for r in arr:
    print(r)
    print("Why?")

While it's understandable that arr is empty, therefore print(r) will return nothing, why the following piece of code does not work?

Does for also tests for boolean?

Body:
The for loop simply iterates over whatever it is given. If the iterable that is being iterated over is empty, then the for loop will never run. Thus, the body will never be executed.

The normal for loop

for var in []:
    print(var)

is basically syntactic sugar for this

iterator = iter([])
while True:
    try:
        var = next(iterator)
        print(var)
    except StopIteration:
        break

That is essentially what Python is doing behind the scenes. It creates an iterator from what is passed in, and continues to ask for the next element from the iterator until it is exhausted and a StopIteration exception is raised.

Since the iterable above is empty, on the first attempt Python makes to get an element from the iterator, it raises a StopIteration. Thus, Python skips the body of the loop, and goes to the except clause, which breaks the loop. The same behavior happens in your example. A StopIteration is immediately raised because arr is empty, so the for loop body is never executed.

Here is an example to further demonstrate this:

>>> arr = []
>>> iterator = iter(arr)
>>> next(iterator)
Traceback (most recent call last):
  File "<pyshell#2>", line 1, in <module>
    next(iterator)
StopIteration
>>>

As you can see, the first call to next() causes a StopIteration exception to be raised. This is the same thing that happens in your for loop body.


问:
C++ parallel average matrix with OpenMP
I have this code in C++ that calculates the average of each column of a matrix. I want to parallelize the code using OpenMP.

#include <vector>
#include <cstdlib>
#include <chrono>
#include <iostream>
using namespace std;

vector<double> average(const vector<vector<unsigned char>>& original){
  vector<vector<double>> result(original.size(), vector<double>(original[0].size()));
  vector<double> average(original[0].size(), 0.0);

  for (int i=0; i<original.size(); i++) {
    const vector<unsigned char>& vector = original[i];
    for (int k = 0; k < vector.size(); ++k) {
      average[k] += vector[k];
    }
  }
  for (double& val : average) {
    val /= original.size();
  }

  return average;
}
```

Adding #pragma omp parallel for before the outer for loop gets me bogus results. Do you have any pointers? I thought I would find tons of examples of this online but wasn't able to find much. This is my first time using OpenMP.

答:
average[k] += vector[k]; is not an atomic operation.

Each thread might (and probably will) read the current value of k (possibly at the same time), add to it, and write the value back.

These types of cross-thread data races are undefined behavior.

Edit:
An easy fix would be to invert the order the loops, and parallelize on the k loop. This way, each thread would be writing to only one value. But then, you would multiply by K the number of lookups on the top-level vector, so you may not get that big of a performance gain as you will start thrashing the cache pretty hard.

Title: C++ parallel average matrix with OpenMP

Body:
I have this code in C++ that calculates the average of each column of a matrix. I want to parallelize the code using OpenMP.

#include <vector>
#include <cstdlib>
#include <chrono>
#include <iostream>
using namespace std;

vector<double> average(const vector<vector<unsigned char>>& original){
  vector<vector<double>> result(original.size(), vector<double>(original[0].size()));
  vector<double> average(original[0].size(), 0.0);

  for (int i=0; i<original.size(); i++) {
    const vector<unsigned char>& vector = original[i];
    for (int k = 0; k < vector.size(); ++k) {
      average[k] += vector[k];
    }
  }
  for (double& val : average) {
    val /= original.size();
  }

  return average;
}

Adding #pragma omp parallel for before the outer for loop gets me bogus results. Do you have any pointers? I thought I would find tons of examples of this online but wasn't able to find much. This is my first time using OpenMP.


问:
GRPC create channel link for Google Assistant API
I'm trying to write a C++ code to create Google Assistant on UDOO x86 board (See https://developers.google.com/assistant/sdk/).
I have tried to follow all the steps regarding in the tutorial, but I'm not sure what URL I should have when I call the creatChannel method?

I do have the credentials JSON downloaded and using it through the "GOOGLE_APPLICATION_CREDENTIALS" environment variable

Object creation:

```<code>GAssistantClient greeter(grpc::CreateChannel(
      "google.com", grpc::GoogleDefaultCredentials()));
</code>```

Contructor:

```<code>GAssistantClient(std::shared_ptr<Channel> channel)
      : stub_(Greeter::NewStub(channel)) {}
</code>```

When I put google.com in there, I get the following error:
E0505 18:30:34.959710444    7635 ssl_transport_security.c:1226] Invalid toplevel subdomain: com
E0505 18:30:34.959836517    7635 ssl_transport_security.c:1226] Invalid toplevel subdomain: com

答:
You have to authenticate using your credentials and then create a channel, after that you have send audio config request about your audio and then send an audio data request which contains your audio captured etc.

You can use ALSA sound API library to capture and playback audio.
and then send and receive in api requests and responses.

You should follow the following order in this doc

Body:
I'm trying to write a C++ code to create Google Assistant on UDOO x86 board (See https://developers.google.com/assistant/sdk/).
I have tried to follow all the steps regarding in the tutorial, but I'm not sure what URL I should have when I call the creatChannel method?

I do have the credentials JSON downloaded and using it through the "GOOGLE_APPLICATION_CREDENTIALS" environment variable

Object creation:

GAssistantClient greeter(grpc::CreateChannel(
      "google.com", grpc::GoogleDefaultCredentials()));

Contructor:

GAssistantClient(std::shared_ptr<Channel> channel)
      : stub_(Greeter::NewStub(channel)) {}

When I put google.com in there, I get the following error:
E0505 18:30:34.959710444    7635 ssl_transport_security.c:1226] Invalid toplevel subdomain: com
E0505 18:30:34.959836517    7635 ssl_transport_security.c:1226] Invalid toplevel subdomain: com


问:
Installing SQL Server Express 2005 from VS setup project - named instance
I'm installing SQL Server Express 2005 from my Visual Studio 2008 setup project.

This works fine and installs the instance "SQLExpress".

Does anyone know if you can pass it some kind of command line to install or change a property to give it a different instance name?

答:
See this article on how to edit the bootstrapper that installs SQL as part of the setup. There is indeed an INSTANCENAME attribute (and you can also pass DEFAULTDATABASE and all sorts of useful command line parameters).

http://www.windowsdevelop.com/clickonce-setup--deployment-projects/generic-bootstrapper--sql-express-named-instance-18693.shtml


问:
Not able to access protected variables
I have created a simple test project to use a class as a custom List type and have a couple of questions regarding the use of different syntax when declaring variables.

I have a class called CustomerInfo which defines all the variables required to be stored for the customer information which will be added to a list as seen below:

```<code>    protected string Firstname { get; set; }

    protected string Surname { get; set; }

    protected int Age
    {
        get
        {
            return Age;
        }
        set
        {
            if(value < 0)
            {
                throw new AgeException("Age cannot be a value below 0");
            }
            else
            {
                Age = value;
            }
        }
    }

    protected string Gender { get; set; }
</code>```

Questions:

1) Why does the code below not allow me to access the protected variables in the CustomerInfo class even though I am inheriting the class?

```<code>class Program : CustomerInfo
{
    static void Main(string[] args)
    {
        CustomerInfo custInfo = new CustomerInfo();
        custInfo.Firstname = "Richard"; //not working
        custInfo.Surname = "Smith"; //not working

        List<CustomerInfo> custList = new List<CustomerInfo>();
        custList.Add(custInfo);
    }
}
</code>```

2) When looking at Windows Forms applications they already contain an inheritence of Form in the code of any Form you create. If you have to inherit a class to access the protected variables & methods it has, how can you access the variables if each form already has an inheritance that you cannot remove?

Thanks

答:
You are misunderstanding the purpose of inheritance.  Inheritance is designed to represent a relationship between two objects where one is a more specialized version of the other.  This is sometimes called an "is-a" relationship.

Consider the following class definitions:

```<code>class Fruit {}
class Apple : Fruit {}
class Banana: Fruit {}
</code>```

In this case, Apple and Banana both inherit from Fruit to express the "is-a" relationship - a Banana is a Fruit.  In object-oriented design, this allows you to write a method like this:

```<code>class Person
{
    public void Eat(Fruit fruit) {}
    {
        // stuff goes here
    }
}
</code>```

The Eat method allows the Person class to eat anything that is a Fruit, including classes that derive from Fruit.  So you can do the following:

```<code>Person person = new Person();
Apple apple = new Apple();
Banana banana = new Banana();

person.Eat(apple);
person.Eat(banana);
</code>```

Compare this to the class definition you have written:

```<code>class Program : CustomerInfo
</code>```

In the language of OOP, this says "a Program is a CustomerInfo."  I don't think that's what you want.  Using the protected keyword doesn't make sense here because your inheritance relationship doesn't make sense.  If Program is supposed to be able to access CustomerInfo members, they should be declared public or internal.

Title: Not able to access protected variables

Body:
I have created a simple test project to use a class as a custom List type and have a couple of questions regarding the use of different syntax when declaring variables.

I have a class called CustomerInfo which defines all the variables required to be stored for the customer information which will be added to a list as seen below:

    protected string Firstname { get; set; }

    protected string Surname { get; set; }

    protected int Age
    {
        get
        {
            return Age;
        }
        set
        {
            if(value < 0)
            {
                throw new AgeException("Age cannot be a value below 0");
            }
            else
            {
                Age = value;
            }
        }
    }

    protected string Gender { get; set; }

Questions:

1) Why does the code below not allow me to access the protected variables in the CustomerInfo class even though I am inheriting the class?

class Program : CustomerInfo
{
    static void Main(string[] args)
    {
        CustomerInfo custInfo = new CustomerInfo();
        custInfo.Firstname = "Richard"; //not working
        custInfo.Surname = "Smith"; //not working

        List<CustomerInfo> custList = new List<CustomerInfo>();
        custList.Add(custInfo);
    }
}

2) When looking at Windows Forms applications they already contain an inheritence of Form in the code of any Form you create. If you have to inherit a class to access the protected variables & methods it has, how can you access the variables if each form already has an inheritance that you cannot remove?

Thanks

Body:
You are misunderstanding the purpose of inheritance.  Inheritance is designed to represent a relationship between two objects where one is a more specialized version of the other.  This is sometimes called an "is-a" relationship.

Consider the following class definitions:

class Fruit {}
class Apple : Fruit {}
class Banana: Fruit {}

In this case, Apple and Banana both inherit from Fruit to express the "is-a" relationship - a Banana is a Fruit.  In object-oriented design, this allows you to write a method like this:

class Person
{
    public void Eat(Fruit fruit) {}
    {
        // stuff goes here
    }
}

The Eat method allows the Person class to eat anything that is a Fruit, including classes that derive from Fruit.  So you can do the following:

Person person = new Person();
Apple apple = new Apple();
Banana banana = new Banana();

person.Eat(apple);
person.Eat(banana);

Compare this to the class definition you have written:

class Program : CustomerInfo

In the language of OOP, this says "a Program is a CustomerInfo."  I don't think that's what you want.  Using the protected keyword doesn't make sense here because your inheritance relationship doesn't make sense.  If Program is supposed to be able to access CustomerInfo members, they should be declared public or internal.


问:
JAVA linux KeyListener seems not working
i'm working on JAVA snake game and it seems my KeyListener not working for some reason. I tried to look for answers but i couldnt find anything helpful. I'm beginner in JAVA so i dont know if i'm using the keylistener properly. I got no output at all.</p>

```<code>public class GameBoard extends JPanel implements Runnable, KeyListener{
    /**
     *
     */
    private boolean up, down, right, left;

    private Thread thread;
    private boolean running;
    private long targetTime;

    public GameBoard() {
        setPreferredSize(new Dimension(WIDTH,HEIGHT));
        setFocusable(true);
        requestFocus();
        addKeyListener(this);
    }

    @Override
    public void keyPressed(KeyEvent e) {
        int k = e.getKeyCode();
        System.out.println("pressed");
        if( k == KeyEvent.VK_W || k == KeyEvent.VK_UP) up = true;
        if( k == KeyEvent.VK_S || k == KeyEvent.VK_DOWN) down = true;
        if( k == KeyEvent.VK_A || k == KeyEvent.VK_LEFT) left = true;
        if( k == KeyEvent.VK_D || k == KeyEvent.VK_RIGHT) right = true;
    }

    @Override
    public void keyReleased(KeyEvent e) {
        int k = e.getKeyCode();
        System.out.println("Released");
        if( k == KeyEvent.VK_W || k == KeyEvent.VK_UP) up = false;
        if( k == KeyEvent.VK_S || k == KeyEvent.VK_DOWN) down = false;
        if( k == KeyEvent.VK_A || k == KeyEvent.VK_LEFT) left = false;
        if( k == KeyEvent.VK_D || k == KeyEvent.VK_RIGHT) right = false;
    }

    @Override
    public void keyTyped(KeyEvent e) {
        int k = e.getKeyCode();
        System.out.println("typed");
    }

    @Override
    public void run() {
        if(running) return;
        init();
        while(running) {
            startTime = System.nanoTime();

            update();
            requestRender();

            elapsed = System.nanoTime()-startTime;
            wait = targetTime - elapsed / 10000000;
            if (wait > 0) {
                try {
                    Thread.sleep(wait);
                }catch(Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

    private void init() {
        addKeyListener(this);
    }

    private void update() {

            if(up && dy == 0) {
                dy = -SIZE;
                dx = 0;
            }
            if(down && dy == 0) {
                dy = SIZE;
                dx = 0;
            }
            if(left && dx == 0) {
                dx = -SIZE;
                dy = 0;
            }
            if(right && dy == 0) {
                dx = SIZE;
                dy = 0;
            }

            if(dy!=0 || dx!= 0) {
                for( int i = snake.size() -1 ;i > 0; i-- ) {
                    snake.get(i).setPosition(snake.get(i-1).getX(),snake.get(i-1).getY());
                }
            }
            head.move(dx,dy);

            if(head.getX() < 0 ) head.setX(WIDTH);
            if(head.getY() < 0 ) head.setY(HEIGHT);
            if(head.getX() > WIDTH) head.setX(0);
            if(head.getY() > HEIGHT) head.setY(0);
    }

    }

}
</code>```

答: Without showing a main() method, everything we say is just a guess. But one problem is that your run() method is an infinite loop that blocks the event thread.</p>

Body:
i'm working on JAVA snake game and it seems my KeyListener not working for some reason. I tried to look for answers but i couldnt find anything helpful. I'm beginner in JAVA so i dont know if i'm using the keylistener properly. I got no output at all.

public class GameBoard extends JPanel implements Runnable, KeyListener{
    /**
     *
     */
    private boolean up, down, right, left;

    private Thread thread;
    private boolean running;
    private long targetTime;

    public GameBoard() {
        setPreferredSize(new Dimension(WIDTH,HEIGHT));
        setFocusable(true);
        requestFocus();
        addKeyListener(this);
    }

    @Override
    public void keyPressed(KeyEvent e) {
        int k = e.getKeyCode();
        System.out.println("pressed");
        if( k == KeyEvent.VK_W || k == KeyEvent.VK_UP) up = true;
        if( k == KeyEvent.VK_S || k == KeyEvent.VK_DOWN) down = true;
        if( k == KeyEvent.VK_A || k == KeyEvent.VK_LEFT) left = true;
        if( k == KeyEvent.VK_D || k == KeyEvent.VK_RIGHT) right = true;
    }

    @Override
    public void keyReleased(KeyEvent e) {
        int k = e.getKeyCode();
        System.out.println("Released");
        if( k == KeyEvent.VK_W || k == KeyEvent.VK_UP) up = false;
        if( k == KeyEvent.VK_S || k == KeyEvent.VK_DOWN) down = false;
        if( k == KeyEvent.VK_A || k == KeyEvent.VK_LEFT) left = false;
        if( k == KeyEvent.VK_D || k == KeyEvent.VK_RIGHT) right = false;
    }

    @Override
    public void keyTyped(KeyEvent e) {
        int k = e.getKeyCode();
        System.out.println("typed");
    }

    @Override
    public void run() {
        if(running) return;
        init();
        while(running) {
            startTime = System.nanoTime();

            update();
            requestRender();

            elapsed = System.nanoTime()-startTime;
            wait = targetTime - elapsed / 10000000;
            if (wait > 0) {
                try {
                    Thread.sleep(wait);
                }catch(Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

    private void init() {
        addKeyListener(this);
    }

    private void update() {

            if(up && dy == 0) {
                dy = -SIZE;
                dx = 0;
            }
            if(down && dy == 0) {
                dy = SIZE;
                dx = 0;
            }
            if(left && dx == 0) {
                dx = -SIZE;
                dy = 0;
            }
            if(right && dy == 0) {
                dx = SIZE;
                dy = 0;
            }

            if(dy!=0 || dx!= 0) {
                for( int i = snake.size() -1 ;i > 0; i-- ) {
                    snake.get(i).setPosition(snake.get(i-1).getX(),snake.get(i-1).getY());
                }
            }
            head.move(dx,dy);

            if(head.getX() < 0 ) head.setX(WIDTH);
            if(head.getY() < 0 ) head.setY(HEIGHT);
            if(head.getX() > WIDTH) head.setX(0);
            if(head.getY() > HEIGHT) head.setY(0);
    }

    }

}


问:
Enable Bootstrap Intellisense using Angular 4 in WebStorm
I'm learning Angular 4 and I'm using Bootstrap CSS.

I've installed Bootstrap libraries using npm and I've imported Bootstrap in my Angular project using the style.css file under the src folder.

Everything works well but WebStorm doesn't suggest me any Bootstrap classes while I'm coding and I can't understand why. Do I have to set something up?

If I link Bootstrap inside my index.html file everything works fine.

答:
Hi I know this is a little late but i recently had the same issue and had to look to one of my older projects. This is due to webstorm looking at your package.json for devDependencis the way to solve this without moving any files around is either when you install bootstrap to do npm install bootstrap@4.0.0-alpha --save-dev which will automatically add it to package.json for you or manually edit it to look something like this "devDependencies": {
    "@angular/cli": "1.0.1",
    "@angular/compiler-cli": "^4.0.0",
    "@types/jasmine": "2.5.38",
    "@types/node": "~6.0.60",
    "bootstrap": "^4.0.0-alpha.6"

I have confirmed that this has solved my issue


问:
Java Data Structure
I'm looking for a data structure that will act like a Queue so that I can hava First In First Out behaviour, but ideally I would also be able to see if an element exists in that Queue in constant time as you can do with a HashMap, rather than the linear time that you get with a LinkedList.

I thought a LinkedHashMap might do the job, but although I could make an iterator and just take and then remove the first element of the iteration to produce a sort of poll() method, I'm wondering if there is a better way.

Many thanks in advance

答:
Often when you want the behaviour of two collections you need to maintain two collections.  A simple approach is to have a Queue and a HashSet, and always perform an add to both and remove from the HashMap when you remove from the Queue.

An alternative is to use a LinkedHashSet. This retains the order elements were added and you can remove the first/oldest element each time.

A third option is to use just a Queue. While you might like O(1) lookup time, you may find it is fast enough to meet your requirements by just searching every element. This might be much faster than you expect. i.e. 1000 elements should be less than 10 micro-seconds.

EDIT: I agree that two collections is best when you don't know the length.

However to show you a brute force search can be fast too. The slowest object to look for is one which is not there. (As it has to compare every element)

```<code>Queue<Point> points = new ArrayBlockingQueue<Point>(1024);
for(int i=0;i<1000;i++)
  points.add(new Point(i,i));
Point missing = new Point(-1, -1);
int runs = 100 * 1000;
long start = System.nanoTime();
for(int i=0;i< runs;i++)
    points.contains(missing);
long time = System.nanoTime() - start;
System.out.printf("Average contains() took %.1f us%n", time/runs/1000.0);
</code>```

Prints

```<code>Average contains() took 5.1 us
</code>```

You may need to test this for your data type as times of equals() and sizes of queue can vary, but you may be surprise what you can do in 10 micro-seconds and that may be fast enough.

Title: Java Data Structure

Body:
Often when you want the behaviour of two collections you need to maintain two collections.  A simple approach is to have a Queue and a HashSet, and always perform an add to both and remove from the HashMap when you remove from the Queue.

An alternative is to use a LinkedHashSet. This retains the order elements were added and you can remove the first/oldest element each time.

A third option is to use just a Queue. While you might like O(1) lookup time, you may find it is fast enough to meet your requirements by just searching every element. This might be much faster than you expect. i.e. 1000 elements should be less than 10 micro-seconds.

EDIT: I agree that two collections is best when you don't know the length.

However to show you a brute force search can be fast too. The slowest object to look for is one which is not there. (As it has to compare every element)

Queue<Point> points = new ArrayBlockingQueue<Point>(1024);
for(int i=0;i<1000;i++)
  points.add(new Point(i,i));
Point missing = new Point(-1, -1);
int runs = 100 * 1000;
long start = System.nanoTime();
for(int i=0;i< runs;i++)
    points.contains(missing);
long time = System.nanoTime() - start;
System.out.printf("Average contains() took %.1f us%n", time/runs/1000.0);

Prints

Average contains() took 5.1 us

You may need to test this for your data type as times of equals() and sizes of queue can vary, but you may be surprise what you can do in 10 micro-seconds and that may be fast enough.


问:
Embedding Matplotlib in PyQt5: Toolbar doesn't work
I'm developing an application for image-manipulation using matplotlib and pyqt5. Here's some code:

```<code>class MainForm(QtWidgets.QMainWindow):

    def __init__(self):
        super(MainForm, self).__init__()
        uic.loadUi("...", self)

        self.setup_ui_elements()

        self.figure = Figure(figsize=(5, 4), dpi=100)

        self.canvas = FigureCanvas(self.figure)
        self.toolbar = NaviToolbar(self.canvas, self)

        self.MiddleRightLayout.addWidget(self.toolbar)
        self.MiddleRightLayout.addWidget(self.canvas)

    def plot(self, img):
        self.figure.figimage(img)
        self.canvas.draw()
</code>```

Now if I load an image and plot it to the canvas, two problems arise:

The toolbar will be shown, but it has no effect (e.g. zoom, pan, etc.)

I haven't found a way to fit the image to the canvas, the image is usually much bigger as the canvas-area.

Any ideas?

greets, dennis

答:
A figimage is directly placed onto the canvas without axes. This means it does not automatically scale to the canvas or anything else and it also means that the zoom and pan tools do not have any effect.

You may use the resize argument to figimage, self.figure.figimage(img, resize=True) to let the canvas fit to the image, if that is what you want. Otherwise, you'd probably want to use an imshow plot.

In order to get the image scaled to its original size, you need to work a bit on the spacings.

```<code>import matplotlib.pyplot as plt
import numpy as np

def plot(self, img):
    self.ax = self.figure.add_subplot(111)
    self.figure.subplots_adjust(.1,.1,.9,.9) # 10% margin around image
    h, w = np.array(img.shape[:2])/self.figure.dpi
    self.figure.set_size_inches(w/0.8,h/0.8)
    self.ax.imshow(img)
    self.ax.axis("off") # in case you want to turn the axes off
    self.canvas.draw()
</code>```

Body:
I'm developing an application for image-manipulation using matplotlib and pyqt5. Here's some code:

class MainForm(QtWidgets.QMainWindow):

    def __init__(self):
        super(MainForm, self).__init__()
        uic.loadUi("...", self)

        self.setup_ui_elements()

        self.figure = Figure(figsize=(5, 4), dpi=100)

        self.canvas = FigureCanvas(self.figure)
        self.toolbar = NaviToolbar(self.canvas, self)

        self.MiddleRightLayout.addWidget(self.toolbar)
        self.MiddleRightLayout.addWidget(self.canvas)

    def plot(self, img):
        self.figure.figimage(img)
        self.canvas.draw()

Now if I load an image and plot it to the canvas, two problems arise:

The toolbar will be shown, but it has no effect (e.g. zoom, pan, etc.)

I haven't found a way to fit the image to the canvas, the image is usually much bigger as the canvas-area.

Any ideas?

greets, dennis

Body:
A figimage is directly placed onto the canvas without axes. This means it does not automatically scale to the canvas or anything else and it also means that the zoom and pan tools do not have any effect.

You may use the resize argument to figimage, self.figure.figimage(img, resize=True) to let the canvas fit to the image, if that is what you want. Otherwise, you'd probably want to use an imshow plot.

In order to get the image scaled to its original size, you need to work a bit on the spacings.

import matplotlib.pyplot as plt
import numpy as np

def plot(self, img):
    self.ax = self.figure.add_subplot(111)
    self.figure.subplots_adjust(.1,.1,.9,.9) # 10% margin around image
    h, w = np.array(img.shape[:2])/self.figure.dpi
    self.figure.set_size_inches(w/0.8,h/0.8)
    self.ax.imshow(img)
    self.ax.axis("off") # in case you want to turn the axes off
    self.canvas.draw()


问:
Retrofit continue work in browser (response as html page)
I'm working with a bank api. When user chooses to add his bank card to his account I need to make request to their API and then continue in browser for user to enter his card credentials in https safety

API looks like this:

```<code>@FormUrlEncoded
@POST("/jsp/hbpay/logon.jsp")
Observable<Response<String>> addCard(@Field("Signed_Order_B64") String order,
                                   @Field("email") String email,
                                   @Field("Language") String lang,
                                   @Field("BackLink") String backLink,
                                   @Field("PostLink ") String postLink,
                                   @Field("FailureBackLink") String failureBackLink);
</code>```

BackLink and others are supposed to be web links to send user in different situations. I don't know what to put there for android.

Next, I have my request:

```<code>private void addCardRequest() {
    showProgress();
    mDisposable.add(createAddCardOrder()
            .flatMap(orderString -> mBankApi.addCard(orderString,
                    mDataManager.getLocalUserInfo().getEmail(),
                    BankApi.EPAY_LANG,
                    BankApi.EPAY_BACK_LINK,//"http://localhost/"?
                    BankApi.EPAY_POST_LINK,
                    BankApi.EPAY_FAILURE_BACK_LINK))
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(this::handleAddCardResponse,
                    this::handleError,
                    () -> Timber.w("addCard completed")));
}
</code>```

Response is a plain html page with a bunch of pics and scripts. What I'm doing for now is just saving it as a .html file and then displaying in a webview:

```<code>private void handleAddCardResponse(Response<String> response) throws Exception {
    hideProgress();
    if (response.isSuccessful()) {
        String fileUrl = getContext().getCacheDir() + "/add_card.html";
        Utils.writeStringToFile(getContext(), response.body(), fileUrl);
        startActivity(WebViewActivity.getIntent(getContext(), fileUrl));
    } else {
        throw handleUnsuccessfulResponse(response);
    }
}
</code>```

What I need is to open incoming response (which is a html markup) in browser, or to make the browser make my request and handle response

答:
I was supposed to call this in WebViewActivity:

```<code>webView.setWebViewClient(new MyWebViewClient());
webView.postUrl(POST_URL, postData.getBytes());
</code>```

postData builds like this:

```<code>private String buildPostData(String order64) {
    try {
        return URLEncoder.encode("Signed_Order_B64", "UTF-8") + "=" + URLEncoder.encode(order64, "UTF-8")
                + "&"
                + URLEncoder.encode("Language", "UTF-8") + "=" + URLEncoder.encode(BankApi.EPAY_LANG, "UTF-8")
                + "&"
                + URLEncoder.encode("BackLink", "UTF-8") + "=" + URLEncoder.encode(BankApi.EPAY_BACK_LINK, "UTF-8")
                + "&"
                + URLEncoder.encode("FailureBackLink", "UTF-8") + "=" + URLEncoder.encode(BankApi.EPAY_FAILURE_BACK_LINK, "UTF-8")
                + "&"
                + URLEncoder.encode("PostLink", "UTF-8") + "=" + URLEncoder.encode(BankApi.EPAY_POST_LINK, "UTF-8");
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
        return "";
    }
}
</code>```

MyWebViewClient should look like this, so it would capture url links:

```<code>private class MyWebViewClient extends WebViewClient {
    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
        Timber.w("URL loading = %s", url);

        if (BankApi.EPAY_POST_LINK.equals(url)) {
            setResult(RESULT_OK);
            finish();
            return true;
        } else if (BankApi.EPAY_BACK_LINK.equals(url)) {
            setResult(RESULT_CANCELED);
            finish();
            return true;
        } else if (BankApi.EPAY_FAILURE_BACK_LINK.equals(url)) {
            setResult(RESULT_FAILURE);
            finish();
            return true;
        } else {
            return false;
        }
    }
</code>```

and then just call startActivityForResult and listen to result

Body:
I'm working with a bank api. When user chooses to add his bank card to his account I need to make request to their API and then continue in browser for user to enter his card credentials in https safety

API looks like this:

@FormUrlEncoded
@POST("/jsp/hbpay/logon.jsp")
Observable<Response<String>> addCard(@Field("Signed_Order_B64") String order,
                                   @Field("email") String email,
                                   @Field("Language") String lang,
                                   @Field("BackLink") String backLink,
                                   @Field("PostLink ") String postLink,
                                   @Field("FailureBackLink") String failureBackLink);

BackLink and others are supposed to be web links to send user in different situations. I don't know what to put there for android.

Next, I have my request:

private void addCardRequest() {
    showProgress();
    mDisposable.add(createAddCardOrder()
            .flatMap(orderString -> mBankApi.addCard(orderString,
                    mDataManager.getLocalUserInfo().getEmail(),
                    BankApi.EPAY_LANG,
                    BankApi.EPAY_BACK_LINK,//"http://localhost/"?
                    BankApi.EPAY_POST_LINK,
                    BankApi.EPAY_FAILURE_BACK_LINK))
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(this::handleAddCardResponse,
                    this::handleError,
                    () -> Timber.w("addCard completed")));
}

Response is a plain html page with a bunch of pics and scripts. What I'm doing for now is just saving it as a .html file and then displaying in a webview:

private void handleAddCardResponse(Response<String> response) throws Exception {
    hideProgress();
    if (response.isSuccessful()) {
        String fileUrl = getContext().getCacheDir() + "/add_card.html";
        Utils.writeStringToFile(getContext(), response.body(), fileUrl);
        startActivity(WebViewActivity.getIntent(getContext(), fileUrl));
    } else {
        throw handleUnsuccessfulResponse(response);
    }
}

What I need is to open incoming response (which is a html markup) in browser, or to make the browser make my request and handle response

Body:
I was supposed to call this in WebViewActivity:

webView.setWebViewClient(new MyWebViewClient());
webView.postUrl(POST_URL, postData.getBytes());

postData builds like this:

private String buildPostData(String order64) {
    try {
        return URLEncoder.encode("Signed_Order_B64", "UTF-8") + "=" + URLEncoder.encode(order64, "UTF-8")
                + "&"
                + URLEncoder.encode("Language", "UTF-8") + "=" + URLEncoder.encode(BankApi.EPAY_LANG, "UTF-8")
                + "&"
                + URLEncoder.encode("BackLink", "UTF-8") + "=" + URLEncoder.encode(BankApi.EPAY_BACK_LINK, "UTF-8")
                + "&"
                + URLEncoder.encode("FailureBackLink", "UTF-8") + "=" + URLEncoder.encode(BankApi.EPAY_FAILURE_BACK_LINK, "UTF-8")
                + "&"
                + URLEncoder.encode("PostLink", "UTF-8") + "=" + URLEncoder.encode(BankApi.EPAY_POST_LINK, "UTF-8");
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
        return "";
    }
}

MyWebViewClient should look like this, so it would capture url links:

private class MyWebViewClient extends WebViewClient {
    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
        Timber.w("URL loading = %s", url);

        if (BankApi.EPAY_POST_LINK.equals(url)) {
            setResult(RESULT_OK);
            finish();
            return true;
        } else if (BankApi.EPAY_BACK_LINK.equals(url)) {
            setResult(RESULT_CANCELED);
            finish();
            return true;
        } else if (BankApi.EPAY_FAILURE_BACK_LINK.equals(url)) {
            setResult(RESULT_FAILURE);
            finish();
            return true;
        } else {
            return false;
        }
    }

and then just call startActivityForResult and listen to result


问:
Can't connect java client to elasticsearch server
I'm trying to connect my java client to an elasticsearch server.

Elasticsearch 2.4.0 is installed on a distant server.
To access to it, I have to use port 10700. (When I run "telnet xxxx 10700", it worked, so the port is open)

I have an error for 2 days now and I read it could be a conflict between netty4 dependencies, but I'm not able to fix it. (My netty dependencies are transitives, I don't import them by myself)

How can I resolve this problem?

The java code:

```<code>public void connexionToEs() throws UnknownHostException {
    String clusterName = "xxxx";
    String serverAddress = "xxxx";

    try{
        Settings settings = Settings.builder()
                .put("cluster.name", clusterName)
                .put("client.transport.sniff", true)
                .build();
        TransportClient client = new PreBuiltTransportClient(settings);
        client.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName(serverAddress), 10700));

        SearchResponse response = client.prepareSearch().execute().actionGet();
        String output = response.toString();
        System.out.println(output);
        client.close();
    }catch(Exception e){
        e.printStackTrace();
    }
}
</code>```

The dependencies:

```<code><!-- DEPENDENCIES FOR ELASTICSEARCH CLIENT -->
<dependency>
  <groupId>org.elasticsearch</groupId>
  <artifactId>elasticsearch</artifactId>
  <version>5.2.0</version>
</dependency>

<dependency>
  <groupId>org.elasticsearch.client</groupId>
  <artifactId>transport</artifactId>
  <version>5.2.0</version>
</dependency>

<dependency>
  <groupId>org.apache.logging.log4j</groupId>
  <artifactId>log4j-api</artifactId>
  <version>2.6.2</version>
</dependency>
<dependency>
  <groupId>org.apache.logging.log4j</groupId>
  <artifactId>log4j-core</artifactId>
  <version>2.6.2</version>
</dependency>
<dependency>
  <groupId>org.apache.logging.log4j</groupId>
  <artifactId>log4j-web</artifactId>
  <version>2.6.2</version>
</dependency>
<dependency>
  <groupId>org.apache.logging.log4j</groupId>
  <artifactId>log4j-to-slf4j</artifactId>
  <version>2.6.2</version>
</dependency>
</code>```

The error:

```<code>Exception in thread "elasticsearch[_client_][management][T#1]" java.lang.NoSuchMethodError: io.netty.buffer.CompositeByteBuf.addComponents(ZLjava/lang/Iterable;)Lio/netty/buffer/CompositeByteBuf;
at org.elasticsearch.transport.netty4.Netty4Utils.toByteBuf(Netty4Utils.java:78)
at org.elasticsearch.transport.netty4.Netty4Transport.sendMessage(Netty4Transport.java:422)
at org.elasticsearch.transport.netty4.Netty4Transport.sendMessage(Netty4Transport.java:93)
at org.elasticsearch.transport.TcpTransport.internalSendMessage(TcpTransport.java:1058)
at org.elasticsearch.transport.TcpTransport.sendRequestToChannel(TcpTransport.java:1040)
at org.elasticsearch.transport.TcpTransport.executeHandshake(TcpTransport.java:1555)
at org.elasticsearch.transport.TcpTransport.openConnection(TcpTransport.java:502)
at org.elasticsearch.transport.TcpTransport.connectToNode(TcpTransport.java:460)
at org.elasticsearch.transport.TransportService.connectToNode(TransportService.java:318)
at org.elasticsearch.client.transport.TransportClientNodesService$SniffNodesSampler$1.run(TransportClientNodesService.java:488)
at org.elasticsearch.common.util.concurrent.ThreadContext$ContextPreservingRunnable.run(ThreadContext.java:527)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)
</code>```

The netty4 dependencies:

```<code>io.netty:netty:3.10.6.Final
io.netty:netty-buffer:4.0.28.Final
io.netty:netty-codec:4.0.28.Final
io.netty:netty-codec-http:4.1.7.Final
io.netty:netty-common:4.0.28.Final
io.netty:netty-handler:4.0.28.Final
io.netty:netty-resolver:4.1.7.Final
io.netty:netty-transport:4.0.28.Final
</code>```

答:
Exclude these netty-all dependency. This will fix your issue.</p>

```<code>compile.exclude group: "io.netty", module:"netty-all"
compile.exclude group: "org.jboss.netty", module:"netty"
</code>```

Body:
I'm trying to connect my java client to an elasticsearch server.

Elasticsearch 2.4.0 is installed on a distant server.
To access to it, I have to use port 10700. (When I run "telnet xxxx 10700", it worked, so the port is open)

I have an error for 2 days now and I read it could be a conflict between netty4 dependencies, but I'm not able to fix it. (My netty dependencies are transitives, I don't import them by myself)

How can I resolve this problem?

The java code:

public void connexionToEs() throws UnknownHostException {
    String clusterName = "xxxx";
    String serverAddress = "xxxx";

    try{
        Settings settings = Settings.builder()
                .put("cluster.name", clusterName)
                .put("client.transport.sniff", true)
                .build();
        TransportClient client = new PreBuiltTransportClient(settings);
        client.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName(serverAddress), 10700));

        SearchResponse response = client.prepareSearch().execute().actionGet();
        String output = response.toString();
        System.out.println(output);
        client.close();
    }catch(Exception e){
        e.printStackTrace();
    }
}

The dependencies:

<dependency>
  <groupId>org.elasticsearch</groupId>
  <artifactId>elasticsearch</artifactId>
  <version>5.2.0</version>
</dependency>

<dependency>
  <groupId>org.elasticsearch.client</groupId>
  <artifactId>transport</artifactId>
  <version>5.2.0</version>
</dependency>

<dependency>
  <groupId>org.apache.logging.log4j</groupId>
  <artifactId>log4j-api</artifactId>
  <version>2.6.2</version>
</dependency>
<dependency>
  <groupId>org.apache.logging.log4j</groupId>
  <artifactId>log4j-core</artifactId>
  <version>2.6.2</version>
</dependency>
<dependency>
  <groupId>org.apache.logging.log4j</groupId>
  <artifactId>log4j-web</artifactId>
  <version>2.6.2</version>
</dependency>
<dependency>
  <groupId>org.apache.logging.log4j</groupId>
  <artifactId>log4j-to-slf4j</artifactId>
  <version>2.6.2</version>
</dependency>

The error:

Exception in thread "elasticsearch[_client_][management][T#1]" java.lang.NoSuchMethodError: io.netty.buffer.CompositeByteBuf.addComponents(ZLjava/lang/Iterable;)Lio/netty/buffer/CompositeByteBuf;
at org.elasticsearch.transport.netty4.Netty4Utils.toByteBuf(Netty4Utils.java:78)
at org.elasticsearch.transport.netty4.Netty4Transport.sendMessage(Netty4Transport.java:422)
at org.elasticsearch.transport.netty4.Netty4Transport.sendMessage(Netty4Transport.java:93)
at org.elasticsearch.transport.TcpTransport.internalSendMessage(TcpTransport.java:1058)
at org.elasticsearch.transport.TcpTransport.sendRequestToChannel(TcpTransport.java:1040)
at org.elasticsearch.transport.TcpTransport.executeHandshake(TcpTransport.java:1555)
at org.elasticsearch.transport.TcpTransport.openConnection(TcpTransport.java:502)
at org.elasticsearch.transport.TcpTransport.connectToNode(TcpTransport.java:460)
at org.elasticsearch.transport.TransportService.connectToNode(TransportService.java:318)
at org.elasticsearch.client.transport.TransportClientNodesService$SniffNodesSampler$1.run(TransportClientNodesService.java:488)
at org.elasticsearch.common.util.concurrent.ThreadContext$ContextPreservingRunnable.run(ThreadContext.java:527)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)

The netty4 dependencies:

io.netty:netty:3.10.6.Final
io.netty:netty-buffer:4.0.28.Final
io.netty:netty-codec:4.0.28.Final
io.netty:netty-codec-http:4.1.7.Final
io.netty:netty-common:4.0.28.Final
io.netty:netty-handler:4.0.28.Final
io.netty:netty-resolver:4.1.7.Final
io.netty:netty-transport:4.0.28.Final

Body:
Exclude these netty-all dependency. This will fix your issue.

compile.exclude group: "io.netty", module:"netty-all"
compile.exclude group: "org.jboss.netty", module:"netty"


问:
Instant Verification prevents onCodeSent() to ever be called & debugged - Firebase SMS Authentication for Android
In Firebase SMS Authentication for Android, I'm trying to debug the stage in which the user has to type in the Verification Code he received via SMS.

However, due to the Instant Verification, I cannot recreate this scenario on my phone anymore because the onCodeSent() event is never called again. The onVerificationCompleted() is called instead - which is GOOD for production, but it leaves me no option to debug my SMS Code Verification screen.

Unfortunately, at the moment there is no way to disable Instant Verification (waiting for @samtstern's response)...

How can I recreate that scenario again? at least for debugging?

This answer didn't help because we can't get the ForceResendingToken without triggering the onCodeSent(..), and as I said, I can't get it triggered...

答:
Closing this question since @samtstern has responded to me on Github, providing an alternate workaround due to the (current) lack of feature to disable Instant Verification:

That's a good point. I'll make sure to add that to the feature request
  internally. One workaround is to use two devices. On one device (with
  no SIM) enter the phone number of the other device (with a SIM). Then
  you'll get the code flow.


问:
Silent printing of a PDF in Python
I'm trying to print a PDF with Python, without opening the PDF viewer application (Adobe, Foxit etc.). I need also to know when printing has finished (to delete the file).

Here I found this implementation:

```<code>import win32ui, dde, os.path, time
from win32api import FindExecutable
from os import spawnl, P_NOWAIT
...
pd = "C:\\temp\\test.pdf"
pdbits = os.path.split(pd)
readerexe = FindExecutable(pdbits[1],pdbits[0])

spawnl(P_NOWAIT,readerexe[1],"DUMMY") #I added "DUMMY" to avoid a weird error

time.sleep(2)

s = dde.CreateServer()
s.Create('')
c = dde.CreateConversation(s)
c.ConnectTo('acroview', 'control')

c.Exec('[FilePrintSilent("%s")]' % (pd,))

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

But it throws this exception at the ConnectTo line:

```<code>dde.error: ConnectTo failed
</code>```

Someone knows how to solve it? Or has a different solution for silent printing? Or at list can give a link to a reference for ConnectTo? Could find nothing on the web about it.

Working with: Python 2.7, Windows 7, Acrobat Reader 10.0

答:
I suggest you install GSView and GSPrint and shell out to gsprint.exe to print the pdf.

```<code>p = subprocess.Popen([r"p:\ath\to\gsprint.exe", "test.pdf"],
                     stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stdout, stderr = p.communicate()
print stdout
print stderr
</code>```

I have used this in a industrial label printing solution, works great.

When the gsprint.exe program exits (i.e. after the call to communicate), you can delete the pdf file.

Title: Silent printing of a PDF in Python

Body:
I'm trying to print a PDF with Python, without opening the PDF viewer application (Adobe, Foxit etc.). I need also to know when printing has finished (to delete the file).

Here I found this implementation:

import win32ui, dde, os.path, time
from win32api import FindExecutable
from os import spawnl, P_NOWAIT
...
pd = "C:\\temp\\test.pdf"
pdbits = os.path.split(pd)
readerexe = FindExecutable(pdbits[1],pdbits[0])

spawnl(P_NOWAIT,readerexe[1],"DUMMY") #I added "DUMMY" to avoid a weird error

time.sleep(2)

s = dde.CreateServer()
s.Create('')
c = dde.CreateConversation(s)
c.ConnectTo('acroview', 'control')

c.Exec('[FilePrintSilent("%s")]' % (pd,))

s.Destroy()

But it throws this exception at the ConnectTo line:

dde.error: ConnectTo failed

Someone knows how to solve it? Or has a different solution for silent printing? Or at list can give a link to a reference for ConnectTo? Could find nothing on the web about it.

Working with: Python 2.7, Windows 7, Acrobat Reader 10.0

Body:
I suggest you install GSView and GSPrint and shell out to gsprint.exe to print the pdf.

p = subprocess.Popen([r"p:\ath\to\gsprint.exe", "test.pdf"],
                     stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stdout, stderr = p.communicate()
print stdout
print stderr

I have used this in a industrial label printing solution, works great.

When the gsprint.exe program exits (i.e. after the call to communicate), you can delete the pdf file.


问:
SELECT multiple tables and WHERE statements
here is my setup.

events: date, time, user_id, business_id

businesses: id, timezone, name, etc...

users: id, email, name, etc...

I want my select statement WHERE to look something like this:

events.date = $myDate, use events.business_id to get timezone from businesses.id and timezone = $myTimezone, and get all info from users where events.user_id = users.id

SELECT * FROM events, businesses, users WHERE ...

Is it possible to do this in one select query? If so, how? Thanks

答:
```<code>SELECT *
FROM events E
     INNER JOIN businesses B ON E.business_id = B.id
     INNER JOIN USERS U ON E.user_id= U.id
WHERE
     E.date = $myDate
</code>```


问:
Print and sum each element in a array in Python
Let's say I have the array list=[1, 2, 3, 4]

How do I get the following output?

```<code>1+2+3+4 = 10
</code>```

I know I could use sum(list), but I need each item on the array printed with "+"

答:
This is the most pythonic solution I can think of; Use string formatting instead of the + operator when using strings - it's more efficient and a good habit to get into, use map to remap the integers to strings and str.join to efficiently create the question string.

```<code>numbers = [1, 2, 3, 4]
print('{} = {}'.format('+'.join(map(str, numbers)), sum(numbers)))
</code>```

Body:
Let's say I have the array list=[1, 2, 3, 4]

How do I get the following output?

1+2+3+4 = 10

I know I could use sum(list), but I need each item on the array printed with "+"

Body:
This is the most pythonic solution I can think of; Use string formatting instead of the + operator when using strings - it's more efficient and a good habit to get into, use map to remap the integers to strings and str.join to efficiently create the question string.

numbers = [1, 2, 3, 4]
print('{} = {}'.format('+'.join(map(str, numbers)), sum(numbers)))


问:
How to manage pages with WordPress?
I am making a wordpress theme that will make reviews about Movies and TV Shows, My question is that if i want to make a page for the movies, page for the tv show, one for the season, one for the episode.
How can I make that? How shoudl i include the seasons in the tv show page.
How the_post() Will know whether this items is movie, or season or or ..
Can you please tell me because i kind of sick of thinking about this.
I am looking for an answer that will put my mind at ease.
This question will have downvotes i know but i have no problem because I am learning and asking, and there is nothing wrong with that</p>

答:
What you could do is create a custom post types.

This article has a good explanation and shows how to create them, either using a plugin or add them manually like so:

```<code>function create_posttype() {

    register_post_type( 'movies',
    // CPT Options
        array(
            'labels' => array(
                'name' => __( 'Movies' ),
                'singular_name' => __( 'Movie' )
            ),
            'public' => true,
            'has_archive' => true,
            'rewrite' => array('slug' => 'movies'),
        )
    );
}
// Hooking up our function to theme setup
add_action( 'init', 'create_posttype' );
</code>```

Title: How to manage pages with WordPress?

Body:
What you could do is create a custom post types.

This article has a good explanation and shows how to create them, either using a plugin or add them manually like so:

function create_posttype() {

    register_post_type( 'movies',
    // CPT Options
        array(
            'labels' => array(
                'name' => __( 'Movies' ),
                'singular_name' => __( 'Movie' )
            ),
            'public' => true,
            'has_archive' => true,
            'rewrite' => array('slug' => 'movies'),
        )
    );
}
// Hooking up our function to theme setup
add_action( 'init', 'create_posttype' );


问:
Tail multiple directories
How do I print only the last (n) file(s) inside nested directories matching a certain pattern?

Doing

```<code>ls -l dir*/history/ | tail
</code>```

gives only the content of the last directory.

I suspect it has to do with xargs but can't really figure out how.

答:
To answer your question directly, use the loop:

```<code>for d in dir*/history/; do
    ls -l "$d" | tail
done
</code>```

But, for more advanced directory "filtering" (and processing) than this, find might come in handy.

Title: Tail multiple directories

Body:
How do I print only the last (n) file(s) inside nested directories matching a certain pattern?

Doing

ls -l dir*/history/ | tail

gives only the content of the last directory.

I suspect it has to do with xargs but can't really figure out how.

Body:
To answer your question directly, use the loop:

for d in dir*/history/; do
    ls -l "$d" | tail
done

But, for more advanced directory "filtering" (and processing) than this, find might come in handy.


问:
create dynamically responsive htmltable from JSON

I'm trying to create table dynamically from Json Object. But table couldn't be able to create in proper format.

```<code>[
  {
    "name" : "water",
    "solutions" : [
      {
        "cost" : "200-300 INR",
        "difficulty" : [1,0,0,0,0],
        "image" : "Cover.png",
        "message" : "Save 40% of water being released from your taps",
        "title" : "Optimise!",
        "description" : " flow.",
        "data" : [
          {
            "step" : 1,
            "content" : [
              {
                "message" : "Collect the following materials.",
                "image" : "0.JPG"
              },
              {
                "alert" : "Measure your tap diameter ",
                "image" : "1.JPG"
              }
            ]
          },
          {
            "step" : 2,
            "content" : [
              {
                "message" : " hand",
                "image" : "2.JPG"
              },
              {
                "image" : "3.JPG"
              }
            ]
          },
          {
            "step" : 3,
            "content" : [
              {
                "message" : " deposits",
                "image" : "/4.JPG"
              }
            ]
          },
          {
            "step" : 4,
            "content" : [
              {
                "message" : "tap!",
                "image" : "5.JPG"
              },
              {
                "image" : "6.JPG"
              },
              {
                "image" : "7.JPG"
              },
              {
                "image" : "8.JPG"
              },
              {
                "alert": " tap."
              }
            ]
          }
        ]
      },
</code>```

and so on , in the same format I,m getting Json from server, however I'll have to show only for "Solutions" in JSON.

Script written by me

```<code>function loadDoc() {
        $.getJSON("/solutions" + , function(result, status, jqXHR) {
        var myList = (jqXHR.responseText);
        myList = JSON.parse(myList);
        var columns =[];
        columns = addAllColumnHeaders(myList);
        var table = document.getElementById("excelDataTable");
        var body = table.createTBody();
        for (var i = 0; i < myList.length; i++) {
            var row = body.insertRow();
            for (var colIndex = 0; colIndex < columns.length; colIndex++) {
              var cellValue = myList[i][columns[colIndex]];
              if (cellValue == null) cellValue = "";
              var cell = row.insertCell();
              cell.innerHTML = cellValue;
            }
          }
        });
    }

    function addAllColumnHeaders(myList) {
        $("#excelDataTable").html("");
        var columnSet = [];
        var table = document.getElementById("excelDataTable");
        var header = table.createTHead();
        var row = header.insertRow();
        for(var k in myList[0]) {
            if(k != "level"){
            columnSet.push(k);
            var cell = row.insertCell();
            cell.innerHTML = k;
            }
        }
        return columnSet;
    }
</code>```

The format in which all data must be shown in table form is ...

each solution will have a single row (title, message, description, ... , data). The data column in that row having other descriptive data (steps) can have multiple rows. You can have multiple rows merged in a single row. Onclick of Data Cell all the information must be shown.

How to perform this?

答:
Try something like this:

```<code>function loadDoc() {
    $.getJSON("/solutions" + , function(result, status, jqXHR) {
    var myList = (jqXHR.responseText);
    myList = JSON.parse(myList);
    var columns =[];
    columns = addAllColumnHeaders(myList);
    var table = document.getElementById("excelDataTable");
    var body = table.createTBody();
    for (var i = 0; i < myList.length; i++) {
        var row = body.insertRow();
        for (var colIndex = 0; colIndex < columns.length; colIndex++) {
          var cellValue = myList[i][columns[colIndex]];
          if (cellValue == null) cellValue = "";
          var cell = row.insertCell();
          if (columns[colIndex] == 'name') {
              cell.innerHTML = cellValue;
          }
          else if (columns[colIndex] == 'solutions') {
              var contents = '';
              for (x in cellValue) {
                  contents += '<div><span>' + x + '</span><span>' + cellValue[x] + '</span></div>';
              }
              cell.innerHTML = contents;
          }
        }
      }
    };
}
</code>```

This will work until you get down to the data property and then you will have to do another for loop.

Body:
I'm trying to create table dynamically from Json Object. But table couldn't be able to create in proper format.

[
  {
    "name" : "water",
    "solutions" : [
      {
        "cost" : "200-300 INR",
        "difficulty" : [1,0,0,0,0],
        "image" : "Cover.png",
        "message" : "Save 40% of water being released from your taps",
        "title" : "Optimise!",
        "description" : " flow.",
        "data" : [
          {
            "step" : 1,
            "content" : [
              {
                "message" : "Collect the following materials.",
                "image" : "0.JPG"
              },
              {
                "alert" : "Measure your tap diameter ",
                "image" : "1.JPG"
              }
            ]
          },
          {
            "step" : 2,
            "content" : [
              {
                "message" : " hand",
                "image" : "2.JPG"
              },
              {
                "image" : "3.JPG"
              }
            ]
          },
          {
            "step" : 3,
            "content" : [
              {
                "message" : " deposits",
                "image" : "/4.JPG"
              }
            ]
          },
          {
            "step" : 4,
            "content" : [
              {
                "message" : "tap!",
                "image" : "5.JPG"
              },
              {
                "image" : "6.JPG"
              },
              {
                "image" : "7.JPG"
              },
              {
                "image" : "8.JPG"
              },
              {
                "alert": " tap."
              }
            ]
          }
        ]
      },

and so on , in the same format I,m getting Json from server, however I'll have to show only for "Solutions" in JSON.

Script written by me

function loadDoc() {
        $.getJSON("/solutions" + , function(result, status, jqXHR) {
        var myList = (jqXHR.responseText);
        myList = JSON.parse(myList);
        var columns =[];
        columns = addAllColumnHeaders(myList);
        var table = document.getElementById("excelDataTable");
        var body = table.createTBody();
        for (var i = 0; i < myList.length; i++) {
            var row = body.insertRow();
            for (var colIndex = 0; colIndex < columns.length; colIndex++) {
              var cellValue = myList[i][columns[colIndex]];
              if (cellValue == null) cellValue = "";
              var cell = row.insertCell();
              cell.innerHTML = cellValue;
            }
          }
        });
    }

    function addAllColumnHeaders(myList) {
        $("#excelDataTable").html("");
        var columnSet = [];
        var table = document.getElementById("excelDataTable");
        var header = table.createTHead();
        var row = header.insertRow();
        for(var k in myList[0]) {
            if(k != "level"){
            columnSet.push(k);
            var cell = row.insertCell();
            cell.innerHTML = k;
            }
        }
        return columnSet;
    }

The format in which all data must be shown in table form is ...

each solution will have a single row (title, message, description, ... , data). The data column in that row having other descriptive data (steps) can have multiple rows. You can have multiple rows merged in a single row. Onclick of Data Cell all the information must be shown.

How to perform this?

Body:
Try something like this:

function loadDoc() {
    $.getJSON("/solutions" + , function(result, status, jqXHR) {
    var myList = (jqXHR.responseText);
    myList = JSON.parse(myList);
    var columns =[];
    columns = addAllColumnHeaders(myList);
    var table = document.getElementById("excelDataTable");
    var body = table.createTBody();
    for (var i = 0; i < myList.length; i++) {
        var row = body.insertRow();
        for (var colIndex = 0; colIndex < columns.length; colIndex++) {
          var cellValue = myList[i][columns[colIndex]];
          if (cellValue == null) cellValue = "";
          var cell = row.insertCell();
          if (columns[colIndex] == 'name') {
              cell.innerHTML = cellValue;
          }
          else if (columns[colIndex] == 'solutions') {
              var contents = '';
              for (x in cellValue) {
                  contents += '<div><span>' + x + '</span><span>' + cellValue[x] + '</span></div>';
              }
              cell.innerHTML = contents;
          }
        }
      }
    };
}

This will work until you get down to the data property and then you will have to do another for loop.


问:
FATAL: The Gradle wrapper has not been found in these directories
When I use jenkins to build react-native app, it failed with below error:</p>

```<code>[Gradle] - Launching build.
FATAL: The Gradle wrapper has not been found in these directories: /Users/arespan/.jenkins/workspace/ZSKQ
Build step 'Invoke Gradle script' marked build as failure
Finished: FAILURE
</code>```

答:
You need to checkout your app into the workspace using the git or other source control plugins.

I you want to build the app directly on your filesystem project using Jenkins, you can provide the path of your project relative to the jenkins job workspace as the "Root Build script" and "Wrapper Location" options

Body:
When I use jenkins to build react-native app, it failed with below error:

[Gradle] - Launching build.
FATAL: The Gradle wrapper has not been found in these directories: /Users/arespan/.jenkins/workspace/ZSKQ
Build step 'Invoke Gradle script' marked build as failure
Finished: FAILURE


问:
Saving an Excel sheet in a current directory with VBA
I have created a sheet in vba Excel. I would like to save it the current directory, but not in absolute path, then, when this is executed somewhere else, there won't be problem.

Can somebody help ?

答:
I am not clear exactly what your situation requires but the following may get you started. The key here is using ThisWorkbook.Path to get a relative file path:

```<code>Sub SaveToRelativePath()
    Dim relativePath As String
    relativePath = ThisWorkbook.Path & Application.PathSeparator & ActiveWorkbook.Name
    ActiveWorkbook.SaveAs Filename:=relativePath
End Sub
</code>```

Body:
I am not clear exactly what your situation requires but the following may get you started. The key here is using ThisWorkbook.Path to get a relative file path:

Sub SaveToRelativePath()
    Dim relativePath As String
    relativePath = ThisWorkbook.Path & Application.PathSeparator & ActiveWorkbook.Name
    ActiveWorkbook.SaveAs Filename:=relativePath
End Sub

ContentLicense: CC BY-SA 4.0