问:
Python 3: Generate byte stream using 'with'
What I'd like to do is generate a byte stream of arbitrary length. The reason for this, is because I need to essentially generate a file of arbitrary size. (For some background, I tried to stream a sparse file but had trouble when the file sizes were large, so instead I'm trying to generate the bytes on the fly instead.)

I've been reading the documentation to make objects work with with, and I'm struggling to make this correctly. Here's what I've been attempting after trial and error, but still doesn't work. I think I'm missing something, but I honestly don't know what.

```<code>class BinaryGenerator:
    def __init__(self, size_in_mbs):
        self.size_in_mbs = size_in_mbs

    def __enter__(self):
        yield self.__bytes_generator__(self.size_in_mbs)
        pass

    def __exit__(self, exc_type, exc_val, exc_tb):
        pass

    @staticmethod
    def __bytes_generator__(mega_bytes):
        for i in range(mega_bytes * 1024):
            yield b'\x00'

def __write_size__(size):
    with open('arbitrary-{}mb.bin'.format(size), 'wb') as file:
        with BinaryGenerator(size) as binary:
            file.write(binary)

if __name__ == '__main__':
    __write_size__(1)
</code>```

I'll actually use this with Requests Streaming Uploads but I'm trying to use this as a test to see if I can replicate the binary stream of data you get when you open a file using with

答:
For the record

a context manager is used, when you have an object that has an initialization and a cleanup function. In the example, it is used with a file object. Since file objects implement the context manager protocol, exiting the with block with a file handle will automatically close the file.

with open('arbitrary-{}mb.bin'.format(size), 'wb') as fd: ...

a generator is a function that (programmatically) generates iterable results. One can think of it as a function that returns multiple times.

As for your problem: You can use a generator to implement result streaming, this is basically what they are for:

```<code>def bytes_generator(mega_bytes):
    for i in range(mega_bytes * 1024):
        yield b'\x00'

def write_size(size):
    with open('arbitrary-{}mb.bin'.format(size), 'wb') as fd:
         for b in bytes_generator(size):
              fd.write(b)
</code>```

This is woefully inefficient, though, since it writes a single byte at a time. But to fix it, you only need to modify the chunking from the generator.

Requests explicitly allow for chunked uploads via generators.

```<code>def gen():
    yield 'hi'
    yield 'there'

requests.post('http://some.url/chunked', data=gen())
</code>```

Body:
What I'd like to do is generate a byte stream of arbitrary length. The reason for this, is because I need to essentially generate a file of arbitrary size. (For some background, I tried to stream a sparse file but had trouble when the file sizes were large, so instead I'm trying to generate the bytes on the fly instead.)

I've been reading the documentation to make objects work with with, and I'm struggling to make this correctly. Here's what I've been attempting after trial and error, but still doesn't work. I think I'm missing something, but I honestly don't know what.

class BinaryGenerator:
    def __init__(self, size_in_mbs):
        self.size_in_mbs = size_in_mbs

    def __enter__(self):
        yield self.__bytes_generator__(self.size_in_mbs)
        pass

    def __exit__(self, exc_type, exc_val, exc_tb):
        pass

    @staticmethod
    def __bytes_generator__(mega_bytes):
        for i in range(mega_bytes * 1024):
            yield b'\x00'

def __write_size__(size):
    with open('arbitrary-{}mb.bin'.format(size), 'wb') as file:
        with BinaryGenerator(size) as binary:
            file.write(binary)

if __name__ == '__main__':
    __write_size__(1)

I'll actually use this with Requests Streaming Uploads but I'm trying to use this as a test to see if I can replicate the binary stream of data you get when you open a file using with

Body:
For the record

a context manager is used, when you have an object that has an initialization and a cleanup function. In the example, it is used with a file object. Since file objects implement the context manager protocol, exiting the with block with a file handle will automatically close the file.

with open('arbitrary-{}mb.bin'.format(size), 'wb') as fd: ...

a generator is a function that (programmatically) generates iterable results. One can think of it as a function that returns multiple times.

As for your problem: You can use a generator to implement result streaming, this is basically what they are for:

def bytes_generator(mega_bytes):
    for i in range(mega_bytes * 1024):
        yield b'\x00'

def write_size(size):
    with open('arbitrary-{}mb.bin'.format(size), 'wb') as fd:
         for b in bytes_generator(size):
              fd.write(b)

This is woefully inefficient, though, since it writes a single byte at a time. But to fix it, you only need to modify the chunking from the generator.

Requests explicitly allow for chunked uploads via generators.

def gen():
    yield 'hi'
    yield 'there'

requests.post('http://some.url/chunked', data=gen())


来源: stackexchange

问:
React Native async (firebase) image fetch in ScrollView / FlatList / SectionList
I have a SectionList with a lot of images that is being fetched from a firebase storage. When scrolling down it rapidly builds up a lot of warnings.

The WebImage component looks like this:

```<code>import React, { Component } from 'react'
import { View, Image } from 'react-native'
import firebase from 'firebase'

class WebImage extends Component {
  state = {
    imgsrc: '',
    mounted: false,
  }

  componentDidMount() {
    this.setState({ mounted: true })

    firebase
      .storage()
      .ref()
      .child(this.props.source)
      .getDownloadURL()
      .then(url => {
        if (this.state.mounted) {
          this.setState({ imgsrc: url })
        }
      })
  }

  componentWillUnmount() {
    this.setState({ mounted: false })
  }

  render() {
    ...
  }
}

export default WebImage
</code>```

As you can see I tried to make it aware of the mounting state, but it haven't worked as expected..

答:
The following seems to work:

```<code>  state = {
    imgsrc: '',
  }

  componentDidMount() {
    this.ref = firebase
      .storage()
      .ref()
      .child(this.props.source)
      .getDownloadURL()
      .then(url => {
        this.setState({ imgsrc: url })
      })
  }

  componentWillUnmount() {
    this.ref.cancel()
  }
</code>```

Read latest on Async React and changed  my answer from componentWillMount to componentDidMount.

There is a common misconception that fetching in componentWillMount lets you avoid the first empty rendering state. In practice this was never true because React has always executed render immediately after componentWillMount. If the data is not available by the time componentWillMount fires, the first render will still show a loading state regardless of where you initiate the fetch. This is why moving the fetch to componentDidMount has no perceptible effect in the vast majority of cases.

ContentLicense: CC BY-SA 3.0

Body:
I have a SectionList with a lot of images that is being fetched from a firebase storage. When scrolling down it rapidly builds up a lot of warnings.

The WebImage component looks like this:

import React, { Component } from 'react'
import { View, Image } from 'react-native'
import firebase from 'firebase'

class WebImage extends Component {
  state = {
    imgsrc: '',
    mounted: false,
  }

  componentDidMount() {
    this.setState({ mounted: true })

    firebase
      .storage()
      .ref()
      .child(this.props.source)
      .getDownloadURL()
      .then(url => {
        if (this.state.mounted) {
          this.setState({ imgsrc: url })
        }
      })
  }

  componentWillUnmount() {
    this.setState({ mounted: false })
  }

  render() {
    ...
  }
}

export default WebImage

As you can see I tried to make it aware of the mounting state, but it haven't worked as expected..

Body:
The following seems to work:

  state = {
    imgsrc: '',
  }

  componentDidMount() {
    this.ref = firebase
      .storage()
      .ref()
      .child(this.props.source)
      .getDownloadURL()
      .then(url => {
        this.setState({ imgsrc: url })
      })
  }

  componentWillUnmount() {
    this.ref.cancel()
  }

Read latest on Async React and changed  my answer from componentWillMount to componentDidMount.

There is a common misconception that fetching in componentWillMount lets you avoid the first empty rendering state. In practice this was never true because React has always executed render immediately after componentWillMount. If the data is not available by the time componentWillMount fires, the first render will still show a loading state regardless of where you initiate the fetch. This is why moving the fetch to componentDidMount has no perceptible effect in the vast majority of cases.

ContentLicense: CC BY-SA 4.0


问:
Why is the following onclick function not executing?
I would like to pass four arguments event, $row['title'], $row['username'] and $row['date'].

```<code><?php
echo "<script>
  function increasevotes(e,location,user,date)
  {
    e.preventDefault();
    console.log(\"Hi!\");
  }
  </script>";

//I've proper code here for fetching the mySQL query results into $rows and that part is working perfectly.

while($rows=mysqli_fetch_array($result))
{
if($rows['public']=="yes")
{echo "<span class=\"right\" id=\"nolikes\">{$rows['vote']}</span><a href=\"\" onclick=\"increasevotes(event,\"{$rows['title']}\",\"{$rows['username']}\",\"{$rows['date']}\")\"><img src=\"img/like.png\" class=\"right\" width=\"30\" height=\"30\"/></a>";
}
?>
</code>```

What is actually being done, is the page is being refreshed instead.
When I click view source page, this is shown:

```<code><span class="right" id="nolikes">0</span>
<a href="" onclick="increasevotes(event,"chennai","venkat","01/07/2017")"><img src="img/like.png" class="right" width="30" height="30"/>
</a>
</code>```

答:
Change double quotes of function parameter to single quotes

```<code>onclick="increasevotes(event,'chennai','venkat','01/07/2017')"
</code>```

or use \ to escape the quotes.

Body:
I would like to pass four arguments event, $row['title'], $row['username'] and $row['date'].

<?php
echo "";

//I've proper code here for fetching the mySQL query results into $rows and that part is working perfectly.

