问:
Git error remote: Empty password
I'm trying to clone my git repo from bitbucket, and when I enter this command:

```<code>git clone https://naor_shoyhat@bitbucket.org/naor_shoyhat/hello-world.git
</code>```

The bash then prompts me a window with areas to enter username and password.

I enter them and then I receive this error:

```<code>remote: Empty password
fatal: Authentication failed for 'https://naor_shoyhat@bitbucket.org/naor_shoyhat/hello-world.git/'
</code>```

答:
You can try:

```<code>git clone https://naor_shoyhat:<password>@bitbucket.org/naor_shoyhat/hello-world.git
</code>```

It worked for me in a pinch, but I do agree that it is not the best solution.

Title: Git error remote: Empty password

Body:
I'm trying to clone my git repo from bitbucket, and when I enter this command:

git clone https://naor_shoyhat@bitbucket.org/naor_shoyhat/hello-world.git

The bash then prompts me a window with areas to enter username and password.

I enter them and then I receive this error:

remote: Empty password
fatal: Authentication failed for 'https://naor_shoyhat@bitbucket.org/naor_shoyhat/hello-world.git/'

Body:
You can try:

git clone https://naor_shoyhat:<password>@bitbucket.org/naor_shoyhat/hello-world.git

It worked for me in a pinch, but I do agree that it is not the best solution.


来源: stackexchange

问:
Java - paintComponent() drastically slowing down the program when repainting an image of high resolution
Recently I've been working on a small project until I've encountered something rather annoying.

What the program currently does is read certain folders which are generated by the program in which files with the file extension ".jpg" and ".png" are displayed (for this to work, the user the user has to manually insert the images in these folders).

That part works, until we get to the animation part that I've created.This is a rectangle with a certain RGBA value which changes its alpha value once the mouse hovers over it and exits it. With low resolution images, this animation works smoothly, but with high resolution images, its very laggy and the animation doesn't look so smooth.

mainFrame Class

```<code>package seriesorganiser;

import java.awt.GridLayout;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.File;
import java.io.IOException;
import javax.swing.JFrame;
import javax.swing.JPanel;

/**
 *
 * @author Luca Muscat
 */
public class mainFrame {

    private static boolean check;
    private static final String DOCUMENTS_LOCATION = System.getProperty("user.home") + "\\Documents";

    public static void main(String[] args) throws IOException {
        check = new File(DOCUMENTS_LOCATION + "\\SeriesOrganiser").exists();
        if (!check) {
            new File(DOCUMENTS_LOCATION + "\\SeriesOrganiser").mkdir();
            new File(DOCUMENTS_LOCATION + "\\SeriesOrganiser\\Shows").mkdir();
            new File(DOCUMENTS_LOCATION + "\\SeriesOrganiser\\Movies").mkdir();
        }
        JFrame frame = new JFrame("Series Organiser");
        frame.setLocationRelativeTo(null);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);

        //Layout Handler
        JPanel container = new JPanel();
        //Movies=0, Shows=1.
        JPanel moviesPanel = new moviesShowsPanel(0);
        JPanel showsPanel = new moviesShowsPanel(1);

        container.setLayout(new GridLayout(1, 2));
        container.add(moviesPanel);
        container.add(showsPanel);

        frame.add(container);
        frame.pack();
    }
}
</code>```

moviesShowsPanel

```<code>package seriesorganiser;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.BorderFactory;
import javax.swing.JPanel;

/**
 *
 * @author Luca Muscat
 */
public class moviesShowsPanel extends JPanel {

    int alpha = 255 / 2;
    boolean isMouseOver = false;
    boolean isMouseHover = false;
    public final static int SHOWS_GENRE = 1;
    public final static int MOVIES_GENRE = 0;
    private int genreHolder;
    public moviesShowsPanel(int genre) {
        genreHolder=genre;
        setPreferredSize(new Dimension(600, 600));
        setBorder(BorderFactory.createLineBorder(Color.black));
        setBackground(Color.LIGHT_GRAY);

        addMouseListener(new MouseAdapter() {
            @Override
            public void mouseEntered(MouseEvent me) {
                if(!isMouseOver)repaint();
                isMouseOver = true;
            }

            @Override
            public void mouseExited(MouseEvent me) {
                if(isMouseOver)repaint();
                isMouseOver = false;
            }
        });

    }
    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        scanForImage findImage = new scanForImage();
        if (isMouseOver && alpha>10) {
            alpha-=10;
        }
        if(!isMouseOver && alpha<145){
            alpha+=10;
        }
        try {
            if(genreHolder==MOVIES_GENRE){
                g.drawImage(findImage.findMoviesImage(), 0, 0, getWidth(), getHeight(), null);
            }
            if(genreHolder==SHOWS_GENRE){
                g.drawImage(findImage.findShowsImage(),0,0,getWidth(),getHeight(),null);
            }
        } catch (IOException ex) {
            Logger.getLogger(moviesShowsPanel.class.getName()).log(Level.SEVERE, null, ex);
        }
        g.setColor(new Color(214, 229, 255, alpha));
        g.fillRect(0, 0, getWidth(), getHeight());
        repaint();
    }
}
</code>```

scanForImage

```<code>package seriesorganiser;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;

/**
 *
 * @author Luca Muscat
 */
public class scanForImage {
    private static final String DOCUMENTS_LOCATION = System.getProperty("user.home")+"\\Documents";
    BufferedImage findMoviesImage() throws IOException{
        BufferedImage img = null;
        File folderMovies = new File(DOCUMENTS_LOCATION+"\\SeriesOrganiser\\Movies");
        img=DRY(folderMovies);
        return img;
    }
    BufferedImage findShowsImage()throws IOException{
       BufferedImage img=null;
       File folderShows = new File(DOCUMENTS_LOCATION+"\\SeriesOrganiser\\Shows");
       img = DRY(folderShows);
       return img;
    }
    private BufferedImage DRY(File f)throws IOException{
        BufferedImage img=null;
        String filepath=String.valueOf(f);
        File[] listOfFiles=f.listFiles();
        for(File c:listOfFiles){
           if(c.isFile()){
               if(c.getName().contains(".jpg") || c.getName().contains(".png")){
                   img=ImageIO.read(new File(filepath+"\\"+c.getName()));
                   break;
               }
           }
       }
        return img;
    }
}
</code>```

To test it out all you guys need to do is put an image in both the Movies and Shows files which is found in a folder called SeriesOrganiser in the "Documents" folder library. (Windows 10).

Wouldn't mind some criticism on the code since I know that I have a lot to improve on.

答:
A couple of comments from the paintComponent() method:

```<code>scanForImage findImage = new scanForImage();
</code>```

Don't do I/O in a painting method. A painting method is for painting only

```<code>repaint();
</code>```

Don't invoke repaint(). This will cause a painting request to be continually added to the event queue.

If you need animation then use a Swing Timer to schedule the animation.

```<code>g.dispose();
</code>```

Don't dispose of the Graphics object that was passed to the method. Other components on the frame may use this Graphics.

You only use the dispose() method on a Graphic object that you create within the paintComponent() method.

ContentLicense: CC BY-SA 3.0

Body:
Recently I've been working on a small project until I've encountered something rather annoying.

What the program currently does is read certain folders which are generated by the program in which files with the file extension ".jpg" and ".png" are displayed (for this to work, the user the user has to manually insert the images in these folders).

That part works, until we get to the animation part that I've created.This is a rectangle with a certain RGBA value which changes its alpha value once the mouse hovers over it and exits it. With low resolution images, this animation works smoothly, but with high resolution images, its very laggy and the animation doesn't look so smooth.

mainFrame Class

package seriesorganiser;

import java.awt.GridLayout;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.File;
import java.io.IOException;
import javax.swing.JFrame;
import javax.swing.JPanel;

/**
 *
 * @author Luca Muscat
 */
public class mainFrame {

    private static boolean check;
    private static final String DOCUMENTS_LOCATION = System.getProperty("user.home") + "\\Documents";

    public static void main(String[] args) throws IOException {
        check = new File(DOCUMENTS_LOCATION + "\\SeriesOrganiser").exists();
        if (!check) {
            new File(DOCUMENTS_LOCATION + "\\SeriesOrganiser").mkdir();
            new File(DOCUMENTS_LOCATION + "\\SeriesOrganiser\\Shows").mkdir();
            new File(DOCUMENTS_LOCATION + "\\SeriesOrganiser\\Movies").mkdir();
        }
        JFrame frame = new JFrame("Series Organiser");
        frame.setLocationRelativeTo(null);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);

        //Layout Handler
        JPanel container = new JPanel();
        //Movies=0, Shows=1.
        JPanel moviesPanel = new moviesShowsPanel(0);
        JPanel showsPanel = new moviesShowsPanel(1);

        container.setLayout(new GridLayout(1, 2));
        container.add(moviesPanel);
        container.add(showsPanel);

        frame.add(container);
        frame.pack();
    }
}

moviesShowsPanel

package seriesorganiser;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.BorderFactory;
import javax.swing.JPanel;

/**
 *
 * @author Luca Muscat
 */
public class moviesShowsPanel extends JPanel {

    int alpha = 255 / 2;
    boolean isMouseOver = false;
    boolean isMouseHover = false;
    public final static int SHOWS_GENRE = 1;
    public final static int MOVIES_GENRE = 0;
    private int genreHolder;
    public moviesShowsPanel(int genre) {
        genreHolder=genre;
        setPreferredSize(new Dimension(600, 600));
        setBorder(BorderFactory.createLineBorder(Color.black));
        setBackground(Color.LIGHT_GRAY);

        addMouseListener(new MouseAdapter() {
            @Override
            public void mouseEntered(MouseEvent me) {
                if(!isMouseOver)repaint();
                isMouseOver = true;
            }

            @Override
            public void mouseExited(MouseEvent me) {
                if(isMouseOver)repaint();
                isMouseOver = false;
            }
        });

    }
    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        scanForImage findImage = new scanForImage();
        if (isMouseOver && alpha>10) {
            alpha-=10;
        }
        if(!isMouseOver && alpha<145){
            alpha+=10;
        }
        try {
            if(genreHolder==MOVIES_GENRE){
                g.drawImage(findImage.findMoviesImage(), 0, 0, getWidth(), getHeight(), null);
            }
            if(genreHolder==SHOWS_GENRE){
                g.drawImage(findImage.findShowsImage(),0,0,getWidth(),getHeight(),null);
            }
        } catch (IOException ex) {
            Logger.getLogger(moviesShowsPanel.class.getName()).log(Level.SEVERE, null, ex);
        }
        g.setColor(new Color(214, 229, 255, alpha));
        g.fillRect(0, 0, getWidth(), getHeight());
        repaint();
    }
}

scanForImage

package seriesorganiser;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;

/**
 *
 * @author Luca Muscat
 */
public class scanForImage {
    private static final String DOCUMENTS_LOCATION = System.getProperty("user.home")+"\\Documents";
    BufferedImage findMoviesImage() throws IOException{
        BufferedImage img = null;
        File folderMovies = new File(DOCUMENTS_LOCATION+"\\SeriesOrganiser\\Movies");
        img=DRY(folderMovies);
        return img;
    }
    BufferedImage findShowsImage()throws IOException{
       BufferedImage img=null;
       File folderShows = new File(DOCUMENTS_LOCATION+"\\SeriesOrganiser\\Shows");
       img = DRY(folderShows);
       return img;
    }
    private BufferedImage DRY(File f)throws IOException{
        BufferedImage img=null;
        String filepath=String.valueOf(f);
        File[] listOfFiles=f.listFiles();
        for(File c:listOfFiles){
           if(c.isFile()){
               if(c.getName().contains(".jpg") || c.getName().contains(".png")){
                   img=ImageIO.read(new File(filepath+"\\"+c.getName()));
                   break;
               }
           }
       }
        return img;
    }
}

To test it out all you guys need to do is put an image in both the Movies and Shows files which is found in a folder called SeriesOrganiser in the "Documents" folder library. (Windows 10).

Wouldn't mind some criticism on the code since I know that I have a lot to improve on.

Body:
A couple of comments from the paintComponent() method:

scanForImage findImage = new scanForImage();

Don't do I/O in a painting method. A painting method is for painting only

repaint();

Don't invoke repaint(). This will cause a painting request to be continually added to the event queue.

If you need animation then use a Swing Timer to schedule the animation.

g.dispose();

Don't dispose of the Graphics object that was passed to the method. Other components on the frame may use this Graphics.

You only use the dispose() method on a Graphic object that you create within the paintComponent() method.


问:
Redmine: Docker failures
I want to install Redmine in Docker. I followed this tutorial. When I tried with Postresql

```<code>docker run --name=postgresql-redmine -d \
  --env='DB_NAME=redmine_production' \
  --env='DB_USER=redmine' --env='DB_PASS=password' \
  --volume=/srv/docker/redmine/postgresql:/var/lib/postgresql \
  sameersbn/postgresql:9.6-2

docker run --name=redmine -d \
  --link=postgresql-redmine:postgresql --publish=10083:80 \
  --env='REDMINE_PORT=10083' \
  --volume=/srv/docker/redmine/redmine:/home/redmine/data \
  sameersbn/redmine:3.3.2-1
</code>```

I got the following error message:

docker: Error response from daemon: Cannot link to a non running
  container: /postgresql-redmine AS /redmine/postgresql-redmine.

And when I try with MySQL:

```<code>docker run --name=mysql-redmine -d \
  --volume=/srv/docker/redmine/mysql:/var/lib/mysql \
  sameersbn/mysql:latest

docker run --name=redmine -it --rm \
  --env='DB_ADAPTER=mysql2' \
  --env='DB_HOST=192.168.1.100' --env='DB_NAME=redmine_production' \
  --env='DB_USER=redmine' --env='DB_PASS=password' \
  --volume=/srv/docker/redmine/redmine:/home/redmine/data \
  sameersbn/redmine:3.3.2-1
</code>```

I don't get error message, but I can't reach it (not in port 3000 and not in port 10083, too)

What's missing?

EDIT:
Output of docker ps -a

```<code>CONTAINER ID        IMAGE                    COMMAND                  CREATED             STATUS                   PORTS               NAMES
3b0d0631080f        sameersbn/mysql:latest   "/sbin/entrypoint...."   3 hours ago         Exited (1) 3 hours ago
</code>```

Output of docker logs 3b0d0631080f

```<code>standard_init_linux.go:178: exec user process caused "exec format error"
</code>```

答:
Raspberry Pi has the ARM architecture. Therefore you can't use "normal" images. I am new to this topic, but this blog post was interesting.

I suppose that it could be possible to build the required docker images on your own by taking the Dockerfile and replacing the base image with a ARM compatible ubuntu image (armhf/ubuntu) one.

If you want to give it a try:

Download the Dockerfile

Replace FROM sameersbn/ubuntu:14.04.20170123 with FROM armhf/ubuntu

Run docker build . in the folder of the edited Dockerfile

This is only guessing, but I am interested if it works.

Title: Redmine: Docker failures

Body:
I want to install Redmine in Docker. I followed this tutorial. When I tried with Postresql

docker run --name=postgresql-redmine -d \
  --env='DB_NAME=redmine_production' \
  --env='DB_USER=redmine' --env='DB_PASS=password' \
  --volume=/srv/docker/redmine/postgresql:/var/lib/postgresql \
  sameersbn/postgresql:9.6-2

docker run --name=redmine -d \
  --link=postgresql-redmine:postgresql --publish=10083:80 \
  --env='REDMINE_PORT=10083' \
  --volume=/srv/docker/redmine/redmine:/home/redmine/data \
  sameersbn/redmine:3.3.2-1

I got the following error message:

docker: Error response from daemon: Cannot link to a non running
  container: /postgresql-redmine AS /redmine/postgresql-redmine.

And when I try with MySQL:

docker run --name=mysql-redmine -d \
  --volume=/srv/docker/redmine/mysql:/var/lib/mysql \
  sameersbn/mysql:latest

docker run --name=redmine -it --rm \
  --env='DB_ADAPTER=mysql2' \
  --env='DB_HOST=192.168.1.100' --env='DB_NAME=redmine_production' \
  --env='DB_USER=redmine' --env='DB_PASS=password' \
  --volume=/srv/docker/redmine/redmine:/home/redmine/data \
  sameersbn/redmine:3.3.2-1

I don't get error message, but I can't reach it (not in port 3000 and not in port 10083, too)

What's missing?

EDIT:
Output of docker ps -a

CONTAINER ID        IMAGE                    COMMAND                  CREATED             STATUS                   PORTS               NAMES
3b0d0631080f        sameersbn/mysql:latest   "/sbin/entrypoint...."   3 hours ago         Exited (1) 3 hours ago

Output of docker logs 3b0d0631080f

standard_init_linux.go:178: exec user process caused "exec format error"


问:
MissingResourceException - Can't find bundle for base name
I know that there are a lot of questions and answers exactly about this error on stackoverflow and other forums. But I still can not find the solution...

For speed reasons I have one utility class which loads all static data maps (for example months) depending on locale provided.

So this utility class looks something like this:

```<code>public static final String GLOBAL_MESSAGES = "globalMessages";

private static Map<Integer,Month> monthsMap;

private ResourceBundle getResourceBundle(Locale locale) {
    ResourceBundle rb = ResourceBundle.getBundle(GLOBAL_MESSAGES, locale);
    return rb;
}

private Map<Integer,Month> getMonths() {
    if(monthsMap == null) {
        setMonths();
    }
    return monthsMap;
}

private void setMonths() {
    try {
        monthsMap = getFactory().getDAO().getAllMonths();
    } catch (SQLException e) {
        logger.error(e);
    } catch (EmptyResultException e) {
        logger.error(e);
    }
}

public Map<Integer,Month> getMonths(Locale locale) {
    if(locale == null) {
        return monthsMap;
    } else {
        if(this.locale != locale) {
            this.locale = locale;
            setMonths();
        }
    }
    ResourceBundle rb = getResourceBundle(locale);
    Map<Integer,Month> map = new HashMap<Integer, Month>();
    for(Month akVO : getMonths().values()) {
        try {
            akVO.setName(rb.getString(akVO.getName()));
        } catch (MissingResourceException e) {
            //already done
        }
        map.put(akVO.getId(), akVO);
    }
    return map;
}
</code>```

Files globalMessages.properties (globalMessages_en_US.properties,...) are directly in source package resources. When deployed on Tomcat there are in folder WEB-INF/classes.

Now the problem. It all works when working in this application. But I have another application which connects throught REST API (JAX-RS) to this one. When making a request App/rest/months.xml I get the following error:

```<code>java.util.MissingResourceException: Can't find bundle for base name globalMessages, locale en_us
</code>```

I am really lost. And desperate...

答:
For anybody having trouble with a Glassfish server in this case, there is the possibility to set the Locale within the Admin Overview

Simple overwrite the default locale as shown in the picture

Somebody might find this useful, I had trouble for multiple hours and dont want anyone to have this kind of problem aswell

ContentLicense: CC BY-SA 2.5

Body:
I know that there are a lot of questions and answers exactly about this error on stackoverflow and other forums. But I still can not find the solution...

For speed reasons I have one utility class which loads all static data maps (for example months) depending on locale provided.

So this utility class looks something like this:

public static final String GLOBAL_MESSAGES = "globalMessages";

private static Map<Integer,Month> monthsMap;

private ResourceBundle getResourceBundle(Locale locale) {
    ResourceBundle rb = ResourceBundle.getBundle(GLOBAL_MESSAGES, locale);
    return rb;
}

private Map<Integer,Month> getMonths() {
    if(monthsMap == null) {
        setMonths();
    }
    return monthsMap;
}

private void setMonths() {
    try {
        monthsMap = getFactory().getDAO().getAllMonths();
    } catch (SQLException e) {
        logger.error(e);
    } catch (EmptyResultException e) {
        logger.error(e);
    }
}

public Map<Integer,Month> getMonths(Locale locale) {
    if(locale == null) {
        return monthsMap;
    } else {
        if(this.locale != locale) {
            this.locale = locale;
            setMonths();
        }
    }
    ResourceBundle rb = getResourceBundle(locale);
    Map<Integer,Month> map = new HashMap<Integer, Month>();
    for(Month akVO : getMonths().values()) {
        try {
            akVO.setName(rb.getString(akVO.getName()));
        } catch (MissingResourceException e) {
            //already done
        }
        map.put(akVO.getId(), akVO);
    }
    return map;
}

Files globalMessages.properties (globalMessages_en_US.properties,...) are directly in source package resources. When deployed on Tomcat there are in folder WEB-INF/classes.

Now the problem. It all works when working in this application. But I have another application which connects throught REST API (JAX-RS) to this one. When making a request App/rest/months.xml I get the following error:

java.util.MissingResourceException: Can't find bundle for base name globalMessages, locale en_us

I am really lost. And desperate...


问:
SSD mount configuration for Varnish file storage
I have Varnish 5.1.1 on Centos 6.5 and want to Use a fresh SSD for file storage, (my RAM 64GB get full quickly as I have a lot of objects to cache)

As said in Varnish Doc I have mounted a tmpfs partition for the working directory :

"The shmlog usually is located in /var/lib/varnish and you can feel free to remove any data found in this directory if needed. Varnish suggests make sure this location is mounted on tmpfs by using /etc/fstab to make sure this gets mounted on server reboot / start."