while($rows=mysqli_fetch_array($result))
{
if($rows['public']=="yes")
{echo "{$rows['vote']}";
}
?>

What is actually being done, is the page is being refreshed instead.
When I click view source page, this is shown:

0

Body:
Change double quotes of function parameter to single quotes

onclick="increasevotes(event,'chennai','venkat','01/07/2017')"

or use \ to escape the quotes.


问:
Why is the strip() function depleting my mustard?
I'm creating a Hot Dog simulator in python, with a class "HotDog".

When I'm formatting the string, if there are 2 condiments, I wrote this code to add it to the string:

```<code>if len(self.condiments) == 2:
    for i in self.condiments:
        msg = msg + i + " and "
    msg = msg.strip(" and ")
</code>```

If the second condiment is "mustard", the strip() function is taking away the "d" of mustard, so the string prints like this:

```<code>Raw hot dog with ketchup and mustar.
</code>```

I've used trial and error to find more info, and it seems "d" is the only letter that will disappear, i.e.: mustarg and mustarb will be fine.

Also, it seems to be the "a" of msg = msg.strip(" and ") that is causing the problem.

If I only strip "d " or "nd ", mustard will be fine.

答:
The strip method doesn't work the way you seem to expect. Its argument is a sequence of characters that will be removed if they appear in any order (and any number of times) at either end of your string. So when you pass in " and ", you're telling it to strip off all spaces, 'a', 'n' and 'd' characters. Since the 'd' in 'mustard' is one of those characters, it will be stripped if it's at the end.

A better way to remove a specific amount of text from the end of a string would be to slice it: msg = msg[:-5] will remove the last five characters.

Or you can avoid creating the extra " and " in any number of ways, such as using str.format or str.join (or a combination of the two).

Body:
I'm creating a Hot Dog simulator in python, with a class "HotDog".

When I'm formatting the string, if there are 2 condiments, I wrote this code to add it to the string:

if len(self.condiments) == 2:
    for i in self.condiments:
        msg = msg + i + " and "
    msg = msg.strip(" and ")

If the second condiment is "mustard", the strip() function is taking away the "d" of mustard, so the string prints like this:

Raw hot dog with ketchup and mustar.

I've used trial and error to find more info, and it seems "d" is the only letter that will disappear, i.e.: mustarg and mustarb will be fine.

Also, it seems to be the "a" of msg = msg.strip(" and ") that is causing the problem.

If I only strip "d " or "nd ", mustard will be fine.


问:
Conditionally overriding Ext JS/Sencha Chart framework
I am new to Ext JS and Sencha charts. For our application we have multiple charts, one of the chart I need to hide the dashes on X - Axis. We are using Ext JS version 5.1, where I could not find dashSize property. After some digging in the framework, I did an empty override like below

```<code>Ext.define('Ext.overrides.chart.axis.sprite.Axis', {
override: 'Ext.chart.axis.sprite.Axis',

renderTicks: function (surface, ctx, layout, clipRect) {
}});
</code>```

This works like a charm for my requirement, but applies to all charts in the application, how do I make a conditional override so I would need something like this, but not quite sure how to pass the configuration to the framework

```<code>Ext.define('Ext.overrides.chart.axis.sprite.Axis', {
override: 'Ext.chart.axis.sprite.Axis',

renderTicks: function (surface, ctx, layout, clipRect) {
   if(condition)
      //empty
   else
      this.superclass.renderTicks.call();
}});
</code>```

Kindly help. Let me know if I need to provide more details...

答:
If you don't need your bottom axis at all, you can just simply set:

```<code>axes: [{
    type: 'category',
    position: 'bottom',
    fields: 'name',
    hidden: true // this will hide the axis
}]
</code>```

If this is not a good option, and your override works for you, you could simply add an additional config to the axis to use it as a conditional, like this:

```<code>axes: [{
    type: 'category',
    position: 'bottom',
    fields: 'name',
    hideMajorTicks: true // custom config
}]

Ext.define('Ext.overrides.chart.axis.sprite.Axis', {
    override: 'Ext.chart.axis.sprite.Axis',

    renderTicks: function (surface, ctx, layout, clipRect) {
        var axis = layout.segmenter && layout.segmenter.getAxis();

        if (axis && axis.hideMajorTicks) return;

        this.callParent([surface, ctx, layout, clipRect]);
    }
});
</code>```

Body:
I am new to Ext JS and Sencha charts. For our application we have multiple charts, one of the chart I need to hide the dashes on X - Axis. We are using Ext JS version 5.1, where I could not find dashSize property. After some digging in the framework, I did an empty override like below

Ext.define('Ext.overrides.chart.axis.sprite.Axis', {
override: 'Ext.chart.axis.sprite.Axis',

renderTicks: function (surface, ctx, layout, clipRect) {
}});

This works like a charm for my requirement, but applies to all charts in the application, how do I make a conditional override so I would need something like this, but not quite sure how to pass the configuration to the framework

Ext.define('Ext.overrides.chart.axis.sprite.Axis', {
override: 'Ext.chart.axis.sprite.Axis',

renderTicks: function (surface, ctx, layout, clipRect) {
   if(condition)
      //empty
   else
      this.superclass.renderTicks.call();
}});

Kindly help. Let me know if I need to provide more details...

Body:
If you don't need your bottom axis at all, you can just simply set:

axes: [{
    type: 'category',
    position: 'bottom',
    fields: 'name',
    hidden: true // this will hide the axis
}]

If this is not a good option, and your override works for you, you could simply add an additional config to the axis to use it as a conditional, like this:

axes: [{
    type: 'category',
    position: 'bottom',
    fields: 'name',
    hideMajorTicks: true // custom config
}]

Ext.define('Ext.overrides.chart.axis.sprite.Axis', {
    override: 'Ext.chart.axis.sprite.Axis',

    renderTicks: function (surface, ctx, layout, clipRect) {
        var axis = layout.segmenter && layout.segmenter.getAxis();

        if (axis && axis.hideMajorTicks) return;

        this.callParent([surface, ctx, layout, clipRect]);
    }
});


问:
How to close Files.write
I am to attempting to create directory and write data into that file. I am trying to use java nio to write file for more efficiently. My doubt is how to close it after write it below is my code. Please advice me.

And is this correct way to create directory and write large data files [200 kb].

```<code>    java.nio.file.Path path = java.nio.file.Paths.get(filePath);

    try {
        if (!java.nio.file.Files.exists(path)) {
            java.nio.file.Files.createDirectories(path.getParent());
            path = java.nio.file.Files.createFile(path);
            path = java.nio.file.Files.write(path, data.getBytes());
        } else {
            java.nio.file.Files.write(path, data.getBytes("utf-8"),
                    java.nio.file.StandardOpenOption.CREATE, java.nio.file.StandardOpenOption.TRUNCATE_EXISTING);
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
    }
</code>```

答:
If you are using JDK 1.7 onwards, use try-with-resource it will automatically take care of closing of the resource. Eg. try(initialize your file resource here){}
Read more about try-with-resource here

Title: How to close Files.write

Body:
I am to attempting to create directory and write data into that file. I am trying to use java nio to write file for more efficiently. My doubt is how to close it after write it below is my code. Please advice me.

And is this correct way to create directory and write large data files [200 kb].

    java.nio.file.Path path = java.nio.file.Paths.get(filePath);

    try {
        if (!java.nio.file.Files.exists(path)) {
            java.nio.file.Files.createDirectories(path.getParent());
            path = java.nio.file.Files.createFile(path);
            path = java.nio.file.Files.write(path, data.getBytes());
        } else {
            java.nio.file.Files.write(path, data.getBytes("utf-8"),
                    java.nio.file.StandardOpenOption.CREATE, java.nio.file.StandardOpenOption.TRUNCATE_EXISTING);
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
    }


问:
Nginx SSL issue - specific port
I migrated to Nginx, but i cannot find the solution for my problem.
On apache, I had 1 virutal host with ssl and specific port.

The apache config seems like this:

```<code><VirtualHost *:443>
    ServerAdmin info@example.com
    ServerName example.in
    DocumentRoot /paht/to/web/files

    SSLEngine on
    SSLCertificateFile /ssl/certificate
    SSLCertificateKeyFile /ssl/key_file
    SSLCACertificateFile /ssl/ca.cer

</VirtualHost>

# intermediate configuration, tweak to your needs
SSLProtocol             all -SSLv2 -SSLv3
SSLCipherSuite          ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES256-GCM-SHA384:DHE-RSA-AES128-GCM-SHA256:DHE-DSS-AES128-GCM-SHA256:kEDH+AESGCM:ECDHE-RSA-AES128-SHA256:ECDHE-ECD$
SSLHonorCipherOrder     on

<Directory /path/to/my/web>
  Options FollowSymLinks Includes ExecCGI
  AllowOverride All
  Order allow,deny
  Allow from all
  Require all granted
</Directory>

<VirtualHost *:9092>
    ServerAdmin info@example.com
    ServerName example.in
    DocumentRoot /paht/to/web/files

    DocumentRoot /another/path/to/api

    SSLEngine on
    SSLCertificateFile /path/to/webcer
    SSLCertificateKeyFile /path/to/webkey
    SSLCACertificateFile /path/to/ca.cer

       <Directory /another/path/to/api>
           Options Indexes FollowSymLinks MultiViews ExecCGI
           AllowOverride All
           Require all granted
        </Directory>

        ErrorLog ${APACHE_LOG_DIR}/api_cable_error.log
        CustomLog ${APACHE_LOG_DIR}/api_cable_access.log combined
</code>```

When I openend https://example.in:9092, it worked without any troubles.
But when I set this up in nginx configuration, i am still getting 'certificate is not valid' error on HTTPS. The Nginx config seems to be:

```<code>server {
    listen      80;
    listen      9092;
    server_name example.com;
    rewrite     ^   https://$server_name$request_uri? permanent;
}

server {
    listen 443 ssl http2;
    listen              [::]:443 ssl http2;
    keepalive_timeout   70;

    ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
    ssl_ciphers 'ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:DHE-RSA-AES128-GCM-SHA256:DHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA256:ECDHE-ECDSA-AES128-SHA:ECDHE-RSA-AES256-SHA384:ECDHE-RSA-AES128-SHA:ECDHE-ECDSA-AES256-SHA384:ECDHE-ECDSA-AES256-SHA:ECDHE-RSA-AES256-SHA:DHE-RSA-AES128-SHA256:DHE-RSA-AES128-SHA:DHE-RSA-AES256-SHA256:DHE-RSA-AES256-SHA:ECDHE-ECDSA-DES-CBC3-SHA:ECDHE-RSA-DES-CBC3-SHA:EDH-RSA-DES-CBC3-SHA:AES128-GCM-SHA256:AES256-GCM-SHA384:AES128-SHA256:AES256-SHA256:AES128-SHA:AES256-SHA:DES-CBC3-SHA:!DSS';
    ssl_prefer_server_ciphers on;
    ssl_certificate     /my/letsencrypt/cert
    ssl_certificate_key /my/letsencrypt/key;
    ssl_stapling        on;
    ssl_stapling_verify off;
    ssl_dhparam         /my/dhparam.pem;
    ssl_session_cache   shared:SSL:10m;
    ssl_session_timeout 10m;
    server_name example.com;

    root /path/to/web/example/com;

    index index.html index.php;
    client_max_body_size 1024M;

    try_files $uri $uri/ /index.php?$args;

    location ~ \.php$ {
        include fastcgi_params;
        fastcgi_pass php-handler;
        fastcgi_index index.php;

        fastcgi_split_path_info ^((?U).+\.php)(/?.+)$;
        fastcgi_param SCRIPT_FILENAME $document_root/$fastcgi_script_name;
        fastcgi_param PATH_TRANSLATED $document_root/$fastcgi_path_info;
        fastcgi_param PATH_INFO $fastcgi_path_info;
    }

}

server {
    listen 9092 ssl http2;
    listen              [::]:9092 ssl http2;
    keepalive_timeout   70;

    ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
    ssl_ciphers 'ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:DHE-RSA-AES128-GCM-SHA256:DHE-RSA-AES256-GCM-S$
    ssl_prefer_server_ciphers on;
    ssl_certificate     /path/to/cert
    ssl_certificate_key path/to/key
    ssl_stapling        on;
    ssl_stapling_verify off;
    ssl_dhparam         /my/dhparam.pem;
    ssl_session_cache   shared:SSL:10m;
    ssl_session_timeout 10m;
    server_name example.com;

    root /another/path/to/files;

    index index.html index.php;
    client_max_body_size 1024M;

    try_files $uri $uri/ /index.php?$args;

    location ~ \.php$ {
        include fastcgi_params;
        fastcgi_pass php-handler;
        fastcgi_index index.php;

        fastcgi_split_path_info ^((?U).+\.php)(/?.+)$;
        fastcgi_param SCRIPT_FILENAME $document_root/$fastcgi_script_name;
        fastcgi_param PATH_TRANSLATED $document_root/$fastcgi_path_info;
        fastcgi_param PATH_INFO $fastcgi_path_info;
    }

}
</code>```

Does anyone have experiences how to get this working?
Thanks.

答:
Fixed. I created new config file:

```<code>server {
    listen 9092 ssl;

    # IPv6 Listening
    # Uncomment to allow nginx to listen on IPv6
    #listen [::]:80;

        ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
    ssl_ciphers 'ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:DHE-RSA-AES128-GCM-SHA256:DHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA256:ECDHE-ECDSA-AES128-SHA:ECDHE-RSA-AES256-SHA384:ECDHE-RSA-AES128-SHA:ECDHE-ECDSA-AES256-SHA384:ECDHE-ECDSA-AES256-SHA:ECDHE-RSA-AES256-SHA:DHE-RSA-AES128-SHA256:DHE-RSA-AES128-SHA:DHE-RSA-AES256-SHA256:DHE-RSA-AES256-SHA:ECDHE-ECDSA-DES-CBC3-SHA:ECDHE-RSA-DES-CBC3-SHA:EDH-RSA-DES-CBC3-SHA:AES128-GCM-SHA256:AES256-GCM-SHA384:AES128-SHA256:AES256-SHA256:AES128-SHA:AES256-SHA:DES-CBC3-SHA:!DSS';
    ssl_prefer_server_ciphers on;
    ssl_certificate     /my/fullchain.pem;
    ssl_certificate_key /my/privkey.pem;
    ssl_stapling        on;
    ssl_stapling_verify off;
    ssl_dhparam         /my/dhparam.pem;
    ssl_session_cache   shared:SSL:10m;
    ssl_session_timeout 10m;
    server_name example.com;

    root /path/to/files;
    access_log /var/log/nginx/access.log;
    error_log /var/log/nginx/error.log;

    index index.html index.php;
    client_max_body_size 1024M;

    try_files $uri $uri/ /index.php?$args;

    location ~ \.php$ {
        include fastcgi_params;
        fastcgi_pass php-handler;
        fastcgi_index index.php;

        fastcgi_split_path_info ^((?U).+\.php)(/?.+)$;
        fastcgi_param SCRIPT_FILENAME $document_root/$fastcgi_script_name;
        fastcgi_param PATH_TRANSLATED $document_root/$fastcgi_path_info;
        fastcgi_param PATH_INFO $fastcgi_path_info;
    }

}
</code>```

The issue was probably in rewrite rule in first server section:

```<code>rewrite     ^   https://$server_name$request_uri? permanent;
</code>```

Removed it and everything is working.

Title: Nginx SSL issue - specific port

Body:
I migrated to Nginx, but i cannot find the solution for my problem.
On apache, I had 1 virutal host with ssl and specific port.

The apache config seems like this:

<VirtualHost *:443>
    ServerAdmin info@example.com
    ServerName example.in
    DocumentRoot /paht/to/web/files

    SSLEngine on
    SSLCertificateFile /ssl/certificate
    SSLCertificateKeyFile /ssl/key_file
    SSLCACertificateFile /ssl/ca.cer

</VirtualHost>

# intermediate configuration, tweak to your needs
SSLProtocol             all -SSLv2 -SSLv3
SSLCipherSuite          ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES256-GCM-SHA384:DHE-RSA-AES128-GCM-SHA256:DHE-DSS-AES128-GCM-SHA256:kEDH+AESGCM:ECDHE-RSA-AES128-SHA256:ECDHE-ECD$
SSLHonorCipherOrder     on

<Directory /path/to/my/web>
  Options FollowSymLinks Includes ExecCGI
  AllowOverride All
  Order allow,deny
  Allow from all
  Require all granted
</Directory>

<VirtualHost *:9092>
    ServerAdmin info@example.com
    ServerName example.in
    DocumentRoot /paht/to/web/files

    DocumentRoot /another/path/to/api

    SSLEngine on
    SSLCertificateFile /path/to/webcer
    SSLCertificateKeyFile /path/to/webkey
    SSLCACertificateFile /path/to/ca.cer

       <Directory /another/path/to/api>
           Options Indexes FollowSymLinks MultiViews ExecCGI
           AllowOverride All
           Require all granted
        </Directory>

        ErrorLog ${APACHE_LOG_DIR}/api_cable_error.log
        CustomLog ${APACHE_LOG_DIR}/api_cable_access.log combined

When I openend https://example.in:9092, it worked without any troubles.
But when I set this up in nginx configuration, i am still getting 'certificate is not valid' error on HTTPS. The Nginx config seems to be:

server {
    listen      80;
    listen      9092;
    server_name example.com;
    rewrite     ^   https://$server_name$request_uri? permanent;
}

server {
    listen 443 ssl http2;
    listen              [::]:443 ssl http2;
    keepalive_timeout   70;

    ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
    ssl_ciphers 'ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:DHE-RSA-AES128-GCM-SHA256:DHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA256:ECDHE-ECDSA-AES128-SHA:ECDHE-RSA-AES256-SHA384:ECDHE-RSA-AES128-SHA:ECDHE-ECDSA-AES256-SHA384:ECDHE-ECDSA-AES256-SHA:ECDHE-RSA-AES256-SHA:DHE-RSA-AES128-SHA256:DHE-RSA-AES128-SHA:DHE-RSA-AES256-SHA256:DHE-RSA-AES256-SHA:ECDHE-ECDSA-DES-CBC3-SHA:ECDHE-RSA-DES-CBC3-SHA:EDH-RSA-DES-CBC3-SHA:AES128-GCM-SHA256:AES256-GCM-SHA384:AES128-SHA256:AES256-SHA256:AES128-SHA:AES256-SHA:DES-CBC3-SHA:!DSS';
    ssl_prefer_server_ciphers on;
    ssl_certificate     /my/letsencrypt/cert
    ssl_certificate_key /my/letsencrypt/key;
    ssl_stapling        on;
    ssl_stapling_verify off;
    ssl_dhparam         /my/dhparam.pem;
    ssl_session_cache   shared:SSL:10m;
    ssl_session_timeout 10m;
    server_name example.com;

    root /path/to/web/example/com;

    index index.html index.php;
    client_max_body_size 1024M;

    try_files $uri $uri/ /index.php?$args;

    location ~ \.php$ {
        include fastcgi_params;
        fastcgi_pass php-handler;
        fastcgi_index index.php;

        fastcgi_split_path_info ^((?U).+\.php)(/?.+)$;
        fastcgi_param SCRIPT_FILENAME $document_root/$fastcgi_script_name;
        fastcgi_param PATH_TRANSLATED $document_root/$fastcgi_path_info;
        fastcgi_param PATH_INFO $fastcgi_path_info;
    }

}

server {
    listen 9092 ssl http2;
    listen              [::]:9092 ssl http2;
    keepalive_timeout   70;

    ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
    ssl_ciphers 'ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:DHE-RSA-AES128-GCM-SHA256:DHE-RSA-AES256-GCM-S$
    ssl_prefer_server_ciphers on;
    ssl_certificate     /path/to/cert
    ssl_certificate_key path/to/key
    ssl_stapling        on;
    ssl_stapling_verify off;
    ssl_dhparam         /my/dhparam.pem;
    ssl_session_cache   shared:SSL:10m;
    ssl_session_timeout 10m;
    server_name example.com;

    root /another/path/to/files;

    index index.html index.php;
    client_max_body_size 1024M;

    try_files $uri $uri/ /index.php?$args;

    location ~ \.php$ {
        include fastcgi_params;
        fastcgi_pass php-handler;
        fastcgi_index index.php;

        fastcgi_split_path_info ^((?U).+\.php)(/?.+)$;
        fastcgi_param SCRIPT_FILENAME $document_root/$fastcgi_script_name;
        fastcgi_param PATH_TRANSLATED $document_root/$fastcgi_path_info;
        fastcgi_param PATH_INFO $fastcgi_path_info;
    }

}

Does anyone have experiences how to get this working?
Thanks.

Body:
Fixed. I created new config file:

server {
    listen 9092 ssl;

    # IPv6 Listening
    # Uncomment to allow nginx to listen on IPv6
    #listen [::]:80;

        ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
    ssl_ciphers 'ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:DHE-RSA-AES128-GCM-SHA256:DHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA256:ECDHE-ECDSA-AES128-SHA:ECDHE-RSA-AES256-SHA384:ECDHE-RSA-AES128-SHA:ECDHE-ECDSA-AES256-SHA384:ECDHE-ECDSA-AES256-SHA:ECDHE-RSA-AES256-SHA:DHE-RSA-AES128-SHA256:DHE-RSA-AES128-SHA:DHE-RSA-AES256-SHA256:DHE-RSA-AES256-SHA:ECDHE-ECDSA-DES-CBC3-SHA:ECDHE-RSA-DES-CBC3-SHA:EDH-RSA-DES-CBC3-SHA:AES128-GCM-SHA256:AES256-GCM-SHA384:AES128-SHA256:AES256-SHA256:AES128-SHA:AES256-SHA:DES-CBC3-SHA:!DSS';
    ssl_prefer_server_ciphers on;
    ssl_certificate     /my/fullchain.pem;
    ssl_certificate_key /my/privkey.pem;
    ssl_stapling        on;
    ssl_stapling_verify off;
    ssl_dhparam         /my/dhparam.pem;
    ssl_session_cache   shared:SSL:10m;
    ssl_session_timeout 10m;
    server_name example.com;

    root /path/to/files;
    access_log /var/log/nginx/access.log;
    error_log /var/log/nginx/error.log;

    index index.html index.php;
    client_max_body_size 1024M;

    try_files $uri $uri/ /index.php?$args;

    location ~ \.php$ {
        include fastcgi_params;
        fastcgi_pass php-handler;
        fastcgi_index index.php;

        fastcgi_split_path_info ^((?U).+\.php)(/?.+)$;
        fastcgi_param SCRIPT_FILENAME $document_root/$fastcgi_script_name;
        fastcgi_param PATH_TRANSLATED $document_root/$fastcgi_path_info;
        fastcgi_param PATH_INFO $fastcgi_path_info;
    }

}

The issue was probably in rewrite rule in first server section:

rewrite     ^   https://$server_name$request_uri? permanent;

Removed it and everything is working.


问:
Landing page for variant
Is it possible to have different landing pages for each variants?

E.g.

https://store-w40xoh.mybigcommerce.com/chanel-the-cheetah/?sku=SKU-F4180933 - this one should have preset size M

https://store-w40xoh.mybigcommerce.com/chanel-the-cheetah/?sku=SKU-1A86555B - this one should have preset size S

答:
You can fetch the request URL and retrieve sku id. You can use the SKU id to customize your page.

I had a similar requirement to configure the landing page based on request URL so we used www.grooveui.com Using this tool also, you can set landing page based on query params, domains or sub-domains.

Title: Landing page for variant


问:
Write output out of grep into a file on Linux?
```<code>find . -name "*.php" | xargs grep -i -n "searchstring" >output.txt
</code>```

Here I am trying to write data into a file which is not happening...

答:
I guess that you have spaces in the php filenames. If you hand them to grep through xargs in the way that you do, the names get split into parts and grep interprets those parts as filenames which it then cannot find.

There is a solution for that. find has a -print0 option that instructs find to separate results by a NUL byte and xargs has a -0 option that instructs xargs to expect a NUL byte as separator. Using those you get:

```<code>find . -name "*.php" -print0 | xargs -0 grep -i -n "searchstring" > output.txt
</code>```

Body:
find . -name "*.php" | xargs grep -i -n "searchstring" >output.txt

Here I am trying to write data into a file which is not happening...

Body:
I guess that you have spaces in the php filenames. If you hand them to grep through xargs in the way that you do, the names get split into parts and grep interprets those parts as filenames which it then cannot find.

There is a solution for that. find has a -print0 option that instructs find to separate results by a NUL byte and xargs has a -0 option that instructs xargs to expect a NUL byte as separator. Using those you get:

find . -name "*.php" -print0 | xargs -0 grep -i -n "searchstring" > output.txt

ContentLicense: CC BY-SA 2.5


问:
How to save and get data in other components using Angular
I am using JSON object in all components. Is there any global declaration and reuse JSON object in Angular?

Otherwise same object we will load in all components?

Where should I declare that object and how can I call it in other components?

I am maintaining onload functions in  HomePage components and I am using in home.html.

I am maintaining the WebserviceProvider for getting values.

But where will I declare and store JSON object and how to re-use other components?

答:
Make use of Angular Services they are one used to store data and passing data between components and also easy as Input and Output you will get stuck in a Spaghetti of event emitters , also you can look at the ngrx store for holding data in one place. but i would suggest you to use ngrx only in case of medium to large scale apps as it adds up a bit of code.

In both Angular service and ngrx you store data in a single place to be passed around components.

Also take a look at this answer

Delegation: EventEmitter or Observable in Angular2

and this

Delegation: EventEmitter or Observable in Angular2

Update

If you want to use the service data in other component you can can have one variable in the service and then push the result to that service which you will get in the component to the service var which will emit that a result has been pushed and then the other component can be notified or you can make use of Input and output event emitters or Behaviour or replay Subject


问:
how to you toggle on and off a web proxy in os x from the command line
In OS X, you turn on and off a web proxy from System Preferences > Network > Proxies, by checking Web Proxy (HTTP) and designating the Web Proxy Server etc. and by clicking OK and then "Apply". This is way too many steps. Is there a way to do this all from the command line and a shell script?</p>

答:
I prepared a script named proxy that might help,

```<code>#!/bin/bash
#
#
#   Author: Md. Sazzad Hissain Khan
#   Date:   8 July, 2017
#
#

NETWORK_SERVICE_NAME="Ethernet"

if [ "$#" -ne 1 ]; then
    echo "Argument missing [on/off]"
    exit 0
fi

if [ $1 == "on" ]; then
    echo "Enabling secure proxy for $NETWORK_SERVICE_NAME"
    networksetup -setsecurewebproxystate "$NETWORK_SERVICE_NAME" on
elif [ $1 == "off" ]; then
    echo "Disabling secure proxy for $NETWORK_SERVICE_NAME"
    networksetup -setsecurewebproxystate "$NETWORK_SERVICE_NAME" off
else
    echo "Argument invalid [permitted:on/off]"
fi
</code>```

NETWORK_SERVICE_NAME is the name of your active network which you need to configure.

Create proxy file in /usr/local/bin.

Copy above script into proxy.

Set executable permission for the file using sudo chmod 777 proxy .

How to use:

```<code>proxy on
proxy off
</code>```

Body:
I prepared a script named proxy that might help,

#!/bin/bash
#
#
#   Author: Md. Sazzad Hissain Khan
#   Date:   8 July, 2017
#
#

NETWORK_SERVICE_NAME="Ethernet"

if [ "$#" -ne 1 ]; then
    echo "Argument missing [on/off]"
    exit 0
fi

if [ $1 == "on" ]; then
    echo "Enabling secure proxy for $NETWORK_SERVICE_NAME"
    networksetup -setsecurewebproxystate "$NETWORK_SERVICE_NAME" on
elif [ $1 == "off" ]; then
    echo "Disabling secure proxy for $NETWORK_SERVICE_NAME"
    networksetup -setsecurewebproxystate "$NETWORK_SERVICE_NAME" off
else
    echo "Argument invalid [permitted:on/off]"
fi

NETWORK_SERVICE_NAME is the name of your active network which you need to configure.

Create proxy file in /usr/local/bin.

Copy above script into proxy.

Set executable permission for the file using sudo chmod 777 proxy .

How to use:

proxy on
proxy off


问:
Most efficient way to find the last digit of a^b
I am a python newbie. I am looking to compute (a ** b) % 10 in the most efficient way possible (i.e. simplifying the power part). I have found one way to do this: ((a % 10) ** b) % 10. My question is, are there more efficient ways to do this? This problem is an extension of a CodeFights task. The original problem accepted (a ** b) % 10.

答:
Since the numbers mod 10 form a ring, you can compute the residue mod 10 at every intermediate value without influencing the result.

There is a O(log b) step algorithm called Square-and-multiply that can drastically speed up your computations.

The basic idea is that for even b, we can just square the argument
and divide the exponent by 2 without changing the result.
For odd b, we extract one power of a (or our current argument) and proceed like in the even case (squaring and halving).

So putting this together, if you implement the Square-and-multiply algorithm and compute the residue mod 10 after every step, you will have a nice and efficient way to compute your last digit.


问:
Laravel Factory: Manual Increment of Column
For the following factory definition, the column order needs to be sequential. There is already a column id that is auto-incremented. The first row's order should start at 1 and each additional row's order should be the next number (1,2,3, etc.)

```<code>$factory->define(App\AliasCommand::class, function (Faker\Generator $faker) {
    return [
        'user_id' => App\User::inRandomOrder()->first()->id,
        'command' => $faker->word,
        'content' => $faker->sentence,
        'order'   => (App\AliasCommand::count()) ?
            App\AliasCommand::orderBy('order', 'desc')->first()->order + 1 : 1
    ];
});
</code>```

It should be setting the order column to be 1 more than the previous row, however, it results in all rows being assigned 1.

答:
Here's something that might work.

```<code>$factory->define(App\AliasCommand::class, function (Faker\Generator $faker) {
    static $order = 1;
    return [
        'user_id' => App\User::inRandomOrder()->first()->id,
        'command' => $faker->word,
        'content' => $faker->sentence,
        'order'   => $order++
    ];
});
</code>```

It just keeps a counter internal to that function.

Update:

Laravel 8 introduced new factory classes so this request becomes:

```<code>class AliasCommandFactory extends Factory {

    private static $order = 1;

    protected $model = AliasCommand::class;

    public function definition() {
         $faker = $this->faker;
         return [
            'user_id' => User::inRandomOrder()->first()->id,
            'command' => $faker->word,
            'content' => $faker->sentence,
            'order'   => self::$order++
        ];
    }
}
</code>```

Body:
For the following factory definition, the column order needs to be sequential. There is already a column id that is auto-incremented. The first row's order should start at 1 and each additional row's order should be the next number (1,2,3, etc.)

$factory->define(App\AliasCommand::class, function (Faker\Generator $faker) {
    return [
        'user_id' => App\User::inRandomOrder()->first()->id,
        'command' => $faker->word,
        'content' => $faker->sentence,
        'order'   => (App\AliasCommand::count()) ?
            App\AliasCommand::orderBy('order', 'desc')->first()->order + 1 : 1
    ];
});

It should be setting the order column to be 1 more than the previous row, however, it results in all rows being assigned 1.

Body:
Here's something that might work.

$factory->define(App\AliasCommand::class, function (Faker\Generator $faker) {
    static $order = 1;
    return [
        'user_id' => App\User::inRandomOrder()->first()->id,
        'command' => $faker->word,
        'content' => $faker->sentence,
        'order'   => $order++
    ];
});

It just keeps a counter internal to that function.

Update:

Laravel 8 introduced new factory classes so this request becomes:

class AliasCommandFactory extends Factory {

    private static $order = 1;

    protected $model = AliasCommand::class;

    public function definition() {
         $faker = $this->faker;
         return [
            'user_id' => User::inRandomOrder()->first()->id,
            'command' => $faker->word,
            'content' => $faker->sentence,
            'order'   => self::$order++
        ];
    }
}


问:
Get selected value in datalist using jQuery
Very simple and straight forward. I pre-populated a HTML datalist with values, on the form when I want select a value and insert it into SQLite database. This is my example code which is not working. Please help out.
HTML5 datalist form creation:

```<code><input  name="TypeList" list="TypeList" placeholder="Select Type"/>
<datalist id="TypeList">
    <option value="State">
    <option value="Area">
    <option value="Town">
    <option value="Street">
    <option value="Number">
    <option value="Local Government">
    <option value="Ward">
    <option value="Country">
</datalist>
</code>```

this is the sample jquery code that did not work:

```<code>var relationshipTemp = $('#TypeList option:selected').text();
</code>```

答:
simple solution to this problem is do it as you get the value from an text input field

Name:

```<code><input id="l" list="bloodgroup" name="blood_group" placeholder="Blood group">
                    <datalist id="bloodgroup">
                        <option value="A+">
                        <option value="B+">
                        <option value="AB+">
                        <option value="O+">
                        <option value="A-">
                        <option value="B-">
                        <option value="AB-">
                        <option value="O-">
                    </datalist>

<button type="button" onclick="myFunction()">Try it</button>

<script>
function myFunction() {
    console.log(document.getElementById("l").value);
}
</script>
</code>```

Body:
Very simple and straight forward. I pre-populated a HTML datalist with values, on the form when I want select a value and insert it into SQLite database. This is my example code which is not working. Please help out.
HTML5 datalist form creation:

<input  name="TypeList" list="TypeList" placeholder="Select Type"/>
<datalist id="TypeList">
    <option value="State">
    <option value="Area">
    <option value="Town">
    <option value="Street">
    <option value="Number">
    <option value="Local Government">
    <option value="Ward">
    <option value="Country">
</datalist>

this is the sample jquery code that did not work:

var relationshipTemp = $('#TypeList option:selected').text();

Body:
simple solution to this problem is do it as you get the value from an text input field

Name:

<input id="l" list="bloodgroup" name="blood_group" placeholder="Blood group">
                    <datalist id="bloodgroup">
                        <option value="A+">
                        <option value="B+">
                        <option value="AB+">
                        <option value="O+">
                        <option value="A-">
                        <option value="B-">
                        <option value="AB-">
                        <option value="O-">
                    </datalist>

<button type="button" onclick="myFunction()">Try it</button>

<script>
function myFunction() {
    console.log(document.getElementById("l").value);
}
</script>


问:
Re-use result of last line Jupyter
In Jupyter notebook, is there any way to re-use the output the line above, within a cell?

Coming from Mathematica, I often find it useful to write things commands which work on the output of the last line using %, here's a stupid example:

```<code>Integrate[f[x],x]
Limit[%,x->1] - Limit[%,x->0]
</code>```

In general one can write %%% for 3rd-last output etc. https://reference.wolfram.com/language/ref/Out.html

@nostradamus reminds me that underscore _ is the output of the last cell, at least in Python. (Get last answer .) I didn't initially ask this, but would particularly like to be able to do this within a cell, so as to be able to execute multiple steps with one shift-enter.

I would also like to know if there's a way of doing either of these in Julia instead of Python.

答:
In case someone else finds this with google, I just discovered a package that does roughly what I wanted, in Julia: ChainRecursive.jl uses it as the magic word, like so:

```<code>julia> using ChainRecursive

julia> @chain for k=1:4
           k^2 + k^3
           print(" $k -> $it ")
       end

 1 -> 2  2 -> 12  3 -> 36  4 -> 80
</code>```

There appears to be no performance lost by using this, as it is un-wrapped before compilation.

Title: Re-use result of last line Jupyter

Body:
In Jupyter notebook, is there any way to re-use the output the line above, within a cell?

Coming from Mathematica, I often find it useful to write things commands which work on the output of the last line using %, here's a stupid example:

Integrate[f[x],x]
Limit[%,x->1] - Limit[%,x->0]

In general one can write %%% for 3rd-last output etc. https://reference.wolfram.com/language/ref/Out.html

@nostradamus reminds me that underscore _ is the output of the last cell, at least in Python. (Get last answer .) I didn't initially ask this, but would particularly like to be able to do this within a cell, so as to be able to execute multiple steps with one shift-enter.

I would also like to know if there's a way of doing either of these in Julia instead of Python.

Body:
In case someone else finds this with google, I just discovered a package that does roughly what I wanted, in Julia: ChainRecursive.jl uses it as the magic word, like so:

julia> using ChainRecursive

julia> @chain for k=1:4
           k^2 + k^3
           print(" $k -> $it ")
       end

 1 -> 2  2 -> 12  3 -> 36  4 -> 80

There appears to be no performance lost by using this, as it is un-wrapped before compilation.


问:
Python event has not Key attribute
I am trying to create a program for when my character moves. here is my code

```<code>while True:
   for event in pygame.event.get():
       if event.type == QUIT:
            pygame.quit()
            sys.exit()
        elif event.type == KEYDOWN:
            if(event.key == K_RIGHT):
            playerPos[0] +=1
    if (event.key == K_RIGHT) and playerPos[0] < MAPWIDTH -1:
        playerPos[0] =+ 1
</code>```

here is the error

```<code>Traceback (most recent call last):
  File "H:\python things\firstgame.py", line 90, in <module>
if (event.key == K_RIGHT) and playerPos[0] < MAPWIDTH -1:
AttributeError: 'Event' object has no attribute 'key'
</code>```

答:
I think the problem is if (event.key == K_RIGHT) and playerPos[0] < MAPWIDTH -1:
is outside of the forloop so the event doesn't have a key attribute.

the event inside the forloop has a key attribute because of pygame.event.get(): move that line inside of the forloop and that should solve your problem.

```<code>while True:
   for event in pygame.event.get():
       if event.type == QUIT:
            pygame.quit()
            sys.exit()
       elif event.type == KEYDOWN:
            if(event.key == K_RIGHT):
            playerPos[0] +=1
       elif (event.key == K_RIGHT) and playerPos[0] < MAPWIDTH -1:
            playerPos[0] =+ 1
</code>```

I would also suggest you combine line 87 and 88 into one like such
elif(event.type == KEYDOWN) and (event.key == K_RIGHT):

I hope this helps.

Title: Python event has not Key attribute

Body:
I am trying to create a program for when my character moves. here is my code

while True:
   for event in pygame.event.get():
       if event.type == QUIT:
            pygame.quit()
            sys.exit()
        elif event.type == KEYDOWN:
            if(event.key == K_RIGHT):
            playerPos[0] +=1
    if (event.key == K_RIGHT) and playerPos[0] < MAPWIDTH -1:
        playerPos[0] =+ 1

here is the error

Traceback (most recent call last):
  File "H:\python things\firstgame.py", line 90, in <module>
if (event.key == K_RIGHT) and playerPos[0] < MAPWIDTH -1:
AttributeError: 'Event' object has no attribute 'key'

Body:
I think the problem is if (event.key == K_RIGHT) and playerPos[0] < MAPWIDTH -1:
is outside of the forloop so the event doesn't have a key attribute.

the event inside the forloop has a key attribute because of pygame.event.get(): move that line inside of the forloop and that should solve your problem.

while True:
   for event in pygame.event.get():
       if event.type == QUIT:
            pygame.quit()
            sys.exit()
       elif event.type == KEYDOWN:
            if(event.key == K_RIGHT):
            playerPos[0] +=1
       elif (event.key == K_RIGHT) and playerPos[0] < MAPWIDTH -1:
            playerPos[0] =+ 1

I would also suggest you combine line 87 and 88 into one like such
elif(event.type == KEYDOWN) and (event.key == K_RIGHT):

I hope this helps.


问:
How to save graphics created on a PictureBox?
In c# and Visual Studio Windows forms I have loaded an image into a picture box (pictureBox2) and then cropped it and show in another picture box (pictureBox3).

Now I want to save what is inside pictureBox3 as an image file.

How can I do this?

```<code>private void crop_bttn_Click(object sender, EventArgs e)
{
    Image crop = GetCopyImage("grayScale.jpg");
    pictureBox2.Image = crop;

    Bitmap sourceBitmap = new Bitmap(pictureBox2.Image,
                                     pictureBox2.Width, pictureBox2.Height);
    Graphics g = pictureBox3.CreateGraphics();

    g.DrawImage(sourceBitmap, new Rectangle(0, 0,
                pictureBox3.Width, pictureBox3.Height), rectCropArea, GraphicsUnit.Pixel);
    sourceBitmap.Dispose();
}
</code>```

答:
The method PictureBox.CreateGraphics() should not be used unless you know what you are doing because it can cause some not-so-obvious problems. For example, in you scenario, the image in pictureBox3 will disappear when you minimize or resize the window.

A better way is to draw to a bitmap, which you also can save:

```<code>var croppedImage = new Bitmap(pictureBox3.Width, pictureBox3.Height);
var g = Graphics.FromImage(croppedImage);
g.DrawImage(crop, new Point(0, 0), rectCropArea, GraphicsUnit.Pixel);
g.Dispose();
//Now you can save the bitmap
croppedImage.Save(...);
pictureBox3.Image = croppedImage;
</code>```

Btw, please use more reasonable variable names, especially for pictureBox1..3.

Body:
In c# and Visual Studio Windows forms I have loaded an image into a picture box (pictureBox2) and then cropped it and show in another picture box (pictureBox3).

Now I want to save what is inside pictureBox3 as an image file.

How can I do this?

private void crop_bttn_Click(object sender, EventArgs e)
{
    Image crop = GetCopyImage("grayScale.jpg");
    pictureBox2.Image = crop;

    Bitmap sourceBitmap = new Bitmap(pictureBox2.Image,
                                     pictureBox2.Width, pictureBox2.Height);
    Graphics g = pictureBox3.CreateGraphics();

    g.DrawImage(sourceBitmap, new Rectangle(0, 0,
                pictureBox3.Width, pictureBox3.Height), rectCropArea, GraphicsUnit.Pixel);
    sourceBitmap.Dispose();
}

Body:
The method PictureBox.CreateGraphics() should not be used unless you know what you are doing because it can cause some not-so-obvious problems. For example, in you scenario, the image in pictureBox3 will disappear when you minimize or resize the window.

A better way is to draw to a bitmap, which you also can save:

var croppedImage = new Bitmap(pictureBox3.Width, pictureBox3.Height);
var g = Graphics.FromImage(croppedImage);
g.DrawImage(crop, new Point(0, 0), rectCropArea, GraphicsUnit.Pixel);
g.Dispose();
//Now you can save the bitmap
croppedImage.Save(...);
pictureBox3.Image = croppedImage;

Btw, please use more reasonable variable names, especially for pictureBox1..3.


问:
React native - connection has no connection handler error meaning?
I created a new react project and when I run it on iOS from xcode, the console gives me this:

```<code>2017-05-19 23:25:34.119 [info][tid:main][RCTBatchedBridge.m:77] Initializing <RCTBatchedBridge: 0x6100001a6c80> (parent: <RCTBridge: 0x6100000c46e0>, executor: RCTJSCExecutor)
2017-05-19 23:25:51.287 [info][tid:main][RCTRootView.m:295] Running application test ({
    initialProps =     {
    };
    rootTag = 1;
})
2017-05-19 23:25:51.289 [info][tid:com.facebook.react.JavaScript] Running application "test" with appParams: {"rootTag":1,"initialProps":{}}. __DEV__ === true, development-level warning are ON, performance optimizations are OFF
2017-05-19 23:25:51.299771-0400 test[21948:1121429] [] nw_connection_get_connected_socket_block_invoke 3 Connection has no connected handler
2017-05-19 23:25:53.335282-0400 test[21948:1121426] [] nw_connection_get_connected_socket_block_invoke 4 Connection has no connected handler
2017-05-19 23:25:55.349190-0400 test[21948:1120112] [] nw_connection_get_connected_socket_block_invoke 5 Connection has no connected handler
</code>```

What do 2017-05-19 23:25:51.299771-0400 test[21948:1121429] [] nw_connection_get_connected_socket_block_invoke 3 Connection has no connected handler these lines mean and how to I resolve the issue?

I first noticed this when I tried to use fetch in my application and found it did not work. I found these messages in the console and later discovered these messages are happening with all my applications so I assume that means it is a config issue on my part?

I created a new test program to test what was causing this and found it happens on a brand new project. Below is my code is that generated the log output above:

```<code>/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 * @flow
 */

import React, { Component } from 'react';
import {
  AppRegistry,
  StyleSheet,
  Text,
  View
} from 'react-native';

export default class test extends Component {
  render() {
    return (
      <View style={styles.container}>
        <Text style={styles.welcome}>
          Welcome to React Native!
        </Text>
        <Text style={styles.instructions}>
          To get started, edit index.ios.js
        </Text>
        <Text style={styles.instructions}>
          Press Cmd+R to reload,{'\n'}
          Cmd+D or shake for dev menu
        </Text>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#F5FCFF',
  },
  welcome: {
    fontSize: 20,
    textAlign: 'center',
    margin: 10,
  },
  instructions: {
    textAlign: 'center',
    color: '#333333',
    marginBottom: 5,
  },
});

AppRegistry.registerComponent('test', () => test);
</code>```

答:
In my case it was due to a firewall application (Little Snitch) that never requests access when running from a react-native app. Steps that work for me:

Open Safari browser in the simulator

Visit google.com or any domain

Make sure it opens the page. It will ask for access, etc

Restart your app in simulator

Restart logging react-native log-ios

That should help.

Body:
I created a new react project and when I run it on iOS from xcode, the console gives me this:

2017-05-19 23:25:34.119 [info][tid:main][RCTBatchedBridge.m:77] Initializing <RCTBatchedBridge: 0x6100001a6c80> (parent: <RCTBridge: 0x6100000c46e0>, executor: RCTJSCExecutor)
2017-05-19 23:25:51.287 [info][tid:main][RCTRootView.m:295] Running application test ({
    initialProps =     {
    };
    rootTag = 1;
})
2017-05-19 23:25:51.289 [info][tid:com.facebook.react.JavaScript] Running application "test" with appParams: {"rootTag":1,"initialProps":{}}. __DEV__ === true, development-level warning are ON, performance optimizations are OFF
2017-05-19 23:25:51.299771-0400 test[21948:1121429] [] nw_connection_get_connected_socket_block_invoke 3 Connection has no connected handler
2017-05-19 23:25:53.335282-0400 test[21948:1121426] [] nw_connection_get_connected_socket_block_invoke 4 Connection has no connected handler
2017-05-19 23:25:55.349190-0400 test[21948:1120112] [] nw_connection_get_connected_socket_block_invoke 5 Connection has no connected handler

What do 2017-05-19 23:25:51.299771-0400 test[21948:1121429] [] nw_connection_get_connected_socket_block_invoke 3 Connection has no connected handler these lines mean and how to I resolve the issue?

I first noticed this when I tried to use fetch in my application and found it did not work. I found these messages in the console and later discovered these messages are happening with all my applications so I assume that means it is a config issue on my part?

I created a new test program to test what was causing this and found it happens on a brand new project. Below is my code is that generated the log output above:

/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 * @flow
 */

import React, { Component } from 'react';
import {
  AppRegistry,
  StyleSheet,
  Text,
  View
} from 'react-native';

export default class test extends Component {
  render() {
    return (
      <View style={styles.container}>
        <Text style={styles.welcome}>
          Welcome to React Native!
        </Text>
        <Text style={styles.instructions}>
          To get started, edit index.ios.js
        </Text>
        <Text style={styles.instructions}>
          Press Cmd+R to reload,{'\n'}
          Cmd+D or shake for dev menu
        </Text>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#F5FCFF',
  },
  welcome: {
    fontSize: 20,
    textAlign: 'center',
    margin: 10,
  },
  instructions: {
    textAlign: 'center',
    color: '#333333',
    marginBottom: 5,
  },
});

AppRegistry.registerComponent('test', () => test);


问:
How to run studio.sh without opening a shell (using Ubuntu)
I can run studio.sh from the shell and it opens just fine.  I can't run it by clicking on it.  It just pauses like it's loading and then does nothing.  Similarly, a desktop shortcut I created pauses and then does nothing.

History (in case it's relevant):
I unpacked Android Studio in ~/android

I ran studio.h from the shell.  It opened and downloaded the sdk to ~/Android and did some other setup.

I wanted to keep Android stuff in one folder in my home directory so I moved android-studio to ~/Android from ~/android.

I can run it in the shell using "./studio.sh" or even from my home folder using "Android/android-studio/studio.sh".

I rm'd ~/.android, ~/.AndroidStudio, and the entire android-studio folder.  I unpacked it again and tried again.  It did some setup again, but still only works from the shell.  It only works from the shell.

I don't think I had this problem in Linux Mint.  I think I did all the same things then - including deleting the folder and unpacking it a second time.

Edit: In case it's relevant, to run it from the folder, I clicked "open with.." "Run Program".  I believe this worked once before I moved it from the original folder.

答:
find location where you stored android-stdio/bin folder /opt/ or /usr/local/ open android stdio folder right click there and open terminal use following command

```<code>sudo gedit android-studio.desktop
</code>```

then write following line in this file

Don't forgot to check your stdio path /opt/ or /usr/local/ And write proper path Exec AND Icon

```<code>[Desktop Entry]
Name=Android Studio
Comment=Integerated Development Environment for Android
Exec=/opt/android-studio/bin/studio.sh
Icon=/opt/android-studio/bin/studio.png
Terminal=false
Type=Application
</code>```

save file and hit command

```<code>desktop-file-install android-studio.desktop
</code>```

now shortcut file is ready click copy and past on desktop

Body:
find location where you stored android-stdio/bin folder /opt/ or /usr/local/ open android stdio folder right click there and open terminal use following command

sudo gedit android-studio.desktop

then write following line in this file

Don't forgot to check your stdio path /opt/ or /usr/local/ And write proper path Exec AND Icon

[Desktop Entry]
Name=Android Studio
Comment=Integerated Development Environment for Android
Exec=/opt/android-studio/bin/studio.sh
Icon=/opt/android-studio/bin/studio.png
Terminal=false
Type=Application

save file and hit command

desktop-file-install android-studio.desktop

now shortcut file is ready click copy and past on desktop


问:
Python beautiful soup4- find_all returns "[]"
I am using python BS4 to scrape the https://skinup.gg website. I am trying to get the multiplier class, in order, from a website.

I tried to scrape the information by taking all the data from the div history class. However it just returns [] and I am stumped on how to get the multipliers.

I wonder if it is because the div tag class values are constantly changing. Which leads me to my second question: how do they have dynamic values in html tags? Is it done via Javascript?

Excuse my grammar.

Here is my code:

```<code>import urllib.request
import requests
from bs4 import BeautifulSoup
import urllib

page = requests.g et("https://skinup.gg/"
soup = BeautifulSoup(page.content, "html.parser")

print(soup.find_all('div', attrs={'class': 'win'}))
</code>```

Relevant website code:

```<code><div class="history"><div class="win" style="">
  <time class="date">23:05</time>
  <span class="multiplier">2.19</span>
</div><div class="win" style="">
  <time class="date">23:04</time>
  <span class="multiplier">2.62</span>
</div><div class="lose" style="">
  <time class="date">23:04</time>
  <span class="multiplier">1.75</span>
</div><div class="lose" style="">
  <time class="date">23:04</time>
  <span class="multiplier">1.00</span>
</div><div class="lose" style="">
  <time class="date">23:04</time>
  <span class="multiplier">1.21</span>
</div><div style="">
  <time class="date">23:03</time>
  <span class="multiplier">1.82</span>
</div><div class="lose" style="">
  <time class="date">23:03</time>
  <span class="multiplier">1.00</span>
</div><div class="win" style="">
  <time class="date">23:03</time>
  <span class="multiplier">2.91</span>
</div><div class="lose" style="">
  <time class="date">23:02</time>
  <span class="multiplier">1.01</span>
</div><div class="win" style="">
  <time class="date">23:02</time>
  <span class="multiplier">1184.44</span>
</div><div class="win" style="">
  <time class="date">23:01</time>
  <span class="multiplier">36.81</span>
</div><div class="lose" style="">
  <time class="date">22:59</time>
  <span class="multiplier">1.38</span>
</div><div class="win" style="">
  <time class="date">22:59</time>
  <span class="multiplier">2.42</span>
</div><div class="win" style="">
  <time class="date">22:59</time>
  <span class="multiplier">8.00</span>
</div><div class="win" style="">
  <time class="date">22:58</time>
  <span class="multiplier">3.42</span>
</div><div class="win" style="">
  <time class="date">22:57</time>
  <span class="multiplier">2.04</span>
</div><div class="lose" style="">
  <time class="date">22:57</time>
  <span class="multiplier">1.17</span>
</div><div class="lose" style="">
  <time class="date">22:57</time>
  <span class="multiplier">1.24</span>
</div><div class="lose" style="">
  <time class="date">22:57</time>
  <span class="multiplier">1.11</span>
</div><div class="lose" style="">
  <time class="date">22:56</time>
  <span class="multiplier">1.53</span>
</div>

                </div>
</code>```

答:
First of all, this should throw up syntax errors:

```<code>page = requests.g et("https://skinup.gg/"
</code>```

Change it to:

```<code>page = requests.get("https://skinup.gg/")
</code>```

I suggest using lxml instead of html.parser, it's faster and lighter.

Now, to answer your question,

The div segments with win as class attribute are under the div segment with history class attribute. So first you search for history and then search for win within the obtained list.

But, when i ran your script and cross checked the page source of the site you linked, there is no div segment with win class attribute.

Could you mention, where you got the Relevant website code from?

Body:
I am using python BS4 to scrape the https://skinup.gg website. I am trying to get the multiplier class, in order, from a website.

I tried to scrape the information by taking all the data from the div history class. However it just returns [] and I am stumped on how to get the multipliers.

I wonder if it is because the div tag class values are constantly changing. Which leads me to my second question: how do they have dynamic values in html tags? Is it done via Javascript?

Excuse my grammar.

Here is my code:

import urllib.request
import requests
from bs4 import BeautifulSoup
import urllib

page = requests.g et("https://skinup.gg/"
soup = BeautifulSoup(page.content, "html.parser")

print(soup.find_all('div', attrs={'class': 'win'}))

Relevant website code:

  <time class="date">23:05</time>
  2.19

  <time class="date">23:04</time>
  2.62

  <time class="date">23:04</time>
  1.75

  <time class="date">23:04</time>
  1.00

  <time class="date">23:04</time>
  1.21

  <time class="date">23:03</time>
  1.82

  <time class="date">23:03</time>
  1.00

  <time class="date">23:03</time>
  2.91

  <time class="date">23:02</time>
  1.01

  <time class="date">23:02</time>
  1184.44

  <time class="date">23:01</time>
  36.81

  <time class="date">22:59</time>
  1.38

  <time class="date">22:59</time>
  2.42

  <time class="date">22:59</time>
  8.00

  <time class="date">22:58</time>
  3.42

  <time class="date">22:57</time>
  2.04

  <time class="date">22:57</time>
  1.17

  <time class="date">22:57</time>
  1.24

  <time class="date">22:57</time>
  1.11

  <time class="date">22:56</time>
  1.53

Body:
First of all, this should throw up syntax errors:

page = requests.g et("https://skinup.gg/"

Change it to:

page = requests.get("https://skinup.gg/")

I suggest using lxml instead of html.parser, it's faster and lighter.

Now, to answer your question,

The div segments with win as class attribute are under the div segment with history class attribute. So first you search for history and then search for win within the obtained list.

But, when i ran your script and cross checked the page source of the site you linked, there is no div segment with win class attribute.

Could you mention, where you got the Relevant website code from?


问:
How to get child element when query by parent key, AngularFire2
I am learning Firebase + AngularFire2.

My DB in firebase is like .

Whe I try to get child of courses > ncjkdhjjd8ejd. by using

```<code>let ll = (_angularFire.list("courses/ncjkdhjjd8ejd"));

ll.subscribe(
  (val) => console.log(val)
)
</code>```

I am getting :

How can I get it in a single json object, not 3 arrays.

I only want values in json structure.

答:
Use an AngularFire2 object observable instead:

let course = _angularFire.object("courses/ncjkdhjjd8ejd");
course.subscribe(val => console.log(val));
```

Body:
I am learning Firebase + AngularFire2.

My DB in firebase is like .

Whe I try to get child of courses > ncjkdhjjd8ejd. by using

let ll = (_angularFire.list("courses/ncjkdhjjd8ejd"));

ll.subscribe(
  (val) => console.log(val)
)

I am getting :

How can I get it in a single json object, not 3 arrays.

I only want values in json structure.


问:
C#, variable value as a part of an object name?
For example i have a player object with a list of suits of cards it has.

```<code>player.card[0] = "diamonds";
player.card[1] = "clubs";
player.card[2] = "spades";
etc...
</code>```

also i have 4 hidden pictureboxes with an image of suites ( pb_spades , pb_hearts m etc. )

and another 4 pictureboxs ( pb_playerCard1 , pb_playerCard2 , etc. ) to which I have to assign an image from a hidden pb corresponding to the suit of card the player object has.

Therefor

```<code>if ( player.card[0] == "diamonds" ) { pb_playerCard1.Image = pb_diamonds.Image; }
</code>```

of course, doing it all with IFs would take quite a long time... Can I somehow use variable value as a part of an objects name?

kinda

```<code>for (int i = 1; i != 5; i++)
{
pb_playerCard+'i'.Image = pb_+'player.card[i+1]'.Image;
}
</code>```

答:
The main class Player and the associated enumeration should be like this:

```<code>
class Player
{
    public Player(int n)
    {
        Cards = new List(n);
    }

    public IList Cards { get; private set; }
}

enum CardType
{
    Diamond,
    Club,
    Spade,
    Heart
}
</code>```

Another method GetPictureBox() should in the winform partial class

```<code>
public PictureBox GetPictureBox(string pictureBoxName)
{
    if(this.Controls.ContainsKey(pictureBoxName))
    {
        Control control = this.Controls[pictureBoxName];
        PictureBox pictureBox;
        if ((pictureBox = control as PictureBox) != null)
        {
            return pictureBox;
        }
    }

    return null;
}
</code>```

Use this method in the class using the player instance.

```<code>
Player player = new Player(3);
player.Cards.Add(CardType.Diamond);
player.Cards.Add(CardType.Club);
player.Cards.Add(CardType.Spade);

Dictionary dictionary = new Dictionary();
dictionary.Add(CardType.Diamond, pb_diamonds);
dictionary.Add(CardType.Spade, pb_spades);
dictionary.Add(CardType.Club, pb_clubs);
dictionary.Add(CardType.Heart, pb_hearts);
</code>```

Finally the assignment to the image property,

for (int i = 1; i < 5; i++)
{
    string playercardPictureBoxName = string.Concat("pb_playercard", i.ToString());
    PictureBox pictureBox = this.GetPictureBox(playercardPictureBoxName);
    if (pictureBox != null)
    {
        pictureBox.Image = dictionary[player.Cards[i - 1]].Image;
    }
}

Body:
For example i have a player object with a list of suits of cards it has.

player.card[0] = "diamonds";
player.card[1] = "clubs";
player.card[2] = "spades";
etc...

also i have 4 hidden pictureboxes with an image of suites ( pb_spades , pb_hearts m etc. )

and another 4 pictureboxs ( pb_playerCard1 , pb_playerCard2 , etc. ) to which I have to assign an image from a hidden pb corresponding to the suit of card the player object has.

Therefor

if ( player.card[0] == "diamonds" ) { pb_playerCard1.Image = pb_diamonds.Image; }

of course, doing it all with IFs would take quite a long time... Can I somehow use variable value as a part of an objects name?

kinda

for (int i = 1; i != 5; i++)
{
pb_playerCard+'i'.Image = pb_+'player.card[i+1]'.Image;
}

Body:
The main class Player and the associated enumeration should be like this:

class Player
{
    public Player(int n)
    {
        Cards = new List(n);
    }

    public IList Cards { get; private set; }
}

enum CardType
{
    Diamond,
    Club,
    Spade,
    Heart
}

Another method GetPictureBox() should in the winform partial class

public PictureBox GetPictureBox(string pictureBoxName)
{
    if(this.Controls.ContainsKey(pictureBoxName))
    {
        Control control = this.Controls[pictureBoxName];
        PictureBox pictureBox;
        if ((pictureBox = control as PictureBox) != null)
        {
            return pictureBox;
        }
    }

    return null;
}

Use this method in the class using the player instance.

Player player = new Player(3);
player.Cards.Add(CardType.Diamond);
player.Cards.Add(CardType.Club);
player.Cards.Add(CardType.Spade);

Dictionary dictionary = new Dictionary();
dictionary.Add(CardType.Diamond, pb_diamonds);
dictionary.Add(CardType.Spade, pb_spades);
dictionary.Add(CardType.Club, pb_clubs);
dictionary.Add(CardType.Heart, pb_hearts);

Finally the assignment to the image property,

for (int i = 1; i < 5; i++)
{
    string playercardPictureBoxName = string.Concat("pb_playercard", i.ToString());
    PictureBox pictureBox = this.GetPictureBox(playercardPictureBoxName);
    if (pictureBox != null)
    {
        pictureBox.Image = dictionary[player.Cards[i - 1]].Image;
    }
}


问:
Wifi hotspot transfer file
I am trying to send data in my app via wifi hotspot to all devices that are connected to that hotSpot. I searched a lot about this but I found nothing </p>

答: That's not how wifi hotspots work.  A wifi hotspot is just like connecting to a wifi router.  You can't broadcast to all connected clients.  Even if you could, there'd need to be an app on each device to listen for the incoming data to make it accept it.</p>

Title: Wifi hotspot transfer file


问:
Ignore / prevent emit of a particular file in wepack
Is there a way to prevent a specific file from being emitted to the output in Webpack (2)?

I'm using html-webpack-plugin and when building for the backend CMS, I'd like to avoid emitting the html file but still emit its meta image dependencies.

答:
this might help: ignore-emit-webpack-plugin

it allows you to ignore emitted files by patterns

```<code>// webpack config
const IgnoreEmitPlugin = require('ignore-emit-webpack-plugin');

module.exports = {
  // ...
  plugins: [ new IgnoreEmitPlugin(/unwanted-file\.html$/) ]
  // ...
};
</code>```

disclosure - i'm the author

Body:
this might help: ignore-emit-webpack-plugin

it allows you to ignore emitted files by patterns

// webpack config
const IgnoreEmitPlugin = require('ignore-emit-webpack-plugin');

module.exports = {
  // ...
  plugins: [ new IgnoreEmitPlugin(/unwanted-file\.html$/) ]
  // ...
};

disclosure - i'm the author


问:
Ember.js: How to remove folders (.svn) from asset compilation
I am using Ember.js with ember-font-awesome. For some reasons I have to version control my project with svn what puts a .svn folder within every directory. When building the project, ember automatically compiles assets (uglify, minify, copy to appropriate directory). This works for assets within dependencies as ember-font-awesonme out of the box. Buit it fails when having a .svn folder within the ember-font-awesonme fonts directory.
This is the error message:
You must pass a file to 'app.import'. For directories specify them to the constructor under thetreesoption. First I really don't know where and how to specify directories to the constructor (maybe somehow in the ember-cli-build.js) ansd more important, I don't want to specify it to the constructor. Insteasd I want to exclude it from compilation process.

Would be very fine if someone had a solution for me.

Thanks in advance.

答:
Secondly - if you don't import files from ember-font-awesome directly using app.import calls in your ember-cli-build file then you could try using specific options in configuration for ember-font-awesome in ember-cli-build. For example you can switch off including assets:

```<code>var app = new EmberApp({
  'ember-font-awesome': {
    includeFontAwesomeAssets: false
  }
});
</code>```

or font files:

```<code>var app = new EmberApp({
  'ember-font-awesome': {
    includeFontFiles: false
  }
});
</code>```

You could definitely switch off automatic font imports and import them directly in your CSS.

So, if experimenting with configuration of addon could help you but... It's possible that ember-font-awesome passes whole directory to app.import call and .svn directory (under fonts) is recursively picked. If this is true, then you would need probably to fork addon and do changes that suits you by yourself. However switching off automatic font import and importing them manually should help you.

Body:
Secondly - if you don't import files from ember-font-awesome directly using app.import calls in your ember-cli-build file then you could try using specific options in configuration for ember-font-awesome in ember-cli-build. For example you can switch off including assets:

var app = new EmberApp({
  'ember-font-awesome': {
    includeFontAwesomeAssets: false
  }
});

or font files:

var app = new EmberApp({
  'ember-font-awesome': {
    includeFontFiles: false
  }
});

You could definitely switch off automatic font imports and import them directly in your CSS.

So, if experimenting with configuration of addon could help you but... It's possible that ember-font-awesome passes whole directory to app.import call and .svn directory (under fonts) is recursively picked. If this is true, then you would need probably to fork addon and do changes that suits you by yourself. However switching off automatic font import and importing them manually should help you.


问:
Messenger not displaying images in Generic template in mobile App
I'm sending Facebook a structured message with a URL to an image file (the file is in Amazon S3). The message is structured according to https://developers.facebook.com/docs/messenger-platform/send-api-reference/generic-template (Generic template).

The message is being received and shown just fine - but the image doesn't appear in the mobile iOS Messenger app (I didn't test Android). It DOES appear in the web version of Messenger.

Anyone know what can cause this?

Thanks in advance!

答:
This happens in iOS Messenger app when there is no subdomain in the URL of the image.

In my case, I change from https://example.com/image.jpg
to https://mysub.example.com/image.jpg and the problem is solved.


答:
Never use control.CreateGraphics! Either draw into a Bitmap bmp using a Graphics g = Graphics.FromImage(bmp) or in the Paint event of a control, using the e.Graphics parameter..

Here is a cropping code that draws into a new Bitmap and that makes use of your controls etc but changes a few things:

It uses a Graphics object  that is created from a new Bitmap

It make use of using clauses to make sure it won't leak

It takes the size of the pictureBox3.ClientSize so it won't include any borders..

```<code>private void crop_bttn_Click(object sender, EventArgs e)
{
    Image crop = GetCopyImage("grayScale.jpg");
    pictureBox2.Image = crop;
    Bitmap targetBitmap = new Bitmap(pictureBox3.ClientSize.Width,
                                    pictureBox3.ClientSize.Height);
    using (Bitmap sourceBitmap = new Bitmap(pictureBox2.Image,
                 pictureBox2.ClientSize.Width, pictureBox2.ClientSize.Height))
    {
        using (Graphics g = Graphics.FromImage(targetBitmap))
        {
            g.DrawImage(sourceBitmap, new Rectangle(0, 0,
                        pictureBox3.ClientSize.Width, pictureBox3.ClientSize.Height),
                        rectCropArea, GraphicsUnit.Pixel);
        }
    }
    if (pictureBox3.Image != null) pictureBox3.Image.Dispose();
    pictureBox3.Image = targetBitmap;
    targetBitmap.Save(somename, someFormat);
}
</code>```

The alternative would be to..:

move all your code to the Paint event

replace the Graphics g = pictureBox3.CreateGraphics(); be Graphics g = e.Graphics;

insert these two lines to the click event:

```<code>Bitmap targetBitmap = new Bitmap(pictureBox3.ClientSize.Width,
                                pictureBox3.ClientSize.Height);
pictureBox3.DrawToBitmap(targetBitmap, pictureBox3.ClientRectangle);
</code>```

Title: How to save graphics created on a PictureBox?

Body:
Never use control.CreateGraphics! Either draw into a Bitmap bmp using a Graphics g = Graphics.FromImage(bmp) or in the Paint event of a control, using the e.Graphics parameter..

Here is a cropping code that draws into a new Bitmap and that makes use of your controls etc but changes a few things:

It uses a Graphics object  that is created from a new Bitmap

It make use of using clauses to make sure it won't leak

It takes the size of the pictureBox3.ClientSize so it won't include any borders..

private void crop_bttn_Click(object sender, EventArgs e)
{
    Image crop = GetCopyImage("grayScale.jpg");
    pictureBox2.Image = crop;
    Bitmap targetBitmap = new Bitmap(pictureBox3.ClientSize.Width,
                                    pictureBox3.ClientSize.Height);
    using (Bitmap sourceBitmap = new Bitmap(pictureBox2.Image,
                 pictureBox2.ClientSize.Width, pictureBox2.ClientSize.Height))
    {
        using (Graphics g = Graphics.FromImage(targetBitmap))
        {
            g.DrawImage(sourceBitmap, new Rectangle(0, 0,
                        pictureBox3.ClientSize.Width, pictureBox3.ClientSize.Height),
                        rectCropArea, GraphicsUnit.Pixel);
        }
    }
    if (pictureBox3.Image != null) pictureBox3.Image.Dispose();
    pictureBox3.Image = targetBitmap;
    targetBitmap.Save(somename, someFormat);
}

The alternative would be to..:

move all your code to the Paint event

replace the Graphics g = pictureBox3.CreateGraphics(); be Graphics g = e.Graphics;

insert these two lines to the click event:

Bitmap targetBitmap = new Bitmap(pictureBox3.ClientSize.Width,
                                pictureBox3.ClientSize.Height);
pictureBox3.DrawToBitmap(targetBitmap, pictureBox3.ClientRectangle);


问:
Why do I keep getting the $[injector:modulerr] uncaught error when all dependencies have been injected?
Below is my index.html page which has two buttons which links to 2 different views which i intend to show using angular routing.

Below is my

HTML

```<code><!DOCTYPE html>
<html>
<head>
    <title>PR_APP</title>
    <link rel="stylesheet" href="css/style.css">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.5/angular.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.5/angular-route.js"></script>
    <script src="js/main.js"></script>
    <script src="js/services.js"></script>
</head>
<body ng-app="new_pr_app">
    <h2>Please select an option</h2><br>
    <div ng-controller="view_controller">
        <button id="view_details" ng-click="view()">View Details</button>
    </div>

    <div ng-controller="update_controller">
        <button id="update_details" ng-click="update()">Update Details</button>
    </div>

    <div ng-view>

    </div>

</body>
</code>```

Below is my main.js file which houses both above mentioned controller and logic for angular routing.

main.js

```<code>var app = angular.module('new_pr_app', ['ngRoute']);

app.config('$routeProvider','$locationProvider', function($routeProvider,$locationProvider){
        $routeProvider.when("/update",
        {
            templateUrl:"update.html",
            controller: "update_controller"
        })
        .when("/view",
        {
            templateUrl: "view.html",
            controller: "view_controller"
        });
});

app.controller("view_controller",function($scope, $location, http_factory){
$scope.view = function(){
    $location.path("/view");
}
    $scope.result =[];
    http_factory.get_request().then(function(response){
        $scope.result = response.data;
    });
});

app.controller("update_controller",function($scope, $location, http_factory){
$scope.update_details = function(){
    $location.path("/update");
}
    $scope.names = [];
    http_factory.get_request().then(function(response){
        $scope.names = response.data;
    });
});
</code>```

I have another file called services.js which has a service factory to get details from a json file using an http get.

My only problem seems to be in the above main.js which gives the error below everytime index.html loads

angular.js:88 Uncaught Error: [$injector:modulerr]

答:
Your config is wrong. You pass in a string as the first (and second argument), while the .config(..) function, expects a function to be passed in (or an array).

In your code, you simply forgot to wrap the arguments in an array. Here's how it should look:

```<code>app.config(['$routeProvider','$locationProvider',
    function($routeProvider,$locationProvider){
        $routeProvider.when("/update",
        {
            templateUrl:"update.html",
            controller: "update_controller"
        })
        .when("/view",
        {
            templateUrl: "view.html",
            controller: "view_controller"
        });
    }]);
</code>```

Note the [ and ] wrapping the content

Body:
Below is my index.html page which has two buttons which links to 2 different views which i intend to show using angular routing.

Below is my

HTML

<!DOCTYPE html>

    <title>PR_APP</title>
    <link rel="stylesheet" href="css/style.css">

Please select an option

        <button id="view_details" ng-click="view()">View Details</button>

        <button id="update_details" ng-click="update()">Update Details</button>

Below is my main.js file which houses both above mentioned controller and logic for angular routing.

main.js

var app = angular.module('new_pr_app', ['ngRoute']);

app.config('$routeProvider','$locationProvider', function($routeProvider,$locationProvider){
        $routeProvider.when("/update",
        {
            templateUrl:"update.html",
            controller: "update_controller"
        })
        .when("/view",
        {
            templateUrl: "view.html",
            controller: "view_controller"
        });
});

app.controller("view_controller",function($scope, $location, http_factory){
$scope.view = function(){
    $location.path("/view");
}
    $scope.result =[];
    http_factory.get_request().then(function(response){
        $scope.result = response.data;
    });
});

app.controller("update_controller",function($scope, $location, http_factory){
$scope.update_details = function(){
    $location.path("/update");
}
    $scope.names = [];
    http_factory.get_request().then(function(response){
        $scope.names = response.data;
    });
});

I have another file called services.js which has a service factory to get details from a json file using an http get.

My only problem seems to be in the above main.js which gives the error below everytime index.html loads

angular.js:88 Uncaught Error: [$injector:modulerr]

Body:
Your config is wrong. You pass in a string as the first (and second argument), while the .config(..) function, expects a function to be passed in (or an array).

In your code, you simply forgot to wrap the arguments in an array. Here's how it should look:

app.config(['$routeProvider','$locationProvider',
    function($routeProvider,$locationProvider){
        $routeProvider.when("/update",
        {
            templateUrl:"update.html",
            controller: "update_controller"
        })
        .when("/view",
        {
            templateUrl: "view.html",
            controller: "view_controller"
        });
    }]);

Note the [ and ] wrapping the content


问:
expected `;' before "pennies"? C++ Debugging (Code Completed)
Can anyone tell me why I get an error on my last cout?

```<code>#include <iostream>
#include <cmath>
#include <stdio.h>
#include <cstring>
#include <conio.h>

using namespace std;
inline void keep_window_open() { char ch; cin>>ch; }

int main()
{
 cout << "How many pennies do you have?\n";
 int pennies;
 cin >> pennies;
 double total_pen;
 total_pen = (0.01 * pennies);
           if (pennies >= 1)
           {
                       string penn = " pennies.";
           }else
           {
                       string penn = " penny.";
 } cout << "How many nickles do you have?\n";
 int nickles;
 cin >> nickles;
 double total_nic;
 total_nic = (0.05 * nickles);
           if (nickles >= 1)
           {
                       string five = " nickels.";
           }else
           {
                       string five = " nickel.";
 } cout << "How many dimes do you have?\n";
 int dimes;
 cin >> dimes;
 double total_dim;
 total_dim = (0.10 * dimes);
           if (dimes >= 1)
           {
                     string ten = " dimes.";
           }else
           {
                     string ten = " dime.";
 } cout << "How many quarters do you have?\n";
 int quarters;
 cin >> quarters;
 double total_qua;
 total_qua = (0.25 * quarters);
           if (quarters >= 1)
           {
                        string twentyfive = " quarters.";
           }else
           {
                        string twentyfive = " quarter.";
 } cout << "How many half-dollars do you have?\n";
 int half_dollars;
 cin >> half_dollars;
 double total_dol;
 total_dol = (0.50 * half_dollars);
           if (half_dollars >= 1)
           {
                        string fifty = " half dollars.";
           }else
           {
                        string fifty = " half dollar.";
           }
string saying = "You have ";
cout << saying pennies penn << "\n" << saying nickles five << "\n" << saying dimes ten << "\n" << saying quarters twentyfive << "\n" << saying half_dollars fifty << "\n";
keep_window_open()
return 0;
}
</code>```

答:
Add more <<:

```<code>cout << saying << pennies << penn << "\n"
     << saying << nickles << five << "\n"
     << saying << dimes << ten << "\n"
     << saying << quarters << twentyfive << "\n"
     << saying << half_dollars << fifty << "\n";
</code>```

EDIT: Also, you are declaring variables in inner blocks - their names are no longer valid outside. Declare your strings earlier.

Body:
Can anyone tell me why I get an error on my last cout?

#include <iostream>
#include <cmath>
#include <stdio.h>
#include <cstring>
#include <conio.h>

using namespace std;
inline void keep_window_open() { char ch; cin>>ch; }

int main()
{
 cout << "How many pennies do you have?\n";
 int pennies;
 cin >> pennies;
 double total_pen;
 total_pen = (0.01 * pennies);
           if (pennies >= 1)
           {
                       string penn = " pennies.";
           }else
           {
                       string penn = " penny.";
 } cout << "How many nickles do you have?\n";
 int nickles;
 cin >> nickles;
 double total_nic;
 total_nic = (0.05 * nickles);
           if (nickles >= 1)
           {
                       string five = " nickels.";
           }else
           {
                       string five = " nickel.";
 } cout << "How many dimes do you have?\n";
 int dimes;
 cin >> dimes;
 double total_dim;
 total_dim = (0.10 * dimes);
           if (dimes >= 1)
           {
                     string ten = " dimes.";
           }else
           {
                     string ten = " dime.";
 } cout << "How many quarters do you have?\n";
 int quarters;
 cin >> quarters;
 double total_qua;
 total_qua = (0.25 * quarters);
           if (quarters >= 1)
           {
                        string twentyfive = " quarters.";
           }else
           {
                        string twentyfive = " quarter.";
 } cout << "How many half-dollars do you have?\n";
 int half_dollars;
 cin >> half_dollars;
 double total_dol;
 total_dol = (0.50 * half_dollars);
           if (half_dollars >= 1)
           {
                        string fifty = " half dollars.";
           }else
           {
                        string fifty = " half dollar.";
           }
string saying = "You have ";
cout << saying pennies penn << "\n" << saying nickles five << "\n" << saying dimes ten << "\n" << saying quarters twentyfive << "\n" << saying half_dollars fifty << "\n";
keep_window_open()
return 0;
}

Body:
Add more <<:

cout << saying << pennies << penn << "\n"
     << saying << nickles << five << "\n"
     << saying << dimes << ten << "\n"
     << saying << quarters << twentyfive << "\n"
     << saying << half_dollars << fifty << "\n";

EDIT: Also, you are declaring variables in inner blocks - their names are no longer valid outside. Declare your strings earlier.