I have a dedicated 256 GB SSD drive for cache storage.
Do I have to mount it as tmpf with noatime like working dir ?
I did not find any suggestion on how to configure SSD for Varnish needs.

答: No, you do not have to mount anything special if you're just going to use your SSD. tempfs is specific for a RAM drive only, and if you're not going to take advantage of the superior speed of RAM over SSD, then leaving /var/lib/varnish as is on the default install is good enough.</p>


问:
get variable located inside callback function
```<code>var request = require('request');

var options = {
  url: 'https://api.github.com/repos/request/request',
  headers: {
    'User-Agent': 'request'
  }
};

function callback(error, response, body) {
  if (!error && response.statusCode == 200) {
    var info = JSON.parse(body);
    console.log(info.stargazers_count + " Stars");
    console.log(info.forks_count + " Forks");
  }
}
exports.parse = function(){
   request(options, callback);
}
</code>```

Hi, how can i get info variable located inside callback function.
Sorry, i'm beginner in js and didn't find answer inside my brain / peace

答:
The callback functions are used to handle the non-blocking - asynchronous nature. When a job is blocking the I/O it simply put it in the task queue and moves forward. After finishing the task it is time to trigger the callback function, we can handle those returned values in any way we want. That's the use of callback functions. You can read about event-loop for better understanding.

Here you have to pass the custom callback function to properly handle the scenario.

```<code>var request = require('request');

var options = {
  url: 'https://api.github.com/repos/request/request',
  headers: {
    'User-Agent': 'request'
  }
};

exports.parse = function(cb){
   request(options, cb);
}
</code>```

In the place where you want to use the parse method use like this..

```<code>parse(function(error, response, body) {
  if (!error && response.statusCode == 200) {
    var info = JSON.parse(body);
    console.log(info.stargazers_count + " Stars");
    console.log(info.forks_count + " Forks");

// TODO with info

  }
});
</code>```

Body:
var request = require('request');

var options = {
  url: 'https://api.github.com/repos/request/request',
  headers: {
    'User-Agent': 'request'
  }
};

function callback(error, response, body) {
  if (!error && response.statusCode == 200) {
    var info = JSON.parse(body);
    console.log(info.stargazers_count + " Stars");
    console.log(info.forks_count + " Forks");
  }
}
exports.parse = function(){
   request(options, callback);
}

Hi, how can i get info variable located inside callback function.
Sorry, i'm beginner in js and didn't find answer inside my brain / peace

Body:
The callback functions are used to handle the non-blocking - asynchronous nature. When a job is blocking the I/O it simply put it in the task queue and moves forward. After finishing the task it is time to trigger the callback function, we can handle those returned values in any way we want. That's the use of callback functions. You can read about event-loop for better understanding.

Here you have to pass the custom callback function to properly handle the scenario.

var request = require('request');

var options = {
  url: 'https://api.github.com/repos/request/request',
  headers: {
    'User-Agent': 'request'
  }
};

exports.parse = function(cb){
   request(options, cb);
}

In the place where you want to use the parse method use like this..

parse(function(error, response, body) {
  if (!error && response.statusCode == 200) {
    var info = JSON.parse(body);
    console.log(info.stargazers_count + " Stars");
    console.log(info.forks_count + " Forks");

// TODO with info

  }
});


问:
Kibana display field value on time
In ElasticSearch I have these following documents (values like index and type was removed) :

```<code>@timestamp:March 29th 2017, 22:03:29.152 totalQuantity:154
@timestamp:March 29th 2017, 22:06:30.242 totalQuantity:153
@timestamp:March 29th 2017, 22:06:32.735 totalQuantity:152
</code>```

Now I want to display the totalQuantity's value evolution during time (in line chart or other graph, maybe timelion) with 3 node

Y: 154 X: 22-03-29

Y: 153 X: 22:06:30

Y: 152 X: 22:06:32

But I can't find how to deal with it, as I only have count, sum, median, etc on these graph but not term.

答: What you want to do is to create a line/bar chart and set x-axis as date histogram where @timestamp is the property, and put sum or average of totalQuantity on y-axis. You will want to set your time interval in seconds so you will see the difference 2 seconds later. No need for TimeLion as you are not calculating anything. </p>

Title: Kibana display field value on time

Body:
In ElasticSearch I have these following documents (values like index and type was removed) :

@timestamp:March 29th 2017, 22:03:29.152 totalQuantity:154
@timestamp:March 29th 2017, 22:06:30.242 totalQuantity:153
@timestamp:March 29th 2017, 22:06:32.735 totalQuantity:152

Now I want to display the totalQuantity's value evolution during time (in line chart or other graph, maybe timelion) with 3 node

Y: 154 X: 22-03-29

Y: 153 X: 22:06:30

Y: 152 X: 22:06:32

But I can't find how to deal with it, as I only have count, sum, median, etc on these graph but not term.


问:
SQL single table with two columns
I have a single table: Checking, with two columns: ID, Memo

ID is the primary key.

I would like a query that returns both columns: ID, Memo BUT only where Memo is DISTINCT

I can do the following to get the distinct values from Memo:

```<code>SELECT DISTINCT(memo)
FROM checking
</code>```

How do I return those Memo values and their values from the ID column?

I've run in circles trying inner and outer joins but I'm failing.

Thanks for your help

Sample data:

```<code>ID        Memo
1         a
2         c
3         e
4         g
5         a
6         c
</code>```

The desired return:

```<code>1,a
2,c
3,e
4,g
</code>```

5 and 6 would not be included because they have duplicate memo values.

Thanks again for your help.

答:
```<code>select id, memo
from checking
join
( /*only where Memo is DISTINCT*/
  select distinct(memo) as memo
  from checking
) as m on checking.memo = m.memo
</code>```

Title: SQL single table with two columns

Body:
I have a single table: Checking, with two columns: ID, Memo

ID is the primary key.

I would like a query that returns both columns: ID, Memo BUT only where Memo is DISTINCT

I can do the following to get the distinct values from Memo:

SELECT DISTINCT(memo)
FROM checking

How do I return those Memo values and their values from the ID column?

I've run in circles trying inner and outer joins but I'm failing.

Thanks for your help

Sample data:

ID        Memo
1         a
2         c
3         e
4         g
5         a
6         c

The desired return:

1,a
2,c
3,e
4,g

5 and 6 would not be included because they have duplicate memo values.

Thanks again for your help.


问:
Align contents of col-xs
I have a col-xs-8 column as follow:

```<code><div class="col-xs-8">
     <div>Every</div>
     <select id="update-frequency"
              ng-model="retentionSettings.triggers.date.repeat"
              ng-disabled="!retentionSettings.triggers.dateStatus">
          <option value="day">day</option>
          <option value="week">week</option>
          <option value="month">month</option>
      </select>

      <div ng-show="retentionSettings.triggers.date.repeat=='week'">
           <div>on</div>
           <select id="weekDayDropDown"
                 ng-model="retentionSettings.triggers.date.weekday"
                 ng-disabled="!retentionSettings.triggers.dateStatus">
                 <option ng-repeat="x in weekdaysList()">{{x}}</option>
            </select>
      </div>
</div>
</code>```

The contents of this column with the above snippet pile up vertically like so:

I'd like to have them horizontally. Im avoiding using more columns inside this one because the spacing wont work for a sentence where the words should be near eachother. How do I achieve this?

答:
The problem you're having is the divs for "Every" and "on" by default have a display: block. You could add custom styling to change the display value to fix this or you could not use div as demonstrated here:

     Every
     <select id="update-frequency"
              ng-model="retentionSettings.triggers.date.repeat"
              ng-disabled="!retentionSettings.triggers.dateStatus">
          <option value="day">day</option>
          <option value="week">week</option>
          <option value="month">month</option>
     </select>

      on
      <select id="weekDayDropDown"
               ng-model="retentionSettings.triggers.date.weekday"
               ng-disabled="!retentionSettings.triggers.dateStatus">
          <option ng-repeat="x in weekdaysList()">{{x}}</option>
      </select>

```

Title: Align contents of col-xs

Body:
I have a col-xs-8 column as follow:

Every

     <select id="update-frequency"
              ng-model="retentionSettings.triggers.date.repeat"
              ng-disabled="!retentionSettings.triggers.dateStatus">
          <option value="day">day</option>
          <option value="week">week</option>
          <option value="month">month</option>
      </select>

on

           <select id="weekDayDropDown"
                 ng-model="retentionSettings.triggers.date.weekday"
                 ng-disabled="!retentionSettings.triggers.dateStatus">
                 <option ng-repeat="x in weekdaysList()">{{x}}</option>
            </select>

The contents of this column with the above snippet pile up vertically like so:

I'd like to have them horizontally. Im avoiding using more columns inside this one because the spacing wont work for a sentence where the words should be near eachother. How do I achieve this?

Body:
The problem you're having is the divs for "Every" and "on" by default have a display: block. You could add custom styling to change the display value to fix this or you could not use div as demonstrated here:

<div class="col-xs-8">
     <span>Every</span>
     <select id="update-frequency"
              ng-model="retentionSettings.triggers.date.repeat"
              ng-disabled="!retentionSettings.triggers.dateStatus">
          <option value="day">day</option>
          <option value="week">week</option>
          <option value="month">month</option>
     </select>

      <span>on</span>
      <select id="weekDayDropDown"
               ng-model="retentionSettings.triggers.date.weekday"
               ng-disabled="!retentionSettings.triggers.dateStatus">
          <option ng-repeat="x in weekdaysList()">{{x}}</option>
      </select>
</div>


问:
Is a statement void(); legal and what is it actually?
I have a little piece of code which has a statement void();

```<code>int main()
{
   void( ); // 1: parses fine in GCC 5.4.0 -Wpedantic
   // void;    // 2: error declaration does not declare anything
}
</code>```

What is 1 void() exactly?

An anonymous function declaration?

A type declaration?

An empty expression?

What makes 1 void() different from 2 void;?

I have read already:

Is sizeof(void()) a legal expression? but there void() is considered a type in sizeof

What does the void() in decltype(void()) mean exactly? where it is considered in declspec.

And I read Is void{} legal or not?

But I am curious if the loose statement void(); is different from one of those (and why of course)

答:
void; is an error because there is no rule in the language grammar which matches that code. In particular, there is no rule type-id ;,

However, the code void() matches two grammar rules:

type-id .

postfix-expression, with the sub-case being  simple-type-specifier ( expression-list-opt ).

Now, the parser needs to match void(); to a grammar rule. Even though void() matches type-id, as mentioned earlier there is no rule that would match type-id ;. So the parser rejects the possible parsing of void() as type-id in this context, and tries the other possibility.

There is a series of rules defining that postfix-expression ; makes a statement. So void() is unambiguously parsed as postfix-expression in this context.

As described by the other answers you linked already, the semantic meaning of this code as a postfix-expression is a prvalue of type void.

Related link: Is sizeof(int()) a legal expression?

Body:
I have a little piece of code which has a statement void();

int main()
{
   void( ); // 1: parses fine in GCC 5.4.0 -Wpedantic
   // void;    // 2: error declaration does not declare anything
}

What is 1 void() exactly?

An anonymous function declaration?

A type declaration?

An empty expression?

What makes 1 void() different from 2 void;?

I have read already:

Is sizeof(void()) a legal expression? but there void() is considered a type in sizeof

What does the void() in decltype(void()) mean exactly? where it is considered in declspec.

And I read Is void{} legal or not?

But I am curious if the loose statement void(); is different from one of those (and why of course)


问:
How can I detect focus in textfields in a webview using Swift 3?
I am building an application, and when I load a website in webview using Swift 3, the screen will appear like this, now I want to detect when user clicks on the email text field, and add a button to the navigation controller.

I don't know how to do it, does anyone have any idea?

答:
The main use of webview is near like an iframe in web.

I mean that webview is just a displaying of internet content. By this way, you cannot detect any action like user clicks on email textfield.

According to me and currently, there is no possibility to do that because it is not the goal of a webview.


问:
Using a button to deselect cells in a collectionview
I have two collection views. Tapping unselected cells in Collection View 1 selects them, and adds the selected cell to Collection View 2. Tapping on selected cells in Collection View 1 (allHobbiesCV) will unselect them and remove them from Collection View 2 (myHobbiesCV). Essentially, all it's doing is toggling.

Cells in Collection View 2 can also be manually removed by selecting as few or many as desired, then pressing a 'Remove' button. This process works great, except the cells in Collection View 1 still remain selected, even if that particular cell was removed from Collection View 2.

How do I use the remove button to deselect cells from Collection View 1 if they were manually selected and removed from Collection View 2?

Class level -

```<code>var allHobbiesArray = [String]()
var allHobbiesArraySelected = [String]()

var myHobbiesArray = [String]()
var myHobbiesArraySelected = [String]()
</code>```

didSelectItemAt

```<code>func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {

    // All Hobbies
    if collectionView == allHobbiesCV {
        let item = allHobbiesArray[indexPath.item]
        let cell = allHobbiesCV.cellForItem(at: indexPath) as! AllHobbiesCell

        if let itemIndex = allHobbiesArraySelected.index(of:item) {
            // DID DESELECT
            allHobbiesArraySelected.remove(at:itemIndex)
            myHobbiesArray.remove(at: itemIndex)
            myHobbiesCV.deleteItems(at: [IndexPath(item: itemIndex, section:0)])
            cell.backgroundColor = UIColor.brown
        }
        else {
            // DID SELECT
            allHobbiesArraySelected.insert(item, at: 0)
            myHobbiesArray.insert(item, at: 0)
            myHobbiesCV.insertItems(at: [IndexPath(item: 0, section:0)])
            cell.backgroundColor = UIColor.green
        }

        allHobbiesCV.deselectItem(at: indexPath, animated: false)

        for cell in myHobbiesCV.visibleCells {
            cell.backgroundColor = UIColor.white
        }
        myHobbiesArraySelected.removeAll()
        //myHobbiesCV.reloadData() // needed?
    }

    // My Hobbies
    else {
        let item = myHobbiesArray[indexPath.item]
        let cell = myHobbiesCV.cellForItem(at: indexPath) as! MyHobbiesCell

        if let itemIndex = myHobbiesArraySelected.index(of:item) {
            // DID DESELECT
            myHobbiesArraySelected.remove(at: itemIndex)
            cell.backgroundColor = UIColor.white
        }
        else {
            // DID SELECT
            myHobbiesArraySelected.insert(item, at: 0)
            cell.backgroundColor = UIColor.red
        }
        myHobbiesCV.deselectItem(at: indexPath, animated: true)
    }
}
</code>```

cellForItem

```<code>func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

    if collectionView == allHobbiesCV {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "ALL", for: indexPath) as! AllHobbiesCell
        cell.allHobbiesCellLabel.text = allHobbiesArray[indexPath.item]

        let allHobbies = allHobbiesArray[indexPath.item]
        if allHobbiesArraySelected.index(of: allHobbies) != nil {
            cell.backgroundColor = UIColor.green
        }
        else {
            cell.backgroundColor = UIColor.brown
        }

        return cell
    }

    else { // myHobbiesCV
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "MY", for: indexPath) as! MyHobbiesCell
        cell.myHobbiesCellLabel.text = myHobbiesArray[indexPath.item]

        let myHobbies = myHobbiesArray[indexPath.item]
        if myHobbiesArraySelected.index(of: myHobbies) != nil {
            cell.backgroundColor = UIColor.red
        }
        else {
            cell.backgroundColor = UIColor.white
        }

        return cell
    }

}
</code>```

numberOfItemsInSection

```<code>    if collectionView == allHobbiesCV {
        return allHobbiesArray.count
    }
    else {
        return myHobbiesArray.count
    }
</code>```

Delete button

```<code>@IBAction func deleteHobbyButtonPressed(_ sender: UIButton) {

    print("all Hobbies - \(allHobbiesCV.indexPathsForSelectedItems!)")

    if let selectedItemPaths = myHobbiesCV.indexPathsForSelectedItems {

        var allItemIndexPaths = [IndexPath]()
        var tempSelectedItems = Array(allHobbiesArraySelected) // Need to use a temporary copy otherwise the element indexes will change
        for itemPath in selectedItemPaths {

            let removeItem = allHobbiesArraySelected[itemPath.item]
            if let removeIndex = tempSelectedItems.index(of: removeItem) {
                print("if let removeIndex")
                tempSelectedItems.remove(at: removeIndex)
            }

            if let allItemsIndex = allHobbiesArray.index(of: removeItem) {
                print("if let allItemsIndex")
                allItemIndexPaths.append(IndexPath(item: allItemsIndex, section: 0))
            }
        }

        allHobbiesArraySelected = tempSelectedItems // Selected items array without the removed items
        myHobbiesCV.deleteItems(at:selectedItemPaths)
        myHobbiesCV.reloadData()
        allHobbiesCV.reloadItems(at: allItemIndexPaths)  // Reload to update the selected status
    }

}
</code>```

The problem now is nothing is evaluating in the remove button. That first print statement always returns an empty array. And nothing prints in the if let check. Is there a way to use myHobbiesArraySelected instead of indexPathsForSelectedItems? (Since I'm saving the selected items in an array now) Along with the original intended functionality of deselecting the cell in allHobbiesCV if it was manually deleted in myHobbiesCV.

Thanks friends.

答:
It is a bad idea to store selected index paths, as these are coupled to the collection view.  If you store the selected items then you can always determine the appropriate index path, using the item's index in the array. You can also determine an item quickly from a given index path.

In the code below I have used the type Item for your underlying item, but it could be String or Int or any object type.  If you use your own class or struct, ensure you make it conform to Equatable and Hashable.

```<code>var allItems:[Item]
var selectedItems[Item]

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
    if collectionView == allItemsCV {
        let item = allItems[IndexPath.row]
        if let itemIndex = selectedItems.index(of:item) {
            selectedItems.remove(at:itemIndex)
            selectedItemsCV.deleteItems(at: [IndexPath(item: itemIndex, section:0)])
        } else {
            selectedItems.insert(item, at: 0)
            selectedItemsCV.insertItems(at: [IndexPath(item: 0, section:0)])
        }
        allItemsCV.deselectItem(at: indexPath, animated: true)
       // cell for item at indexPath needs to render the selected/deselected
          state correctly based on the item being in the selectedItems array

        allItemsCV.reloadItems(at: [indexPath])

    }
}

@IBAction func removeButtonPressed(_ sender: UIButton) {
//...
    if let selectedItemPaths = selectedItemCV.indexPathsForSelectedItems {
        var allItemIndexPaths = [IndexPath]()
        var tempSelectedItems = Array(selectedItems) // Need to use a temporary copy otherwise the element indexes will change
        for itemPath in selectedItemPaths {
            let removeItem = selectedItems[itemPath.item]
            if let removeIndex = tempSelectedItems.index(of: removeItem) {
                tempSelectedItems.remove(at: removeItem)
            }
            if let allItemsIndex = allItems.index(of: removeItem) {
                allItemIndexPaths.append(IndexPath(item: allItemsIndex, section: 0))
            }
        }
        selectedItems = tempSelectedItems // Selected items array without the removed items
        selectedItemsCV.deleteItems(at:selectedItemPaths)
        allItemsCV.reloadItems(at: allItemIndexPaths)  // Reload to update the selected status
    }
}
</code>```

Body:
I have two collection views. Tapping unselected cells in Collection View 1 selects them, and adds the selected cell to Collection View 2. Tapping on selected cells in Collection View 1 (allHobbiesCV) will unselect them and remove them from Collection View 2 (myHobbiesCV). Essentially, all it's doing is toggling.

Cells in Collection View 2 can also be manually removed by selecting as few or many as desired, then pressing a 'Remove' button. This process works great, except the cells in Collection View 1 still remain selected, even if that particular cell was removed from Collection View 2.

How do I use the remove button to deselect cells from Collection View 1 if they were manually selected and removed from Collection View 2?

Class level -

var allHobbiesArray = [String]()
var allHobbiesArraySelected = [String]()

var myHobbiesArray = [String]()
var myHobbiesArraySelected = [String]()

didSelectItemAt

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {

    // All Hobbies
    if collectionView == allHobbiesCV {
        let item = allHobbiesArray[indexPath.item]
        let cell = allHobbiesCV.cellForItem(at: indexPath) as! AllHobbiesCell

        if let itemIndex = allHobbiesArraySelected.index(of:item) {
            // DID DESELECT
            allHobbiesArraySelected.remove(at:itemIndex)
            myHobbiesArray.remove(at: itemIndex)
            myHobbiesCV.deleteItems(at: [IndexPath(item: itemIndex, section:0)])
            cell.backgroundColor = UIColor.brown
        }
        else {
            // DID SELECT
            allHobbiesArraySelected.insert(item, at: 0)
            myHobbiesArray.insert(item, at: 0)
            myHobbiesCV.insertItems(at: [IndexPath(item: 0, section:0)])
            cell.backgroundColor = UIColor.green
        }

        allHobbiesCV.deselectItem(at: indexPath, animated: false)

        for cell in myHobbiesCV.visibleCells {
            cell.backgroundColor = UIColor.white
        }
        myHobbiesArraySelected.removeAll()
        //myHobbiesCV.reloadData() // needed?
    }

    // My Hobbies
    else {
        let item = myHobbiesArray[indexPath.item]
        let cell = myHobbiesCV.cellForItem(at: indexPath) as! MyHobbiesCell

        if let itemIndex = myHobbiesArraySelected.index(of:item) {
            // DID DESELECT
            myHobbiesArraySelected.remove(at: itemIndex)
            cell.backgroundColor = UIColor.white
        }
        else {
            // DID SELECT
            myHobbiesArraySelected.insert(item, at: 0)
            cell.backgroundColor = UIColor.red
        }
        myHobbiesCV.deselectItem(at: indexPath, animated: true)
    }
}

cellForItem

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

    if collectionView == allHobbiesCV {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "ALL", for: indexPath) as! AllHobbiesCell
        cell.allHobbiesCellLabel.text = allHobbiesArray[indexPath.item]

        let allHobbies = allHobbiesArray[indexPath.item]
        if allHobbiesArraySelected.index(of: allHobbies) != nil {
            cell.backgroundColor = UIColor.green
        }
        else {
            cell.backgroundColor = UIColor.brown
        }

        return cell
    }

    else { // myHobbiesCV
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "MY", for: indexPath) as! MyHobbiesCell
        cell.myHobbiesCellLabel.text = myHobbiesArray[indexPath.item]

        let myHobbies = myHobbiesArray[indexPath.item]
        if myHobbiesArraySelected.index(of: myHobbies) != nil {
            cell.backgroundColor = UIColor.red
        }
        else {
            cell.backgroundColor = UIColor.white
        }

        return cell
    }

}

numberOfItemsInSection

    if collectionView == allHobbiesCV {
        return allHobbiesArray.count
    }
    else {
        return myHobbiesArray.count
    }

Delete button

@IBAction func deleteHobbyButtonPressed(_ sender: UIButton) {

    print("all Hobbies - \(allHobbiesCV.indexPathsForSelectedItems!)")

    if let selectedItemPaths = myHobbiesCV.indexPathsForSelectedItems {

        var allItemIndexPaths = [IndexPath]()
        var tempSelectedItems = Array(allHobbiesArraySelected) // Need to use a temporary copy otherwise the element indexes will change
        for itemPath in selectedItemPaths {

            let removeItem = allHobbiesArraySelected[itemPath.item]
            if let removeIndex = tempSelectedItems.index(of: removeItem) {
                print("if let removeIndex")
                tempSelectedItems.remove(at: removeIndex)
            }

            if let allItemsIndex = allHobbiesArray.index(of: removeItem) {
                print("if let allItemsIndex")
                allItemIndexPaths.append(IndexPath(item: allItemsIndex, section: 0))
            }
        }

        allHobbiesArraySelected = tempSelectedItems // Selected items array without the removed items
        myHobbiesCV.deleteItems(at:selectedItemPaths)
        myHobbiesCV.reloadData()
        allHobbiesCV.reloadItems(at: allItemIndexPaths)  // Reload to update the selected status
    }

}

The problem now is nothing is evaluating in the remove button. That first print statement always returns an empty array. And nothing prints in the if let check. Is there a way to use myHobbiesArraySelected instead of indexPathsForSelectedItems? (Since I'm saving the selected items in an array now) Along with the original intended functionality of deselecting the cell in allHobbiesCV if it was manually deleted in myHobbiesCV.

Thanks friends.

Body:
It is a bad idea to store selected index paths, as these are coupled to the collection view.  If you store the selected items then you can always determine the appropriate index path, using the item's index in the array. You can also determine an item quickly from a given index path.

In the code below I have used the type Item for your underlying item, but it could be String or Int or any object type.  If you use your own class or struct, ensure you make it conform to Equatable and Hashable.

var allItems:[Item]
var selectedItems[Item]

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
    if collectionView == allItemsCV {
        let item = allItems[IndexPath.row]
        if let itemIndex = selectedItems.index(of:item) {
            selectedItems.remove(at:itemIndex)
            selectedItemsCV.deleteItems(at: [IndexPath(item: itemIndex, section:0)])
        } else {
            selectedItems.insert(item, at: 0)
            selectedItemsCV.insertItems(at: [IndexPath(item: 0, section:0)])
        }
        allItemsCV.deselectItem(at: indexPath, animated: true)
       // cell for item at indexPath needs to render the selected/deselected
          state correctly based on the item being in the selectedItems array

        allItemsCV.reloadItems(at: [indexPath])

    }
}

@IBAction func removeButtonPressed(_ sender: UIButton) {
//...
    if let selectedItemPaths = selectedItemCV.indexPathsForSelectedItems {
        var allItemIndexPaths = [IndexPath]()
        var tempSelectedItems = Array(selectedItems) // Need to use a temporary copy otherwise the element indexes will change
        for itemPath in selectedItemPaths {
            let removeItem = selectedItems[itemPath.item]
            if let removeIndex = tempSelectedItems.index(of: removeItem) {
                tempSelectedItems.remove(at: removeItem)
            }
            if let allItemsIndex = allItems.index(of: removeItem) {
                allItemIndexPaths.append(IndexPath(item: allItemsIndex, section: 0))
            }
        }
        selectedItems = tempSelectedItems // Selected items array without the removed items
        selectedItemsCV.deleteItems(at:selectedItemPaths)
        allItemsCV.reloadItems(at: allItemIndexPaths)  // Reload to update the selected status
    }
}


问:
How to query records in multiple time zones using their own time zones with Rails or raw SQL
Here's my issue: I have records stored in my DB with UTC time zones but! I need to query those records and return everything within a day according the record's own time zone, regardless of its UTC date.

Example?

Let's say I have a record uploaded at 00:30 on a Tuesday in America/Denver and I have a bunch of records uploaded at 00:30 on a Monday in America/Los_Angeles.

Alright, now, when I query for records made on Monday, the whole day, I'm getting that Tuesday record because 00:30 in America/Denver is technically on Monday in America/Los_Angeles. I'm running raw SQL to try and solve this in my Rails project, but... no dice.

Any help on this?

```<code>SELECT
DATE(uploaded_at AT TIME ZONE 'UTC' AT TIME ZONE areas.iso_time_zone) as uploaded_at,
count(DISTINCT photos.id)
FROM photos, areas
WHERE photos.category IN ('landscape', 'family', 'animal', 'saucy', 'feet', 'portrait')
AND photos.uploaded_at
BETWEEN '2017-03-27 00:00:00 UTC' AND '2017-04-02 23:59:59 UTC'
GROUP BY DATE(uploaded_at AT TIME ZONE 'UTC' AT TIME ZONE areas.iso_time_zone)
ORDER BY DATE(uploaded_at AT TIME ZONE 'UTC' AT TIME ZONE areas.iso_time_zone);
</code>```

答:
Here I am adding on top of @bkunzi01's answer:

There is no way to find out a record's timezone now. So in your action you'll have to provide a timezone based on user's timezone or some logic.

Then use the in_time_zone method.  Docs here: http://apidock.com/rails/DateTime/in_time_zone

Ex. usage:

```<code>t = foo.start_time
=> 2000-01-01 14:20:00 UTC
t.zone
=> "UTC"
t = t.in_time_zone("America/New_York").at_end_of_day
=> Sat, 01 Jan 2000 09:20:00 EST -05:00
Model.where("created_at > ?", t - 24.hours)
</code>```

You can use this to convert the times based on their corresponding time zone thus giving you the proper range to query the UTC records.

Body:
Here's my issue: I have records stored in my DB with UTC time zones but! I need to query those records and return everything within a day according the record's own time zone, regardless of its UTC date.

Example?

Let's say I have a record uploaded at 00:30 on a Tuesday in America/Denver and I have a bunch of records uploaded at 00:30 on a Monday in America/Los_Angeles.

Alright, now, when I query for records made on Monday, the whole day, I'm getting that Tuesday record because 00:30 in America/Denver is technically on Monday in America/Los_Angeles. I'm running raw SQL to try and solve this in my Rails project, but... no dice.

Any help on this?

SELECT
DATE(uploaded_at AT TIME ZONE 'UTC' AT TIME ZONE areas.iso_time_zone) as uploaded_at,
count(DISTINCT photos.id)
FROM photos, areas
WHERE photos.category IN ('landscape', 'family', 'animal', 'saucy', 'feet', 'portrait')
AND photos.uploaded_at
BETWEEN '2017-03-27 00:00:00 UTC' AND '2017-04-02 23:59:59 UTC'
GROUP BY DATE(uploaded_at AT TIME ZONE 'UTC' AT TIME ZONE areas.iso_time_zone)
ORDER BY DATE(uploaded_at AT TIME ZONE 'UTC' AT TIME ZONE areas.iso_time_zone);

Body:
Here I am adding on top of @bkunzi01's answer:

There is no way to find out a record's timezone now. So in your action you'll have to provide a timezone based on user's timezone or some logic.

Then use the in_time_zone method.  Docs here: http://apidock.com/rails/DateTime/in_time_zone

Ex. usage:

t = foo.start_time
=> 2000-01-01 14:20:00 UTC
t.zone
=> "UTC"
t = t.in_time_zone("America/New_York").at_end_of_day
=> Sat, 01 Jan 2000 09:20:00 EST -05:00
Model.where("created_at > ?", t - 24.hours)

You can use this to convert the times based on their corresponding time zone thus giving you the proper range to query the UTC records.


问:
Android - can not access the html file on sdCard
I am trying to open html file that I have on my sdCard in Chrome or any other web browser (not html Viewer).

I have tried to enter path to file like this

```<code> file:///storage/extSdCard/page/page.html
</code>```

I get this error:

```<code> ERR_ACCESS_DENIED
</code>```

What could be wrong please?

EDIT: I have to mention that I am not developing a android app. I just want to view a html file, that is on my SD card in chrome mobile browser

EDIT2: It is not working from ext. sdcard and also from internal memory

Thank you.

答:
I had the same problem and the only way I found to solve the problem of reading the html file in Chrome in a device that isn't rooted is to copy or move the html file into the device's internal memory storage.

The alternative is to root the device and change the permissions to allow sdCard access in Chrome.

Body:
I am trying to open html file that I have on my sdCard in Chrome or any other web browser (not html Viewer).

I have tried to enter path to file like this

 file:///storage/extSdCard/page/page.html

I get this error:

 ERR_ACCESS_DENIED

What could be wrong please?

EDIT: I have to mention that I am not developing a android app. I just want to view a html file, that is on my SD card in chrome mobile browser

EDIT2: It is not working from ext. sdcard and also from internal memory

Thank you.


问:
Tableau Workbook won't appear in website when trying to embed with Javascript
So I've been able to successfully embed a workbook hosted on Tableau Server using the html embed code. I now want some more flexibility with which reports I'm displaying to certain users of the website so I'm moving to the Javascript API. Unfortunately the workbook now isn't loading.

I'm following the Basic Embed tutorial on Tableau's website: https://onlinehelp.tableau.com/current/api/js_api/en-us/JavaScriptAPI/js_api_sample_basic_embed.html

Here's my code:

```<code>function initViz() {
        var placeholderDiv = document.getElementById('tableauPlaceholder');
        var url = 'https://#########.#######.###/views/EnrollmentTool/EnrollmentChange'
        var options = {
            hideTabs: true,
                    onFirstInteractive: function () {
                        console.log("Run this code when the viz has finished loading.");
                    }
        };
        var viz = new tableau.Viz(placeholderDiv, url, options);
    }
</code>```

The onFirstInteractive log statement doesn't get called, so it seems that the viz isn't actually loading.

答:
I discovered the issue, the API version I was importing into my HTML file was viz_v1.js.

I had to use tableau-2.min.js instead.

Body:
So I've been able to successfully embed a workbook hosted on Tableau Server using the html embed code. I now want some more flexibility with which reports I'm displaying to certain users of the website so I'm moving to the Javascript API. Unfortunately the workbook now isn't loading.

I'm following the Basic Embed tutorial on Tableau's website: https://onlinehelp.tableau.com/current/api/js_api/en-us/JavaScriptAPI/js_api_sample_basic_embed.html

Here's my code:

function initViz() {
        var placeholderDiv = document.getElementById('tableauPlaceholder');
        var url = 'https://#########.#######.###/views/EnrollmentTool/EnrollmentChange'
        var options = {
            hideTabs: true,
                    onFirstInteractive: function () {
                        console.log("Run this code when the viz has finished loading.");
                    }
        };
        var viz = new tableau.Viz(placeholderDiv, url, options);
    }

The onFirstInteractive log statement doesn't get called, so it seems that the viz isn't actually loading.


问:
How to translate this this instructions in a query expression in Django
I have a set of instructions to query my database and I wonder myself if these are possible in a compact way as Query expression, so I have a model who has a field called solapin as you can see here:

```<code>class Question(models.Model):
    question_text = models.CharField(max_length=200)
    ...
    solapin = models.CharField(max_length=250)

    def __str__(self):  # __unicode__ on Python 2
        return self.solapin
</code>```

and I want to change the solapin field for every Question object whose solapin has between 0 to 9 characters, adding as '0' characters as the difference between 10 and the current solapin length of the everyone as you can see here:

```<code>from appname.models import Question

resultset = Question.objects.filter(solapin__iregex=r'^.{0,9}$')

for item in resultset:
    diff = 10 - len(item.solapin)
    item.solapin = "0"*diff + item.solapin
    item.save()
</code>```

This works perfectly for me, but I want to see if is possible to improve it.

答:
You can do this with single query using postgres repeat function with django Func and using Length and Concat functions:</p>

```<code>from django.db.models import Func, Value, CharField, F
from django.db.models.functions import Length, Concat

Question.objects.annotate(len=Length('solapin')).filter(len__lt=10). \
annotate(
    zeroes=Func(
           Value('0', output_field=CharField()), 10 - F('len'),
           function='repeat', output_field=CharField()
    ),
    new_solapin=Concat(F('zeroes'),'solapin')
).update(solapin=F('new_solapin'))
</code>```

Body:
I have a set of instructions to query my database and I wonder myself if these are possible in a compact way as Query expression, so I have a model who has a field called solapin as you can see here:

class Question(models.Model):
    question_text = models.CharField(max_length=200)
    ...
    solapin = models.CharField(max_length=250)

    def __str__(self):  # __unicode__ on Python 2
        return self.solapin

and I want to change the solapin field for every Question object whose solapin has between 0 to 9 characters, adding as '0' characters as the difference between 10 and the current solapin length of the everyone as you can see here:

from appname.models import Question

resultset = Question.objects.filter(solapin__iregex=r'^.{0,9}$')

for item in resultset:
    diff = 10 - len(item.solapin)
    item.solapin = "0"*diff + item.solapin
    item.save()

This works perfectly for me, but I want to see if is possible to improve it.

Body:
You can do this with single query using postgres repeat function with django Func and using Length and Concat functions:

from django.db.models import Func, Value, CharField, F
from django.db.models.functions import Length, Concat

Question.objects.annotate(len=Length('solapin')).filter(len__lt=10). \
annotate(
    zeroes=Func(
           Value('0', output_field=CharField()), 10 - F('len'),
           function='repeat', output_field=CharField()
    ),
    new_solapin=Concat(F('zeroes'),'solapin')
).update(solapin=F('new_solapin'))


问:
List of all html entities as name value pairs
I'm attempting to create css icon utilities that utilize html entities as the icon content.  Here's a set of examples in my github repository and here's one individual example:

```<code>.u-icon-olt {
    content: "⧀";
}

.u-icon-ogt {
    content: "⧁";
}
</code>```

So far I have been adding each entity one by one as needed, but if I have a list of entities as key value pairs [olt: ⧀, ogt: ⧁, ...] then I can generate the above CSS.  Anyone know if there exists such a list?

答:
If I had to do this, I'd parse the reference at w3c.

Here's what that page looks parsed into JSON.

And here's the code I used to parse it (in python).

Body:
I'm attempting to create css icon utilities that utilize html entities as the icon content.  Here's a set of examples in my github repository and here's one individual example:

.u-icon-olt {
    content: "⧀";
}

.u-icon-ogt {
    content: "⧁";
}

So far I have been adding each entity one by one as needed, but if I have a list of entities as key value pairs [olt: ⧀, ogt: ⧁, ...] then I can generate the above CSS.  Anyone know if there exists such a list?


问:
How do you initialize static map of private member function pointers?
I'm trying to make a MARIE code simulator, or whatever you would call it, and I'm trying to avoid a long switch case to access some private functions in the class.

MARIEapp.h:

```<code>MARIEapp.h{
public:
   typedef void (MARIEapp::*Instruction)();
private:
   static std::map<char, Instruction> MARIEinstruction;
   void JnS();
   void Load();
   void Store();
   void Add();
   void Subt();
   void Input();
   void Output();
   void Halt();
   void Skipcond();
   void Jump();
   void Clear();
   void AddI();
   void JumpI();
   void LoadI();
   void StoreI();
};
</code>```

MARIEapp.cpp:

```<code>static std::map<char, MARIEapp::Instruction> MARIEinstruction = {
    { '0', &MARIEapp::JnS },
    { '1', &MARIEapp::Load },
    { '2', &MARIEapp::Store },
    { '3', &MARIEapp::Add },
    { '4', &MARIEapp::Subt },
    { '5', &MARIEapp::Input },
    { '6', &MARIEapp::Output },
    { '7', &MARIEapp::Halt },
    { '8', &MARIEapp::Skipcond },
    { '9', &MARIEapp::Jump },
    { 'A', &MARIEapp::Clear },
    { 'B', &MARIEapp::AddI },
    { 'C', &MARIEapp::JumpI },
    { 'D', &MARIEapp::LoadI },
    { 'E', &MARIEapp::StoreI }
};
</code>```

The long list of void functions access private members and are properly defined in the cpp file

The problem is that, when initializing the MARIEinstruction map, I get an error that says that those functions are not accessible. I know it's because they're private, and I can fix this by just making them public.

Is there a way I can do this and leave these all as private?
Also are there any other ways you recommend I do this?

答:
Don't worry, you're allowed to name private members from inside the initializer of a static class member, just like from inside the definition of a member function.

Your trouble here is that you're not defining the static class member.  You're defining an unrelated global object named MARIEinstruction.  To define the class member, you must use the class member access syntax MARIEapp::MARIEinstruction.  Also, don't put the static keyword on the definition, just on the declaration.

```<code>std::map<char, MARIEapp::Instruction> MARIEapp::MARIEinstruction = {
    { '0', &MARIEapp::JnS },
    { '1', &MARIEapp::Load },
    { '2', &MARIEapp::Store },
    { '3', &MARIEapp::Add },
    { '4', &MARIEapp::Subt },
    { '5', &MARIEapp::Input },
    { '6', &MARIEapp::Output },
    { '7', &MARIEapp::Halt },
    { '8', &MARIEapp::Skipcond },
    { '9', &MARIEapp::Jump },
    { 'A', &MARIEapp::Clear },
    { 'B', &MARIEapp::AddI },
    { 'C', &MARIEapp::JumpI },
    { 'D', &MARIEapp::LoadI },
    { 'E', &MARIEapp::StoreI }
};
</code>```

Body:
I'm trying to make a MARIE code simulator, or whatever you would call it, and I'm trying to avoid a long switch case to access some private functions in the class.

MARIEapp.h:

MARIEapp.h{
public:
   typedef void (MARIEapp::*Instruction)();
private:
   static std::map<char, Instruction> MARIEinstruction;
   void JnS();
   void Load();
   void Store();
   void Add();
   void Subt();
   void Input();
   void Output();
   void Halt();
   void Skipcond();
   void Jump();
   void Clear();
   void AddI();
   void JumpI();
   void LoadI();
   void StoreI();
};

MARIEapp.cpp:

static std::map<char, MARIEapp::Instruction> MARIEinstruction = {
    { '0', &MARIEapp::JnS },
    { '1', &MARIEapp::Load },
    { '2', &MARIEapp::Store },
    { '3', &MARIEapp::Add },
    { '4', &MARIEapp::Subt },
    { '5', &MARIEapp::Input },
    { '6', &MARIEapp::Output },
    { '7', &MARIEapp::Halt },
    { '8', &MARIEapp::Skipcond },
    { '9', &MARIEapp::Jump },
    { 'A', &MARIEapp::Clear },
    { 'B', &MARIEapp::AddI },
    { 'C', &MARIEapp::JumpI },
    { 'D', &MARIEapp::LoadI },
    { 'E', &MARIEapp::StoreI }
};

The long list of void functions access private members and are properly defined in the cpp file

The problem is that, when initializing the MARIEinstruction map, I get an error that says that those functions are not accessible. I know it's because they're private, and I can fix this by just making them public.

Is there a way I can do this and leave these all as private?
Also are there any other ways you recommend I do this?

Body:
Don't worry, you're allowed to name private members from inside the initializer of a static class member, just like from inside the definition of a member function.

Your trouble here is that you're not defining the static class member.  You're defining an unrelated global object named MARIEinstruction.  To define the class member, you must use the class member access syntax MARIEapp::MARIEinstruction.  Also, don't put the static keyword on the definition, just on the declaration.

std::map<char, MARIEapp::Instruction> MARIEapp::MARIEinstruction = {
    { '0', &MARIEapp::JnS },
    { '1', &MARIEapp::Load },
    { '2', &MARIEapp::Store },
    { '3', &MARIEapp::Add },
    { '4', &MARIEapp::Subt },
    { '5', &MARIEapp::Input },
    { '6', &MARIEapp::Output },
    { '7', &MARIEapp::Halt },
    { '8', &MARIEapp::Skipcond },
    { '9', &MARIEapp::Jump },
    { 'A', &MARIEapp::Clear },
    { 'B', &MARIEapp::AddI },
    { 'C', &MARIEapp::JumpI },
    { 'D', &MARIEapp::LoadI },
    { 'E', &MARIEapp::StoreI }
};


问:
Making a visual grid on a Frame in tkinter
I'm tring to create 3 Frames (right, center, left) in the root in tkinter 8.6
and then making a visual grid ( using "-") in each frame. I get the following error message when I try to make the grid on the first panel.

TypeError: grid_configure() takes at least 1 argument (0 given).

Here is my code:

```<code>from tkinter import *

root = Tk()
root.geometry("1366x768")

frame_right = Frame(root,width = 1366/4,height = 768bg = "powder blue")
frame_right.pack(side = LEFT)

frame_center = Frame(root,width = 1366/2,height = 768,bg = "red")
frame_center.pack(side = LEFT)

frame_left = Frame(root,width = 1366/4,height = 768,bg = "steel blue")
frame_center.pack(side = LEFT)

for i in range(0,10):
    for j in range(0,20):

        Label(frame_left,text = "-",width = 10,height = 1)
        Label.grid(row = i,column = j)

root.mainloop()
</code>```

答:
I have something similar I use in my code to add visible spacing on my main row and column.

I don't think you need to define height because the text will do that for you.

You might want to try using something like this.

```<code>for col_num in range(20):
    spacer=Label(root, text=str(col_num))
        #replace root with your frame
        #you can replace str(col_num) with your "-"
    spacer.grid(row = 0, column = col_num)
    root.columnconfigure(col_num, minsize=10)
for row_num in range(10):
    spacer=Label(root, text=str(row_num)) #replace root with your frame
    spacer.grid(row = row_num, column = 0)
    root.rowconfigure(row_num, minsize=10)
</code>```

Body:
I'm tring to create 3 Frames (right, center, left) in the root in tkinter 8.6
and then making a visual grid ( using "-") in each frame. I get the following error message when I try to make the grid on the first panel.

TypeError: grid_configure() takes at least 1 argument (0 given).

Here is my code:

from tkinter import *

root = Tk()
root.geometry("1366x768")

frame_right = Frame(root,width = 1366/4,height = 768bg = "powder blue")
frame_right.pack(side = LEFT)

frame_center = Frame(root,width = 1366/2,height = 768,bg = "red")
frame_center.pack(side = LEFT)

frame_left = Frame(root,width = 1366/4,height = 768,bg = "steel blue")
frame_center.pack(side = LEFT)

for i in range(0,10):
    for j in range(0,20):

        Label(frame_left,text = "-",width = 10,height = 1)
        Label.grid(row = i,column = j)

root.mainloop()

Body:
I have something similar I use in my code to add visible spacing on my main row and column.

I don't think you need to define height because the text will do that for you.

You might want to try using something like this.

for col_num in range(20):
    spacer=Label(root, text=str(col_num))
        #replace root with your frame
        #you can replace str(col_num) with your "-"
    spacer.grid(row = 0, column = col_num)
    root.columnconfigure(col_num, minsize=10)
for row_num in range(10):
    spacer=Label(root, text=str(row_num)) #replace root with your frame
    spacer.grid(row = row_num, column = 0)
    root.rowconfigure(row_num, minsize=10)


问:
jQuery - function inside $(document).ready function
Is it correct to create functions inside of

```<code>$(document).ready(function() {
</code>```

like so:

```<code>$(document).ready(function() {
     function callMe() {

     }
 });
</code>```

The function inside of the .ready() does not have to call before DOM is ready and event inside of the ready() is triggered.

Just to clarify a little bit - here's the code which would illustrate the problem:

```<code>$(function() {
    var ind = 0;

    // some event is executed and changes the value of the ind

    // another event which affects the ind variable

    // and another one - after this event we call our function

    // there's another event - and we call our function again
</code>```

The function which I need to call needs the updated value of the ind variable - which I guess I could pass as a parameter, but is there a better way of doing it?

Also - another important thing is that the function() in question can also change the value of the ind variable - for instance incrementing it (ind++).

答: See if you can eliminate the need for using document.ready by moving your  tag to the bottom of the html file. This should make things alot simpler. Otherwise, declare the function outside the scope of the document.ready and just call it in the document.ready function scope.</p>

ContentLicense: CC BY-SA 4.0

Body:
Is it correct to create functions inside of

$(document).ready(function() {

like so:

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

     }
 });

The function inside of the .ready() does not have to call before DOM is ready and event inside of the ready() is triggered.

Just to clarify a little bit - here's the code which would illustrate the problem:

$(function() {
    var ind = 0;

    // some event is executed and changes the value of the ind

    // another event which affects the ind variable

    // and another one - after this event we call our function

    // there's another event - and we call our function again

The function which I need to call needs the updated value of the ind variable - which I guess I could pass as a parameter, but is there a better way of doing it?

Also - another important thing is that the function() in question can also change the value of the ind variable - for instance incrementing it (ind++).


问:
Can't create indexed view with schemabinding
I'm trying to script a pretty straight-forward indexed view but SQL is simply refusing my efforts. I've tried researching the issue but haven't had any luck, and unfortunately I'm not exactly a SQL expert so I'm not sure if there's something simple that I'm missing. The template for this script was handed to me by a DBA, but he doesn't know any more than I do. Here's the top end of the script where the first error appears:

```<code>--Set the options to support indexed views.
SET NUMERIC_ROUNDABORT OFF;
GO
SET ANSI_PADDING, ANSI_WARNINGS, CONCAT_NULL_YIELDS_NULL, ARITHABORT,
    QUOTED_IDENTIFIER, ANSI_NULLS ON;
GO
--Create view with schemabinding.
IF OBJECT_ID ('[dbo].[APIMenus]', 'view') IS NOT NULL
    DROP VIEW [dbo].[APIMenus] ;
GO
BEGIN
    CREATE VIEW [dbo].[APIMenus]
    WITH SCHEMABINDING
    AS
        SELECT
            [t0].[GroupName] AS [defaultValue],
            [t1].[GroupName] AS [transValue],.....
</code>```

The error is "CREATE VIEW must be the only statement in the batch" but from what I understand, wrapping it in the BEGIN...END with proper GO statements before and after should have solved the problem, yet it persists. Can anyone spot what I'm doing wrong?

答:
The error is accurate. Wrapping a CREATE VIEW in BEGIN/END does not work to avoid this message.  If you remove the BEGIN/END entirely, so the batch starts with CREATE VIEW and ends with another GO after the view is defined, then the error will be gone, and you can continue to use this DROP before CREATE structure.

A slightly different way to handle this problem of not creating a view that already exists, is to invoke dynamic SQL:

```<code>if OBJECT_ID ('[dbo].[cars]', 'view') IS NOT NULL
    exec ('create view cars as select * from vans where type=1')
go
</code>```

Sometimes I have seen this:

```<code>if OBJECT_ID ('[dbo].[cars]', 'view') IS NOT NULL
    exec ('create view cars as select 1')
go
alter view cars as
    select * from vans where type==1
GO
</code>```

This latter technique has the advantage that your complex SQL is not embedded in a string, and you can format it nicely.

Body:
I'm trying to script a pretty straight-forward indexed view but SQL is simply refusing my efforts. I've tried researching the issue but haven't had any luck, and unfortunately I'm not exactly a SQL expert so I'm not sure if there's something simple that I'm missing. The template for this script was handed to me by a DBA, but he doesn't know any more than I do. Here's the top end of the script where the first error appears:

--Set the options to support indexed views.
SET NUMERIC_ROUNDABORT OFF;
GO
SET ANSI_PADDING, ANSI_WARNINGS, CONCAT_NULL_YIELDS_NULL, ARITHABORT,
    QUOTED_IDENTIFIER, ANSI_NULLS ON;
GO
--Create view with schemabinding.
IF OBJECT_ID ('[dbo].[APIMenus]', 'view') IS NOT NULL
    DROP VIEW [dbo].[APIMenus] ;
GO
BEGIN
    CREATE VIEW [dbo].[APIMenus]
    WITH SCHEMABINDING
    AS
        SELECT
            [t0].[GroupName] AS [defaultValue],
            [t1].[GroupName] AS [transValue],.....

The error is "CREATE VIEW must be the only statement in the batch" but from what I understand, wrapping it in the BEGIN...END with proper GO statements before and after should have solved the problem, yet it persists. Can anyone spot what I'm doing wrong?

Body:
The error is accurate. Wrapping a CREATE VIEW in BEGIN/END does not work to avoid this message.  If you remove the BEGIN/END entirely, so the batch starts with CREATE VIEW and ends with another GO after the view is defined, then the error will be gone, and you can continue to use this DROP before CREATE structure.

A slightly different way to handle this problem of not creating a view that already exists, is to invoke dynamic SQL:

if OBJECT_ID ('[dbo].[cars]', 'view') IS NOT NULL
    exec ('create view cars as select * from vans where type=1')
go

Sometimes I have seen this:

if OBJECT_ID ('[dbo].[cars]', 'view') IS NOT NULL
    exec ('create view cars as select 1')
go
alter view cars as
    select * from vans where type==1
GO

This latter technique has the advantage that your complex SQL is not embedded in a string, and you can format it nicely.


问:
Have public channels visible to all non admin users and forbid user from creating channels
How can I have the existing public channels visible to all users ?

How can I forbid users (non admin) from creating channels ?

Version: 0.49.0

答:
The way I handled this was to create two main channels (Lobby and Announcements) for all of my employees.

I then used the REST API to add all users to those two channels. This won't prevent them from leaving the channels, but you could simply call the API every so often to add people back in that left (or new users, if setting the Default channel to True under Rooms in Administration doesn't seem to be working).

Here's the steps to do this, using curl:

Get your authentication Token and UserId [1]

Use your Token and Id from step 1 to get the full channel list [2]

Take the desired roomId from step 2 and (as well as using your Token and Id from step 1) use the addAll API [3] to add literally all users to the channel.

For the second one, you can use the Permissions [4] tab under Administration, it is "create-c" for public or "create-p" for private.

I can't post more than two links, so..

[1] httpx://rocket.chat/docs/developer-guides/rest-api/authentication/login

[2] httpx://rocket.chat/docs/developer-guides/rest-api/channels/list

[3] https://rocket.chat/docs/developer-guides/rest-api/channels/addall

[4] https://rocket.chat/docs/administrator-guides/permissions/


问:
Sending FCM message from client not working
Note: I am well aware of the dangers of exposing my API Key. This is a personal app.

I'm using this:

```<code>String urlString = "https://fcm.googleapis.com/fcm/send";
        JSONObject jsonObjects = new JSONObject();
        try {
            jsonObjects.put("title", titleET.getText().toString());
            jsonObjects.put("body", textET.getText().toString());
            jsonObjects.put("to","/topics/subscribed");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        RequestBody body = RequestBody.create(JSON, jsonObjects.toString());
        Request req = new Request.Builder()
                .url(urlString)
                .post(body)
                .addHeader("Authorization","key=AAAA0lrtzQs:APA91bHiergBa6_A5KEVlV00LiovITBwnkZfgoGEUx-Ofg4hnk48A_nEyTwwpyriOOHHM96ZkDiUeUgpPOApSS4zaivtRKxP4dQjdwH7CFROR5l51ZA85jaFgMa5VmSsu8_yqUb4kc1U")
                .build();
        try {
            Response res = client.newCall(req).execute();
            if (!res.isSuccessful()) {
                throw new UnknownError("Error: " + res.code() + " " + res.body().string());
            }
            Log.d("MainActivity", res.body().toString());
        } catch (IOException e) {
            send();
        }
</code>```

And nothing is being sent.

If I use the Firebase Console everything is working fine. When I do this request nothing even shows up in the console.
What am I missing?

答:
One problem is that you are not building the JSON for a notification correctly.  It should be:

```<code>    JSONObject notif = new JSONObject();
    JSONObject jsonObjects = new JSONObject();
    try {
        notif.put("title", titleET.getText().toString());
        notif.put("body", textET.getText().toString());
        jsonObjects.put("notification", notif);
        jsonObjects.put("to","/topics/subscribed");
    } catch (JSONException e) {
        e.printStackTrace();
    }
</code>```

That won't cause the message to not be sent, but may muddle your expected results.

I was able to copy your code, fill in the missing pieces, and successfully send and receive a message to a topic.

The "missing pieces" I added:

```<code>    final OkHttpClient client = new OkHttpClient();
    final MediaType JSON = MediaType.parse("application/json");
</code>```

For authorization key, I used the "Server key" shown in the Cloud Messaging tab of the Firebase console settings for my project.

Body:
Note: I am well aware of the dangers of exposing my API Key. This is a personal app.

I'm using this:

String urlString = "https://fcm.googleapis.com/fcm/send";
        JSONObject jsonObjects = new JSONObject();
        try {
            jsonObjects.put("title", titleET.getText().toString());
            jsonObjects.put("body", textET.getText().toString());
            jsonObjects.put("to","/topics/subscribed");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        RequestBody body = RequestBody.create(JSON, jsonObjects.toString());
        Request req = new Request.Builder()
                .url(urlString)
                .post(body)
                .addHeader("Authorization","key=AAAA0lrtzQs:APA91bHiergBa6_A5KEVlV00LiovITBwnkZfgoGEUx-Ofg4hnk48A_nEyTwwpyriOOHHM96ZkDiUeUgpPOApSS4zaivtRKxP4dQjdwH7CFROR5l51ZA85jaFgMa5VmSsu8_yqUb4kc1U")
                .build();
        try {
            Response res = client.newCall(req).execute();
            if (!res.isSuccessful()) {
                throw new UnknownError("Error: " + res.code() + " " + res.body().string());
            }
            Log.d("MainActivity", res.body().toString());
        } catch (IOException e) {
            send();
        }

And nothing is being sent.

If I use the Firebase Console everything is working fine. When I do this request nothing even shows up in the console.
What am I missing?

Body:
One problem is that you are not building the JSON for a notification correctly.  It should be:

    JSONObject notif = new JSONObject();
    JSONObject jsonObjects = new JSONObject();
    try {
        notif.put("title", titleET.getText().toString());
        notif.put("body", textET.getText().toString());
        jsonObjects.put("notification", notif);
        jsonObjects.put("to","/topics/subscribed");
    } catch (JSONException e) {
        e.printStackTrace();
    }

That won't cause the message to not be sent, but may muddle your expected results.

I was able to copy your code, fill in the missing pieces, and successfully send and receive a message to a topic.

The "missing pieces" I added:

    final OkHttpClient client = new OkHttpClient();
    final MediaType JSON = MediaType.parse("application/json");

For authorization key, I used the "Server key" shown in the Cloud Messaging tab of the Firebase console settings for my project.


问:
Meteor iron router auto reload page
I have site on meteor, with iron router as router.
Site is generated by Meteor-kitchen with my templates editing.

It works good, but if i go some way directly, not from link on the site.

For example http://hitzroad.ru/login, some time it begins reload page unstoppable.

This problem causes only on remote vpn server, on my local machine, when i develop it, theres is no problems with page reloading.

And i don't understand how to diagnose these problem.

Has anyone ideas about it?

答: Do you have any errors in browser console or at server? BTW, I just opened your site and there is error (you wrote "slick" instead "click" somewhere in the code), but I don't think this "slick" makes your site to hang...</p>

Title: Meteor iron router auto reload page


问:
Spring Boot JOOQ sql dialect not picked up from application.properties
Background: i am hosting the trial version of jooq 3.9.1 (proprietary eg oracle db compatible) in my nexus repository - all the dependencies in my pom relating to jooq point to that.

i have this line in my application.properties

```<code>jooq.sql-dialect=ORACLE
</code>```

but when i inspect the injected dslContext the dialect is set to "DEFAULT" and not ORACLE as expected/desired.

I am currently getting round it by autowiring the datasource rather than the dslcontext and then setting the sql dialect (as shown below) - but wondering why autowiring the dslcontext directly doesnt work as expected

```<code>@Autowired
private DataSourceConnectionProvider dataSource;

public static final SQLDialect sqlDialect = SQLDialect.ORACLE;

public DSLContext getDSL(){
    return DSL.using(dataSource, sqlDialect);
}
</code>```

答:
Spring Boot by default uses the org.jooq dependency, which is the Maven groupId for the jOOQ Open Source Edition:

<dependency>
    <groupId>org.jooq</groupId>
    <artifactId>jooq</artifactId>
</dependency>
```

<p>However, the Oracle <code>SQLDialect</code> is contained only in the commercial distributions of jOOQ, which are available under different <code>groupId</code> (and not from Maven Central but from here (trial) and here (express, professional, enterprise edition)):</p>

<pre class="lang-xml prettyprint-override"><code><groupId>org.jooq.pro</groupId>        <!-- for commercial editions -->
<groupId>org.jooq.pro-java-6</groupId> <!-- for commercial editions with Java 6 support -->
<groupId>org.jooq.trial</groupId>      <!-- for the free trial edition -->
</code>```

The distributions are almost completely binary compatible, so you should be able to simply replace the <groupId> in your own pom.xml for Spring Boot to work with jOOQ and Oracle.

Body:
Background: i am hosting the trial version of jooq 3.9.1 (proprietary eg oracle db compatible) in my nexus repository - all the dependencies in my pom relating to jooq point to that.

i have this line in my application.properties

jooq.sql-dialect=ORACLE

but when i inspect the injected dslContext the dialect is set to "DEFAULT" and not ORACLE as expected/desired.

I am currently getting round it by autowiring the datasource rather than the dslcontext and then setting the sql dialect (as shown below) - but wondering why autowiring the dslcontext directly doesnt work as expected

@Autowired
private DataSourceConnectionProvider dataSource;

public static final SQLDialect sqlDialect = SQLDialect.ORACLE;

public DSLContext getDSL(){
    return DSL.using(dataSource, sqlDialect);
}

Body:
Spring Boot by default uses the org.jooq dependency, which is the Maven groupId for the jOOQ Open Source Edition:

<dependency>
    <groupId>org.jooq</groupId>
    <artifactId>jooq</artifactId>
</dependency>

However, the Oracle SQLDialect is contained only in the commercial distributions of jOOQ, which are available under different groupId (and not from Maven Central but from here (trial) and here (express, professional, enterprise edition)):

<groupId>org.jooq.pro</groupId>        <!-- for commercial editions -->
<groupId>org.jooq.pro-java-6</groupId> <!-- for commercial editions with Java 6 support -->
<groupId>org.jooq.trial</groupId>      <!-- for the free trial edition -->

The distributions are almost completely binary compatible, so you should be able to simply replace the <groupId> in your own pom.xml for Spring Boot to work with jOOQ and Oracle.


问:
Remove sql table after x days
I am looking for a way for my system made in C ++ to remove old sqls tables after 90 days, I searched but did not find anything related.

The names of my tables are generated according to the days, for example 20170323

Now the way to remove I can not think of anything that can be done

答:
Assuming those SQL tables live in a DBMS rather than your own software system - don't bother taking that task into your own code. Use system facilities such as cron and write an appropriate few-line script (e.g. in bash, python or perl) to check for old tables and issue the command to delete them. This is not the kind of task you should bother yourself to custom-code.

and I say this as a Modern C++ enthusiast :-)

Edit: On second thought - why do you even have per-day tables? I think that's almost certainly a mis-design. That all probably needs to be in the same table, with an extra date column - and possibly some partitioning, or columnar storage, etc.

Title: Remove sql table after x days


问:
Getting ERR_INCOMPLETE_CHUNKED_ENCODING on server when Django APIView is used
We are using

Django

rest_framework

gunicorn

Postgres

nginx

Everything is working locally. But on server, when I hit request from Chrome then I got ERR_INCOMPLETE_CHUNKED_ENCODING error and when I did curl then response was

```<code>curl: (18) transfer closed with outstanding read data remaining
</code>```

Even when I restart gunicorn then I immediately get the response for 1st request but then it hangs somewhere and further requests do not work.
I am returning a blank array in response to test which is not working so response length is not the concern.

In Django, I am inheriting MyView class from APIView(from rest_framework.views import APIView). When I changed APIView to View(from django.views import View) everything started working fine on server. Not sure what is causing issue? Is it APIView library or gunicorn.
I tried gunicorn locally and it works.

答:
I added </p>

```<code>'django.middleware.http.ConditionalGetMiddleware'
</code>```

<p>in MIDDLEWARE_CLASSES in settings.py and it started working.
This class adds the Content-Length header in the response. </p>

Body:
We are using

Django

rest_framework

gunicorn

Postgres

nginx

Everything is working locally. But on server, when I hit request from Chrome then I got ERR_INCOMPLETE_CHUNKED_ENCODING error and when I did curl then response was

curl: (18) transfer closed with outstanding read data remaining

Even when I restart gunicorn then I immediately get the response for 1st request but then it hangs somewhere and further requests do not work.
I am returning a blank array in response to test which is not working so response length is not the concern.

In Django, I am inheriting MyView class from APIView(from rest_framework.views import APIView). When I changed APIView to View(from django.views import View) everything started working fine on server. Not sure what is causing issue? Is it APIView library or gunicorn.
I tried gunicorn locally and it works.

Body:
I added

'django.middleware.http.ConditionalGetMiddleware'

in MIDDLEWARE_CLASSES in settings.py and it started working.
This class adds the Content-Length header in the response.